face-api/dist/face-api.esm.js

4122 lines
1.1 MiB
JavaScript
Raw Normal View History

2020-10-29 05:16:50 +01:00
var Mm=Object.defineProperty,LJ=Object.prototype.hasOwnProperty,ES=(r,l)=>()=>(l||(l={exports:{}},r(l.exports,l)),l.exports),XC=r=>Mm(r,"__esModule",{value:!0}),Pm=(r,l)=>{XC(r);for(var u in l)Mm(r,u,{get:l[u],enumerable:!0})},SJ=(r,l)=>{if(XC(r),typeof l=="object"||typeof l=="function")for(let u in l)!LJ.call(r,u)&&u!=="default"&&Mm(r,u,{get:()=>l[u],enumerable:!0});return r},Je=r=>r&&r.__esModule?r:SJ(Mm({},"default",{value:r,enumerable:!0}),r);var ZC=ES((Ac,JC)=>{"use strict";var IJ=function(){if(typeof self!="undefined")return self;if(typeof window!="undefined")return window;if(typeof mr!="undefined")return mr;throw new Error("unable to locate global object")},mr=IJ();JC.exports=Ac=mr.fetch;mr.fetch&&(Ac.default=mr.fetch.bind(mr));Ac.Headers=mr.Headers;Ac.Request=mr.Request;Ac.Response=mr.Response});var Ze=ES((zm,QC)=>{(function(r,l){typeof zm=="object"&&typeof QC!="undefined"?l(zm):typeof define=="function"&&define.amd?define(["exports"],l):(r=r||self,l(r.tf=r.tf||{}))})(zm,function(r){"use strict";const l=1e-7,u=1e-4;class p{constructor(e,t){this.backend=e,this.dataMover=t,this.data=new WeakMap,this.dataIdsCount=0}get(e){return this.data.has(e)||this.dataMover.moveData(this.backend,e),this.data.get(e)}set(e,t){this.dataIdsCount++,this.data.set(e,t)}has(e){return this.data.has(e)}delete(e){return this.dataIdsCount--,this.data.delete(e)}numDataIds(){return this.dataIdsCount}}class y{time(e){return g("time")}read(e){return g("read")}readSync(e){return g("readSync")}numDataIds(){return g("numDataIds")}disposeData(e){return g("disposeData")}write(e,t,n){return g("write")}move(e,t,n,s){return g("move")}memory(){return g("memory")}floatPrecision(){return g("floatPrecision")}epsilon(){return this.floatPrecision()===32?l:u}batchMatMul(e,t,n,s){return g("batchMatMul")}fusedBatchMatMul({a:e,b:t,transposeA:n,transposeB:s,bias:i,activation:o,preluActivationWeights:a}){return g("fusedBatchMatMul")}slice(e,t,n){return g("slice")}stridedSlice(e,t,n,s){return g("stridedSlice")}unstack(e,t){return g("unstack")}reverse(e,t){return g("reverse")}concat(e,t){return g("concat")}neg(e){return g("neg")}add(e,t){return g("add")}addN(e){return g("addN")}subtract(e,t){return g("subtract")}multiply(e,t){return g("multiply")}realDivide(e,t){return g("realDivide")}floorDiv(e,t){return g("floorDiv")}sum(e,t){return g("sum")}prod(e,t){return g("prod")}unsortedSegmentSum(e,t,n){return g("unsortedSegmentSum")}argMin(e,t){return g("argMin")}argMax(e,t){return g("argMax")}equal(e,t){return g("equal")}notEqual(e,t){return g("notEqual")}less(e,t){return g("less")}lessEqual(e,t){return g("lessEqual")}greater(e,t){return g("greater")}greaterEqual(e,t){return g("greaterEqual")}logicalNot(e){return g("logicalNot")}logicalAnd(e,t){return g("logicalAnd")}logicalOr(e,t){return g("logicalOr")}where(e){return g("where")}select(e,t,n){return g("select")}topk(e,t,n){return g("topk")}min(e,t){return g("min")}minimum(e,t){return g("minimum")}mod(e,t){return g("mod")}max(e,t){return g("max")}maximum(e,t){return g("maximum")}all(e,t){return g("all")}any(e,t){return g("any")}squaredDifference(e,t){return g("squaredDifference")}ceil(e){return g("ceil")}floor(e){return g("floor")}round(e){return g("round")}sign(e){return g("sign")}isNaN(e){return g("isNaN")}isInf(e){return g("isInf")}isFinite(e){return g("isFinite")}pow(e,t){return g("pow")}exp(e){return g("exp")}expm1(e){return g("expm1")}softmax(e,t){return g("softmax")}log(e){return g("log")}log1p(e){return g("log1p")}sqrt(e){return g("sqrt")}rsqrt(e){return g("rsqrt")}square(e){return g("square")}reciprocal(e){return g("reciprocal")}relu(e){return g("relu")}relu6(e){return g("relu6")}prelu(e,t){return g("prelu")}elu(e){return g("elu")}eluDer(e,t){return g("eluDer")}selu(e){return g("selu")}int(e){return g("int")}clip(e,t,n){return g("clip")}abs(e){return g("abs")}complexAbs(e){return g("complexAbs")}sigmoid(e){return g("sigmoid")}softplus(e){return g("softplus")}sin(e){return g("sin")}cos(e){return g("cos")}tan(e){return g("tan")}asin(e){return g("asin")}acos(e){return g("acos")}atan(e){return g("atan")}atan2(e,t){r
2020-10-13 22:57:06 +02:00
`)),h.join(`
2020-10-29 05:16:50 +01:00
`)}function rk(e,t,n,s){const i=P(t),o=s[s.length-1],a=new Array(o).fill(0),c=t.length,h=n==="complex64"?Zl(e):e;if(c>1)for(let d=0;d<i/o;d++){const m=d*o;for(let f=0;f<o;f++)a[f]=Math.max(a[f],Jl(h[m+f],0,n).length)}return a}function Jl(e,t,n){let s;return Array.isArray(e)?s=`${parseFloat(e[0].toFixed(ky))} + ${parseFloat(e[1].toFixed(ky))}j`:Yi(e)?s=`'${e}'`:n==="bool"?s=iT(e):s=parseFloat(e.toFixed(ky)).toString(),pt(s,t)}function iT(e){return e===0?"false":"true"}function $d(e,t,n,s,i,o=!0){const a=n==="complex64"?2:1,c=t[0],h=t.length;if(h===0){if(n==="complex64"){const x=Zl(e);return[Jl(x[0],0,n)]}return n==="bool"?[iT(e[0])]:[e[0].toString()]}if(h===1){if(c>sT){const v=Xl*a;let N=Array.from(e.slice(0,v)),O=Array.from(e.slice((c-Xl)*a,c*a));return n==="complex64"&&(N=Zl(N),O=Zl(O)),["["+N.map((E,k)=>Jl(E,i[k],n)).join(", ")+", ..., "+O.map((E,k)=>Jl(E,i[c-Xl+k],n)).join(", ")+"]"]}const x=n==="complex64"?Zl(e):Array.from(e);return["["+x.map((v,N)=>Jl(v,i[N],n)).join(", ")+"]"]}const d=t.slice(1),m=s.slice(1),f=s[0]*a,b=[];if(c>sT){for(let x=0;x<Xl;x++){const v=x*f,N=v+f;b.push(...$d(e.slice(v,N),d,n,m,i,!1))}b.push("...");for(let x=c-Xl;x<c;x++){const v=x*f,N=v+f;b.push(...$d(e.slice(v,N),d,n,m,i,x===c-1))}}else for(let x=0;x<c;x++){const v=x*f,N=v+f;b.push(...$d(e.slice(v,N),d,n,m,i,x===c-1))}const w=h===2?",":"";b[0]="["+b[0]+w;for(let x=1;x<b.length-1;x++)b[x]=" "+b[x]+w;let L=`,
`;for(let x=2;x<h;x++)L+=`
`;return b[b.length-1]=" "+b[b.length-1]+"]"+(o?"":L),b}function Zl(e){const t=[];for(let n=0;n<e.length;n+=2)t.push([e[n],e[n+1]]);return t}class an{constructor(e,t,n){if(this.dtype=t,this.shape=e.slice(),this.size=P(e),n!=null){const s=n.length;A(s===this.size,()=>`Length of values '${s}' does not match the size inferred by the shape '${this.size}'.`)}if(t==="complex64")throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=n||ws(t,this.size),this.strides=je(e)}set(e,...t){t.length===0&&(t=[0]),A(t.length===this.rank,()=>`The number of provided coordinates (${t.length}) must match the rank (${this.rank})`);const n=this.locToIndex(t);this.values[n]=e}get(...e){e.length===0&&(e=[0]);let t=0;for(const s of e){if(s<0||s>=this.shape[t]){const i=`Requested out of range element at ${e}. Buffer shape=${this.shape}`;throw new Error(i)}t++}let n=e[e.length-1];for(let s=0;s<e.length-1;++s)n+=this.strides[s]*e[s];return this.values[n]}locToIndex(e){if(this.rank===0)return 0;if(this.rank===1)return e[0];let t=e[e.length-1];for(let n=0;n<e.length-1;++n)t+=this.strides[n]*e[n];return t}indexToLoc(e){if(this.rank===0)return[];if(this.rank===1)return[e];const t=new Array(this.shape.length);for(let n=0;n<t.length-1;++n)t[n]=Math.floor(e/this.strides[n]),e-=t[n]*this.strides[n];return t[t.length-1]=e,t}get rank(){return this.shape.length}toTensor(){return Si().makeTensor(this.values,this.shape,this.dtype)}}let Si=null,Oa=null,rT=null;function ok(e){Si=e}function ak(e){Oa=e}function ck(e){rT=e}class ee{constructor(e,t,n,s){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=P(e),this.strides=je(e),this.dataId=n,this.id=s,this.rankType=this.rank<5?this.rank.toString():"higher"}get rank(){return this.shape.length}async buffer(){const e=await this.data();return Oa.buffer(this.shape,this.dtype,e)}bufferSync(){return Oa.buffer(this.shape,this.dtype,this.dataSync())}async array(){const e=await this.data();return Ls(this.shape,e)}arraySync(){return Ls(this.shape,this.dataSync())}async data(){this.throwIfDisposed();const e=Si().read(this.dataId);if(this.dtype==="string"){const t=await e;try{return t.map(n=>Kl(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=Si().readSync(this.dataId);if(this.dtype==="string")try{return e.map(t=>Kl(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 Si().read(this.dataId);return this.dtype==="string"?e:new Uint8Array(e.buffer)}dispose(){if(this.isDisposed)return;Si().disposeTensor(this),this.isDisposedInternal=!0}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return Oa.print(this,e)}clone(){return this.throwIfDisposed(),Oa.clone(this)}toString(e=!1){const t=this.dataSync();return ik(t,this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),Oa.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),Si().makeVariable(this,e,t,n)}}Object.defineProperty(ee,Symbol.hasInstance,{value:e=>!!e&&e.data!=null&&e.dataSync!=null&&e.throwIfDisposed!=null});class Ql extends ee{constructor(e,t,n,s){super(e.shape,e.dtype,e.dataId,s);this.trainable=t,this.name=n}assign(e){if(e.dtype!==this.dtype)throw new Error(`dtype of the new value (${e.dtype}) and previous value (${this.dtype}) must match`);if(!ae(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);Si().disposeTensor(this),this.dataId=e.dataId,Si().incRef(this,null)}dispose(){Si().disposeVariable(this),this.isDisposedInternal=!0}}Object.defineProperty(Ql,Symbol.hasInstance,{value:e=>e instanceof ee&&e.assign!=null&&e.assign instanceof Function});(function(e){e.R0="R0",e.R1="R1",
Manifest JSON has weights with names: ${c.join(", ")}.`)}const h=i.reduce((w,L,x)=>(L&&w.push(x),w),[]),d=[];h.forEach(w=>{t[w].paths.forEach(L=>{const x=n+(n.endsWith("/")?"":"/")+L;d.push(x)})});const m=await e(d),f={};let b=0;return h.forEach(w=>{const L=t[w].paths.length;let x=0;for(let k=0;k<L;k++)x+=m[b+k].byteLength;const v=new ArrayBuffer(x),N=new Uint8Array(v);let O=0;for(let k=0;k<L;k++){const F=new Uint8Array(m[b+k]);N.set(F,O),O+=F.byteLength}const E=o[w];E.forEach(k=>{const F=v.slice(k.groupOffset,k.groupOffset+k.sizeBytes),U=Pd(F,[k.manifestEntry]);for(const $ in U)f[$]=U[$]}),b+=L}),f}}const Qk="application/octet-stream",eF="application/json";class qy{constructor(e,t){if(this.DEFAULT_METHOD="POST",t==null&&(t={}),this.weightPathPrefix=t.weightPathPrefix,this.onProgress=t.onProgress,this.weightUrlConverter=t.weightUrlConverter,t.fetchFunc!=null?(A(typeof t.fetchFunc=="function",()=>"Must pass a function that matches the signature of `fetch` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)"),this.fetch=t.fetchFunc):this.fetch=oe().platform.fetch,A(e!=null&&e.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(e)&&A(e.length===2,()=>`URL paths for http must have a length of 2, (actual length is ${e.length}).`),this.path=e,t.requestInit!=null&&t.requestInit.body!=null)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=t.requestInit||{}}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");const t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit);t.body=new FormData;const n=[{paths:["./model.weights.bin"],weights:e.weightSpecs}],s={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,userDefinedMetadata:e.userDefinedMetadata,weightsManifest:n};t.body.append("model.json",new Blob([JSON.stringify(s)],{type:eF}),"model.json"),e.weightData!=null&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:Qk}),"model.weights.bin");const i=await this.fetch(this.path,t);if(i.ok)return{modelArtifactsInfo:nh(e),responses:[i]};throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${i.status}.`)}async load(){const e=await this.fetch(this.path,this.requestInit);if(!e.ok)throw new Error(`Request to ${this.path} failed with status code ${e.status}. Please verify this URL points to the model JSON of the model to load.`);let t;try{t=await e.json()}catch(b){let w=`Failed to parse model JSON of response from ${this.path}.`;throw this.path.endsWith(".pb")?w+=" Your path contains a .pb file extension. Support for .pb models have been removed in TensorFlow.js 1.0 in favor of .json models. You can re-convert your Python TensorFlow model using the TensorFlow.js 1.0 conversion scripts or you can convert your.pb models with the 'pb2json'NPM script in the tensorflow/tfjs-converter repository.":w+=" Please make sure the server is serving valid JSON for this request.",new Error(w)}const n=t.modelTopology,s=t.weightsManifest,i=t.generatedBy,o=t.convertedBy,a=t.format,c=t.userDefinedMetadata;if(n==null&&s==null)throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`);let h,d;if(s!=null){const b=await this.loadWeights(s);[h,d]=b}const m={modelTopology:n,weightSpecs:h,weightData:d,userDefinedMetadata:c,generatedBy:i,convertedBy:o,format:a},f=t.modelInitializer;return f&&(m.modelInitializer=f),m}async loadWeights(e){const t=Array.isArray(this.path)?this.path[1]:this.path,[n,s]=tF(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 AT(a,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress});return[o,zd(h)]}}qy.URL_SCHEME_REGEX=/^https?:\/\//;function
2020-10-12 20:28:19 +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-12 20:28:19 +02:00
Actual: ${i}.
2020-10-29 05:16:50 +01:00
Expected: ${o}.`)}}function SF(e,t){e().then(()=>t.fail(),()=>t())}function IF(e,t){const n=typeof t=="string"||typeof t=="number"||typeof t=="boolean"?[t]:t;return Yi(e)||Yi(e[0])||Yi(t)||Yi(t[0])?nb(e,n,(s,i)=>s==i):nb(e,t,(s,i)=>ib(s,i,0))}function sb(e,t,n){if(n==null&&(n=Xd()),!ib(e,t,n))throw new Error(`Numbers differ: actual === ${e}, expected === ${t}`)}function ib(e,t,n){return!isFinite(e)&&!isFinite(t)?!0:!(isNaN(e)||isNaN(t)||Math.abs(e-t)>n)}function xF(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 TF(e,t){expect(new Float32Array(e)).toEqual(new Float32Array(t))}var AF=Object.freeze({__proto__:null,TEST_EPSILON_FLOAT16:PT,expectArraysClose:LF,testEpsilon:Xd,expectPromiseToFail:SF,expectArraysEqual:IF,expectNumbersClose:sb,expectValuesInRange:xF,expectArrayBuffersEqual:TF});const zT="2.7.0";function vF(){oe().set("PROD",!0)}function NF(){oe().set("DEBUG",!0)}function CF(){oe().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function un(e){oe().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(e+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}ck(un);function RF(){G.disposeVariables()}function Ki(){return G}function Jd(){return G.memory()}function OF(e){return G.profile(e)}function Q(e,t){return G.tidy(e,t)}function He(e){const t=Hi(e);t.forEach(n=>n.dispose())}function bn(e){return G.keep(e)}function EF(e){return G.time(e)}function VT(e){return G.setBackend(e)}function DF(){return G.ready()}function kF(){return G.backendName}function FF(e){G.removeBackend(e)}function _F(e){return G.findBackend(e)}function WF(e){return G.findBackendFactory(e)}function rb(e,t,n=1){return G.registerBackend(e,t,n)}function GT(){return G.backend}function $F(e,t){oe().setPlatform(e,t)}function UF(e,t){let n=W(e,"a","add"),s=W(t,"b","add");[n,s]=Gt(n,s);const i=(a,c)=>{const h=a.add(n,s);return c([n,s]),h},o={a:n,b:s};return G.runKernelFunc(i,o,null,wo)}const be=z({add_:UF});function BF(e,t){let n=W(e,"a","floorDiv"),s=W(t,"b","floorDiv");[n,s]=Gt(n,s);const i=(a,c)=>{const h=a.floorDiv(n,s);return c([n,s]),h},o={a:n,b:s};return G.runKernelFunc(i,o,null,sy)}const Zd=z({floorDiv_:BF});function MF(e,t){let n=W(e,"a","div"),s=W(t,"b","div");if([n,s]=Gt(n,s),n.dtype==="int32"&&s.dtype==="int32")return Zd(n,s);const i=(c,h)=>{const d=c.realDivide(n,s);return h([n,s]),d},o={a:n,b:s},a={};return G.runKernelFunc(i,o,null,xa,a)}const We=z({div_:MF});function PF(e,t){let n=W(e,"a","mul"),s=W(t,"b","mul");[n,s]=Gt(n,s);const i=(a,c)=>{const h=a.multiply(n,s);return c([n,s]),h},o={a:n,b:s};return G.runKernelFunc(i,o,null,Ta)}const X=z({mul_:PF});function zF(e){const t=W(e,"x","abs"),n={x:t};return G.runKernelFunc((s,i)=>(i([t]),t.dtype==="complex64"?s.complexAbs(t):s.abs(t)),n,null,td)}const dn=z({abs_:zF});function VF(e){const t=W(e,"x","acos"),n={x:t};return G.runKernelFunc((s,i)=>{const o=s.acos(t);return i([t]),o},n,null,ol)}const ob=z({acos_:VF});function GF(e){const t=W(e,"x","acosh"),n={x:t};return G.runKernelFunc((s,i)=>{const o=s.acosh(t);return i([t]),o},n,null,al)}const ab=z({acosh_:GF});function YF(e){A(Array.isArray(e),()=>"The argument passed to tf.addN() must be a list of tensors"),A(e.length>=1,()=>`Must pass at least one tensor to tf.addN(), but got ${e.length}`);const t=e.map((o,a)=>W(o,`tensors${a}`,"addN")),n=t[0];t.forEach(o=>{if(o.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),t.forEach(o=>{if(!ae(o.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});const s=(o,a)=>{const c=o.addN(t);return a(t),c},i=t;return G.runKernelFunc(s,i,null,Gg)}const YT=z({addN_:YF});function cb(e,t){for(let n=0;n<e.length;++n)if(e[e.length-n-1]!==t-1-n)return!1;return!0}function HT(e,t,n){const s=e.length+t.length,i=[];let o=0,a=0;for(let c=0;c<s;c++)n.indexOf(c)===-1?i.push(e[o++]):i.push(t[a++]);return i}function An(e,t){const n=[],s=e.length;for(let o=0;o<s;o++)t.indexOf(o)===-1&&
with dtype ${a.dtype}. `)});const s=(a,c)=>{const h=qe(t,n[0].shape)[0],d=Xi(n.map(b=>b.shape),h);if(P(d)===0)return sn([],d);if(n=n.filter(b=>b.size>0),n.length===1)return n[0];const m=n.map(b=>b.shape);np(m,h);const f=a.concat(n,h);return c(n),f},i=n,o={axis:t};return G.runKernelFunc(s,i,null,fl,o)}const Yt=z({concat_:a_});function c_(e){const t=W(e,"x","sigmoid"),n={x:t};return G.runKernelFunc((s,i)=>{const o=s.sigmoid(t);return i([o]),o},n,null,zl)}const Ti=z({sigmoid_:c_});function l_(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]=Kd(s,t,n);return Qy(s,d,m),h([s]),c.slice(s,d,m)},o={x:s},a={begin:t,size:n};return G.runKernelFunc(i,o,null,Ad,a)}const tt=z({slice_:l_});function h_(e){const t=W(e,"x","tanh"),n={x:t};return G.runKernelFunc((s,i)=>{const o=s.tanh(t);return i([o]),o},n,null,Yl)}const $a=z({tanh_:h_});function u_(e,t,n,s,i,o){const a=W(e,"forgetBias","basicLSTMCell"),c=W(t,"lstmKernel","basicLSTMCell"),h=W(n,"lstmBias","basicLSTMCell"),d=W(s,"data","basicLSTMCell"),m=W(i,"c","basicLSTMCell"),f=W(o,"h","basicLSTMCell"),b=Yt([d,f],1),w=ct(b,c),L=be(w,h),x=L.shape[0],v=L.shape[1]/4,N=[x,v],O=tt(L,[0,0],N),E=tt(L,[0,v],N),k=tt(L,[0,v*2],N),F=tt(L,[0,v*3],N),U=be(X(Ti(O),$a(E)),X(m,Ti(be(a,k)))),$=X($a(U),Ti(F));return[U,$]}const d_=z({basicLSTMCell_:u_});function p_(e,t,n){const s=W(e,"x","batchToSpaceND"),i=t.reduce((h,d)=>h*d);A(s.rank>=1+t.length,()=>`input rank is ${s.rank} but should be > than blockShape.length ${t.length}`),A(n.length===t.length,()=>`crops.length is ${n.length} but should be equal to blockShape.length ${t.length}`),A(s.shape[0]%i===0,()=>`input tensor batch is ${s.shape[0]} but is not divisible by the product of the elements of blockShape ${t.join(" * ")} === ${i}`);const o=h=>h.batchToSpaceND(s,t,n),a={x:s},c={blockShape:t,crops:n};return G.runKernelFunc(o,a,null,jg,c)}const ch=z({batchToSpaceND_:p_});function m_(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 f_(e,t,n,s,i,o){o==null&&(o=.001);const a=W(e,"x","batchNorm"),c=W(t,"mean","batchNorm"),h=W(n,"variance","batchNorm");let d;i!=null&&(d=W(i,"scale","batchNorm"));let m;s!=null&&(m=W(s,"offset","batchNorm")),A(c.rank===h.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),A(m==null||c.rank===m.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),A(d==null||c.rank===d.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");const f=m_(a),b=(v,N)=>(N([f,c,h,d]),v.batchNorm(f,sp(c),sp(h),sp(m),sp(d),o)),w={x:f,scale:d,offset:m,mean:c,variance:h},L={varianceEpsilon:o},x=G.runKernelFunc(b,w,null,Il,L);return K(x,a.shape)}function sp(e){return e==null?null:e.rank===0?K(e,[e.size]):e.rank===1?e:e.rank===2?K(e,[1,1,e.shape[0],e.shape[1]]):e.rank===3?K(e,[1,e.shape[0],e.shape[1],e.shape[2]]):e}const No=z({batchNorm_:f_});function g_(e,t,n,s,i,o){const a=W(e,"x","batchNorm"),c=W(t,"mean","batchNorm"),h=W(n,"variance","batchNorm");let d;i!=null&&(d=W(i,"scale","batchNorm"));let m;return s!=null&&(m=W(s,"offset","batchNorm")),A(a.rank===2,()=>`Error in batchNorm2D: x must be rank 2 but got rank ${a.rank}.`),A(c.rank===2||c.rank===1,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${c.rank}.`),A(h.rank===2||h.rank===1,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${h.rank}.`),d!=null&&A(d.rank===2||d.rank===1,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${d.rank}.`),m!=null&&A(m.rank===2||m.rank===1,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${m.rank}.`),No(a,c,h,m,d,o)}const qT=z({batchNorm2d_:g_});function y_(e,t,n,s,i,o){const a=W(e,"x","batchNorm"),c=W(t,"mean","batchNorm"),h=W(n,"variance","batchNorm");let d;i!=null&&(d=W(i,"scale","batchNorm"));let m;return s!=null&&(m=W(s,"offset","batchNorm")),A(a.rank===3,()=>`Error in ba
2020-10-12 20:28:19 +02:00
${i} and ${t} for depthToSpace with input shape
2020-10-29 05:16:50 +01:00
${s.shape}`),A(o*t>=0,()=>`Negative dimension size caused by overflow when multiplying
2020-10-13 22:57:06 +02:00
${o} and ${t} for depthToSpace with input shape
2020-10-29 05:16:50 +01:00
${s.shape}`),A(a%(t*t)===0,()=>`Dimension size must be evenly divisible by ${t*t} but is ${a} for depthToSpace with input shape ${s.shape}`);const c=m=>m.depthToSpace(s,t,n),h={x:s},d={blockSize:t,dataFormat:n};return G.runKernelFunc(c,h,null,kx,d)}const Sb=z({depthToSpace_:$_});function U_(e,t,n,s,i="NHWC",o=[1,1],a){const c=W(e,"x","depthwiseConv2d"),h=W(t,"filter","depthwiseConv2d");let d=c,m=!1;c.rank===3&&(m=!0,d=K(c,[1,c.shape[0],c.shape[1],c.shape[2]])),A(d.rank===4,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${d.rank}.`),A(h.rank===4,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${h.rank}.`),A(d.shape[3]===h.shape[2],()=>`Error in depthwiseConv2d: number of input channels (${d.shape[3]}) must match the inChannels dimension in filter ${h.shape[2]}.`),a!=null&&A(Le(s),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${s}.`);const f=(x,v)=>{o==null&&(o=[1,1]),A(cn(n,o),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${o}'`);const N=kn(d.shape,h.shape,n,o,s,a,!0),O=x.depthwiseConv2D(d,h,N);return v([d,h]),O},b={x:d,filter:h},w={strides:n,pad:s,dataFormat:i,dilations:o,dimRoundingMode:a},L=G.runKernelFunc(f,b,null,ld,w);return m?K(L,[L.shape[1],L.shape[2],L.shape[3]]):L}const Co=z({depthwiseConv2d_:U_});function B_(e){const t=W(e,"x","diag"),n=i=>{const o=K(t,[t.size]),a=i.diag(o),c=[...e.shape,...e.shape];return K(a,c)},s={x:t};return G.runKernelFunc(n,s,null,Fx)}const M_=z({diag_:B_});function P_(e,t,n,s,i=[1,1],o="NHWC"){const a=W(e,"x","dilation2d"),c=W(t,"filter","dilation2d");A(a.rank===3||a.rank===4,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${a.rank}.`),A(c.rank===3,()=>`Error in dilation2d: filter must be rank 3, but got rank ${c.rank}.`),A(o==="NHWC",()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${o}`);let h=a,d=!1;a.rank===3&&(h=K(a,[1,a.shape[0],a.shape[1],a.shape[2]]),d=!0);const m={x:h,filter:c},f={strides:n,pad:s,dilations:i},b=G.runKernel(hd,m,f);return d?K(b,[b.shape[1],b.shape[2],b.shape[3]]):b}const Ib=z({dilation2d_:P_});function Ro(e,t){const n=e.length,s=[];for(let i=0;i<n;i++){const o=n-1-i,a=e[o]||1,c=t[t.length-1-i]||1;c>1&&a===1&&s.unshift(o)}return s}function pn(e,t){const n=[];for(let s=0;s<t.length;s++){const i=e[e.length-s-1],o=t.length-s-1,a=t[o];(i==null||i===1&&a>1)&&n.unshift(o)}return n}function nt(e,t){const n=[],s=Math.max(e.length,t.length);for(let i=0;i<s;i++){let o=e[e.length-i-1];o==null&&(o=1);let a=t[t.length-i-1];if(a==null&&(a=1),o===1)n.unshift(a);else if(a===1)n.unshift(o);else if(o!==a){const c=`Operands could not be broadcast together with shapes ${e} and ${t}.`;throw Error(c)}else n.unshift(o)}return n}function z_(e,t){let n=W(e,"a","equal"),s=W(t,"b","equal");[n,s]=Gt(n,s),nt(n.shape,s.shape);const i=a=>a.equal(n,s),o={a:n,b:s};return G.runKernelFunc(i,o,null,Wx)}const Xs=z({equal_:z_});function V_(e,t,n){const s=W(t,"a","where"),i=W(n,"b","where"),o=W(e,"condition","where","bool"),a=nt(s.shape,i.shape),c=lh(s,a),h=lh(i,a);o.rank===1&&A(o.shape[0]===s.shape[0],()=>"The first dimension of `a` must match the size of `condition`."),o.rank!==1&&B(o.shape,h.shape,"Error in where: ");const d=(f,b)=>{const w=f.select(o,c,h);return b([o]),w},m={condition:o,t:c,e:h};return G.runKernelFunc(d,m,null,Iy)}const Bn=z({where_:V_});function G_(e){const t=W(e,"x","zerosLike"),n={x:t};return G.runKernelFunc(s=>s.zerosLike(t),n,null,Ry)}const et=z({zerosLike_:G_});function Y_(e,t){let n=W(e,"a","div"),s=W(t,"b","div");[n,s]=Gt(n,s);const i=We(n,s),o=et(i),a=Xs(s,o);return Bn(a,o,i)}const xb=z({divNoNan_:Y_});function H_(e,t){const n=W(e,"t1","dot"),s=W(t,"t2","dot");A((n.rank===1||n.rank===2)&&(s.rank===1||s.rank===2),()=>`Error in dot: inputs must all be rank 1 or 2, but got ranks ${n.rank} and ${s.rank}.`);const i=n.rank===1?n.size:n.shape[1],o=s.rank===1?s.size:s.shape[0];if(A(i===o,()=>`Error in dot: inner dimensions of inputs must match, but got ${i} and ${o}.`),n.rank==
rank ${o.rank}.`),A(Le(t),()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`);let a=o,c=!1;o.rank===3&&(c=!0,a=K(o,[1,o.shape[0],o.shape[1],o.shape[2]]));const h=(b,w)=>{const L=b.localResponseNormalization4D(a,t,n,s,i);return w([a,L]),L},d={x:a},m={depthRadius:t,bias:n,alpha:s,beta:i},f=G.runKernelFunc(h,d,null,ay,m);return c?K(f,[f.shape[1],f.shape[2],f.shape[3]]):f}const Nb=z({localResponseNormalization_:fW});function gW(e){const t=W(e,"x","log"),n={x:t};return G.runKernelFunc((s,i)=>{const o=s.log(t);return i([t]),o},n,null,Nl)}const cs=z({log_:gW});function yW(e){const t=W(e,"x","log1p"),n={x:t};return G.runKernelFunc((s,i)=>{const o=s.log1p(t);return i([t]),o},n,null,Cl)}const hp=z({log1p_:yW});function bW(e){return A(Rr(e),()=>"The f passed in grad(f) must be a function"),(t,n)=>{const s=W(t,"x","tf.grad",null),i=n!=null?W(n,"dy","tf.grad"):null;return G.tidy(()=>{const{value:o,grads:a}=G.gradients(()=>e(s),[s],i);return i!=null&&B(o.shape,i.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),up(a),a[0]})}}function wW(e){return A(Rr(e),()=>"The f passed in grads(f) must be a function"),(t,n)=>{A(Array.isArray(t),()=>"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s");const s=th(t,"args","tf.grads",null),i=n!=null?W(n,"dy","tf.grads"):null;return G.tidy(()=>{const{value:o,grads:a}=G.gradients(()=>e(...s),s,i);return i!=null&&B(o.shape,i.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),up(a),a})}}function LW(e){return A(Rr(e),()=>"The f passed in valueAndGrad(f) must be a function"),(t,n)=>{A(t instanceof ee,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),A(n==null||n instanceof ee,()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");const{grads:s,value:i}=G.gradients(()=>e(t),[t],n);return up(s),{grad:s[0],value:i}}}function SW(e){return A(Rr(e),()=>"The f passed in valueAndGrads(f) must be a function"),(t,n)=>{A(Array.isArray(t)&&t.every(i=>i instanceof ee),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),A(n==null||n instanceof ee,()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");const s=G.gradients(()=>e(...t),t,n);return n!=null&&B(s.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),up(s.grads),s}}function Cb(e,t){A(Rr(e),()=>"The f passed in variableGrads(f) must be a function"),A(t==null||Array.isArray(t)&&t.every(d=>d instanceof Ql),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");const n=t!=null;if(!n){t=[];for(const d in G.registeredVariables)t.push(G.registeredVariables[d])}const s=n?t.filter(d=>!d.trainable):null,i=t.length;t=t.filter(d=>d.trainable),A(t.length>0,()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${i} variables is trainable.`);const o=!0,{value:a,grads:c}=G.gradients(e,t,null,o);A(c.some(d=>d!=null),()=>"Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize()."),A(a.rank===0,()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${a.rank} tensor`);const h={};return t.forEach((d,m)=>{c[m]!=null&&(h[d.name]=c[m])}),s!=null&&s.forEach(d=>h[d.name]=null),{value:a,grads:h}}function Ai(e){return G.customGrad(e)}function up(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 IW(e){const t=W(e,"x","neg"),n={x:t};return G.runKernelFunc(s=>s.neg(t),n,null,my)}const Ht=z({neg_:IW});function xW(e){const t=W(e,"x","softplus"),n={x:t};return G.runKernelFunc((s,i)=>{const o=s.softplus(t);return i([t]),o},n,null,Vl)}const za=z({softplus_:xW});function TW(e){const t=W(e,"x","logSigmoid"),n=Ai(s=>{const i=Ht(za(Ht(s))),o=a=>{const c=X(a,Ti(Ht(s)));return c};return{value:i,gradFunc:o}});return n(t)}const aA=z({logSigmoid_:TW});function AW(e,t=null,n=!1){const s=W(e,"x","max"),i=(c,h)=>{const d=qe(t,s.shape);let m=d;const f=Xn(m,s.rank);let b=s;f!=null&&(b=Ye(s,f),m=as(m.length,b.rank));const w=c.max(b,m);f!=null&&b.dispose();let L=w;if(n){const x=vn(L.shape,qe(t,s.shape));L=K(L,x),w.dispose()}return h([s,L]),L},o={x:s},a={reductionIndices:t,keepDims:n};return G.runKernelFunc(i,o,null,Rl,a)}const Qn=z({max_:AW});function vW(e,t){let n=W(e,"a","sub"),s=W(t,"b","sub");[n,s]=Gt(n,s);const i=(a,c)=>{const h=a.subtract(n,s);return c([n,s]),h},o={a:n,b:s};return G.runKernelFunc(i,o,null,Na)}const Re=z({sub_:vW});function NW(e,t=null,n=!1){let s=W(e,"x","sum");s.dtype==="bool"&&(s=Ae(s,"int32"));const i=(c,h)=>{h([s]);const d=qe(t,s.shape),m=Xn(d,s.rank);let f=d,b=s;m!=null&&(b=Ye(s,m),f=as(f.length,s.rank));let w=c.sum(b,f);if(n){const L=vn(w.shape,d);w=K(w,L)}return w},o={x:s},a={axis:t,keepDims:n};return G.runKernelFunc(i,o,null,xy,a)}const $e=z({sum_:NW});function CW(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=Qn(e,t,!0),m=Re(e,d),f=Re(Ae(m,"float32"),cs($e(Is(m),t,h)));return c([f]),f},i={logits:n},o={axis:t};return G.runKernelFunc(s,i,null,oy,o)}const dp=z({logSoftmax_:CW});function RW(e,t=null,n=!1){const s=W(e,"x","logSumExp"),i=qe(t,s.shape),o=Qn(s,i,!0),a=Re(s,o),c=Is(a),h=$e(c,i),d=cs(h),m=be(K(o,d.shape),d);if(n){const f=vn(m.shape,i);return K(m,f)}return m}const Rb=z({logSumExp_:RW});function OW(e,t){const n=W(e,"a","logicalAnd","bool"),s=W(t,"b","logicalAnd","bool");nt(n.shape,s.shape);const i={a:n,b:s};return G.runKernelFunc(o=>o.logicalAnd(n,s),i,null,zx)}const Us=z({logicalAnd_:OW});function EW(e){const t=W(e,"x","logicalNot","bool"),n={x:t};return G.runKernelFunc(s=>s.logicalNot(t),n,null,yd)}const mh=z({logicalNot_:EW});function DW(e,t){const n=W(e,"a","logicalOr","bool"),s=W(t,"b","logicalOr","bool");nt(n.shape,s.shape);const i={a:n,b:s};return G.runKernelFunc(o=>o.logicalOr(n,s),i,null,Vx)}const pp=z({logicalOr_:DW});function kW(e,t){const n=W(e,"a","logicalXor","bool"),s=W(t,"b","logicalXor","bool");return nt(n.shape,s.shape),Us(pp(e,t),mh(Us(e,t)))}const cA=z({logicalXor_:kW});function FW(e,t,n,s,i){const o=W(e,"x","maxPool"),a=1;let c=o,h=!1;o.rank===3&&(h=!0,c=K(o,[1,o.shape[0],o.shape[1],o.shape[2]])),A(c.rank===4,()=>`Error in maxPool: input must be rank 4 but got rank ${c.rank}.`),A(cn(n,a),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`),i!=null&&A(Le(s),()=>`Error in maxPool: pad must be an integer when using, dimRoundingMode ${i} but got pad ${s}.`);const d=(w,L)=>{const x=Un(c.shape,t,n,1,s,i);let v;return x.filterWidth===1&&x.filterHeight===1&&ae(x.inShape,x.outShape)?v=c.clone():v=w.maxPool(c,x),L([c,v]),v},m={x:c},f={filterSize:t,strides:n,pad:s,dimRoundingMode:i},b=G.runKernelFunc(d,m,null,Ol,f);return h?K(b,[b.shape[1],b.shape[2],b.shape[3]]):b}const fh=z({maxPool_:FW});function _W(e,t=[1,1,1],n,s,i,o="NDHWC",a){a==null?a=[1,1,1]:un("dilations is deprecated, this field will be gone in v3.0.0.");const c=W(e,"x","maxPool3d");let h=c,d=!1;c.rank===4&&(d=!0,h=K(c,[1,c.shape[0],c.shape[1],c.shape[2],c.shape[3]])),A(h.rank===5,()=>`Error in maxPool3d: x must be rank 5 but got rank ${h.rank}.`),A(o==="NDHWC",()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${o}`),A(cn(n,a),()=>`Error in maxPool3d: Either strides or dilations must be 1. G
2020-10-13 22:57:06 +02:00
1. The ${s} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
2020-10-29 05:16:50 +01:00
2. The custom ${s} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);return a}else{const o=e;if(o.className==null||o.config==null)throw new q(`${s}: Improper config format: ${JSON.stringify(o)}.
'className' and 'config' must set.`);const a=o.className;let c,h;if(a in n?[c,h]=n[a]:a in Bs?[c,h]=Bs.className:a in t&&([c,h]=t[a]),c==null)throw new q(`Unknown ${s}: ${a}. This may be due to one of the following reasons:
2020-10-13 22:57:06 +02:00
1. The ${s} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
2020-10-29 05:16:50 +01:00
2. The custom ${s} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);if(h!=null){const d={};for(const w of Object.keys(Bs))d[w]=Bs[w];for(const w of Object.keys(n))d[w]=n[w];const m=o.config;m.customObjects=d;const f=Object.assign({},Bs);for(const w of Object.keys(n))Bs[w]=n[w];pw(o.config);const b=h(c,o.config,n,i);return Bs=Object.assign({},f),b}else{const d=Object.assign({},Bs);for(const f of Object.keys(n))Bs[f]=n[f];const m=new c(o.config);return Bs=Object.assign({},d),m}}}function dz(e,t){return e<t?-1:e>t?1:0}function Bp(e,t){return-1*dz(e,t)}function Oee(e){switch(e){case"float32":return"float32";default:throw new q(`Invalid dtype: ${e}`)}}function Eee(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 Vr(e){if(e==null)return e;const t=[];for(const n of e)t.indexOf(n)===-1&&t.push(n);return t}function pz(e){if(e==null)throw new q(`Invalid value in obj: ${JSON.stringify(e)}`);for(const t in e)if(e.hasOwnProperty(t))return!1;return!0}function Qa(e,t,n){if(n==null)return;if(e.indexOf(n)<0)throw new q(`${n} is not a valid ${t}. Valid values are ${e} or null/undefined.`)}function mw(e,t,n=0,s=Infinity){return As(n>=0),As(s>=n),Array.isArray(e)&&e.length>=n&&e.length<=s&&e.every(i=>typeof i===t)}function wn(e,t){Array.isArray(e)?(A(e.length>0,()=>`${t} is unexpectedly an empty array.`),e.forEach((n,s)=>wn(n,`element ${s+1} of ${t}`))):A(Number.isInteger(e)&&e>0,()=>`Expected ${t} to be a positive integer, but got ${av(e)}.`)}function av(e){return e===null?"null":Array.isArray(e)?"["+e.map(t=>av(t)).join(",")+"]":typeof e=="string"?`"${e}"`:`${e}`}function mz(e,t){let n=jn(),s;const i=(...o)=>{const a=jn();return a-n<t||(n=a,s=e(...o)),s};return i}function cv(e){return e==="relu"?"relu":e==="linear"?"linear":e==="elu"?"elu":null}function Dee(...e){As(e.length>0,"arrayOfValues is empty");for(const t of e)As(Array.isArray(t),"one of the values is not an array"),As(t.length>0,"one of the values is empty");return e.reduce((t,n)=>t.length===0?n.map(s=>[s]):n.map(s=>t.map(i=>[...i,s])).reduce((s,i)=>s.concat(i),[]),[])}function fw(e,t){return Q(()=>Nn($e(X(e,e),t,!0)))}class Fh extends Ao{getConfig(){return{}}}class gw extends Fh{constructor(e){super();this.defaultMaxValue=2,this.defaultAxis=0,this.maxValue=e.maxValue!=null?e.maxValue:this.defaultMaxValue,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return Q(()=>{const t=fw(e,this.axis),n=Jn(t,0,this.maxValue);return X(e,We(n,be(mn(),t)))})}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}}gw.className="MaxNorm",fe(gw);class yw extends Fh{constructor(e){super();this.defaultAxis=0,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return Q(()=>We(e,be(mn(),fw(e,this.axis))))}getConfig(){return{axis:this.axis}}}yw.className="UnitNorm",fe(yw);class bw extends Fh{apply(e){return Ni(e)}}bw.className="NonNeg",fe(bw);class ww extends Fh{constructor(e){super();this.defaultMinValue=0,this.defaultMaxValue=1,this.defaultRate=1,this.defaultAxis=0,this.minValue=e.minValue!=null?e.minValue:this.defaultMinValue,this.maxValue=e.maxValue!=null?e.maxValue:this.defaultMaxValue,this.rate=e.rate!=null?e.rate:this.defaultRate,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return Q(()=>{const t=fw(e,this.axis),n=be(X(this.rate,Jn(t,this.minValue,this.maxValue)),X(1-this.rate,t));return X(e,We(n,be(mn(),t)))})}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}}ww.className="MinMaxNorm",fe(ww);const lv={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function fn(e){return dw(e)}function hv(e,t={}){return kh(e,Ws.getMap().classNameMap,t,"constraint")}function gn(e){if(e==null)return null;if(typeof e=="string"){const t=e in lv?lv[e]:e,n={className:t,config:{}};return hv(n)}else return e instanceof Fh?e:hv(e)}function fz(e){return new gw(e)}function gz(e){return new yw(e)}function yz(){return new bw}function bz(e){return new ww(e)}var wz=Object.freeze({__prot
because the value dtype is ${t.dtype}, but TensorArray dtype is ${this.dtype}.`);if(this.size()===0&&(this.elementShape==null||this.elementShape.length===0)&&(this.elementShape=t.shape),zs(this.elementShape,t.shape,`TensorArray ${this.name}: Could not write to TensorArray index ${e}.`),n.read)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been read.`);if(n.written)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been written.`);n.tensor=t,bn(t),n.written=!0,this.tensors[e]=n}writeMany(e,t){if(e.length!==t.length)throw new Error(`TensorArray ${this.name}: could not write multiple tensors,because the index size: ${e.length} is not the same as tensors size: ${t.length}.`);e.forEach((n,s)=>this.write(n,t[s]))}gather(e,t){if(!!t&&t!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but gather requested dtype ${t}`);if(e)e=e.slice(0,this.size());else{e=[];for(let s=0;s<this.size();s++)e.push(s)}if(e.length===0)return sn([],[0].concat(this.elementShape));const n=this.readMany(e);return zs(this.elementShape,n[0].shape,"TensorArray shape mismatch: "),es(n,0)}concat(e){if(!!e&&e!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but concat requested dtype ${e}`);if(this.size()===0)return sn([],[0].concat(this.elementShape));const t=[];for(let s=0;s<this.size();s++)t.push(s);const n=this.readMany(t);return zs(this.elementShape,n[0].shape,`TensorArray shape mismatch: tensor array shape (${this.elementShape}) vs first tensor shape (${n[0].shape})`),Yt(n,0)}scatter(e,t){if(t.dtype!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${t.dtype}`);if(e.length!==t.shape[0])throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${e.length} vs. ${t.shape[0]}`);const n=Math.max(...e);if(!this.dynamicSize&&n>=this.maxSize)throw new Error(`Max index must be < array size (${n} vs. ${this.maxSize})`);this.writeMany(e,Qs(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-12 20:28:19 +02:00
tensor.shape[0], but sum of lengths is
2020-10-29 05:16:50 +01:00
${n}, and tensor's shape is: ${t.shape}`);if(!this.dynamicSize&&e.length!==this.maxSize)throw new Error(`TensorArray's size is not equal to the size of lengths (${this.maxSize} vs. ${e.length}), and the TensorArray is not marked as dynamically resizeable`);const i=n===0?0:t.size/n,o=[];Q(()=>{t=K(t,[1,n,i]);for(let c=0;c<e.length;++c){const h=c===0?0:s[c-1],d=[0,h,0],m=[1,e[c],i];o[c]=K(tt(t,d,m),this.elementShape)}return o});const a=[];for(let c=0;c<e.length;c++)a[c]=c;this.writeMany(a,o)}}class nu{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}`);zs(t,i.shape,"TensorList shape mismatch: "),bn(i)}),this.idTensor=Ce(0),this.maxNumElements=s,bn(this.idTensor)}get id(){return this.idTensor.id}copy(){return new nu([...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 zs(e,this.elementShape,"TensorList shape mismatch: "),Q(()=>{const s=this.tensors.map(i=>K(i,e));return es(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 zs(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(zs(e.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");bn(e),this.tensors.push(e)}resize(e){if(e<0)throw new Error(`TensorListResize expects size to be non-negative. Got: ${e}`);if(this.maxNumElements!==-1&&e>this.maxNumElements)throw new Error(`TensorListResize input size ${e} is greater maxNumElement ${this.maxNumElements}.`);this.tensors.length=e}getItem(e,t,n){if(n!==this.elementDtype)throw new Error(`Invalid data types; op elements ${n}, but list elements ${this.elementDtype}`);if(e<0||e>this.tensors.length)throw new Error(`Trying to access element ${e} in a list with ${this.tensors.length} elements.`);if(this.tensors[e]==null)throw new Error(`element at index ${e} is null.`);return zs(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.`);zs(this.elementShape,t.shape,"TensorList shape mismatch: "),bn(t),this.tensors[e]=t}gather(e,t,n){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);return zs(this.elementShape,n,"TensorList shape mismatch: "),e=e.slice(0,this.size()),e.length===0?sn([],[0].concat(this.elementShape)):Q(()=>{const s=e.map(i=>K(this.tensors[i],n));return es(s,0)})}concat(e,t){if(!!e&&e!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${e}`);return zs(this.elementShape,t,"TensorList shape mismatch: "),this.size()===0?sn([],[0].concat(this.elementShape)):Q(()=>{const n=this.tensors.map(s=>K(s,t));return Yt(n,0)})}}function UY(e,t,n){const s=e.dtype;if(e.shape.length<1)throw new Error(`Tensor must be at least a vector, but saw shape: ${e.shape}`);if(e.dtype!==n)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${n}`);const i=e.shape
2020-10-12 20:28:19 +02:00
tensor.shape[0], but sum of lengths is
2020-10-29 05:16:50 +01:00
${s}, and tensor's shape is: ${e.shape}`);const o=s===0?0:e.size/s,a=Q(()=>{const h=[];e=K(e,[1,s,o]);for(let d=0;d<t.length;++d){const m=d===0?0:i[d-1],f=[0,m,0],b=[1,t[d],o];h[d]=K(tt(e,f,b),n)}return e.dispose(),h}),c=new nu([],n,e.dtype,t.length);for(let h=0;h<a.length;h++)c.setItem(h,a[h]);return c}const zY=async(e,t,n)=>{switch(e.op){case"If":case"StatelessIf":{const s=R("thenBranch",e,t,n),i=R("elseBranch",e,t,n),o=R("cond",e,t,n),a=R("args",e,t,n),c=await o.data();return c[0]?n.functionMap[s].executeFunctionAsync(a,n.tensorArrayMap,n.tensorListMap):n.functionMap[i].executeFunctionAsync(a,n.tensorArrayMap,n.tensorListMap)}case"While":case"StatelessWhile":{const s=R("body",e,t,n),i=R("cond",e,t,n),o=R("args",e,t,n),a=await n.functionMap[i].executeFunctionAsync(o,n.tensorArrayMap,n.tensorListMap),c=o.map(m=>m.id);let h=await a[0].data();a.forEach(m=>{!m.kept&&c.indexOf(m.id)===-1&&m.dispose()});let d=o;for(;h[0];){const m=d;d=await n.functionMap[s].executeFunctionAsync(d,n.tensorArrayMap,n.tensorListMap);const f=d.map(w=>w.id);m.forEach(w=>{!w.kept&&c.indexOf(w.id)===-1&&f.indexOf(w.id)===-1&&w.dispose()});const b=await n.functionMap[i].executeFunctionAsync(d,n.tensorArrayMap,n.tensorListMap);h=await b[0].data(),b.forEach(w=>{!w.kept&&c.indexOf(w.id)===-1&&f.indexOf(w.id)===-1&&w.dispose()})}return d}case"LoopCond":{const s=R("pred",e,t,n);return[ar(s)]}case"Switch":{const s=R("pred",e,t,n);let i=R("data",e,t,n);return i.kept||(i=ar(i)),(await s.data())[0]?[void 0,i]:[i,void 0]}case"Merge":{const s=e.inputNames.find(i=>ss(i,t,n)!==void 0);if(s){const i=ss(s,t,n);return[ar(i)]}return}case"Enter":{const s=R("frameName",e,t,n),i=R("tensor",e,t,n);return n.enterFrame(s),[ar(i)]}case"Exit":{const s=R("tensor",e,t,n);return n.exitFrame(),[ar(s)]}case"NextIteration":{const s=R("tensor",e,t,n);return n.nextIteration(),[ar(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 $Y(d,i,s,o,h,a,c);return n.addTensorArray(m),[m.idTensor,Ce(1)]}case"TensorArrayWriteV3":{const s=R("tensorArrayId",e,t,n),i=R("index",e,t,n),o=R("tensor",e,t,n),a=n.getTensorArray(s.id);return a.write(i,o),[a.idTensor]}case"TensorArrayReadV3":{const s=R("tensorArrayId",e,t,n),i=R("index",e,t,n),o=n.getTensorArray(s.id);return[o.read(i)]}case"TensorArrayGatherV3":{const s=R("tensorArrayId",e,t,n),i=R("indices",e,t,n),o=R("dtype",e,t,n),a=n.getTensorArray(s.id);return[a.gather(i,o)]}case"TensorArrayScatterV3":{const s=R("tensorArrayId",e,t,n),i=R("indices",e,t,n),o=R("tensor",e,t,n),a=n.getTensorArray(s.id);return a.scatter(i,o),[a.idTensor]}case"TensorArrayConcatV3":{const s=R("tensorArrayId",e,t,n),i=n.getTensorArray(s.id),o=R("dtype",e,t,n);return[i.concat(o)]}case"TensorArraySplitV3":{const s=R("tensorArrayId",e,t,n),i=R("tensor",e,t,n),o=R("lengths",e,t,n),a=n.getTensorArray(s.id);return a.split(o,i),[a.idTensor]}case"TensorArraySizeV3":{const s=R("tensorArrayId",e,t,n),i=n.getTensorArray(s.id);return[Ce(i.size(),"int32")]}case"TensorArrayCloseV3":{const s=R("tensorArrayId",e,t,n),i=n.getTensorArray(s.id);return i.clearAndClose(),[i.idTensor]}case"TensorListSetItem":{const s=R("tensorListId",e,t,n),i=R("index",e,t,n),o=R("tensor",e,t,n),a=n.getTensorList(s.id);return a.setItem(i,o),[a.idTensor]}case"TensorListGetItem":{const s=R("tensorListId",e,t,n),i=R("index",e,t,n),o=R("elementShape",e,t,n),a=R("elementDType",e,t,n),c=n.getTensorList(s.id);return[c.getItem(i,o,a)]}case"TensorListScatterV2":case"TensorListScatter":{const s=R("indices",e,t,n),i=R("tensor",e,t,n),o=R("elementShape",e,t,n),a=R("numElements",e,t,n),c=MY(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=BY(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),ps(async()=>(await n.iterator()).columnMajorBatch(e,t,_H),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,ps(async()=>(await t.iterator()).concatenate(await e.iterator()),n)}filter(e){const t=this;let n;return this.size===Infinity?n=Infinity:n=null,ps(async()=>(await t.iterator()).filter(s=>Q(()=>e(s))),n)}async forEachAsync(e){return(await this.iterator()).forEachAsync(e)}map(e){const t=this;return ps(async()=>(await t.iterator()).map(n=>Q(()=>e(n))),this.size)}mapAsync(e){const t=this;return ps(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 ps(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,ps(async()=>{const s=su(async()=>({value:await t.iterator(),done:!1}));return t0(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,ps(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=Ha(t||jn().toString());return ps(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,ps(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()}}lc.MAX_BUFFER_SIZE=1e4;function ps(e,t=null){return new class extends lc{constructor(){super(...arguments);this.size=t}async iterator(){return e()}}}function kH(e){return ps(async()=>e0(e),e.length)}function FH(e){if(!cc(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 ps(async()=>{const n=await ZN(e,s=>{if(s instanceof lc)return{value:s.iterator(),recurse:!1};if(cc(s))return{value:null,recurse:!0};throw new Error("Leaves of the structure passed to zip() must be Datasets, not primitives.")});return LH(n,Jr.SHORTEST)},t)}function _H(e){if(e===null)return null;const t=e[0];if(gH(t)){const n=WH(e);return{value:n,recurse:!1}}return{value:null,recurse:!0}}function WH(e){if(e.length===0)throw new Error("Can't make a batch of zero elements.");return e[0]instanceof ee?es(e):sn(e)}class r0 extends lc{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 xm='"',iu=Symbol("out"),o0=Symbol("field"),Tm=Symbol("quote"),aS=Symbol("quoteafterquote"),a0=Symbol("quoteinquote");class c0 extends lc{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 r0(e),t||(t={}),this.hasHeader=!(t.hasHeader===!1),this.fullColumnNames=t.columnNames,this.columnConfigs=t.columnConfigs,this.configuredColumnsOnly=t.configuredColumnsOnly,t.delimWhitespace?(A(t.delimiter==null,()=>"Delimiter should not be provided when delimWhitespace is true."),this.delimWhitespace=!0,this.delimiter=" "):this.delimiter=t.delimiter?t.delimiter:","}async columnNames(){return this.columnNamesValidated||await this.setColumnNames(),this.configuredColumnsOnly?Object.keys(this.columnConfigs):this.fullColumnNames}async setColumnNames(){const e=await this.maybeReadHeaderLine();if(!this.fullColumnNames&&!e)throw new Error("Column names must be provided if there is no header line.");this.fullColumnNames&&e&&A(e.length===this.fullColumnNames.length,()=>"The length of provided columnNames ("+this.fullColumnNames.length.toString()+") does not match the length of the header line read from file ("+e.length.toString()+")."),this.fullColumnNames||(this.fullColumnNames=e);const t=this.fullColumnNames.reduce((s,i)=>(s[i]=s[i]+1||1,s),{}),n=Object.keys(t).filter(s=>t[s]>1);if(A(n.length===0,()=>"Duplicate column names found: "+n.toString()),this.columnConfigs)for(const s of Object.keys(this.columnConfigs)){const i=this.fullColumnNames.indexOf(s);if(i===-1)throw new Error('The key "'+s+'" provided in columnConfigs does not match any of the column names ('+this.fullColumnNames.toString()+").")}this.columnNamesValidated=!0}async maybeReadHeaderLine(){if(this.hasHeader){const e=await this.base.iterator(),t=await e.next();if(t.done)throw new Error("No data was found for CSV parsing.");const n=t.value,s=this.parseRow(n,!1);return s}else return null}async iterator(){this.columnNamesValidated||await this.setColumnNames();let e=await this.base.iterator();return this.hasHeader&&(e=e.skip(1)),e.map(t=>this.makeDataElement(t))}makeDataElement(e){const t=this.parseRow(e),n={},s={};for(let i=0;i<this.fullColumnNames.length;i++){const o=this.fullColumnNames[i],a=this.columnConfigs?this.columnConfigs[o]:null;if(this.configuredColumnsOnly&&!a)continue;{const c=t[i];let h=null;if(c==="")if(a&&a.default!==void 0)h=a.default;else{if(a&&(a.required||a.isLabel))throw new Error(`Required column ${o} is empty in this line: ${e}`);h=void 0}else{const d=Number(c);if(isNaN(d))a&&a.dtype==="bool"?h=this.getBoolean(c):h=c;else if(!a||!a.dtype)h=d;else switch(a.dtype){case"float32":h=d;break;case"int32":h=Math.floor(d);break;case"bool":h=this.getBoolean(c);break;default:h=d}}a&&a.isLabel?s[o]=h:n[o]=h}}return Object.keys(s).length===0?n:{xs:n,ys:s}}getBoolean(e){return e==="1"||e.toLowerCase()==="true"?1:0}parseRow(e,t=!0){const n=[];let s=0;const i=e.length;let o=iu;for(let a=0;a<i;a++)switch(o){case iu:switch(e.charAt(a)){case xm:s=a+1,o=Tm;break;case this.delimiter:if(s=a+1,this.delimiter===" "&&this.delimWhitespace)break;n.push(""),o=iu;break;default:o=o0,s=a;break}break;case o0:switch(e.charAt(a)){case this.delimiter:n.push(e.substring(s,a)),o=iu,s=a+1;break;default:}break;case Tm:switch(e.charAt(a)){case xm:o=aS;break;default:}break;case aS:switch(e.charAt(a)){case this.delimiter:n.push(e.substring(s,a-1)),o=iu,s=a+1;break;case xm:o=Tm;break;default:o=a0;break}break;case a0:switch(e.charAt(a)){case xm:o=Tm;break;default:}break;default:}if(o===aS?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 l0 extends Sn{constructor(e){super();this.microphoneConfig=e,this.isClosed=!1,this.fftSize=e.fftSize||1024;const t=Math.log2(this.fftSize);if(this.fftSize<0||t<4|
2020-10-12 20:28:19 +02:00
============================
Hi there 👋. Looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, which binds to TensorFlow C++, by running npm i @tensorflow/tfjs-node, or npm i @tensorflow/tfjs-node-gpu if you have CUDA. Then call require('@tensorflow/tfjs-node'); (-gpu suffix for CUDA) at the start of your program. Visit https://github.com/tensorflow/tfjs-node for more details.
2020-10-29 05:16:50 +01:00
============================`));const s={};return this.data.set(s,{values:e,dtype:n,refCount:1}),s}makeTensorInfo(e,t,n){let s;if(t==="string"&&n!=null&&n.length>0&&Yi(n[0])){const i=n.map(o=>Wd(o));s=this.write(i,e,t)}else s=this.write(n,e,t);return{dataId:s,shape:e,dtype:t}}incRef(e){const t=this.data.get(e);t.refCount++}decRef(e){if(this.data.has(e)){const t=this.data.get(e);t.refCount--}}move(e,t,n,s){this.data.set(e,{values:t,dtype:s,refCount:1})}numDataIds(){return this.data.numDataIds()}async read(e){return this.readSync(e)}readSync(e){const{dtype:t,complexTensorInfos:n}=this.data.get(e);if(t==="complex64"){const s=this.readSync(n.real.dataId),i=this.readSync(n.imag.dataId);return tr(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=>Kl(s))}catch(s){throw new Error("Failed to decode encoded string bytes into utf-8")}return wt(e.shape,e.dtype,n)}makeOutput(e,t,n){const s=this.write(e,t,n);return Ki().makeTensorFromDataId(s,t,n,this)}disposeData(e){if(this.data.has(e)){const{complexTensorInfos:t}=this.data.get(e);t!=null&&(this.disposeData(t.real.dataId),this.disposeData(t.imag.dataId)),this.data.delete(e)}}disposeIntermediateTensorInfo(e){const t=e.dataId;if(this.data.has(t)){const n=this.data.get(t);n.refCount--,n.refCount<1&&this.disposeData(t)}}async time(e){const t=jn();e();const n=jn()-t;return{kernelMs:n}}memory(){return{unreliable:!0,reasons:["The reported memory is an upper bound. Due to automatic garbage collection, the true allocated memory may be less."]}}stridedSlice(e,t,n,s){Te(e,"stridedSlice");const i=jd(t,n,s);if(i.some(c=>c===0))return sn([],i);const o=wt(i,e.dtype),a=this.bufferSync(e);for(let c=0;c<o.size;c++){const h=o.indexToLoc(c),d=new Array(h.length);for(let m=0;m<d.length;m++)d[m]=h[m]*s[m]+t[m];o.set(a.get(...d),...h)}return o.toTensor()}diag(e){const t=this.readSync(e.dataId),n=wt([e.size,e.size],e.dtype),s=n.values;for(let i=0;i<t.length;i++)s[i*e.size+i]=t[i];return n.toTensor()}unstack(e,t){const n=e.shape[t],s=new Array(e.rank-1);let i=0;for(let h=0;h<e.rank;h++)h!==t&&(s[i++]=e.shape[h]);const o=new Array(e.rank).fill(0),a=e.shape.slice();a[t]=1;const c=new Array(n);for(let h=0;h<c.length;h++)o[t]=h,c[h]=tt(e,o,a).reshape(s);return c}reverse(e,t){Te(e,"reverse");const n=wt(e.shape,e.dtype),s=this.bufferSync(e);for(let i=0;i<n.size;i++){const o=n.indexToLoc(i),a=o.slice();t.forEach(c=>a[c]=e.shape[c]-1-a[c]),n.set(s.get(...a),...o)}return n.toTensor()}neg(e){return Te(e,"neg"),X(Ce(-1),e)}addN(e){Te(e,"addN");const t=e.map(i=>this.readSync(i.dataId)),n=wt(e[0].shape,e[0].dtype),s=n.values;for(let i=0;i<e.length;i++){const o=t[i];for(let a=0;a<s.length;a++)s[a]+=o[a]}return n.toTensor()}softmax(e,t){const n=qe([t],e.shape),s=Qn(e,n),i=vn(s.shape,n),o=Re(e,s.reshape(i)),a=Is(o),c=this.sum(a,n).reshape(i);return We(a,c)}pow(e,t){return Te([e,t],"pow"),this.broadcastedBinaryOp(e,t,e.dtype,(n,s)=>Math.pow(n,s))}floorDiv(e,t){Te([e,t],"floorDiv");const n=(i,o)=>Math.floor(i/o),s="int32";return this.broadcastedBinaryOp(e,t,s,n)}sum(e,t){Te(e,"sum"),Kn("sum",t,e.rank);const[n,s]=An(e.shape,t),i=$n(e.dtype,"int32"),o=dt(n,i),a=P(s),c=this.readSync(o.dataId),h=this.readSync(e.dataId);for(let d=0;d<c.length;++d){const m=d*a;let f=0;for(let b=0;b<a;++b)f+=h[m+b];c[d]=f}return o}prod(e,t){Te(e,"sum");const[n,s]=An(e.shape,t),i=$n(e.dtype,"int32"),o=dt(n,i),a=P(s),c=this.readSync(o.dataId),h=this.readSync(e.dataId);for(let d=0;d<c.length;++d){const m=d*a;let f=1;for(let b=0;b<a;++b)f*=h[m+b];c[d]=f}return o}unsortedSegmentSum(e,t,n){Te(e,"unsortedSegmentSum");const s=[],i=e.rank-t.rank;for(let o=0;o<i;++o)t=t.expandDims(o+1);for(let o=0;o<n;++o){const a=Ce(o,"int32"),c=Xs(a,t).asType("float32"),h=c.mul(e).sum(0);s.push(h)}return es(s)}argMin(e,t){Te(e,"argMin");const n=[t];Kn("argMin",n,e.rank);const[s,i]=An(e.shape,n),o=dt(s,"int32"),a=P(i),c=this.readSync(o.dataId),h=this.readSync(e.dataId);for(let d=0;d<c.length;++d){const m=d*a;let f=h[m],b=0;for(let w=0;w<a;++w){const L=h[m+w];L<f&&(f=L,b=w)}c[d]=b}return o}argMax(e,t
`),o=i.length.toString().length+2,a=i.map((f,b)=>pt((b+1).toString(),o)+f);let c=0;for(let f=0;f<a.length;f++)c=Math.max(a[f].length,c);const h=a.slice(0,s-1),d=a.slice(s-1,s),m=a.slice(s);console.log(h.join(`
2020-10-12 20:28:19 +02:00
`)),console.log(t.split(`
2020-10-29 05:16:50 +01:00
`)[0]),console.log(`%c ${pt(d[0],c)}`,"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(m.join(`
`))}function xK(e){return cr(e,()=>e.createProgram(),"Unable to create WebGLProgram.")}function TK(e,t){if(Ee(e,()=>e.linkProgram(t)),e.getProgramParameter(t,e.LINK_STATUS)===!1)throw console.log(e.getProgramInfoLog(t)),new Error("Failed to link vertex and fragment shaders.")}function yS(e,t){if(Ee(e,()=>e.validateProgram(t)),e.getProgramParameter(t,e.VALIDATE_STATUS)===!1)throw console.log(e.getProgramInfoLog(t)),new Error("Shader program validation failed.")}function AK(e,t){const n=cr(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return Ee(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n)),Ee(e,()=>e.bufferData(e.ARRAY_BUFFER,t,e.STATIC_DRAW)),n}function vK(e,t){const n=cr(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return Ee(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,n)),Ee(e,()=>e.bufferData(e.ELEMENT_ARRAY_BUFFER,t,e.STATIC_DRAW)),n}function Zte(){return oe().getNumber("WEBGL_VERSION")===2?1:4}function NK(e){return cr(e,()=>e.createTexture(),"Unable to create WebGLTexture.")}function CK(e,t){const n=oe().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(e<=0||t<=0){const s=`[${e}x${t}]`;throw new Error("Requested texture size "+s+" is invalid.")}if(e>n||t>n){const s=`[${e}x${t}]`,i=`[${n}x${n}]`;throw new Error("Requested texture size "+s+" greater than WebGL maximum on this browser / GPU "+i+".")}}function RK(e){return cr(e,()=>e.createFramebuffer(),"Unable to create WebGLFramebuffer.")}function q0(e,t,n,s,i,o,a){const c=e.getAttribLocation(t,n);return c===-1?!1:(Ee(e,()=>e.bindBuffer(e.ARRAY_BUFFER,s)),Ee(e,()=>e.vertexAttribPointer(c,i,e.FLOAT,!1,o,a)),Ee(e,()=>e.enableVertexAttribArray(c)),!0)}function OK(e,t,n){K0(e,n),Ee(e,()=>e.activeTexture(e.TEXTURE0+n)),Ee(e,()=>e.bindTexture(e.TEXTURE_2D,t))}function Qte(e,t){K0(e,t),Ee(e,()=>e.activeTexture(e.TEXTURE0+t)),Ee(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function EK(e,t,n){return cr(e,()=>e.getUniformLocation(t,n),'uniform "'+n+'" not present in program.')}function DK(e,t,n){return e.getUniformLocation(t,n)}function kK(e,t,n,s){Ee(e,()=>OK(e,t,s)),Ee(e,()=>e.uniform1i(n,s))}function ene(e){Ee(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,null)),Ee(e,()=>e.viewport(0,0,e.canvas.width,e.canvas.height)),Ee(e,()=>e.scissor(0,0,e.canvas.width,e.canvas.height))}function bS(e,t,n){Ee(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,n)),Ee(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0))}function j0(e,t){Ee(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,t)),Ee(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0))}function Nm(e){const t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+FK(e,t))}function FK(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 cr(e,t,n){const s=Ee(e,()=>t());if(s==null)throw new Error(n);return s}function K0(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 mc(e,t=2){return P(e.slice(0,e.length-t))}function fc(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 wS(e){let t=[1,1,1];const n=e.length===0||e.length===1&&e[0]===1;return n||(t=[mc(e),...fc(e)]),t}function _K(e,t=!1){let n=oe().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(t&&(n=n*2,e=e.map((i,o)=>o>=e.length-2?T(e[o]):e[o]),e.length===1&&(e=[2,e[0]])),e.length!==2){const i=ln(e);e=i.newShape}let s=P(e);if(e.length<=1&&s<=n)return[1,s];if(e.length===2&&e[0]<=n&&e[1]<=n)return e;if(e.length===3&&e[0]*e[1]<=n&&e[2]<=n)return[e[0]*e[1],e[2]];if(e.length===3&&e[0]<=n&&e[1]*e[2]<=n)return[e[0],e[1]*e[2]];if(e.length===4&&e[0]*e[1]*e[2]<=n&&e
2020-10-12 20:28:19 +02:00
void main() {
2020-10-13 22:57:06 +02:00
${n.join(`
2020-10-12 20:28:19 +02:00
`)}
2020-10-13 22:57:06 +02:00
float result = ${s};
2020-10-12 20:28:19 +02:00
setOutput(result);
}
2020-10-29 05:16:50 +01:00
`}}class s5{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-12 20:28:19 +02:00
void main() {
2020-10-13 22:57:06 +02:00
${n.join(`
2020-10-12 20:28:19 +02:00
`)}
2020-08-29 20:56:29 +02:00
2020-10-13 22:57:06 +02:00
vec4 result = ${s};
2020-10-12 20:28:19 +02:00
setOutput(result);
}
2020-10-29 05:16:50 +01:00
`}}class i5{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-12 20:28:19 +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-12 20:28:19 +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-12 20:28:19 +02:00
float candidate = getA(batch, inIdx);
2020-10-13 22:57:06 +02:00
if (candidate ${a} bestValue) {
2020-10-12 20:28:19 +02:00
bestValue = candidate;
bestIndex = inIdx;
}
}
setOutput(float(bestIndex));
}
2020-10-29 05:16:50 +01:00
`}}function J0(e,t){return["x","y","z","w","u","v"].slice(0,t).map(n=>`${e}.${n}`)}function Mn(e,t){return t===1?[e]:J0(e,t)}function r5(e,t){if(e===1)return"rc";let n="";for(let s=0;s<e;s++)n+=t[s],s<e-1&&(n+=",");return n}function Pn(){let e,t,n,s,i,o,a,c,h,d;return oe().getNumber("WEBGL_VERSION")===2?(e="#version 300 es",t="in",n="out",s="in",i="texture",o="outputColor",a="out vec4 outputColor;",c=`
2020-10-12 20:28:19 +02:00
bool isnan_custom(float val) {
return (val > 0.0 || val < 0.0) ? false : val != 0.0;
}
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
bvec4 isnan_custom(vec4 val) {
return bvec4(isnan_custom(val.x),
isnan_custom(val.y), isnan_custom(val.z), isnan_custom(val.w));
}
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
#define isnan(value) isnan_custom(value)
2020-10-13 22:57:06 +02:00
`,h="",d=`
2020-10-12 20:28:19 +02:00
#define round(value) newRound(value)
int newRound(float value) {
return int(floor(value + 0.5));
}
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
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-12 20:28:19 +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-12 20:28:19 +02:00
uniform float INFINITY;
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
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-12 20:28:19 +02:00
int round(float value) {
return int(floor(value + 0.5));
}
ivec4 round(vec4 value) {
return ivec4(floor(value + vec4(0.5)));
}
2020-10-29 05:16:50 +01:00
`),{version:e,attribute:t,varyingVs:n,varyingFs:s,texture2D:i,output:o,defineOutput:a,defineSpecialNaN:c,defineSpecialInf:h,defineRound:d}}function Yo(e,t,n="index"){const s=je(t);return s.map((i,o)=>{const a=`int ${e[o]} = ${n} / ${i}`,c=o===s.length-1?`int ${e[o+1]} = ${n} - ${e[o]} * ${i}`:`index -= ${e[o]} * ${i}`;return`${a}; ${c};`}).join("")}function Dm(e){return e.length===1?`${e[0]}`:`vec${e.length}(${e.join(",")})`}function sne(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(`${Dm(a)}, ${Dm(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(`${Dm(o)}, ${Dm(a)}`)}return n.map((o,a)=>`dot(${o})`).join("+")}function IS(e){const t=je(e).map(n=>n.toString());return`
2020-10-12 20:28:19 +02:00
int getFlatIndex(ivec3 coords) {
return coords.x * ${t[0]} + coords.y * ${t[1]} + coords.z;
}
2020-10-29 05:16:50 +01:00
`}const Z0=`
2020-10-12 20:28:19 +02:00
const float FLOAT_MAX = 1.70141184e38;
const float FLOAT_MIN = 1.17549435e-38;
lowp vec4 encode_float(highp float v) {
if (isnan(v)) {
return vec4(255, 255, 255, 255);
}
highp float av = abs(v);
if(av < FLOAT_MIN) {
return vec4(0.0, 0.0, 0.0, 0.0);
} else if(v > FLOAT_MAX) {
return vec4(0.0, 0.0, 128.0, 127.0) / 255.0;
} else if(v < -FLOAT_MAX) {
return vec4(0.0, 0.0, 128.0, 255.0) / 255.0;
}
highp vec4 c = vec4(0,0,0,0);
highp float e = floor(log2(av));
highp float m = exp2(fract(log2(av))) - 1.0;
c[2] = floor(128.0 * m);
m -= c[2] / 128.0;
c[1] = floor(32768.0 * m);
m -= c[1] / 32768.0;
c[0] = floor(8388608.0 * m);
highp float ebias = e + 127.0;
c[3] = floor(ebias / 2.0);
ebias -= c[3] * 2.0;
c[2] += floor(ebias) * 128.0;
c[3] += 128.0 * step(0.0, -v);
return c / 255.0;
}
2020-10-29 05:16:50 +01:00
`;const{getBroadcastDims:Q0}=cw;function o5(e,t,n,s){const i=[];e.forEach(L=>{const x=P(L.shapeInfo.logicalShape);L.shapeInfo.isUniform?i.push(`uniform float ${L.name}${x>1?`[${x}]`:""};`):(i.push(`uniform sampler2D ${L.name};`),i.push(`uniform int offset${L.name};`))});const o=i.join(`
`),a=e.map(L=>a5(L,t,s)).join(`
`),c=t.texShape,h=Pn(),d=h5(h);let m,f,b=p5(h);t.isPacked?(m=c5(t.logicalShape,c),f=d5(h)):(m=l5(t.logicalShape,c),f=u5(h)),s&&(b+=y5);const w=[b,d,f,o,m,a,n].join(`
`);return w}function gc(e){const t=e.shapeInfo.logicalShape;switch(t.length){case 0:return R5(e);case 1:return E5(e);case 2:return k5(e);case 3:return _5(e);case 4:return $5(e);case 5:return U5(e);case 6:return B5(e);default:throw new Error(`${t.length}-D input sampling is not yet supported`)}}function eC(e){const t=e.shapeInfo.logicalShape;switch(t.length){case 0:return C5(e);case 1:return O5(e);case 2:return D5(e);case 3:return F5(e);default:return W5(e)}}function a5(e,t,n=!1){let s="";n?s+=eC(e):s+=gc(e);const i=e.shapeInfo.logicalShape,o=t.logicalShape;return i.length<=o.length&&(n?s+=M5(e,t):s+=P5(e,t)),s}function c5(e,t){switch(e.length){case 0:return tC();case 1:return b5(e,t);case 2:return v5(e,t);case 3:return L5(e,t);default:return I5(e,t)}}function l5(e,t){switch(e.length){case 0:return tC();case 1:return w5(e,t);case 2:return N5(e,t);case 3:return S5(e,t);case 4:return x5(e,t);case 5:return T5(e,t);case 6:return A5(e,t);default:throw new Error(`${e.length}-D output sampling is not yet supported`)}}function h5(e){return`
2020-10-12 20:28:19 +02:00
float sampleTexture(sampler2D textureSampler, vec2 uv) {
return ${e.texture2D}(textureSampler, uv).r;
}
2020-10-29 05:16:50 +01:00
`}function u5(e){return`
2020-10-12 20:28:19 +02:00
void setOutput(float val) {
${e.output} = vec4(val, 0, 0, 0);
}
2020-10-29 05:16:50 +01:00
`}function d5(e){return`
2020-10-12 20:28:19 +02:00
void setOutput(vec4 val) {
${e.output} = val;
}
2020-10-29 05:16:50 +01:00
`}function p5(e){const t=`${e.version}
2020-10-12 20:28:19 +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);
2020-08-29 20:56:29 +02:00
}
2020-10-12 20:28:19 +02:00
int idiv(int a, int b, float sign) {
int res = a / b;
int mod = imod(a, b);
if (sign < 0. && mod != 0) {
res -= 1;
}
return res;
}
//Based on the work of Dave Hoskins
//https://www.shadertoy.com/view/4djSRW
#define HASHSCALE1 443.8975
float random(float seed){
vec2 p = resultUV * seed;
vec3 p3 = fract(vec3(p.xyx) * HASHSCALE1);
p3 += dot(p3, p3.yzx + 19.19);
return fract((p3.x + p3.y) * p3.z);
}
2020-10-29 05:16:50 +01:00
${m5}
${f5}
${g5}
`;return t}const m5=`
2020-10-12 20:28:19 +02:00
vec2 uvFromFlat(int texNumR, int texNumC, int index) {
int texR = index / texNumC;
int texC = index - texR * texNumC;
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
}
vec2 packedUVfrom1D(int texNumR, int texNumC, int index) {
int texelIndex = index / 2;
int texR = texelIndex / texNumC;
int texC = texelIndex - texR * texNumC;
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
}
2020-10-29 05:16:50 +01:00
`,f5=`
2020-10-12 20:28:19 +02:00
vec2 packedUVfrom2D(int texelsInLogicalRow, int texNumR,
int texNumC, int row, int col) {
int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2);
int texR = texelIndex / texNumC;
int texC = texelIndex - texR * texNumC;
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
}
2020-10-29 05:16:50 +01:00
`,g5=`
2020-10-12 20:28:19 +02:00
vec2 packedUVfrom3D(int texNumR, int texNumC,
int texelsInBatch, int texelsInLogicalRow, int b,
int row, int col) {
int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2);
int texR = index / texNumC;
int texC = index - texR * texNumC;
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
}
2020-10-29 05:16:50 +01:00
`,y5=`
2020-10-12 20:28:19 +02:00
float getChannel(vec4 frag, vec2 innerDims) {
vec2 modCoord = mod(innerDims, 2.);
return modCoord.x == 0. ?
(modCoord.y == 0. ? frag.r : frag.g) :
(modCoord.y == 0. ? frag.b : frag.a);
}
float getChannel(vec4 frag, int dim) {
float modCoord = mod(float(dim), 2.);
return modCoord == 0. ? frag.r : frag.g;
}
2020-10-29 05:16:50 +01:00
`;function tC(){return`
2020-10-12 20:28:19 +02:00
int getOutputCoords() {
return 0;
}
2020-10-29 05:16:50 +01:00
`}function b5(e,t){const n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];return n[0]===1?`
2020-10-12 20:28:19 +02:00
int getOutputCoords() {
2020-10-13 22:57:06 +02:00
return 2 * int(resultUV.x * ${n[1]}.0);
2020-10-12 20:28:19 +02:00
}
2020-10-13 22:57:06 +02:00
`:n[1]===1?`
2020-10-12 20:28:19 +02:00
int getOutputCoords() {
2020-10-13 22:57:06 +02:00
return 2 * int(resultUV.y * ${n[0]}.0);
2020-10-12 20:28:19 +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-12 20:28:19 +02:00
}
2020-10-29 05:16:50 +01:00
`}function w5(e,t){return t[0]===1?`
2020-10-12 20:28:19 +02:00
int getOutputCoords() {
return int(resultUV.x * ${t[1]}.0);
}
`:t[1]===1?`
int getOutputCoords() {
return int(resultUV.y * ${t[0]}.0);
}
`:`
int getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
return resTexRC.x * ${t[1]} + resTexRC.y;
}
2020-10-29 05:16:50 +01:00
`}function L5(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-12 20:28:19 +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-12 20:28:19 +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-12 20:28:19 +02:00
return ivec3(b, r, c);
}
2020-10-29 05:16:50 +01:00
`}function S5(e,t){const n=Yo(["r","c","d"],e);return`
2020-10-12 20:28:19 +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-12 20:28:19 +02:00
return ivec3(r, c, d);
}
2020-10-29 05:16:50 +01:00
`}function I5(e,t){const n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],s=Math.ceil(e[e.length-1]/2),i=s*Math.ceil(e[e.length-2]/2);let o=i,a="",c="b, r, c";for(let h=2;h<e.length-1;h++)o*=e[e.length-h-1],a=`
2020-10-13 22:57:06 +02:00
int b${h} = index / ${o};
index -= b${h} * ${o};
`+a,c=`b${h}, `+c;return`
2020-10-12 20:28:19 +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-12 20:28:19 +02:00
2020-10-13 22:57:06 +02:00
${a}
2020-10-12 20:28:19 +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-12 20:28:19 +02:00
2020-10-13 22:57:06 +02:00
return ivec${e.length}(${c});
2020-10-12 20:28:19 +02:00
}
2020-10-29 05:16:50 +01:00
`}function x5(e,t){const n=Yo(["r","c","d","d2"],e);return`
2020-10-12 20:28:19 +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-12 20:28:19 +02:00
return ivec4(r, c, d, d2);
}
2020-10-29 05:16:50 +01:00
`}function T5(e,t){const n=Yo(["r","c","d","d2","d3"],e);return`
2020-10-12 20:28:19 +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-12 20:28:19 +02:00
ivec5 outShape = ivec5(r, c, d, d2, d3);
return outShape;
}
2020-10-29 05:16:50 +01:00
`}function A5(e,t){const n=Yo(["r","c","d","d2","d3","d4"],e);return`
2020-10-12 20:28:19 +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-12 20:28:19 +02:00
ivec6 result = ivec6(r, c, d, d2, d3, d4);
return result;
}
2020-10-29 05:16:50 +01:00
`}function v5(e,t){const n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(ae(e,t))return`
2020-10-12 20:28:19 +02:00
ivec2 getOutputCoords() {
2020-10-13 22:57:06 +02:00
return 2 * ivec2(resultUV.yx * vec2(${n[0]}, ${n[1]}));
2020-10-12 20:28:19 +02:00
}
2020-10-13 22:57:06 +02:00
`;const s=Math.ceil(e[1]/2);return`
2020-10-12 20:28:19 +02:00
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
2020-10-13 22:57:06 +02:00
vec2(${n[0]}, ${n[1]}));
2020-10-12 20:28:19 +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-12 20:28:19 +02:00
return ivec2(r, c);
2020-08-29 20:56:29 +02:00
}
2020-10-29 05:16:50 +01:00
`}function N5(e,t){return ae(e,t)?`
2020-10-12 20:28:19 +02:00
ivec2 getOutputCoords() {
return ivec2(resultUV.yx * vec2(${t[0]}, ${t[1]}));
}
`:e[1]===1?`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
return ivec2(index, 0);
}
`:e[0]===1?`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
return ivec2(0, index);
}
`:`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
int r = index / ${e[1]};
int c = index - r * ${e[1]};
return ivec2(r, c);
}
2020-10-29 05:16:50 +01:00
`}function Ho(e){return`offset${e}`}function C5(e){const t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1),s=Pn();return`
2020-10-13 22:57:06 +02:00
vec4 ${n}() {
return ${s.texture2D}(${t}, halfCR);
2020-10-12 20:28:19 +02:00
}
2020-10-29 05:16:50 +01:00
`}function R5(e){const t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1);if(e.shapeInfo.isUniform)return`float ${n}() {return ${t};}`;const[s,i]=e.shapeInfo.texShape;if(s===1&&i===1)return`
2020-10-13 22:57:06 +02:00
float ${n}() {
2020-10-12 20:28:19 +02:00
return sampleTexture(${t}, halfCR);
}
2020-10-29 05:16:50 +01:00
`;const[o,a]=e.shapeInfo.texShape,c=Ho(t);return`
2020-10-13 22:57:06 +02:00
float ${n}() {
vec2 uv = uvFromFlat(${o}, ${a}, ${c});
2020-10-12 20:28:19 +02:00
return sampleTexture(${t}, uv);
}
2020-10-29 05:16:50 +01:00
`}function O5(e){const t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1),s=e.shapeInfo.texShape,i=[Math.ceil(s[0]/2),Math.ceil(s[1]/2)],o=Pn();return`
2020-10-13 22:57:06 +02:00
vec4 ${n}(int index) {
2020-10-12 20:28:19 +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-12 20:28:19 +02:00
}
2020-10-29 05:16:50 +01:00
`}function E5(e){const t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1);if(e.shapeInfo.isUniform)return`
2020-10-13 22:57:06 +02:00
float ${n}(int index) {
2020-10-29 05:16:50 +01:00
${yc(e)}
2020-10-12 20:28:19 +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-12 20:28:19 +02:00
return sampleTexture(${t}, halfCR);
}
2020-10-29 05:16:50 +01:00
`;const a=Ho(t);return o===1?`
2020-10-13 22:57:06 +02:00
float ${n}(int index) {
vec2 uv = vec2(0.5, (float(index + ${a}) + 0.5) / ${i}.0);
2020-10-12 20:28:19 +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-12 20:28:19 +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-12 20:28:19 +02:00
return sampleTexture(${t}, uv);
2020-08-29 20:56:29 +02:00
}
2020-10-29 05:16:50 +01:00
`}function D5(e){const t=e.shapeInfo.logicalShape,n=e.name,s="get"+n.charAt(0).toUpperCase()+n.slice(1),i=e.shapeInfo.texShape,o=i[0],a=i[1],c=Pn();if(i!=null&&ae(t,i))return`
2020-10-13 22:57:06 +02:00
vec4 ${s}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${a}.0, ${o}.0);
2020-10-12 20:28:19 +02:00
2020-10-13 22:57:06 +02:00
return ${c.texture2D}(${n}, uv);
2020-10-12 20:28:19 +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-12 20:28:19 +02:00
}
2020-10-29 05:16:50 +01:00
`}function k5(e){const t=e.shapeInfo.logicalShape,n=e.name,s="get"+n.charAt(0).toUpperCase()+n.slice(1),i=e.shapeInfo.texShape;if(i!=null&&ae(t,i)){const f=i[0],b=i[1];return`
2020-10-13 22:57:06 +02:00
float ${s}(int row, int col) {
2020-10-29 05:16:50 +01:00
vec2 uv = (vec2(col, row) + halfCR) / vec2(${b}.0, ${f}.0);
2020-10-13 22:57:06 +02:00
return sampleTexture(${n}, uv);
2020-10-12 20:28:19 +02:00
}
2020-10-29 05:16:50 +01:00
`}const{newShape:o,keptDims:a}=ln(t),c=o;if(c.length<t.length){const f=bc(e,c),b=["row","col"];return`
${gc(f)}
2020-10-13 22:57:06 +02:00
float ${s}(int row, int col) {
2020-10-29 05:16:50 +01:00
return ${s}(${wc(b,a)});
2020-10-12 20:28:19 +02:00
}
`}if(e.shapeInfo.isUniform)return`
2020-10-13 22:57:06 +02:00
float ${s}(int row, int col) {
2020-10-12 20:28:19 +02:00
int index = round(dot(vec2(row, col), vec2(${t[1]}, 1)));
2020-10-29 05:16:50 +01:00
${yc(e)}
2020-10-12 20:28:19 +02:00
}
2020-10-29 05:16:50 +01:00
`;const h=i[0],d=i[1],m=Ho(n);return d===1?`
2020-10-13 22:57:06 +02:00
float ${s}(int row, int col) {
float index = dot(vec3(row, col, ${m}), vec3(${t[1]}, 1, 1));
vec2 uv = vec2(0.5, (index + 0.5) / ${h}.0);
return sampleTexture(${n}, uv);
2020-10-12 20:28:19 +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-12 20:28:19 +02:00
}
`:`
2020-10-13 22:57:06 +02:00
float ${s}(int row, int col) {
2020-10-12 20:28:19 +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-12 20:28:19 +02:00
}
2020-10-29 05:16:50 +01:00
`}function F5(e){const t=e.shapeInfo.logicalShape,n=e.name,s="get"+n.charAt(0).toUpperCase()+n.slice(1),i=e.shapeInfo.texShape,o=[Math.ceil(i[0]/2),Math.ceil(i[1]/2)];if(t[0]===1){const f=t.slice(1),b=[1,2],w=bc(e,f),L=["b","row","col"];return`
${eC(w)}
2020-10-13 22:57:06 +02:00
vec4 ${s}(int b, int row, int col) {
2020-10-29 05:16:50 +01:00
return ${s}(${wc(L,b)});
2020-10-12 20:28:19 +02:00
}
2020-10-29 05:16:50 +01:00
`}const a=o[0],c=o[1],h=Math.ceil(t[2]/2),d=h*Math.ceil(t[1]/2),m=Pn();return`
2020-10-13 22:57:06 +02:00
vec4 ${s}(int b, int row, int col) {
2020-10-12 20:28:19 +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-12 20:28:19 +02:00
}
2020-10-29 05:16:50 +01:00
`}function _5(e){const t=e.shapeInfo.logicalShape,n=e.name,s="get"+n.charAt(0).toUpperCase()+n.slice(1),i=t[1]*t[2],o=t[2],{newShape:a,keptDims:c}=ln(t),h=a;if(h.length<t.length){const L=bc(e,h),x=["row","col","depth"];return`
${gc(L)}
2020-10-13 22:57:06 +02:00
float ${s}(int row, int col, int depth) {
2020-10-29 05:16:50 +01:00
return ${s}(${wc(x,c)});
2020-10-12 20:28:19 +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-12 20:28:19 +02:00
int index = round(dot(vec3(row, col, depth),
2020-10-13 22:57:06 +02:00
vec3(${i}, ${o}, 1)));
2020-10-29 05:16:50 +01:00
${yc(e)}
2020-10-12 20:28:19 +02:00
}
2020-10-29 05:16:50 +01:00
`;const d=e.shapeInfo.texShape,m=d[0],f=d[1],b=e.shapeInfo.flatOffset;if(f===i&&b==null)return`
2020-10-13 22:57:06 +02:00
float ${s}(int row, int col, int depth) {
2020-10-12 20:28:19 +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-12 20:28:19 +02:00
vec2 uv = (vec2(texC, texR) + halfCR) /
2020-10-29 05:16:50 +01:00
vec2(${f}.0, ${m}.0);
2020-10-13 22:57:06 +02:00
return sampleTexture(${n}, uv);
2020-10-12 20:28:19 +02:00
}
2020-10-29 05:16:50 +01:00
`;if(f===o&&b==null)return`
2020-10-13 22:57:06 +02:00
float ${s}(int row, int col, int depth) {
2020-10-12 20:28:19 +02:00
float texR = dot(vec2(row, col), vec2(${t[1]}, 1));
float texC = float(depth);
2020-10-29 05:16:50 +01:00
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${f}.0, ${m}.0);
2020-10-13 22:57:06 +02:00
return sampleTexture(${n}, uv);
2020-10-12 20:28:19 +02:00
}
2020-10-29 05:16:50 +01:00
`;const w=Ho(n);return`
2020-10-13 22:57:06 +02:00
float ${s}(int row, int col, int depth) {
2020-10-12 20:28:19 +02:00
// Explicitly use integer operations as dot() only works on floats.
2020-10-13 22:57:06 +02:00
int index = row * ${i} + col * ${o} + depth + ${w};
2020-10-29 05:16:50 +01:00
vec2 uv = uvFromFlat(${m}, ${f}, index);
2020-10-13 22:57:06 +02:00
return sampleTexture(${n}, uv);
}
2020-10-29 05:16:50 +01:00
`}function W5(e){const t=e.shapeInfo.logicalShape,n=t.length,s=e.name,i="get"+s.charAt(0).toUpperCase()+s.slice(1),o=e.shapeInfo.texShape,a=[Math.ceil(o[0]/2),Math.ceil(o[1]/2)],c=a[0],h=a[1],d=Math.ceil(t[n-1]/2);let m=d*Math.ceil(t[n-2]/2),f="int b, int row, int col",b=`b * ${m} + (row / 2) * ${d} + (col / 2)`;for(let L=2;L<n-1;L++)f=`int b${L}, `+f,m*=t[n-L-1],b=`b${L} * ${m} + `+b;const w=Pn();return`
vec4 ${i}(${f}) {
2020-10-13 22:57:06 +02:00
int index = ${b};
int texR = index / ${h};
int texC = index - texR * ${h};
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${h}, ${c});
return ${w.texture2D}(${s}, uv);
2020-10-12 20:28:19 +02:00
}
2020-10-29 05:16:50 +01:00
`}function $5(e){const t=e.shapeInfo.logicalShape,n=e.name,s="get"+n.charAt(0).toUpperCase()+n.slice(1),i=t[3],o=t[2]*i,a=t[1]*o,{newShape:c,keptDims:h}=ln(t);if(c.length<t.length){const L=bc(e,c),x=["row","col","depth","depth2"];return`
${gc(L)}
2020-10-13 22:57:06 +02:00
float ${s}(int row, int col, int depth, int depth2) {
2020-10-29 05:16:50 +01:00
return ${s}(${wc(x,h)});
2020-10-12 20:28:19 +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-12 20:28:19 +02:00
int index = round(dot(vec4(row, col, depth, depth2),
2020-10-13 22:57:06 +02:00
vec4(${a}, ${o}, ${i}, 1)));
2020-10-29 05:16:50 +01:00
${yc(e)}
2020-10-12 20:28:19 +02:00
}
2020-10-29 05:16:50 +01:00
`;const d=e.shapeInfo.flatOffset,m=e.shapeInfo.texShape,f=m[0],b=m[1];if(b===a&&d==null)return`
2020-10-13 22:57:06 +02:00
float ${s}(int row, int col, int depth, int depth2) {
2020-10-12 20:28:19 +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-12 20:28:19 +02:00
vec2 uv = (vec2(texC, texR) + halfCR) /
2020-10-29 05:16:50 +01:00
vec2(${b}.0, ${f}.0);
2020-10-13 22:57:06 +02:00
return sampleTexture(${n}, uv);
2020-10-12 20:28:19 +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-12 20:28:19 +02:00
float texR = dot(vec3(row, col, depth),
vec3(${t[1]*t[2]}, ${t[2]}, 1));
float texC = float(depth2);
vec2 uv = (vec2(texC, texR) + halfCR) /
2020-10-29 05:16:50 +01:00
vec2(${b}.0, ${f}.0);
2020-10-13 22:57:06 +02:00
return sampleTexture(${n}, uv);
2020-10-12 20:28:19 +02:00
}
2020-10-29 05:16:50 +01:00
`;const w=Ho(n);return`
2020-10-13 22:57:06 +02:00
float ${s}(int row, int col, int depth, int depth2) {
2020-10-12 20:28:19 +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-12 20:28:19 +02:00
depth * ${i} + depth2;
2020-10-29 05:16:50 +01:00
vec2 uv = uvFromFlat(${f}, ${b}, index + ${w});
2020-10-13 22:57:06 +02:00
return sampleTexture(${n}, uv);
2020-10-12 20:28:19 +02:00
}
2020-10-29 05:16:50 +01:00
`}function U5(e){const t=e.shapeInfo.logicalShape,n=e.name,s="get"+n.charAt(0).toUpperCase()+n.slice(1),i=t[4],o=t[3]*i,a=t[2]*o,c=t[1]*a,{newShape:h,keptDims:d}=ln(t);if(h.length<t.length){const x=bc(e,h),v=["row","col","depth","depth2","depth3"];return`
${gc(x)}
2020-10-13 22:57:06 +02:00
float ${s}(int row, int col, int depth, int depth2, int depth3) {
2020-10-29 05:16:50 +01:00
return ${s}(${wc(v,d)});
2020-10-12 20:28:19 +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-12 20:28:19 +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-12 20:28:19 +02:00
depth3;
2020-10-29 05:16:50 +01:00
${yc(e)}
2020-10-12 20:28:19 +02:00
}
2020-10-29 05:16:50 +01:00
`;const m=e.shapeInfo.flatOffset,f=e.shapeInfo.texShape,b=f[0],w=f[1];if(w===c&&m==null)return`
2020-10-13 22:57:06 +02:00
float ${s}(int row, int col, int depth, int depth2, int depth3) {
2020-10-12 20:28:19 +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-12 20:28:19 +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-12 20:28:19 +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-12 20:28:19 +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-12 20:28:19 +02:00
}
2020-10-29 05:16:50 +01:00
`;const L=Ho(n);return`
2020-10-13 22:57:06 +02:00
float ${s}(int row, int col, int depth, int depth2, int depth3) {
2020-10-12 20:28:19 +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-12 20:28:19 +02:00
}
2020-10-29 05:16:50 +01:00
`}function B5(e){const t=e.shapeInfo.logicalShape,n=e.name,s="get"+n.charAt(0).toUpperCase()+n.slice(1),{newShape:i,keptDims:o}=ln(t);if(i.length<t.length){const v=bc(e,i),N=["row","col","depth","depth2","depth3","depth4"];return`
${gc(v)}
2020-10-13 22:57:06 +02:00
float ${s}(int row, int col, int depth,
2020-10-12 20:28:19 +02:00
int depth2, int depth3, int depth4) {
2020-10-29 05:16:50 +01:00
return ${s}(${wc(N,o)});
2020-10-12 20:28:19 +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-12 20:28:19 +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-12 20:28:19 +02:00
dot(
vec2(depth3, depth4),
2020-10-13 22:57:06 +02:00
vec2(${a}, 1)));
2020-10-29 05:16:50 +01:00
${yc(e)}
2020-10-12 20:28:19 +02:00
}
2020-10-29 05:16:50 +01:00
`;const f=e.shapeInfo.flatOffset,b=e.shapeInfo.texShape,w=b[0],L=b[1];if(L===m&&f==null)return`
2020-10-13 22:57:06 +02:00
float ${s}(int row, int col, int depth,
2020-10-12 20:28:19 +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-12 20:28:19 +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-12 20:28:19 +02:00
}
2020-10-29 05:16:50 +01:00
`;if(L===a&&f==null)return`
2020-10-13 22:57:06 +02:00
float ${s}(int row, int col, int depth,
2020-10-12 20:28:19 +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-12 20:28:19 +02:00
}
2020-10-29 05:16:50 +01:00
`;const x=Ho(n);return`
2020-10-13 22:57:06 +02:00
float ${s}(int row, int col, int depth,
2020-10-12 20:28:19 +02:00
int depth2, int depth3, int depth4) {
// Explicitly use integer operations as dot() only works on floats.
2020-10-13 22:57:06 +02:00
int index = row * ${m} + col * ${d} + depth * ${h} +
2020-10-29 05:16:50 +01:00
depth2 * ${c} + depth3 * ${a} + depth4 + ${x};
2020-10-13 22:57:06 +02:00
vec2 uv = uvFromFlat(${w}, ${L}, index);
return sampleTexture(${n}, uv);
2020-10-12 20:28:19 +02:00
}
2020-10-29 05:16:50 +01:00
`}function yc(e){const t=e.name,n=P(e.shapeInfo.logicalShape);return n<2?`return ${t};`:`
2020-10-13 22:57:06 +02:00
for (int i = 0; i < ${n}; i++) {
2020-10-12 20:28:19 +02:00
if (i == index) {
return ${t}[i];
}
2020-08-29 20:56:29 +02:00
}
2020-10-29 05:16:50 +01:00
`}function M5(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=Q0(e.shapeInfo.logicalShape,t.logicalShape),h=Rt(a),d=a-o;let m;const f=["x","y","z","w","u","v"];o===0?m="":a<2&&c.length>=1?m="coords = 0;":m=c.map(O=>`coords.${f[O+d]} = 0;`).join(`
`);let b="";a<2&&o>0?b="coords":b=e.shapeInfo.logicalShape.map((O,E)=>`coords.${f[E+d]}`).join(", ");let w="return outputValue;";const L=P(e.shapeInfo.logicalShape),x=L===1,v=P(t.logicalShape),N=v===1;if(o===1&&!x&&!N)w=`
2020-10-12 20:28:19 +02:00
return vec4(outputValue.xy, outputValue.xy);
2020-10-29 05:16:50 +01:00
`;else if(x&&!N)a===1?w=`
2020-10-12 20:28:19 +02:00
return vec4(outputValue.x, outputValue.x, 0., 0.);
2020-10-13 22:57:06 +02:00
`:w=`
2020-10-12 20:28:19 +02:00
return vec4(outputValue.x);
2020-10-29 05:16:50 +01:00
`;else if(c.length){const O=o-2,E=o-1;c.indexOf(O)>-1&&c.indexOf(E)>-1?w="return vec4(outputValue.x);":c.indexOf(O)>-1?w="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":c.indexOf(E)>-1&&(w="return vec4(outputValue.xx, outputValue.zz);")}return`
2020-10-12 20:28:19 +02:00
vec4 ${i}() {
2020-10-13 22:57:06 +02:00
${h} coords = getOutputCoords();
${m}
vec4 outputValue = get${s}(${b});
${w}
2020-10-12 20:28:19 +02:00
}
2020-10-29 05:16:50 +01:00
`}function P5(e,t){const n=e.name,s=n.charAt(0).toUpperCase()+n.slice(1),i="get"+s+"AtOutCoords",o=t.texShape,a=e.shapeInfo.texShape,c=e.shapeInfo.logicalShape.length,h=t.logicalShape.length;if(!e.shapeInfo.isUniform&&c===h&&e.shapeInfo.flatOffset==null&&ae(a,o))return`
2020-10-12 20:28:19 +02:00
float ${i}() {
2020-10-13 22:57:06 +02:00
return sampleTexture(${n}, resultUV);
2020-10-12 20:28:19 +02:00
}
2020-10-29 05:16:50 +01:00
`;const d=Rt(h),m=Q0(e.shapeInfo.logicalShape,t.logicalShape),f=h-c;let b;const w=["x","y","z","w","u","v"];c===0?b="":h<2&&m.length>=1?b="coords = 0;":b=m.map(x=>`coords.${w[x+f]} = 0;`).join(`
`);let L="";return h<2&&c>0?L="coords":L=e.shapeInfo.logicalShape.map((x,v)=>`coords.${w[v+f]}`).join(", "),`
2020-10-12 20:28:19 +02:00
float ${i}() {
2020-10-13 22:57:06 +02:00
${d} coords = getOutputCoords();
${b}
return get${s}(${L});
2020-10-12 20:28:19 +02:00
}
2020-10-29 05:16:50 +01:00
`}function Rt(e){if(e<=1)return"int";if(e===2)return"ivec2";if(e===3)return"ivec3";if(e===4)return"ivec4";if(e===5)return"ivec5";if(e===6)return"ivec6";throw Error(`GPU for rank ${e} is not yet supported`)}function bc(e,t){const n=JSON.parse(JSON.stringify(e));return n.shapeInfo.logicalShape=t,n}function wc(e,t){return t.map(n=>e[n]).join(", ")}class z5{constructor(e,t,n,s){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,A(e.length>2,()=>`Packed arg${n.charAt(0).toUpperCase()+n.slice(1)} supports only inputs with rank above 2.`);const i=e[e.length-1],o=Math.ceil(i/t);this.outputShape=e.slice(0,-1),o>1&&this.outputShape.push(o),s||this.variableNames.push("bestIndicesA");const a=this.outputShape,c=a.length,h=Rt(c),d=Mn("coords",c);let m,f;if(o===1){f=c+1;const $=Rt(f);m=`
2020-10-13 22:57:06 +02:00
${$} sourceLocR = ${$}(${d.join()}, 0);
++${d[c-1]};
${$} sourceLocG = ${$}(${d.join()}, 0);
++${d[c-2]};
${$} sourceLocA = ${$}(${d.join()}, 0);
--${d[c-1]};
${$} sourceLocB = ${$}(${d.join()}, 0);
2020-10-29 05:16:50 +01:00
--${d[c-2]};`}else f=c,m=`
2020-10-13 22:57:06 +02:00
${h} sourceLocR = coords;
++${d[c-1]};
${h} sourceLocG = coords;
++${d[c-2]};
${h} sourceLocA = coords;
--${d[c-1]};
${h} sourceLocB = coords;
2020-10-29 05:16:50 +01:00
--${d[c-2]};`;const b=["x","y","z","w","u","v"].slice(0,f),w="."+b[f-1],L=b.map($=>"int "+$),x=Mn("sourceLocR",f-1).concat("inIdx.r"),v=Mn("sourceLocG",f-1).concat("inIdx.g"),N=Mn("sourceLocB",f-1).concat("inIdx.b"),O=Mn("sourceLocA",f-1).concat("inIdx.a"),E=n==="max"?"greaterThan":"lessThan",k=s?"":`
inIdx = round(vec4(getBestIndicesAChannel(${x.join()}),
getBestIndicesAChannel(${v.join()}),
2020-10-13 22:57:06 +02:00
getBestIndicesAChannel(${N.join()}),
2020-10-29 05:16:50 +01:00
getBestIndicesAChannel(${O.join()})));`,F=`vec4(
getAChannel(${x.join()}),
hasNextCol ? getAChannel(${v.join()}) : 0.,
2020-10-13 22:57:06 +02:00
hasNextRow ? getAChannel(${N.join()}) : 0.,
2020-10-29 05:16:50 +01:00
hasNextRow && hasNextCol ? getAChannel(${O.join()}) : 0.)`,U=s?"":`
2020-10-13 22:57:06 +02:00
float getBestIndicesAChannel(${L.join()}) {
return getChannel(getBestIndicesA(${b.join()}),
vec2(${b.slice(-2).join()}));
2020-10-12 20:28:19 +02:00
}`;this.userCode=`
2020-10-13 22:57:06 +02:00
float getAChannel(${L.join()}) {
return getChannel(getA(${b.join()}),
vec2(${b.slice(-2).join()}));
}
2020-10-29 05:16:50 +01:00
${U}
2020-10-13 22:57:06 +02:00
void main() {
${h} coords = getOutputCoords();
bool hasNextCol = ${d[c-1]} < ${a[c-1]-1};
bool hasNextRow = ${d[c-2]} < ${a[c-2]-1};
${m}
ivec4 srcIdx = ivec4(sourceLocR${w}, sourceLocG${w},
sourceLocB${w}, sourceLocA${w}) * ${t};
2020-10-12 20:28:19 +02:00
ivec4 inIdx = srcIdx;
vec4 bestIndex = vec4(inIdx);
2020-10-29 05:16:50 +01:00
vec4 bestValue = ${F};
2020-10-12 20:28:19 +02:00
for (int i = 0; i < ${t}; i++) {
inIdx = srcIdx;
2020-10-29 05:16:50 +01:00
${k}
vec4 candidate = ${F};
2020-10-12 20:28:19 +02:00
bvec4 nan = isnan(candidate);
bvec4 replace = bvec4(
2020-10-29 05:16:50 +01:00
vec4(${E}(candidate, bestValue)) * (vec4(1.0) - vec4(nan)));
2020-10-12 20:28:19 +02:00
bestValue = vec4(replace.x ? candidate.x : bestValue.x,
replace.y ? candidate.y : bestValue.y,
replace.z ? candidate.z : bestValue.z,
replace.w ? candidate.w : bestValue.w);
bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace));
srcIdx++;
}
setOutput(bestIndex);
}
2020-10-29 05:16:50 +01:00
`}}class V5{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;const t=e.filterHeight,n=e.filterWidth,s=e.strideHeight,i=e.strideWidth,o=e.dilationHeight,a=e.dilationWidth,c=e.effectiveFilterHeight,h=e.effectiveFilterWidth,d=c-1-e.padInfo.top,m=h-1-e.padInfo.left,f=1/(t*n);this.userCode=`
2020-10-13 22:57:06 +02:00
const ivec2 pads = ivec2(${d}, ${m});
2020-10-29 05:16:50 +01:00
const float avgMultiplier = float(${f});
2020-10-12 20:28:19 +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-12 20:28:19 +02:00
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
2020-08-29 20:56:29 +02:00
2020-10-13 22:57:06 +02:00
for (int wC = 0; wC < ${h};
wC+= ${a}) {
2020-10-12 20:28:19 +02:00
float dyC = float(dyCCorner + wC) / ${i}.0;
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
float dyValue = getDy(b, idyR, idyC, d);
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
dotProd += dyValue * avgMultiplier;
}
}
setOutput(dotProd);
}
2020-10-29 05:16:50 +01:00
`}}class G5{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;const t=e.filterDepth,n=e.filterHeight,s=e.filterWidth,i=e.strideDepth,o=e.strideHeight,a=e.strideWidth,c=e.dilationDepth,h=e.dilationHeight,d=e.dilationWidth,m=e.effectiveFilterDepth,f=e.effectiveFilterHeight,b=e.effectiveFilterWidth,w=m-1-e.padInfo.front,L=f-1-e.padInfo.top,x=b-1-e.padInfo.left,v=1/(t*n*s);this.userCode=`
const ivec3 pads = ivec3(${w}, ${L}, ${x});
const float avgMultiplier = float(${v});
2020-10-12 20:28:19 +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-12 20:28:19 +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-08-29 20:56:29 +02:00
2020-10-29 05:16:50 +01:00
for (int wR = 0; wR < ${f};
2020-10-13 22:57:06 +02:00
wR += ${h}) {
float dyR = float(dyRCorner + wR) / ${o}.0;
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
2020-08-29 20:56:29 +02:00
2020-10-13 22:57:06 +02:00
for (int wC = 0; wC < ${b};
wC += ${d}) {
float dyC = float(dyCCorner + wC) / ${a}.0;
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
float dyValue = getDy(batch, idyD, idyR, idyC, ch);
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
dotProd += dyValue * avgMultiplier;
}
}
}
setOutput(dotProd);
}
2020-10-29 05:16:50 +01:00
`}}const nC=`
2020-10-12 20:28:19 +02:00
if (isnan(a)) return a;
if (isnan(b)) return b;
2020-10-29 05:16:50 +01:00
`,Y5=`
2020-10-12 20:28:19 +02:00
float s = sign(a) * sign(b);
int ia = round(a);
int ib = round(b);
if (ib != 0) {
// Windows (D3D) wants guaranteed non-zero int division at compile-time.
return float(idiv(ia, ib, s));
} else {
return NAN;
}
2020-10-29 05:16:50 +01:00
`,H5=`
2020-10-12 20:28:19 +02:00
if(a < 0.0 && floor(b) < b){
return NAN;
}
if (b == 0.0) {
return 1.0;
}
return (round(mod(b, 2.0)) != 1) ?
pow(abs(a), b) : sign(a) * pow(abs(a), b);
2020-10-29 05:16:50 +01:00
`,ine="return (a - b) * (a - b);",q5="return float(a == b);",j5="return float(a < b);",K5="return float(a <= b);",X5="return float(a > b);",J5="return float(a >= b);",Z5="return float(a >= 1.0 && b >= 1.0);",Q5="return float(a >= 1.0 || b >= 1.0);",e8=nC+`
2020-10-12 20:28:19 +02:00
return max(a, b);
2020-10-29 05:16:50 +01:00
`,t8=nC+`
2020-10-12 20:28:19 +02:00
return min(a, b);
2020-10-29 05:16:50 +01:00
`,n8=`if (b == 0.0) return NAN;
return mod(a, b);`,s8="return (b >= 1.0) ? a : a * (b + 1.0);",sC="return (a < 0.) ? b * a : a;";class _n{constructor(e,t,n){this.variableNames=["A","B"],this.outputShape=nt(t,n),this.userCode=`
2020-10-12 20:28:19 +02:00
float binaryOperation(float a, float b) {
${e}
}
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
void main() {
float a = getAAtOutCoords();
float b = getBAtOutCoords();
setOutput(binaryOperation(a, b));
}
2020-10-29 05:16:50 +01:00
`}}const km=`
2020-10-12 20:28:19 +02:00
result.r = isNaN.r > 0. ? NAN : result.r;
result.g = isNaN.g > 0. ? NAN : result.g;
result.b = isNaN.b > 0. ? NAN : result.b;
result.a = isNaN.a > 0. ? NAN : result.a;
2020-10-29 05:16:50 +01:00
`,i8=`
2020-10-12 20:28:19 +02:00
ivec4 ia = round(a);
ivec4 ib = round(b);
bvec4 cond = notEqual(ib, ivec4(0));
ivec4 result = ivec4(0);
vec4 s = sign(a) * sign(b);
// Windows (D3D) wants guaranteed non-zero int division at compile-time.
if (cond[0]) {
result[0] = idiv(ia[0], ib[0], s[0]);
}
if (cond[1]) {
result[1] = idiv(ia[1], ib[1], s[1]);
}
if (cond[2]) {
result[2] = idiv(ia[2], ib[2], s[2]);
}
if (cond[3]) {
result[3] = idiv(ia[3], ib[3], s[3]);
}
return vec4(result);
2020-10-29 05:16:50 +01:00
`,r8=`
2020-10-12 20:28:19 +02:00
// isModRound1 has 1 for components with round(mod(b, 2.0)) == 1, 0 otherwise.
vec4 isModRound1 = vec4(equal(round(mod(b, 2.0)), ivec4(1)));
vec4 multiplier = sign(a) * isModRound1 + (vec4(1.0) - isModRound1);
vec4 result = multiplier * pow(abs(a), b);
// Ensure that a^0 = 1, including 0^0 = 1 as this correspond to TF and JS
bvec4 isExpZero = equal(b, vec4(0.0));
result.r = isExpZero.r ? 1.0 : result.r;
result.g = isExpZero.g ? 1.0 : result.g;
result.b = isExpZero.b ? 1.0 : result.b;
result.a = isExpZero.a ? 1.0 : result.a;
vec4 isNaN = vec4(lessThan(a, vec4(0.0))) * vec4(lessThan(floor(b), b));
2020-10-29 05:16:50 +01:00
`+km+`
2020-10-12 20:28:19 +02:00
return result;
2020-10-29 05:16:50 +01:00
`,iC=`
2020-10-12 20:28:19 +02:00
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
2020-10-29 05:16:50 +01:00
`,o8=`
2020-10-12 20:28:19 +02:00
vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));
return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));
2020-10-29 05:16:50 +01:00
`,a8=`
2020-10-12 20:28:19 +02:00
return vec4(equal(a, b));
2020-10-29 05:16:50 +01:00
`,rne=`
2020-10-12 20:28:19 +02:00
return vec4(notEqual(a, b));
2020-10-29 05:16:50 +01:00
`,c8=`
2020-10-12 20:28:19 +02:00
return vec4(lessThan(a, b));
2020-10-29 05:16:50 +01:00
`,l8=`
2020-10-12 20:28:19 +02:00
return vec4(lessThanEqual(a, b));
2020-10-29 05:16:50 +01:00
`,h8=`
2020-10-12 20:28:19 +02:00
return vec4(greaterThan(a, b));
2020-10-29 05:16:50 +01:00
`,u8=`
2020-10-12 20:28:19 +02:00
return vec4(greaterThanEqual(a, b));
2020-10-29 05:16:50 +01:00
`,d8=`
2020-10-12 20:28:19 +02:00
return vec4(
vec4(greaterThanEqual(a, vec4(1.0))) *
vec4(greaterThanEqual(b, vec4(1.0))));
2020-10-29 05:16:50 +01:00
`,p8=`
2020-10-12 20:28:19 +02:00
return min(
vec4(greaterThanEqual(a, vec4(1.0))) +
vec4(greaterThanEqual(b, vec4(1.0))),
vec4(1.0));
2020-10-29 05:16:50 +01:00
`,m8=`
2020-10-12 20:28:19 +02:00
vec4 result = vec4(max(a, b));
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
2020-10-29 05:16:50 +01:00
`+km+`
2020-10-12 20:28:19 +02:00
return result;
2020-10-29 05:16:50 +01:00
`,f8=`
2020-10-12 20:28:19 +02:00
vec4 result = vec4(min(a, b));
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
2020-10-29 05:16:50 +01:00
`+km+`
2020-10-12 20:28:19 +02:00
return result;
2020-10-29 05:16:50 +01:00
`,g8=`
2020-10-12 20:28:19 +02:00
vec4 result = mod(a, b);
vec4 isNaN = vec4(equal(b, vec4(0.0)));
2020-10-29 05:16:50 +01:00
`+km+`
2020-10-12 20:28:19 +02:00
return result;
2020-10-29 05:16:50 +01:00
`;class lr{constructor(e,t,n,s=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=nt(t,n);const i=this.outputShape.length;let o="";if(s)if(i===0||P(this.outputShape)===1)o=`
2020-10-12 20:28:19 +02:00
result.y = 0.;
result.z = 0.;
result.w = 0.;
2020-10-29 05:16:50 +01:00
`;else{const a=Rt(i);if(o=`
2020-10-13 22:57:06 +02:00
${a} coords = getOutputCoords();
`,i===1)o+=`
2020-10-12 20:28:19 +02:00
result.y = (coords + 1) >= ${this.outputShape[0]} ? 0. : result.y;
result.z = 0.;
result.w = 0.;
2020-10-29 05:16:50 +01:00
`;else{const c=Mn("coords",i);o+=`
2020-10-12 20:28:19 +02:00
bool nextRowOutOfBounds =
2020-10-13 22:57:06 +02:00
(${c[i-2]} + 1) >= ${this.outputShape[i-2]};
2020-10-12 20:28:19 +02:00
bool nextColOutOfBounds =
2020-10-13 22:57:06 +02:00
(${c[i-1]} + 1) >= ${this.outputShape[i-1]};
2020-10-12 20:28:19 +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}
}
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
void main() {
vec4 a = getAAtOutCoords();
vec4 b = getBAtOutCoords();
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
vec4 result = binaryOperation(a, b);
2020-10-13 22:57:06 +02:00
${o}
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
setOutput(result);
}
2020-10-29 05:16:50 +01:00
`}}class y8{constructor(e){this.variableNames=["A"],this.outputShape=e,this.userCode=`
2020-10-12 20:28:19 +02:00
uniform float minVal;
uniform float maxVal;
void main() {
float value = getAAtOutCoords();
if (isnan(value)) {
setOutput(value);
return;
}
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
setOutput(clamp(value, minVal, maxVal));
}
2020-10-29 05:16:50 +01:00
`}getCustomSetupFunc(e,t){return(n,s)=>{this.minLoc==null&&(this.minLoc=n.getUniformLocationNoThrow(s,"minVal"),this.maxLoc=n.getUniformLocationNoThrow(s,"maxVal")),n.gl.uniform1f(this.minLoc,e),n.gl.uniform1f(this.maxLoc,t)}}}class b8{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.userCode=`
2020-10-12 20:28:19 +02:00
uniform float minVal;
uniform float maxVal;
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
void main() {
vec4 value = getAAtOutCoords();
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
if (any(isnan(value))) {
setOutput(value);
return;
}
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
setOutput(clamp(value, vec4(minVal), vec4(maxVal)));
}
2020-10-29 05:16:50 +01:00
`}getCustomSetupFunc(e,t){return(n,s)=>{this.minLoc==null&&(this.minLoc=n.getUniformLocationNoThrow(s,"minVal"),this.maxLoc=n.getUniformLocationNoThrow(s,"maxVal")),n.gl.uniform1f(this.minLoc,e),n.gl.uniform1f(this.maxLoc,t)}}}class w8{constructor(e){this.variableNames=["real","imag"],this.outputShape=e,this.userCode=`
2020-10-12 20:28:19 +02:00
void main() {
float re = abs(getRealAtOutCoords());
float im = abs(getImagAtOutCoords());
float mx = max(re, im);
// sadly the length function in glsl is not underflow-safe
// (at least not on Intel GPUs). So the safe solution is
// to ensure underflow-safety in all cases.
setOutput(
mx == 0.0 ? 0.0 : mx * length(vec2(1, min(re, im)/mx))
);
}
2020-10-29 05:16:50 +01:00
`}}class L8{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-12 20:28:19 +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-12 20:28:19 +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-12 20:28:19 +02:00
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
2020-10-13 22:57:06 +02:00
if (${o}) {
2020-10-12 20:28:19 +02:00
float dyValue = getDy(b, yR, yC, d2);
float xValue = getX(b, xR, xC, d1);
dotProd += (xValue * dyValue);
} else {
float dyValue = getDy(b, d2, yR, yC);
float xValue = getX(b, d1, xR, xC);
dotProd += (xValue * dyValue);
}
}
}
}
setOutput(dotProd);
}
2020-10-29 05:16:50 +01:00
`}}class S8{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterHeight,n=e.filterWidth,s=e.strideHeight,i=e.strideWidth,o=e.dataFormat==="channelsLast",a=t-1-e.padInfo.top,c=n-1-e.padInfo.left,h=o?1:2,d=o?2:3,m=o?3:1;this.userCode=`
2020-10-13 22:57:06 +02:00
const ivec2 pads = ivec2(${a}, ${c});
2020-10-12 20:28:19 +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-12 20:28:19 +02:00
2020-10-13 22:57:06 +02:00
ivec2 dyCorner = ivec2(coords[${h}], coords[${d}]) - pads;
2020-10-12 20:28:19 +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-12 20:28:19 +02:00
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
int wRPerm = ${t} - 1 - wR;
2020-08-29 20:56:29 +02:00
2020-10-13 22:57:06 +02:00
for (int wC = 0; wC < ${n}; wC++) {
2020-10-12 20:28:19 +02:00
float dyC = float(dyCCorner + wC) / ${i}.0;
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
2020-08-29 20:56:29 +02:00
2020-10-13 22:57:06 +02:00
int wCPerm = ${n} - 1 - wC;
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
for (int d2 = 0; d2 < ${e.outChannels}; d2++) {
2020-08-29 20:56:29 +02:00
2020-10-13 22:57:06 +02:00
if (${o}) {
2020-10-12 20:28:19 +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;
}
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
}
}
}
setOutput(dotProd);
}
2020-10-29 05:16:50 +01:00
`}}class I8{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-12 20:28:19 +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-12 20:28:19 +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-12 20:28:19 +02:00
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
float dyValue = getDy(b, yF, yR, yC, d2);
float xValue = getX(b, xF, xR, xC, d1);
dotProd += (xValue * dyValue);
}
}
}
}
setOutput(dotProd);
}
2020-10-29 05:16:50 +01:00
`}}class x8{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterDepth,n=e.filterHeight,s=e.filterWidth,i=e.strideDepth,o=e.strideHeight,a=e.strideWidth,c=t-1-e.padInfo.front,h=n-1-e.padInfo.top,d=s-1-e.padInfo.left;this.userCode=`
2020-10-13 22:57:06 +02:00
const ivec3 pads = ivec3(${c}, ${h}, ${d});
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int d1 = coords.u;
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
int dyFCorner = dyCorner.x;
int dyRCorner = dyCorner.y;
int dyCCorner = dyCorner.z;
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
float dotProd = 0.0;
for (int wF = 0; wF < ${t}; wF++) {
float dyF = float(dyFCorner + wF) / ${i}.0;
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
if (dyF < 0.0 || dyF >= ${e.outDepth}.0 || fract(dyF) > 0.0) {
continue;
}
int idyF = int(dyF);
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
int wFPerm = ${t} - 1 - wF;
2020-08-29 20:56:29 +02:00
2020-10-13 22:57:06 +02:00
for (int wR = 0; wR < ${n}; wR++) {
float dyR = float(dyRCorner + wR) / ${o}.0;
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
2020-08-29 20:56:29 +02:00
2020-10-13 22:57:06 +02:00
int wRPerm = ${n} - 1 - wR;
2020-08-29 20:56:29 +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-12 20:28:19 +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-12 20:28:19 +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;
}
}
}
2020-08-29 20:56:29 +02:00
}
2020-10-12 20:28:19 +02:00
setOutput(dotProd);
}
2020-10-29 05:16:50 +01:00
`}}class T8{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-12 20:28:19 +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-12 20:28:19 +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-12 20:28:19 +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-12 20:28:19 +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);
}
2020-08-29 20:56:29 +02:00
}
}
2020-10-12 20:28:19 +02:00
setOutput(dotProd);
}
2020-10-29 05:16:50 +01:00
`}}class A8{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterHeight,n=e.filterWidth,s=e.strideHeight,i=e.strideWidth,o=t-1-e.padInfo.top,a=n-1-e.padInfo.left,c=e.outChannels/e.inChannels;this.userCode=`
2020-10-13 22:57:06 +02:00
const ivec2 pads = ivec2(${o}, ${a});
2020-10-12 20:28:19 +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-12 20:28:19 +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-12 20:28:19 +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-12 20:28:19 +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-12 20:28:19 +02:00
float xValue = getDy(batch, idyR, idyC, d2);
float wValue = getW(wRPerm, wCPerm, d1, dm);
dotProd += xValue * wValue;
}
}
2020-08-29 20:56:29 +02:00
}
2020-10-12 20:28:19 +02:00
setOutput(dotProd);
}
2020-10-29 05:16:50 +01:00
`}}class rC{constructor(e,t=!1,n=null,s=!1){this.variableNames=["x","W"],this.outputShape=e.outShape;const i=e.padInfo.top,o=e.padInfo.left,a=e.strideHeight,c=e.strideWidth,h=e.dilationHeight,d=e.dilationWidth,m=e.filterHeight,f=e.filterWidth,b=Math.floor(e.inChannels/4)*4,w=e.inChannels%4,L=e.dataFormat==="channelsLast",x=L?1:2,v=L?2:3,N=L?3:1;let O="",E="";n&&(s?O=`float activation(float a) {
2020-10-12 20:28:19 +02:00
float b = getPreluActivationWeightsAtOutCoords();
2020-10-13 22:57:06 +02:00
${n}
2020-10-29 05:16:50 +01:00
}`:O=`
2020-10-12 20:28:19 +02:00
float activation(float x) {
2020-10-13 22:57:06 +02:00
${n}
2020-10-12 20:28:19 +02:00
}
2020-10-29 05:16:50 +01:00
`,E="result = activation(result);");const k=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),s&&this.variableNames.push("preluActivationWeights"),this.userCode=`
${O}
2020-10-12 20:28:19 +02:00
2020-10-13 22:57:06 +02:00
const ivec2 strides = ivec2(${a}, ${c});
const ivec2 pads = ivec2(${i}, ${o});
2020-10-12 20:28:19 +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-12 20:28:19 +02:00
ivec2 xRCCorner =
2020-10-29 05:16:50 +01:00
ivec2(coords[${x}], coords[${v}]) * strides - pads;
2020-10-12 20:28:19 +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-12 20:28:19 +02:00
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
2020-08-29 20:56:29 +02:00
2020-10-29 05:16:50 +01:00
for (int wC = 0; wC < ${f}; wC++) {
2020-10-13 22:57:06 +02:00
int xC = xCCorner + wC * ${d};
2020-10-12 20:28:19 +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-12 20:28:19 +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-12 20:28:19 +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-12 20:28:19 +02:00
2020-10-13 22:57:06 +02:00
if (${L}) {
2020-10-12 20:28:19 +02:00
dotProd +=
2020-10-13 22:57:06 +02:00
getX(batch, xR, xC, ${b}) *
getW(wR, wC, ${b}, d2);
2020-10-12 20:28:19 +02:00
} else {
dotProd +=
2020-10-13 22:57:06 +02:00
getX(batch, ${b}, xR, xC) *
getW(wR, wC, ${b}, d2);
2020-10-12 20:28:19 +02:00
}
2020-10-13 22:57:06 +02:00
} else if (${w===2}) {
2020-10-12 20:28:19 +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-12 20:28:19 +02:00
);
2020-10-13 22:57:06 +02:00
if (${L}) {
2020-10-12 20:28:19 +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-12 20:28:19 +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-12 20:28:19 +02:00
);
dotProd += dot(xValues, wValues);
}
2020-10-13 22:57:06 +02:00
} else if (${w===3}) {
2020-10-12 20:28:19 +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-12 20:28:19 +02:00
);
2020-10-13 22:57:06 +02:00
if (${L}) {
2020-10-12 20:28:19 +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-12 20:28:19 +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-12 20:28:19 +02:00
);
dotProd += dot(xValues, wValues);
}
}
}
}
float result = dotProd;
2020-10-29 05:16:50 +01:00
${k}
${E}
2020-10-12 20:28:19 +02:00
setOutput(result);
2020-08-29 20:56:29 +02:00
}
2020-10-29 05:16:50 +01:00
`}}class v8{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;const t=e.padInfo.front,n=e.padInfo.top,s=e.padInfo.left,i=e.strideDepth,o=e.strideHeight,a=e.strideWidth,c=e.dilationDepth,h=e.dilationHeight,d=e.dilationWidth,m=e.filterDepth,f=e.filterHeight,b=e.filterWidth,w=Math.floor(e.inChannels/4)*4,L=e.inChannels%4;this.userCode=`
2020-10-13 22:57:06 +02:00
const ivec3 strides = ivec3(${i}, ${o}, ${a});
const ivec3 pads = ivec3(${t}, ${n}, ${s});
2020-10-12 20:28:19 +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-12 20:28:19 +02:00
if (xF < 0 || xF >= ${e.inDepth}) {
continue;
}
2020-08-29 20:56:29 +02:00
2020-10-29 05:16:50 +01:00
for (int wR = 0; wR < ${f}; wR++) {
2020-10-13 22:57:06 +02:00
int xR = xRCorner + wR * ${h};
2020-10-12 20:28:19 +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-12 20:28:19 +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-12 20:28:19 +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-12 20:28:19 +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-12 20:28:19 +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-12 20:28:19 +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-12 20:28:19 +02:00
);
dotProd += dot(xValues, wValues);
2020-10-13 22:57:06 +02:00
} else if (${L===3}) {
2020-10-12 20:28:19 +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-12 20:28:19 +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-12 20:28:19 +02:00
);
dotProd += dot(xValues, wValues);
}
}
}
}
setOutput(dotProd);
}
2020-10-29 05:16:50 +01:00
`}}class oC{constructor(e,t=!1,n=null,s=!1){this.variableNames=["x","W"],this.outputShape=e.outShape;const i=e.inHeight,o=e.inWidth,a=e.padInfo.top,c=e.padInfo.left,h=e.strideHeight,d=e.strideWidth,m=e.dilationHeight,f=e.dilationWidth,b=e.filterHeight,w=e.filterWidth,L=e.outChannels/e.inChannels;let x="",v="";n&&(s?x=`float activation(float a) {
2020-10-12 20:28:19 +02:00
float b = getPreluActivationWeightsAtOutCoords();
2020-10-13 22:57:06 +02:00
${n}
2020-10-29 05:16:50 +01:00
}`:x=`
2020-10-12 20:28:19 +02:00
float activation(float x) {
2020-10-13 22:57:06 +02:00
${n}
2020-10-12 20:28:19 +02:00
}
2020-10-29 05:16:50 +01:00
`,v="result = activation(result);");const N=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),s&&this.variableNames.push("preluActivationWeights"),this.userCode=`
${x}
2020-10-12 20:28:19 +02:00
2020-10-13 22:57:06 +02:00
const ivec2 strides = ivec2(${h}, ${d});
const ivec2 pads = ivec2(${a}, ${c});
2020-10-12 20:28:19 +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-12 20:28:19 +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-12 20:28:19 +02:00
if (xR < 0 || xR >= ${i}) {
continue;
}
2020-08-29 20:56:29 +02:00
2020-10-13 22:57:06 +02:00
for (int wC = 0; wC < ${w}; wC++) {
2020-10-29 05:16:50 +01:00
int xC = xCCorner + wC * ${f};
2020-08-29 20:56:29 +02:00
2020-10-13 22:57:06 +02:00
if (xC < 0 || xC >= ${o}) {
2020-10-12 20:28:19 +02:00
continue;
}
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
float xVal = getX(batch, xR, xC, d1);
float wVal = getW(wR, wC, d1, q);
dotProd += xVal * wVal;
}
}
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
float result = dotProd;
2020-10-13 22:57:06 +02:00
${N}
2020-10-29 05:16:50 +01:00
${v}
2020-10-12 20:28:19 +02:00
setOutput(result);
}
2020-10-29 05:16:50 +01:00
`}}class aC{constructor(e,t=!1,n=null,s=!1){this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e.outShape;const i=e.inHeight,o=e.inWidth,a=e.padInfo.top,c=e.padInfo.left,h=e.strideHeight,d=e.strideWidth,m=e.dilationHeight,f=e.dilationWidth,b=e.filterHeight,w=e.filterWidth,L=w;let x="int xR; int xC; int xCOffset;";for(let E=0;E<b;E++)for(let k=0;k<w;k++)x+=`
vec4 xTexelR${E}C${k*2} = vec4(0.);
vec4 wR${E}C${k} = vec4(0.);
vec4 xR${E}C${k} = vec4(0.);`;for(let E=0;E<b;E++)for(let k=0;k<L;k++){const F=k*2;if(x+=`
xR = xRCorner + ${E*m};
xC = xCCorner + ${F*f};
`,d===1){if(F<w&&(c%2===1?x+=`
2020-10-12 20:28:19 +02:00
xCOffset = xC + 1;
2020-10-13 22:57:06 +02:00
if(xR >= 0 && xR < ${i} && xCOffset >= 0 && xCOffset < ${o}) {
2020-10-29 05:16:50 +01:00
xTexelR${E}C${F} = getX(batch, xR, xCOffset, d1);
2020-10-12 20:28:19 +02:00
// Need to manually clear unused channels in case
// we're reading from recycled texture.
2020-10-13 22:57:06 +02:00
if(xCOffset + 1 >= ${o}) {
2020-10-29 05:16:50 +01:00
xTexelR${E}C${F}.zw = vec2(0.);
2020-10-12 20:28:19 +02:00
}
} else {
2020-10-29 05:16:50 +01:00
xTexelR${E}C${F} = vec4(0.);
2020-10-12 20:28:19 +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-12 20:28:19 +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-12 20:28:19 +02:00
previous.zw = vec2(0.);
}
2020-10-29 05:16:50 +01:00
xR${E}C${F} = vec4(previous.zw, xTexelR${E}C${F}.xy);
2020-10-12 20:28:19 +02:00
} else {
2020-10-29 05:16:50 +01:00
xR${E}C${F} = vec4(0, 0, xTexelR${E}C${F}.xy);
2020-10-12 20:28:19 +02:00
}
2020-10-29 05:16:50 +01:00
`:x+=`
2020-10-13 22:57:06 +02:00
if(xR >= 0 && xR < ${i} && xC >= 0 && xC < ${o}) {
2020-10-29 05:16:50 +01:00
xTexelR${E}C${F} = getX(batch, xR, xC, d1);
2020-10-12 20:28:19 +02:00
} else {
2020-10-29 05:16:50 +01:00
xTexelR${E}C${F} = vec4(0.);
2020-10-12 20:28:19 +02:00
}
2020-10-29 05:16:50 +01:00
xR${E}C${F} = xTexelR${E}C${F};
`,F+1<w)){const U=c%2===0?T(f):f;f%2===0&&c%2===1||f%2!==0&&c%2!==1?(x+=`
xCOffset = xC + ${c%2} + ${U};
2020-10-12 20:28:19 +02:00
if(xR >= 0 && xR < ${i} &&
2020-10-13 22:57:06 +02:00
xCOffset >= 0 && xCOffset < ${o}) {
2020-10-29 05:16:50 +01:00
xTexelR${E}C${F+2} = getX(batch, xR, xCOffset, d1);
2020-10-12 20:28:19 +02:00
}
2020-10-29 05:16:50 +01:00
`,f>1&&(x+=`
2020-10-12 20:28:19 +02:00
xCOffset -= 2;
if(xR >= 0 && xR < ${i} &&
2020-10-13 22:57:06 +02:00
xCOffset >= 0 && xCOffset < ${o}) {
2020-10-29 05:16:50 +01:00
xTexelR${E}C${F} = getX(batch, xR, xCOffset, d1);
2020-10-12 20:28:19 +02:00
} else {
2020-10-29 05:16:50 +01:00
xTexelR${E}C${F} = vec4(0.);
2020-10-12 20:28:19 +02:00
}
2020-10-29 05:16:50 +01:00
`),x+=`
xR${E}C${F+1} = vec4(
xTexelR${E}C${F}.zw, xTexelR${E}C${F+2}.xy);
`):x+=`
xCOffset = xC + ${U};
2020-10-12 20:28:19 +02:00
if(xR >= 0 && xR < ${i} &&
2020-10-13 22:57:06 +02:00
xCOffset >= 0 && xCOffset < ${o}) {
2020-10-29 05:16:50 +01:00
xTexelR${E}C${F+2} = getX(batch, xR, xCOffset, d1);
2020-10-12 20:28:19 +02:00
}
2020-10-29 05:16:50 +01:00
xR${E}C${F+1} = xTexelR${E}C${F+2};
`}}else F<w&&(x+=`
2020-10-12 20:28:19 +02:00
if(xR >= 0 && xR < ${i}) {
2020-10-29 05:16:50 +01:00
`,c%2===1?(x+=`
2020-10-13 22:57:06 +02:00
xCOffset = xC + 1 - ${d};
if(xCOffset >= 0 && xCOffset < ${o}) {
2020-10-29 05:16:50 +01:00
xTexelR${E}C${F} = getX(batch, xR, xCOffset, d1);
2020-10-12 20:28:19 +02:00
} else {
2020-10-29 05:16:50 +01:00
xTexelR${E}C${F} = vec4(0.);
2020-10-12 20:28:19 +02:00
}
2020-10-13 22:57:06 +02:00
if(xC + 1 >= 0 && xC + 1 < ${o}) {
2020-10-29 05:16:50 +01:00
xTexelR${E}C${F+2} = getX(batch, xR, xC + 1, d1);
2020-10-12 20:28:19 +02:00
} else {
2020-10-29 05:16:50 +01:00
xTexelR${E}C${F+2} = vec4(0.);
2020-10-12 20:28:19 +02:00
}
2020-10-29 05:16:50 +01:00
xR${E}C${F} = vec4(
xTexelR${E}C${F}.zw, xTexelR${E}C${F+2}.zw);
`,F+1<w&&(x+=`
2020-10-12 20:28:19 +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-12 20:28:19 +02:00
final = getX(batch, xR, xCOffset, d1);
}
2020-10-29 05:16:50 +01:00
xR${E}C${F+1} = vec4(xTexelR${E}C${F+2}.xy, final.xy);
`)):(x+=`
2020-10-13 22:57:06 +02:00
if(xC >= 0 && xC < ${o}) {
2020-10-29 05:16:50 +01:00
xTexelR${E}C${F} = getX(batch, xR, xC, d1);
2020-10-12 20:28:19 +02:00
} else {
2020-10-29 05:16:50 +01:00
xTexelR${E}C${F} = vec4(0.);
2020-10-12 20:28:19 +02:00
}
2020-10-13 22:57:06 +02:00
xCOffset = xC + ${d};
if(xCOffset >= 0 && xCOffset < ${o}) {
2020-10-29 05:16:50 +01:00
xTexelR${E}C${F+2} = getX(batch, xR, xCOffset, d1);
2020-10-12 20:28:19 +02:00
} else {
2020-10-29 05:16:50 +01:00
xTexelR${E}C${F+2} = vec4(0.);
2020-10-12 20:28:19 +02:00
}
2020-10-29 05:16:50 +01:00
xR${E}C${F} = vec4(
xTexelR${E}C${F}.xy, xTexelR${E}C${F+2}.xy);
`,F+1<w&&(x+=`
xR${E}C${F+1} = vec4(
xTexelR${E}C${F}.zw, xTexelR${E}C${F+2}.zw);
`)),x+="}");F<w&&(x+=`
vec4 wTexelR${E}C${F} = getW(${E}, ${F}, d1, q);
wR${E}C${F} = vec4(wTexelR${E}C${F}.xz, wTexelR${E}C${F}.xz);
`,F+1<w&&(x+=`
vec4 wTexelR${E}C${F+1} = getW(${E}, ${F+1}, d1, q);
wR${E}C${F+1} =
vec4(wTexelR${E}C${F+1}.xz, wTexelR${E}C${F+1}.xz);`))}for(let E=0;E<b;E++)for(let k=0;k<w;k++)x+=`dotProd += xR${E}C${k} * wR${E}C${k};`;let v="",N="";n&&(s?v=`vec4 activation(vec4 a) {
2020-10-12 20:28:19 +02:00
vec4 b = getPreluActivationWeightsAtOutCoords();
2020-10-13 22:57:06 +02:00
${n}
2020-10-29 05:16:50 +01:00
}`:v=`vec4 activation(vec4 x) {
2020-10-13 22:57:06 +02:00
${n}
2020-10-29 05:16:50 +01:00
}`,N="result = activation(result);");const O=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),s&&this.variableNames.push("preluActivationWeights"),this.userCode=`
${v}
2020-10-12 20:28:19 +02:00
2020-10-13 22:57:06 +02:00
const ivec2 strides = ivec2(${h}, ${d});
const ivec2 pads = ivec2(${a}, ${c});
2020-10-12 20:28:19 +02:00
void main() {
ivec4 coords = getOutputCoords();
int batch = coords.x;
ivec2 xRCCorner = coords.yz * strides - pads;
int d2 = coords.w;
int d1 = d2;
int q = 0;
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
vec4 dotProd = vec4(0.);
2020-10-29 05:16:50 +01:00
${x}
2020-10-12 20:28:19 +02:00
vec4 result = dotProd;
2020-10-29 05:16:50 +01:00
${O}
2020-10-13 22:57:06 +02:00
${N}
2020-10-12 20:28:19 +02:00
setOutput(result);
}
2020-10-29 05:16:50 +01:00
`}}class N8{constructor(e,t,n,s,i){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];const[o,a,c,h]=e,[d]=t,[m,f]=n;this.outputShape=[d,m,f,h];const b=s==="bilinear"?1:0,[w,L]=[`${a-1}.0`,`${c-1}.0`],[x,v,N]=m>1?[`${(a-1)/(m-1)}`,"(y2-y1) * height_ratio",`y1*${w} + float(y)*(height_scale)`]:["0.0","0.0",`0.5 * (y1+y2) * ${w}`],[O,E,k]=f>1?[`${(c-1)/(f-1)}`,"(x2-x1) * width_ratio",`x1*${L} + float(x)*(width_scale)`]:["0.0","0.0",`0.5 * (x1+x2) * ${L}`];this.userCode=`
const float height_ratio = float(${x});
const float width_ratio = float(${O});
2020-10-12 20:28:19 +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-12 20:28:19 +02:00
return;
}
2020-08-29 20:56:29 +02:00
2020-10-29 05:16:50 +01:00
float height_scale = ${v};
float width_scale = ${E};
2020-08-29 20:56:29 +02:00
2020-10-13 22:57:06 +02:00
float in_y = ${N};
if( in_y < 0.0 || in_y > ${w} ) {
2020-10-12 20:28:19 +02:00
setOutput(float(${i}));
return;
}
2020-10-29 05:16:50 +01:00
float in_x = ${k};
2020-10-13 22:57:06 +02:00
if( in_x < 0.0 || in_x > ${L} ) {
2020-10-12 20:28:19 +02:00
setOutput(float(${i}));
return;
}
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
vec2 sourceFracIndexCR = vec2(in_x,in_y);
2020-10-13 22:57:06 +02:00
if(${b} == 1) {
2020-10-12 20:28:19 +02:00
// Compute the four integer indices.
ivec2 sourceFloorCR = ivec2(sourceFracIndexCR);
ivec2 sourceCeilCR = ivec2(ceil(sourceFracIndexCR));
float topLeft = getImage(b, sourceFloorCR.y, sourceFloorCR.x, d);
float bottomLeft = getImage(b, sourceCeilCR.y, sourceFloorCR.x, d);
float topRight = getImage(b, sourceFloorCR.y, sourceCeilCR.x, d);
float bottomRight = getImage(b, sourceCeilCR.y, sourceCeilCR.x, d);
vec2 fracCR = sourceFracIndexCR - vec2(sourceFloorCR);
float top = topLeft + (topRight - topLeft) * fracCR.x;
float bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x;
float newValue = top + (bottom - top) * fracCR.y;
setOutput(newValue);
} else {
// Compute the coordinators of nearest neighbor point.
ivec2 sourceNearestCR = ivec2(floor(
sourceFracIndexCR + vec2(0.5,0.5)));
float newValue = getImage(b, sourceNearestCR.y, sourceNearestCR.x, d);
setOutput(newValue);
}
}
2020-10-29 05:16:50 +01:00
`}}class cC{constructor(e,t,n){this.variableNames=["x"],this.outputShape=e;const s=e.length,i=t?"0.0":`getX(${lC(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-12 20:28:19 +02:00
uniform float index;
void main() {
2020-10-29 05:16:50 +01:00
${Rt(s)} coords = getOutputCoords();
int end = ${hC(s,"coords")};
2020-10-12 20:28:19 +02:00
float val = ${i};
int pow2 = int(pow(2.0, index));
2020-10-13 22:57:06 +02:00
if (${a}) {
int idx = ${c};
2020-10-29 05:16:50 +01:00
${hC(s,"coords")} = idx;
val += getX(${lC(s,"coords")});
2020-10-12 20:28:19 +02:00
}
setOutput(val);
}
2020-10-29 05:16:50 +01:00
`}getCustomSetupFunc(e){return(t,n)=>{this.index==null&&(this.index=t.getUniformLocation(n,"index")),t.gl.uniform1f(this.index,e)}}}function lC(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 hC(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 C8{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=lu.DENSE;const t=uu(e),n=Pn();this.outputShape=e,this.userCode=`
2020-10-12 20:28:19 +02:00
ivec3 outCoordsFromFlatIndex(int index) {
2020-10-29 05:16:50 +01:00
${Yo(["r","c","d"],e)}
2020-10-12 20:28:19 +02:00
return ivec3(r, c, d);
}
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
void main() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = 4 * (resTexRC.x * ${t[1]} + resTexRC.y);
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
vec4 result = vec4(0.);
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
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-08-29 20:56:29 +02:00
2020-10-13 22:57:06 +02:00
${n.output} = result;
2020-10-12 20:28:19 +02:00
}
2020-10-29 05:16:50 +01:00
`}}class R8{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=lu.DENSE;const t=uu(e),n=Pn();this.outputShape=e,this.userCode=`
2020-10-12 20:28:19 +02:00
ivec3 outCoordsFromFlatIndex(int index) {
2020-10-29 05:16:50 +01:00
${Yo(["r","c","d"],e)}
2020-10-12 20:28:19 +02:00
return ivec3(r, c, d);
}
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
void main() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = 4 * (resTexRC.x * ${t[1]} + resTexRC.y);
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
vec4 result = vec4(0.);
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
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-08-29 20:56:29 +02:00
2020-10-13 22:57:06 +02:00
${n.output} = result;
2020-10-12 20:28:19 +02:00
}
2020-10-29 05:16:50 +01:00
`}}class O8{constructor(e,t,n){this.variableNames=["x"],this.outputShape=[],this.outputShape=e,this.blockSize=t,this.dataFormat=n,this.userCode=`
2020-10-12 20:28:19 +02:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int h = ${this.getHeightCoordString()};
int w = ${this.getWidthCoordString()};
int d = ${this.getDepthCoordString()};
int in_h = h / ${t};
int offset_h = imod(h, ${t});
int in_w = w / ${t};
int offset_w = imod(w, ${t});
int offset_d = (offset_h * ${t} + offset_w) *
${this.getOutputDepthSize()};
int in_d = d + offset_d;
float result = ${this.getInputSamplingString()};
setOutput(result);
}
2020-10-29 05:16:50 +01:00
`}getHeightCoordString(){return this.dataFormat==="NHWC"?"coords[1]":"coords[2]"}getWidthCoordString(){return this.dataFormat==="NHWC"?"coords[2]":"coords[3]"}getDepthCoordString(){return this.dataFormat==="NHWC"?"coords[3]":"coords[1]"}getOutputDepthSize(){return this.dataFormat==="NHWC"?this.outputShape[3]:this.outputShape[1]}getInputSamplingString(){return this.dataFormat==="NHWC"?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"}}class E8{constructor(e){this.variableNames=["X"],this.outputShape=[e,e],this.userCode=`
2020-10-12 20:28:19 +02:00
void main() {
ivec2 coords = getOutputCoords();
float val = coords[0] == coords[1] ? getX(coords[0]) : 0.0;
setOutput(val);
}
2020-10-29 05:16:50 +01:00
`}}class D8{constructor(e){this.variableNames=["A"],this.outTexUsage=Ns.DOWNLOAD;const t=Pn();this.outputShape=e,this.userCode=`
${Z0}
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
void main() {
float x = getAAtOutCoords();
${t.output} = encode_float(x);
}
2020-10-29 05:16:50 +01:00
`}}class k8{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=Ns.DOWNLOAD;const t=Pn();this.outputShape=e,this.userCode=`
${Z0}
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
void main() {
ivec3 coords = getOutputCoords();
float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));
${t.output} = encode_float(x);
}
2020-10-29 05:16:50 +01:00
`}}class F8{constructor(e,t,n=!1){this.variableNames=["A"];const s=Pn(),[i,o]=t;this.outputShape=e;let a="result";n&&(a="floor(result * 255. + 0.5)"),this.userCode=`
${IS(e)}
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
void main() {
ivec3 coords = getOutputCoords();
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
int flatIndex = getFlatIndex(coords);
int offset = imod(flatIndex, 4);
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
flatIndex = idiv(flatIndex, 4, 1.);
2020-08-29 20:56:29 +02:00
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-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
float result;
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
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-08-29 20:56:29 +02:00
2020-10-13 22:57:06 +02:00
${s.output} = vec4(${a}, 0., 0., 0.);
2020-10-12 20:28:19 +02:00
}
2020-10-29 05:16:50 +01:00
`}}class _8{constructor(e,t,n=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;const s=Pn(),[i,o]=t;this.outputShape=e;let a="",c="result";n&&(c="floor(result * 255. + 0.5)");for(let h=0;h<=1;h++)for(let d=0;d<=1;d++){const m=h*2+d;a+=`
2020-10-12 20:28:19 +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-12 20:28:19 +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-12 20:28:19 +02:00
if(offset == 0) {
2020-10-13 22:57:06 +02:00
result[${m}] = values[0];
2020-10-12 20:28:19 +02:00
} else if(offset == 1) {
2020-10-13 22:57:06 +02:00
result[${m}] = values[1];
2020-10-12 20:28:19 +02:00
} else if(offset == 2) {
2020-10-13 22:57:06 +02:00
result[${m}] = values[2];
2020-10-12 20:28:19 +02:00
} else {
2020-10-13 22:57:06 +02:00
result[${m}] = values[3];
2020-10-12 20:28:19 +02:00
}
}
}
`}this.userCode=`
2020-10-29 05:16:50 +01:00
${IS(e)}
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
void main() {
ivec3 coords = getOutputCoords();
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
vec4 result = vec4(0.);
int flatIndex, r, c, offset;
ivec3 localCoords;
vec2 uv;
vec4 values;
2020-08-29 20:56:29 +02:00
2020-10-13 22:57:06 +02:00
${a}
2020-08-29 20:56:29 +02:00
2020-10-13 22:57:06 +02:00
${s.output} = ${c};
2020-10-12 20:28:19 +02:00
}
2020-10-29 05:16:50 +01:00
`}}class W8{constructor(e,t){this.outputShape=[],this.variableNames=["x"],this.outputShape=e,this.userCode=`
2020-10-12 20:28:19 +02:00
uniform float value;
void main() {
// Input can be obtained from uniform value.
setOutput(value);
}
2020-10-29 05:16:50 +01:00
`}getCustomSetupFunc(e){return(t,n)=>{this.valueLoc==null&&(this.valueLoc=t.getUniformLocationNoThrow(n,"value")),t.gl.uniform1f(this.valueLoc,e)}}}class $8{constructor(e,t,n){this.variableNames=["A","indices"];const s=e.slice();s[n]=t,this.outputShape=s,this.rank=s.length;const i=Rt(this.rank),o=U8(e,n);this.userCode=`
2020-10-12 20:28:19 +02:00
void main() {
${i} resRC = getOutputCoords();
2020-10-13 22:57:06 +02:00
setOutput(getA(${o}));
2020-10-12 20:28:19 +02:00
}
2020-10-29 05:16:50 +01:00
`}}function U8(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 B8{constructor(e,t,n){this.sliceDim=e,this.strides=t,this.variableNames=["x","indices"],this.outputShape=n;const s=Rt(t.length),i=Rt(n.length),o=this.sliceDim>1?"strides[j]":"strides";this.userCode=`
2020-10-13 22:57:06 +02:00
${s} strides = ${s}(${this.strides});
2020-10-12 20:28:19 +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-12 20:28:19 +02:00
}
setOutput(getX(flattenIndex, coords[1]));
}
2020-10-29 05:16:50 +01:00
`}}function M8(e){const t=Pn(),n=`${t.version}
2020-10-12 20:28:19 +02:00
precision highp float;
${t.attribute} vec3 clipSpacePos;
${t.attribute} vec2 uv;
${t.varyingVs} vec2 resultUV;
void main() {
gl_Position = vec4(clipSpacePos, 1);
resultUV = uv;
2020-10-29 05:16:50 +01:00
}`;return wK(e,n)}function P8(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 AK(e,t)}function z8(e){const t=new Uint16Array([0,1,2,2,1,3]);return vK(e,t)}function pu(e,t,n,s,i,o){CK(t,n);const a=NK(e),c=e.TEXTURE_2D;return Ee(e,()=>e.bindTexture(c,a)),Ee(e,()=>e.texParameteri(c,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE)),Ee(e,()=>e.texParameteri(c,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)),Ee(e,()=>e.texParameteri(c,e.TEXTURE_MIN_FILTER,e.NEAREST)),Ee(e,()=>e.texParameteri(c,e.TEXTURE_MAG_FILTER,e.NEAREST)),Ee(e,()=>e.texImage2D(c,0,s,t,n,0,i,o,null)),Ee(e,()=>e.bindTexture(e.TEXTURE_2D,null)),a}function uC(e){return e.internalFormatFloat}function V8(e,t,n,s){const[i,o]=hu(t,n);return pu(e,i,o,uC(s),s.textureFormatFloat,e.FLOAT)}function dC(e){return e.internalFormatHalfFloat}function G8(e,t,n,s){const[i,o]=hu(t,n);return pu(e,i,o,dC(s),s.textureFormatFloat,s.textureTypeHalfFloat)}function pC(e){return e.downloadTextureFormat}function Y8(e,t,n,s){const[i,o]=hu(t,n);return pu(e,i,o,pC(s),e.RGBA,e.UNSIGNED_BYTE)}function mC(e){return e.internalFormatPackedFloat}function H8(e,t,n,s){const[i,o]=pc(t,n);return pu(e,i,o,mC(s),e.RGBA,e.FLOAT)}function fC(e){return e.internalFormatPackedHalfFloat}function q8(e,t,n,s){const[i,o]=pc(t,n);return pu(e,i,o,fC(s),e.RGBA,s.textureTypeHalfFloat)}function j8(e,t,n){const s=0,i=3*4,o=3*4+2*4;Ee(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n));const a=q0(e,t,"clipSpacePos",n,3,o,s);return a&&q0(e,t,"uv",n,2,o,i)}function K8(e,t,n,s,i,o){Ee(e,()=>e.bindTexture(e.TEXTURE_2D,t));let a,c,h;i instanceof Uint8Array?(a=new Uint8Array(n*s*4),c=e.UNSIGNED_BYTE,h=e.RGBA):(a=new Float32Array(n*s*4),c=e.FLOAT,h=o.internalFormatPackedFloat),a.set(i),Ee(e,()=>e.texImage2D(e.TEXTURE_2D,0,h,n,s,0,e.RGBA,c,a)),Ee(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function X8(e,t,n){Ee(e,()=>e.bindTexture(e.TEXTURE_2D,t)),n.data instanceof Uint8Array?Ee(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,n.width,n.height,0,e.RGBA,e.UNSIGNED_BYTE,n.data)):Ee(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,n)),Ee(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function J8(e,t,n,s){const i=e.createBuffer();Ee(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,i));const o=4,a=4,c=o*a*t*n;return Ee(e,()=>e.bufferData(e.PIXEL_PACK_BUFFER,c,e.STREAM_READ)),Ee(e,()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,0)),Ee(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,null)),i}function Z8(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 Q8(e,t,n,s){const[i,o]=hu(t,n),a=4,c=new Uint8Array(dK(t*n,a));return Ee(e,()=>e.readPixels(0,0,i,o,s.downloadTextureFormat,e.UNSIGNED_BYTE,c)),new Float32Array(c.buffer)}function e6(e,t,n,s,i,o,a,c){const h=e,d=new Float32Array(pK(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 t6(e,t,n){const s=new Float32Array(t*n*4);return Ee(e,()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,s)),s}class n6{constructor(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];const t=oe().getNumber("WEBGL_VERSION");e!=null?(this.gl=e,lK(t,e)):this.gl=ki(t);let n="WEBGL_color_buffer_float";const s="EXT_color_buffer_half_float";if(oe().getNumber("WEBGL_VERSION")===1){const i="OES_texture_float",o="OES_texture_half_float";if(this.textureFloatExtension=vm(this.gl,i),Vs(this.gl,o))this.textureHalfFloatExtension=vm(this.gl,o);else if(oe().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support half float textures, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.");if(this.colorBufferFloatExtension=this.gl.getExtension(n),Vs(this.gl,s))this.colorBufferHalfFloatExtension=vm(this.gl,s);else if(oe().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support color renderable half floats, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.")}else if(n="EXT_color_buffer_float",Vs(this.gl,n))this.colorBufferFloatExt
blockIndex = rc.y + ${F};
pos = rc.x + ${k};
2020-10-12 20:28:19 +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-12 20:28:19 +02:00
2020-10-13 22:57:06 +02:00
if(d0 < ${t[N]} && d0 >= 0) {
2020-10-12 20:28:19 +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-12 20:28:19 +02:00
2020-10-29 05:16:50 +01:00
if(d1 < ${t[O]} && d1 >= 0) {
2020-10-12 20:28:19 +02:00
ch = int(mod(float(pos), ${i}.));
2020-10-29 05:16:50 +01:00
if (${v}) {
2020-10-12 20:28:19 +02:00
innerDims = vec2(d1, ch);
2020-10-29 05:16:50 +01:00
result[${k*2+F}] = getChannel(
2020-10-12 20:28:19 +02:00
getA(d0, int(innerDims.x),
int(innerDims.y)), innerDims);
} else {
innerDims = vec2(d0, d1);
2020-10-29 05:16:50 +01:00
result[${k*2+F}] = getChannel(
2020-10-12 20:28:19 +02:00
getA(ch, int(innerDims.x),
int(innerDims.y)), innerDims);
}
}
}
}
`;this.userCode=`
void main() {
ivec2 rc = getOutputCoords();
vec4 result = vec4(0);
int blockIndex, pos, offsetY, d0, offsetX, d1, ch;
vec2 innerDims;
2020-10-29 05:16:50 +01:00
${E}
2020-10-12 20:28:19 +02:00
2020-10-29 05:16:50 +01:00
${x.output} = result;
2020-10-12 20:28:19 +02:00
}
2020-10-29 05:16:50 +01:00
`}}class c6{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-12 20:28:19 +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-12 20:28:19 +02:00
int idx = d + j;
2020-10-13 22:57:06 +02:00
if (idx >= 0 && idx <= ${a}) {
2020-10-12 20:28:19 +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-12 20:28:19 +02:00
setOutput(val);
}
2020-10-29 05:16:50 +01:00
`}}class l6{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-12 20:28:19 +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-12 20:28:19 +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-12 20:28:19 +02:00
* float(${i})
* getInputImage(b ,r ,c, k) * getOutputImage(b, r, c, d)
/ norm;
if (k == d) {
dyi += pow(norm, -1.0 * ${i});
}
if (k == coords[3]) {
dyi *= getDy(b, r, c, d);
result += dyi;
}
}
else {
break;
}
}
}
setOutput(result);
}
2020-10-29 05:16:50 +01:00
`}}class h6{constructor(e,t,n,s,i){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;const o=t,a=e[3]-1;this.outputShape=e;let c;const h=`float(${n}) + float(${s}) * sum`;i===.5?c=`inversesqrt(${h})`:i===1?c=`1.0/(${h})`:c=`exp(log(${h}) * float(-${i}));`,this.userCode=`
2020-10-12 20:28:19 +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-12 20:28:19 +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));
}
}
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
ivec2 depth = ivec2(d, d + 1);
2020-10-13 22:57:06 +02:00
for (int j = - ${o}; j <= ${o}; j++) {
2020-10-12 20:28:19 +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-12 20:28:19 +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-12 20:28:19 +02:00
setOutput(result);
}
2020-10-29 05:16:50 +01:00
`}}class u6{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;const t=e.strideHeight,n=e.strideWidth,s=e.dilationHeight,i=e.effectiveFilterHeight,o=e.effectiveFilterWidth,a=i-1-e.padInfo.top,c=o-1-e.padInfo.left,h=i*o-1;this.userCode=`
2020-10-13 22:57:06 +02:00
const ivec2 pads = ivec2(${a}, ${c});
2020-10-12 20:28:19 +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-12 20:28:19 +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-08-29 20:56:29 +02:00
2020-10-13 22:57:06 +02:00
for (int wC = 0; wC < ${o}; wC++) {
float dyC = float(dyCCorner + wC) / ${n}.0;
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
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-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +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-12 20:28:19 +02:00
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
dotProd += dyValue * mask;
}
}
setOutput(dotProd);
}
2020-10-29 05:16:50 +01:00
`}}class d6{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;const t=e.strideDepth,n=e.strideHeight,s=e.strideWidth,i=e.dilationDepth,o=e.dilationHeight,a=e.dilationWidth,c=e.effectiveFilterDepth,h=e.effectiveFilterHeight,d=e.effectiveFilterWidth,m=c-1-e.padInfo.front,f=h-1-e.padInfo.top,b=d-1-e.padInfo.left,w=c*h*d-1;this.userCode=`
const ivec3 pads = ivec3(${m}, ${f}, ${b});
2020-10-12 20:28:19 +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-12 20:28:19 +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-12 20:28:19 +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-12 20:28:19 +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-12 20:28:19 +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-12 20:28:19 +02:00
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
dotProd += dyValue * mask;
}
}
}
setOutput(dotProd);
}
2020-10-29 05:16:50 +01:00
`}}class xS{constructor(e,t,n,s=!1,i=!1,o=!1,a=null,c=!1){this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=n;const h=s?e[1]:e[2],d=Math.ceil(h/2),m=s?"i * 2, rc.y":"rc.y, i * 2",f=i?"rc.z, i * 2":"i * 2, rc.z",b=s?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],w=i?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"];let L="",x="";a&&(c?L=`vec4 activation(vec4 a) {
2020-10-12 20:28:19 +02:00
vec4 b = getPreluActivationWeightsAtOutCoords();
2020-10-29 05:16:50 +01:00
${a}
}`:L=`vec4 activation(vec4 x) {
${a}
}`,x="result = activation(result);");const v=o?"result += getBiasAtOutCoords();":"";o&&this.variableNames.push("bias"),c&&this.variableNames.push("preluActivationWeights");let N="rc.x",O="rc.x";e[0]<t[0]?N=`int(min(float(rc.x), ${e[0]-1}.))`:t[0]<e[0]&&(O=`int(min(float(rc.x), ${t[0]-1}.))`),this.userCode=`
${L}
2020-10-12 20:28:19 +02:00
2020-10-29 05:16:50 +01:00
const float sharedDimension = ${d}.0;
2020-10-12 20:28:19 +02:00
vec4 dot2x2ARowBCol(ivec3 rc) {
vec4 result = vec4(0);
2020-10-29 05:16:50 +01:00
for (int i = 0; i < ${d}; i++) {
int batchA = ${N};
int batchB = ${O};
vec4 a = getMatrixA(batchA, ${m});
vec4 b = getMatrixB(batchB, ${f});
2020-10-12 20:28:19 +02:00
// These swizzled products need to be separately added.
// See: https://github.com/tensorflow/tfjs/issues/1735
2020-10-29 05:16:50 +01:00
result += (${b[0]} * ${w[0]});
result += (${b[1]} * ${w[1]});
2020-10-12 20:28:19 +02:00
}
return result;
}
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
void main() {
ivec3 rc = getOutputCoords();
vec4 result = dot2x2ARowBCol(rc);
2020-08-29 20:56:29 +02:00
2020-10-29 05:16:50 +01:00
${v}
2020-08-29 20:56:29 +02:00
2020-10-29 05:16:50 +01:00
${x}
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
setOutput(result);
}
2020-10-29 05:16:50 +01:00
`}}class p6{constructor(e,t,n){this.variableNames=["probs"],this.outputShape=[e,n],this.userCode=`
2020-10-12 20:28:19 +02:00
uniform float seed;
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
float r = random(seed);
float cdf = 0.0;
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
for (int i = 0; i < ${t-1}; i++) {
cdf += getProbs(batch, i);
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
if (r < cdf) {
setOutput(float(i));
return;
}
}
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
// If no other event happened, last event happened.
setOutput(float(${t-1}));
}
2020-10-29 05:16:50 +01:00
`}getCustomSetupFunc(e){return(t,n)=>{this.seedLoc==null&&(this.seedLoc=t.getUniformLocation(n,"seed")),t.gl.uniform1f(this.seedLoc,e)}}}class m6{constructor(e,t,n,s){this.variableNames=["indices"],this.outputShape=[e,t],this.userCode=`
2020-10-12 20:28:19 +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-12 20:28:19 +02:00
float(index == coords.y)));
}
2020-10-29 05:16:50 +01:00
`}}class f6{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-12 20:28:19 +02:00
void main() {
setOutput(vec4(getA(), 0., 0., 0.));
}
2020-10-29 05:16:50 +01:00
`;else{const n=Mn("rc",t),s=Rt(t),i=y6(t,e,n),o=b6(t,e[e.length-1],e[e.length-2],n),a=w6(e,n);this.userCode=`
2020-10-12 20:28:19 +02:00
void main() {
2020-10-13 22:57:06 +02:00
${s} rc = getOutputCoords();
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
if(${i}) {
setOutput(vec4(0));
} else {
2020-10-13 22:57:06 +02:00
${o}
2020-08-29 20:56:29 +02:00
2020-10-13 22:57:06 +02:00
setOutput(vec4(${a}));
2020-10-12 20:28:19 +02:00
}
}
2020-10-29 05:16:50 +01:00
`}}}function g6(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 y6(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 b6(e,t,n,s){if(e===1)return"";const i=s.slice(-2);return`
2020-10-12 20:28:19 +02:00
int r = ${i[0]};
int c = ${i[1]};
int rp1 = r + 1;
int cp1 = c + 1;
bool cEdge = cp1 >= ${t};
2020-10-13 22:57:06 +02:00
bool rEdge = rp1 >= ${n};
2020-10-29 05:16:50 +01:00
`}function w6(e,t){const n=e.length,s=g6(n,t);return n===1?`getA(rc),
2020-10-12 20:28:19 +02:00
rc + 1 >= ${e[0]} ? 0. : getA(rc + 1),
2020-10-13 22:57:06 +02:00
0, 0`:`getA(${s[0]}),
cEdge ? 0. : getA(${s[1]}),
rEdge ? 0. : getA(${s[2]}),
2020-10-29 05:16:50 +01:00
rEdge || cEdge ? 0. : getA(${s[3]})`}class L6{constructor(e,t,n){this.variableNames=["x"],this.outputShape=t.map((h,d)=>h[0]+e[d]+h[1]);const s=e.length,i=Rt(s),o=t.map(h=>h[0]).join(","),a=t.map((h,d)=>h[0]+e[d]).join(","),c=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,s);if(s===1){this.userCode=`
2020-10-13 22:57:06 +02:00
int start = ${o};
int end = ${a};
2020-10-12 20:28:19 +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-12 20:28:19 +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-12 20:28:19 +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-12 20:28:19 +02:00
} else {
${i} coords = outC - start;
2020-10-13 22:57:06 +02:00
setOutput(getX(${c}));
2020-10-12 20:28:19 +02:00
}
}
2020-10-29 05:16:50 +01:00
`}}class S6{constructor(e,t,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.map((L,x)=>L[0]+e[x]+L[1]);const s=e.length,i=Rt(s),o=t.map(L=>L[0]).join(","),a=t.map((L,x)=>L[0]+e[x]).join(","),c=Mn("rc",s),h=Mn("source",s),d=`${c[s-1]} < ${this.outputShape[s-1]}`,m=s===1?"source":`vec2(${h.slice(-2).join()})`,f=[`${i} rc = outputLoc;`,`${c[s-1]} += 1;
2020-10-13 22:57:06 +02:00
if(${d}) {
`,s===1?"":`}
2020-10-12 20:28:19 +02:00
rc = outputLoc;
2020-10-13 22:57:06 +02:00
${c[s-2]} += 1;
if(${c[s-2]} < ${this.outputShape[s-2]}) {`,s===1?"":` ${c[s-1]} += 1;
2020-10-29 05:16:50 +01:00
if(${d}) {`],b=s===1?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))";let w="";for(let L=0,x=s===1?2:4;L<x;L++)w+=`
${f[L]}
2020-10-13 22:57:06 +02:00
if (${b}) {
result[${L}] = float(${n});
2020-10-12 20:28:19 +02:00
} else {
${i} source = rc - start;
2020-10-13 22:57:06 +02:00
result[${L}] = getChannel(getX(${h.join()}), ${m});
2020-10-12 20:28:19 +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-12 20:28:19 +02:00
void main() {
${i} outputLoc = getOutputCoords();
vec4 result = vec4(0.);
2020-10-13 22:57:06 +02:00
${w}
2020-10-12 20:28:19 +02:00
setOutput(result);
}
2020-10-29 05:16:50 +01:00
`}}class mu{constructor(e,t,n,s=!1,i=!1){if(this.variableNames=["x"],t==="avg"&&n)throw new Error("Cannot compute positions for average pool.");const o=e.filterWidth,a=e.strideHeight,c=e.strideWidth,h=e.dilationHeight,d=e.dilationWidth,m=e.effectiveFilterHeight,f=e.effectiveFilterWidth,b=e.padInfo.top,w=e.padInfo.left;this.outputShape=e.outShape;const L=t==="avg",x=`((batch * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + d`,v=`(xR * ${e.inWidth} + xC) * ${e.inChannels} + d`;let N="0.0";if(L||(N="-1.0 / 1e-20"),n){const $=">=";this.userCode=`
2020-10-13 22:57:06 +02:00
const ivec2 strides = ivec2(${a}, ${c});
const ivec2 pads = ivec2(${b}, ${w});
2020-10-12 20:28:19 +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-12 20:28:19 +02:00
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
2020-10-29 05:16:50 +01:00
for (int wC = 0; wC < ${f};
2020-10-13 22:57:06 +02:00
wC += ${d}) {
2020-10-12 20:28:19 +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-12 20:28:19 +02:00
minMaxValue = value;
minMaxValueFound = 1.0;
2020-10-29 05:16:50 +01:00
minMaxPosition = ${s?i?x:v:`wR * ${f} + wC`};
2020-10-12 20:28:19 +02:00
}
}
}
setOutput(float(minMaxPosition));
}
2020-10-29 05:16:50 +01:00
`;return}const O="max";let E=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(E="avgValue / count");const k=Math.floor(o/4)*4,F=o%4,U=`
2020-10-13 22:57:06 +02:00
if (${L}) {
2020-10-12 20:28:19 +02:00
avgValue += dot(values, ones);
} else {
2020-10-29 05:16:50 +01:00
minMaxValue = ${O}(values, minMaxValue);
2020-10-12 20:28:19 +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-12 20:28:19 +02:00
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
float count = 0.0;
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
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);
}
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d = coords[3];
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
ivec2 xRCCorner = coords.yz * strides - pads;
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
// 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-12 20:28:19 +02:00
float avgValue = 0.0;
count = 0.0;
2020-08-29 20:56:29 +02:00
2020-10-13 22:57:06 +02:00
for (int wR = 0; wR < ${m};
wR += ${h}) {
2020-10-12 20:28:19 +02:00
int xR = xRCorner + wR;
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
2020-08-29 20:56:29 +02:00
2020-10-29 05:16:50 +01:00
for (int wC = 0; wC < ${k}; wC += 4) {
2020-10-13 22:57:06 +02:00
int xC = xCCorner + wC * ${d};
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +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-12 20:28:19 +02:00
);
2020-08-29 20:56:29 +02:00
2020-10-29 05:16:50 +01:00
${U}
2020-10-12 20:28:19 +02:00
}
2020-08-29 20:56:29 +02:00
2020-10-29 05:16:50 +01:00
int xC = xCCorner + ${k};
if (${F===1}) {
2020-10-12 20:28:19 +02:00
vec4 values = vec4(
getValue(batch, xR, xC, d),
initializationValue,
initializationValue,
initializationValue
);
2020-10-29 05:16:50 +01:00
${U}
} else if (${F===2}) {
2020-10-12 20:28:19 +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-12 20:28:19 +02:00
initializationValue,
initializationValue
);
2020-10-29 05:16:50 +01:00
${U}
} else if (${F===3}) {
2020-10-12 20:28:19 +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-12 20:28:19 +02:00
initializationValue
);
2020-10-29 05:16:50 +01:00
${U}
2020-10-12 20:28:19 +02:00
}
}
2020-10-29 05:16:50 +01:00
setOutput(${E});
2020-10-12 20:28:19 +02:00
}
2020-10-29 05:16:50 +01:00
`}}class TS{constructor(e,t,n,s=!1,i=!1){if(this.variableNames=["x"],t==="avg"&&n)throw new Error("Cannot compute positions for average pool.");const o=e.filterWidth,a=e.strideDepth,c=e.strideHeight,h=e.strideWidth,d=e.dilationDepth,m=e.dilationHeight,f=e.dilationWidth,b=e.effectiveFilterDepth,w=e.effectiveFilterHeight,L=e.effectiveFilterWidth,x=e.padInfo.front,v=e.padInfo.top,N=e.padInfo.left;this.outputShape=e.outShape;const O=t==="avg";let E="0.0";if(O||(E="-1.0 / 1e-20"),n){const j=">=";this.userCode=`
2020-10-12 20:28:19 +02:00
const ivec3 strides =
2020-10-13 22:57:06 +02:00
ivec3(${a}, ${c}, ${h});
2020-10-29 05:16:50 +01:00
const ivec3 pads = ivec3(${x}, ${v}, ${N});
2020-10-12 20:28:19 +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-12 20:28:19 +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-12 20:28:19 +02:00
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
2020-10-13 22:57:06 +02:00
for (int wC = 0; wC < ${L};
2020-10-29 05:16:50 +01:00
wC += ${f}) {
2020-10-12 20:28:19 +02:00
int xC = xCCorner + wC;
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
float value = getX(batch, xD, xR, xC, ch);
// If a min / max value has already been found, use it. If not,
// use the current value.
float currMinMaxValue = mix(
value, minMaxValue, minMaxValueFound);
2020-10-29 05:16:50 +01:00
if (value ${j} currMinMaxValue) {
2020-10-12 20:28:19 +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-12 20:28:19 +02:00
}
}
}
}
setOutput(float(minMaxPosition));
}
2020-10-29 05:16:50 +01:00
`;return}const k="max";let F=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(F="avgValue / count");const U=Math.floor(o/4)*4,$=o%4,Y=`
if (${O}) {
2020-10-12 20:28:19 +02:00
avgValue += dot(values, ones);
} else {
2020-10-29 05:16:50 +01:00
minMaxValue = ${k}(values, minMaxValue);
2020-10-12 20:28:19 +02:00
}
`;this.userCode=`
const ivec3 strides =
2020-10-13 22:57:06 +02:00
ivec3(${a}, ${c}, ${h});
2020-10-29 05:16:50 +01:00
const ivec3 pads = ivec3(${x}, ${v}, ${N});
const float initializationValue = ${E};
2020-10-12 20:28:19 +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);
}
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int ch = coords.u;
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
int xDCorner = xCorner.x;
int xRCorner = xCorner.y;
int xCCorner = xCorner.z;
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
// max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch).
// ? = to be determined
2020-10-29 05:16:50 +01:00
vec4 minMaxValue = vec4(${E});
2020-10-12 20:28:19 +02:00
float avgValue = 0.0;
count = 0.0;
2020-08-29 20:56:29 +02:00
2020-10-13 22:57:06 +02:00
for (int wD = 0; wD < ${b};
wD += ${d}) {
2020-10-12 20:28:19 +02:00
int xD = xDCorner + wD;
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
if (xD < 0 || xD >= ${e.inDepth}) {
continue;
}
2020-08-29 20:56:29 +02:00
2020-10-13 22:57:06 +02:00
for (int wR = 0; wR < ${w};
wR += ${m}) {
2020-10-12 20:28:19 +02:00
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
2020-10-29 05:16:50 +01:00
for (int wC = 0; wC < ${U}; wC += 4) {
int xC = xCCorner + wC * ${f};
2020-10-12 20:28:19 +02:00
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
2020-10-29 05:16:50 +01:00
getValue(batch, xD, xR, xC + ${f}, ch),
getValue(batch, xD, xR, xC + 2 * ${f}, ch),
getValue(batch, xD, xR, xC + 3 * ${f}, ch)
2020-10-12 20:28:19 +02:00
);
2020-10-29 05:16:50 +01:00
${Y}
2020-10-12 20:28:19 +02:00
}
2020-10-29 05:16:50 +01:00
int xC = xCCorner + ${U};
2020-10-13 22:57:06 +02:00
if (${$===1}) {
2020-10-12 20:28:19 +02:00
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
initializationValue,
initializationValue,
initializationValue
);
2020-10-29 05:16:50 +01:00
${Y}
2020-10-13 22:57:06 +02:00
} else if (${$===2}) {
2020-10-12 20:28:19 +02:00
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
2020-10-29 05:16:50 +01:00
getValue(batch, xD, xR, xC + ${f}, ch),
2020-10-12 20:28:19 +02:00
initializationValue,
initializationValue
);
2020-10-29 05:16:50 +01:00
${Y}
2020-10-13 22:57:06 +02:00
} else if (${$===3}) {
2020-10-12 20:28:19 +02:00
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
2020-10-29 05:16:50 +01:00
getValue(batch, xD, xR, xC + ${f}, ch),
getValue(batch, xD, xR, xC + 2 * ${f}, ch),
2020-10-12 20:28:19 +02:00
initializationValue
);
2020-10-29 05:16:50 +01:00
${Y}
2020-10-12 20:28:19 +02:00
}
}
2020-10-29 05:16:50 +01:00
setOutput(${F});
2020-10-12 20:28:19 +02:00
}
}
2020-10-29 05:16:50 +01:00
`}}class yC{constructor(e,t){this.variableNames=["x"];const{windowSize:n,batchSize:s,inSize:i,outSize:o}=e;this.outputShape=[s,o];let a="0.0",c="";t==="prod"?a="1.0":t==="min"?(a="1.0 / 1e-20",c="min"):t==="max"&&(a="-1.0 / 1e-20",c="max");let h=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="sum"?h="sumValue":t==="prod"?h="prodValue":t==="all"?h="allValue":t==="any"&&(h="anyValue");const d=Math.floor(n/4)*4,m=n%4;let f=`
2020-10-12 20:28:19 +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-12 20:28:19 +02:00
}
2020-10-29 05:16:50 +01:00
`,b="vec4";t==="all"?(a="1.0",f=`
2020-10-12 20:28:19 +02:00
bool reducedAllValue = all(values);
float floatedReducedAllValue = float(reducedAllValue);
allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);
2020-10-29 05:16:50 +01:00
`,b="bvec4"):t==="any"&&(a="0.0",f=`
2020-10-12 20:28:19 +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-12 20:28:19 +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-12 20:28:19 +02:00
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
float getValue(int batch, int inIdx) {
2020-10-13 22:57:06 +02:00
${w}
2020-10-12 20:28:19 +02:00
return getX(batch, inIdx);
}
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +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 * ${n};
2020-10-12 20:28:19 +02:00
2020-10-13 22:57:06 +02:00
vec4 minMaxValue = vec4(${a});
2020-10-12 20:28:19 +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-12 20:28:19 +02:00
int inIdx = inOffset + i;
2020-10-13 22:57:06 +02:00
${b} values = ${b}(
2020-10-12 20:28:19 +02:00
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
getValue(batch, inIdx + 3)
);
2020-10-29 05:16:50 +01:00
${f}
2020-10-12 20:28:19 +02:00
}
2020-08-29 20:56:29 +02:00
2020-10-13 22:57:06 +02:00
int inIdx = inOffset + ${d};
if (${m===1}) {
${b} values = ${b}(
2020-10-12 20:28:19 +02:00
getValue(batch, inIdx),
initializationValue,
initializationValue,
initializationValue
);
2020-10-29 05:16:50 +01:00
${f}
2020-10-13 22:57:06 +02:00
} else if (${m===2}) {
${b} values = ${b}(
2020-10-12 20:28:19 +02:00
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
initializationValue,
initializationValue
);
2020-10-29 05:16:50 +01:00
${f}
2020-10-13 22:57:06 +02:00
} else if (${m===3}) {
${b} values = ${b}(
2020-10-12 20:28:19 +02:00
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
initializationValue
);
2020-10-29 05:16:50 +01:00
${f}
2020-10-12 20:28:19 +02:00
}
2020-10-13 22:57:06 +02:00
setOutput(${h});
2020-08-29 20:56:29 +02:00
}
2020-10-29 05:16:50 +01:00
`}}class bC{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-12 20:28:19 +02:00
${i}
2020-10-13 22:57:06 +02:00
${s>0?"if(thisRC.y < rows && thisRC.z < cols){":""}
2020-10-12 20:28:19 +02:00
int flatIndex = getFlatIndex(thisRC);
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
ivec3 inputRC = inputCoordsFromReshapedOutCoords(flatIndex);
vec2 inputRCInnerDims = vec2(float(inputRC.y),float(inputRC.z));
2020-08-29 20:56:29 +02:00
2020-10-13 22:57:06 +02:00
result[${s}] =
2020-10-12 20:28:19 +02:00
getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);
2020-10-13 22:57:06 +02:00
${s>0?"}":""}
2020-10-12 20:28:19 +02:00
`}this.userCode=`
2020-10-29 05:16:50 +01:00
${I6(t)}
${IS(e)}
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
void main() {
ivec3 rc = getOutputCoords();
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
vec4 result = vec4(0.);
ivec3 thisRC;
int rows = ${e[1]};
int cols = ${e[2]};
2020-08-29 20:56:29 +02:00
2020-10-13 22:57:06 +02:00
${n}
2020-10-12 20:28:19 +02:00
setOutput(result);
}
2020-10-29 05:16:50 +01:00
`}}function I6(e){const t=Yo(["r","c","d"],e);return`
2020-10-12 20:28:19 +02:00
ivec3 inputCoordsFromReshapedOutCoords(int index) {
${t}
return ivec3(r, c, d);
2020-08-29 20:56:29 +02:00
}
2020-10-29 05:16:50 +01:00
`}class x6{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t.shape;const[,s,i]=t.shape,[,o,a]=e.shape,c=[n&&o>1?s-1:s,n&&a>1?i-1:i],h=[n&&o>1?o-1:o,n&&a>1?a-1:a],d=c[0]/h[0],m=c[1]/h[1],f=1/d,b=1/m,w=Math.ceil(f)*2+2,L=Math.ceil(b)*2+2;this.userCode=`
2020-10-12 20:28:19 +02:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
int r = coords[1];
int c = coords[2];
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
float accumulator = 0.0;
2020-08-29 20:56:29 +02:00
2020-10-13 22:57:06 +02:00
const float heightScale = float(${d});
const float widthScale = float(${m});
2020-08-29 20:56:29 +02:00
2020-10-29 05:16:50 +01:00
const float invHeightScale = float(${f});
2020-10-13 22:57:06 +02:00
const float invWidthScale = float(${b});
2020-08-29 20:56:29 +02:00
2020-10-13 22:57:06 +02:00
const int winHeight = int(${w});
const int winWidth = int(${L});
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
// Compute bounds for where in dy we will look
float startRLerp = floor(float(r) * invHeightScale);
int startDyR = int(startRLerp - float(winHeight / 2));
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
float startCLerp = floor(float(c) * invWidthScale);
int startDyC = int(startCLerp - float(winWidth / 2));
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
// Loop over dy
for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {
int dyR = dyROffset + startDyR;
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
// Guard against the window exceeding the bounds of dy
2020-10-13 22:57:06 +02:00
if (dyR < 0 || dyR >= ${o}) {
2020-10-12 20:28:19 +02:00
continue;
}
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
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-12 20:28:19 +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-12 20:28:19 +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;
}
2020-08-29 20:56:29 +02:00
}
}
2020-10-12 20:28:19 +02:00
// End loop over dy
setOutput(accumulator);
}
2020-10-29 05:16:50 +01:00
`}}class T6{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-12 20:28:19 +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-12 20:28:19 +02:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 yRC = coords.yz;
// Fractional source index.
vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;
// Compute the four integer indices.
ivec2 sourceFloorRC = ivec2(sourceFracIndexRC);
ivec2 sourceCeilRC = ivec2(
min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));
float topLeft = getA(b, sourceFloorRC.x, sourceFloorRC.y, d);
float bottomLeft = getA(b, sourceCeilRC.x, sourceFloorRC.y, d);
float topRight = getA(b, sourceFloorRC.x, sourceCeilRC.y, d);
float bottomRight = getA(b, sourceCeilRC.x, sourceCeilRC.y, d);
vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC);
float top = topLeft + (topRight - topLeft) * fracRC.y;
float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;
float newValue = top + (bottom - top) * fracRC.x;
setOutput(newValue);
}
2020-10-29 05:16:50 +01:00
`}}class A6{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-12 20:28:19 +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-12 20:28:19 +02:00
float getAValue(int b, int r, int c, int d) {
return getChannel(getA(b, r, c, d), vec2(c, d));
2020-08-29 20:56:29 +02:00
}
2020-10-12 20:28:19 +02:00
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-12 20:28:19 +02:00
// In parallel, construct four corners for all four components in
// packed 2x2 cell.
vec4 topLeft = vec4(
getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d),
hasNextCol ? getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d + 1)
: 0.0,
hasNextRow ? getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d)
: 0.0,
(hasNextRow && hasNextCol) ?
getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d + 1) : 0.0);
vec4 bottomLeft = vec4(
getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d),
hasNextCol ? getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d + 1)
: 0.0,
hasNextRow ? getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d)
: 0.0,
(hasNextRow && hasNextCol) ?
getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d + 1) : 0.0);
vec4 topRight = vec4(
getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d),
hasNextCol ? getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d + 1)
: 0.0,
hasNextRow ? getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d)
: 0.0,
(hasNextRow && hasNextCol) ?
getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d + 1) : 0.0);
vec4 bottomRight = vec4(
getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d),
hasNextCol ? getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d + 1)
: 0.0,
hasNextRow ? getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d)
: 0.0,
(hasNextRow && hasNextCol) ?
getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d + 1) : 0.0);
vec3 fracRC = sourceFracIndexRC - vec3(sourceFloorRC);
vec4 top = mix(topLeft, topRight, fracRC.yyzz);
vec4 bottom = mix(bottomLeft, bottomRight, fracRC.yyzz);
vec4 newValue = mix(top, bottom, fracRC.x);
setOutput(newValue);
}
2020-10-29 05:16:50 +01:00
`}}class v6{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t.shape;const[,s,i]=t.shape,[,o,a]=e.shape,c=[n&&o>1?s-1:s,n&&a>1?i-1:i],h=[n&&o>1?o-1:o,n&&a>1?a-1:a],d=c[0]/h[0],m=c[1]/h[1],f=1/d,b=1/m,w=Math.ceil(f)*2+2,L=Math.ceil(b)*2+2;this.userCode=`
2020-10-12 20:28:19 +02:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
int r = coords[1];
int c = coords[2];
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
float accumulator = 0.0;
2020-08-29 20:56:29 +02:00
2020-10-13 22:57:06 +02:00
const float heightScale = float(${d});
const float widthScale = float(${m});
2020-08-29 20:56:29 +02:00
2020-10-29 05:16:50 +01:00
const float invHeightScale = float(${f});
2020-10-13 22:57:06 +02:00
const float invWidthScale = float(${b});
2020-08-29 20:56:29 +02:00
2020-10-13 22:57:06 +02:00
const int winHeight = int(${w});
const int winWidth = int(${L});
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +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)));
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
float startCLerp = floor(float(c) * invWidthScale);
int startDyC = int(floor(startCLerp - float(winWidth / 2)));
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
// Loop over dy
for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {
int dyR = dyROffset + startDyR;
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
// Guard against the window exceeding the bounds of dy
2020-10-13 22:57:06 +02:00
if (dyR < 0 || dyR >= ${o}) {
2020-10-12 20:28:19 +02:00
continue;
}
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {
int dyC = dyCOffset + startDyC;
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
// Guard against the window exceeding the bounds of dy
2020-10-13 22:57:06 +02:00
if (dyC < 0 || dyC >= ${a}) {
2020-10-12 20:28:19 +02:00
continue;
}
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
float sourceFracRow =
2020-10-13 22:57:06 +02:00
float(${c[0]}) *
(float(dyR) / float(${h[0]}));
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
float sourceFracCol =
2020-10-13 22:57:06 +02:00
float(${c[1]}) *
(float(dyC) / float(${h[1]}));
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
int sourceNearestRow = int(min(
2020-10-13 22:57:06 +02:00
float(int(${s}) - 1),
${n} ? float(round(sourceFracRow)) :
2020-10-12 20:28:19 +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-12 20:28:19 +02:00
float(floor(sourceFracCol))));
if (r == sourceNearestRow && c == sourceNearestCol) {
accumulator += getDy(b, dyR, dyC, d);
}
}
}
// End loop over dy
setOutput(accumulator);
2020-08-29 20:56:29 +02:00
}
2020-10-29 05:16:50 +01:00
`}}class N6{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-12 20:28:19 +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-12 20:28:19 +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-12 20:28:19 +02:00
float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);
setOutput(newValue);
2020-08-29 20:56:29 +02:00
}
2020-10-29 05:16:50 +01:00
`}}class C6{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-12 20:28:19 +02:00
void main() {
int coord = getOutputCoords();
setOutput(getX(${e[0]} - coord - 1));
}
2020-10-29 05:16:50 +01:00
`;return}const s=a=>t.indexOf(a)!==-1&&e[a]!==1?`${e[a]} - coords[${a}] - 1`:`coords[${a}]`,i=e.map((a,c)=>s(c)).join(","),o=Rt(n);this.userCode=`
2020-10-12 20:28:19 +02:00
void main() {
2020-10-13 22:57:06 +02:00
${o} coords = getOutputCoords();
2020-10-12 20:28:19 +02:00
setOutput(getX(${i}));
2020-08-29 20:56:29 +02:00
}
2020-10-29 05:16:50 +01:00
`}}class R6{constructor(e,t){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;const n=e.length;if(n>4)throw new Error(`WebGL backend: Reverse of rank-${n} tensor is not yet supported`);this.outputShape=e;const s=Mn("rc",n),i=`${s[n-1]} + 1 < ${this.outputShape[n-1]}`,o=`${s[n-2]} + 1 < ${this.outputShape[n-2]}`,a=Rt(n);n===1?this.userCode=`
2020-10-12 20:28:19 +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-12 20:28:19 +02:00
vec4 result = vec4(0.);
2020-10-13 22:57:06 +02:00
result.r = ${c(s.slice())};
2020-10-12 20:28:19 +02:00
if(${i}){
2020-10-13 22:57:06 +02:00
result.g = ${h(s.slice())};
2020-10-12 20:28:19 +02:00
}
2020-10-13 22:57:06 +02:00
if(${o}) {
result.b = ${d(s.slice())};
2020-10-12 20:28:19 +02:00
if(${i}) {
2020-10-13 22:57:06 +02:00
result.a = ${m(s.slice())};
2020-10-12 20:28:19 +02:00
}
}
setOutput(result);
}
2020-10-29 05:16:50 +01:00
`;function c(w){return f(w)}function h(w){return w[n-1]="("+w[n-1]+" + 1)",f(w)}function d(w){return w[n-2]="("+w[n-2]+" + 1)",f(w)}function m(w){return w[n-1]="("+w[n-1]+" + 1)",w[n-2]="("+w[n-2]+" + 1)",f(w)}function f(w){const L=e.map((N,O)=>b(O,w)),x=L.join(","),v=L.slice(-2).join(",");return`getChannel(getX(${x}), vec2(${v}))`}function b(w,L){return t.indexOf(w)!==-1&&e[w]!==1?`${e[w]} - ${L[w]} - 1`:`${L[w]}`}}}class wC{constructor(e,t,n,s,i,o,a=!0){this.variableNames=["updates","indices","defaultValue"],this.outputShape=o;const c=Rt(i.length),h=Rt(o.length);let d="";n===1?d="i":n===2&&(d="i, j");const m=`getIndices(${d})`;let f="";s===1?f="i":s===2&&(f="i, coords[1]");const b=`getUpdates(${f})`,w=t>1?"strides[j]":"strides";this.userCode=`
2020-10-13 22:57:06 +02:00
${c} strides = ${c}(${i});
2020-10-12 20:28:19 +02:00
void main() {
2020-10-13 22:57:06 +02:00
${h} coords = getOutputCoords();
2020-10-12 20:28:19 +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-12 20:28:19 +02:00
}
if (flattenedIndex == coords[0]) {
2020-10-13 22:57:06 +02:00
sum += ${b};
2020-10-12 20:28:19 +02:00
found = true;
}
}
setOutput(mix(getDefaultValue(), sum, float(found)));
}
2020-10-29 05:16:50 +01:00
`}}class O6{constructor(e,t){this.variableNames=["x","segmentIds"];const n=e.windowSize,s=e.batchSize,i=e.inSize,o=e.numSegments,a=o*Math.ceil(i/n);this.outputShape=[s,a];const c="0.0",h="sumValue",d=Math.floor(n/4)*4,m=n%4,f=`
2020-10-12 20:28:19 +02:00
sumValue += dot(values, segFilter);
2020-10-13 22:57:06 +02:00
`;let b="";i%n>0&&(b=`
2020-10-12 20:28:19 +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-12 20:28:19 +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-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
float getValue(int batch, int inIdx) {
2020-10-13 22:57:06 +02:00
${b}
2020-10-12 20:28:19 +02:00
return getX(batch, inIdx);
}
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
float getSegmentIdAtIndex(int inIdx) {
2020-10-13 22:57:06 +02:00
${w}
2020-10-12 20:28:19 +02:00
return getSegmentIds(inIdx);
}
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
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-12 20:28:19 +02:00
float sumValue = 0.0;
2020-10-13 22:57:06 +02:00
for (int i = 0; i < ${d}; i += 4) {
2020-10-12 20:28:19 +02:00
int inIdx = inOffset + i;
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
getValue(batch, inIdx + 3)
);
vec4 segFilter = vec4(
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 3)) == currentSeg ? 1 : 0
);
2020-10-29 05:16:50 +01:00
${f}
2020-10-12 20:28:19 +02:00
}
2020-08-29 20:56:29 +02:00
2020-10-13 22:57:06 +02:00
int inIdx = inOffset + ${d};
if (${m===1}) {
2020-10-12 20:28:19 +02:00
vec4 values = vec4(
getValue(batch, inIdx),
initializationValue,
initializationValue,
initializationValue
);
int inIdxSeg = int(getSegmentIdAtIndex(inIdx));
vec4 segFilter = vec4(
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
0,
0,
0
);
2020-10-29 05:16:50 +01:00
${f}
2020-10-13 22:57:06 +02:00
} else if (${m===2}) {
2020-10-12 20:28:19 +02:00
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
initializationValue,
initializationValue
);
vec4 segFilter = vec4(
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
0,
0
);
2020-10-29 05:16:50 +01:00
${f}
2020-10-13 22:57:06 +02:00
} else if (${m===3}) {
2020-10-12 20:28:19 +02:00
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
initializationValue
);
vec4 segFilter = vec4(
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,
0
);
2020-10-29 05:16:50 +01:00
${f}
2020-10-12 20:28:19 +02:00
}
2020-10-13 22:57:06 +02:00
setOutput(${h});
2020-10-12 20:28:19 +02:00
}
2020-10-29 05:16:50 +01: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=Rt(n);this.userCode=`
2020-10-12 20:28:19 +02:00
void main() {
2020-10-13 22:57:06 +02:00
${o} resRC = getOutputCoords();
float cVal = getC(${s});
2020-10-12 20:28:19 +02:00
if (cVal >= 1.0) {
setOutput(getA(${i}));
} else {
setOutput(getB(${i}));
}
}
2020-10-29 05:16:50 +01:00
`}}class D6{constructor(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;const t=Rt(this.rank),n=`uniform int start[${this.rank}];`,s=k6(this.rank);let i;const o=e.map((a,c)=>`sourceLoc.${AS[c]} = start[${c}] + coords.${AS[c]};`);i=`
2020-10-12 20:28:19 +02:00
${t} sourceLoc;
${t} coords = getOutputCoords();
2020-10-13 22:57:06 +02:00
${o.join(`
2020-10-12 20:28:19 +02:00
`)}
`,this.userCode=`
2020-10-13 22:57:06 +02:00
${n}
2020-10-12 20:28:19 +02:00
void main() {
${i}
2020-10-13 22:57:06 +02:00
setOutput(getSource(${s}));
}
2020-10-29 05:16:50 +01:00
`}getCustomSetupFunc(e){if(e.length!==this.rank)throw Error(`The rank (${this.rank}) of the program must match the length of start (${e.length})`);return(t,n)=>{if(this.startLoc==null&&(this.startLoc=t.getUniformLocationNoThrow(n,"start"),this.startLoc==null))return;t.gl.uniform1iv(this.startLoc,e)}}}const AS=["x","y","z","w","u","v"];function k6(e){if(e===1)return"sourceLoc";if(e<=6)return AS.slice(0,e).map(t=>"sourceLoc."+t).join(",");throw Error(`Slicing for rank ${e} is not yet supported`)}class F6{constructor(e){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.rank=e.length;const t=Rt(this.rank),n=Mn("coords",this.rank),s=Mn("sourceLoc",this.rank),i=this.rank===1?"sourceLoc":`vec2(${s.slice(-2).join()})`,o=`getChannel(getSource(${s.join()}), ${i})`,a=`
2020-10-13 22:57:06 +02:00
result.x = ${o};
if (++${n[this.rank-1]} < ${e[this.rank-1]}) {
++${s[this.rank-1]};
result.y = ${o};
--${s[this.rank-1]};
}
`,c=this.rank===1?"":`
--${n[this.rank-1]};
if (++${n[this.rank-2]} < ${e[this.rank-2]}) {
++${s[this.rank-2]};
result.z = ${o};
if (++${n[this.rank-1]} < ${e[this.rank-1]}) {
++${s[this.rank-1]};
result.w = ${o};
}
}
`,h=this.rank<=4?`sourceLoc = coords +
${t}(${e.map((d,m)=>`start[${m}]`).join()});`:e.map((d,m)=>`${s[m]} = ${n[m]} + start[${m}];`).join(`
2020-10-12 20:28:19 +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-12 20:28:19 +02:00
vec4 result = vec4(0.);
${a}
2020-10-13 22:57:06 +02:00
${c}
2020-10-12 20:28:19 +02:00
setOutput(result);
}
2020-10-29 05:16:50 +01:00
`}getCustomSetupFunc(e){if(e.length!==this.rank)throw Error(`The rank (${this.rank}) of the program must match the length of start (${e.length})`);return(t,n)=>{if(this.startLoc==null&&(this.startLoc=t.getUniformLocationNoThrow(n,"start"),this.startLoc==null))return;t.gl.uniform1iv(this.startLoc,e)}}}class _6{constructor(e,t,n){this.variableNames=["x"],this.outputShape=n;const s=n.length,i=Rt(n.length),o=Rt(n.length);let a="";if(s===1)a="coords * strides + begin";else{let c=0;a=n.map((h,d)=>(c++,n.length===1?`coords * strides[${d}] + begin[${d}]`:`coords[${c-1}] * strides[${d}] + begin[${d}]`)).join(",")}this.userCode=`
2020-10-12 20:28:19 +02:00
${i} begin = ${i}(${e});
${i} strides = ${i}(${t});
2020-08-29 20:56:29 +02:00
2020-10-12 20:28:19 +02:00
void main() {
2020-10-13 22:57:06 +02:00
${o} coords = getOutputCoords();
setOutput(getX(${a}));
2020-10-12 20:28:19 +02:00
}
2020-10-29 05:16:50 +01:00
`}}class W6{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=SC(t,n),i=IC(e,s,n);i in this.freeTextures||(this.freeTextures[i]=[]),i in this.usedTextures||(this.usedTextures[i]=[]);const o=LC(e,s,this.gpgpu.gl,this.gpgpu.textureConfig,n);if(this.freeTextures[i].length>0){this.numFreeTextures--,this.numUsedTextures++,this._numBytesFree-=o,this.log();const c=this.freeTextures[i].shift();return this.usedTextures[i].push(c),c}let a;return s===Cn.PACKED_2X2_FLOAT32?a=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):s===Cn.PACKED_2X2_FLOAT16?a=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):s===Cn.UNPACKED_FLOAT32?a=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):s===Cn.UNPACKED_FLOAT16?a=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):s===Cn.PACKED_4X1_UNSIGNED_BYTE&&(a=this.gpgpu.createUnsignedBytesMatrixTexture(e[0],e[1])),this.usedTextures[i].push(a),this.numUsedTextures++,this._numBytesAllocated+=o,this.log(),a}releaseTexture(e,t,n,s){if(this.freeTextures==null)return;const i=SC(n,s),o=IC(t,i,s);o in this.freeTextures||(this.freeTextures[o]=[]);const a=LC(t,i,this.gpgpu.gl,this.gpgpu.textureConfig,s),c=oe().get("WEBGL_DELETE_TEXTURE_THRESHOLD");c!==-1&&this._numBytesAllocated>c?(this.gpgpu.deleteMatrixTexture(e),this._numBytesAllocated-=a):(this.freeTextures[o].push(e),this.numFreeTextures++,this._numBytesFree+=a),this.numUsedTextures--;const h=this.usedTextures[o],d=h.indexOf(e);if(d<0)throw new Error("Cannot release a texture that was never provided by this texture manager");h.splice(d,1),this.log()}log(){if(!this.logEnabled)return;const e=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",`${this.numFreeTextures} / ${this.numUsedTextures}`,`(${e})`);const t=this._numBytesFree/this._numBytesAllocated;console.log(`Bytes allocated: ${this._numBytesAllocated}`),console.log(`Bytes unused: ${this._numBytesFree} (${Math.round(100*t)}%)`)}get numBytesAllocated(){return this._numBytesAllocated}get numBytesFree(){return this._numBytesFree}getNumUsedTextures(){return this.numUsedTextures}getNumFreeTextures(){return this.numFreeTextures}dispose(){if(this.freeTextures==null)return;for(const e in this.freeTextures)this.freeTextures[e].forEach(t=>{this.gpgpu.deleteMatrixTexture(t)});for(const e in this.usedTextures)this.usedTextures[e].forEach(t=>{this.gpgpu.deleteMatrixTexture(t)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0}}function $6(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 LC(e,t,n,s,i){const o=U6(t,s);let a;if(i){const[h,d]=pc(e[0],e[1]);a=h*d}else{const[h,d]=hu(e[0],e[1]);a=h*d}const c=$6(n,o);return a*c}function U6(e,t){switch(e){case Cn.PACKED_2X2_FLOAT32:return mC(t);case Cn.PACKED_2X2_FLOAT16:return fC(t);case Cn.UNPACKED_FLOAT32:return uC(t);case Cn.UNPACKED_FLOAT16:return dC(t);case Cn.PACKED_4X1_UNSIGNED_BYTE:return pC(t);default:throw new Error(`Unknown physical texture type ${e}`)}}function B6(e){return oe().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?Cn.PACKED_2X2_FLOAT32:Cn.UNPACKED_FLOAT32:e?Cn.PACKED_2X2_FLOAT16:Cn.UNPACKED_FLOAT16}function SC(e,t){if(e===Ns.UPLOAD)return Cn.PACKED_2X2_FLOAT32;if(e===Ns.RENDER||e==null)return B6(t);if(e===Ns.DOWNLOAD||e===Ns.PIXELS)return Cn.PACKED_4X1_UNSIGNED_BYTE;throw new Error(`Unknown logical texture type ${e}`)}function IC(e,t,n){return`${e[0]}_${e[1]}_${t}_${n}`}class M6{constructor(e,t){this.variableNames=["A"];const n=new Array(e.length);for(let o=0;o<n.length;o++)n[o]=e[o]*t[o];this.outputShape=n,this.rank=n.length;const s=Rt(this.rank),i=P6(e);this.userCode=`
2020-10-12 20:28:19 +02:00
void main() {
2020-10-13 22:57:06 +02:00
${s} resRC = getOutputCoords();
2020-10-12 20:28:19 +02:00
setOutput(getA(${i}));
}
2020-10-29 05:16:50 +01:00
`}}function P6(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-12 20:28:19 +02:00
float unaryOperation(float x) {
${t}
}
2020-10-12 20:28:19 +02:00
void main() {
float x = getAAtOutCoords();
float y = unaryOperation(x);
setOutput(y);
}
2020-10-29 05:16:50 +01:00
`}}const hr="if (isnan(x)) return x;",z6="return x;",xC="return abs(x);",TC=hr+`
2020-10-12 20:28:19 +02:00
return (x < 0.0) ? 0.0 : x;
2020-10-29 05:16:50 +01:00
`,AC=hr+`
2020-10-12 20:28:19 +02:00
return (x < 0.0) ? 0.0 : min(6.0, x);
2020-10-29 05:16:50 +01:00
`,vC="return (x >= 0.0) ? x : (exp(x) - 1.0);",V6=`
2020-10-12 20:28:19 +02:00
// Stable and Attracting Fixed Point (0, 1) for Normalized Weights.
// see: https://arxiv.org/abs/1706.02515
2020-10-29 05:16:50 +01:00
float scaleAlpha = ${Wp};
float scale = ${$p};
2020-10-12 20:28:19 +02:00
return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);
2020-10-29 05:16:50 +01:00
`;function G6(e=0){return hr+`
2020-10-12 20:28:19 +02:00
return x > 0.0 ? 1.0 : float(${e});
2020-10-29 05:16:50 +01:00
`}const NC="return -x;",CC="return ceil(x);",RC="return floor(x);",Y6=`
2020-10-12 20:28:19 +02:00
if (isnan(x)) { return 0.0; }
return sign(x);
2020-10-29 05:16:50 +01:00
`,H6="return float(isnan(x));",q6="return float(isinf(x));",j6="return float(!isnan(x) && !isinf(x));",K6=`
2020-10-12 20:28:19 +02:00
// OpenGL ES does not support round function.
// The algorithm is based on banker's rounding.
float base = floor(x);
if ((x - base) < 0.5) {
return floor(x);
} else if ((x - base) > 0.5) {
return ceil(x);
} else {
if (mod(base, 2.0) == 0.0) {
return base;
} else {
return base + 1.0;
}
}
2020-10-29 05:16:50 +01:00
`,OC="return exp(x);",EC="return exp(x) - 1.0;",X6=`if (x < 0.0) return NAN;
return log(x);`,J6="return log(1.0 + x);",Z6="return sqrt(x);",Q6="return inversesqrt(x);",eX="return 1.0 / (1.0 + exp(-1.0 * x));",tX=`
2020-10-12 20:28:19 +02:00
float epsilon = 1.1920928955078125e-7;
float threshold = log(epsilon) + 2.0;
bool too_large = x > -threshold;
bool too_small = x < threshold;
float result;
float exp_x = exp(x);
if (too_large){
result = x;
}
else if (too_small){
result = exp_x;
}
else{
result = log(exp_x + 1.0);
}
return result;
2020-10-29 05:16:50 +01:00
`,nX=hr+`
2020-10-12 20:28:19 +02:00
if (abs(x) > 1.) {
return NAN;
}
return asin(x);
2020-10-29 05:16:50 +01:00
`,sX=hr+`
2020-10-12 20:28:19 +02:00
if (abs(x) > 1.) {
return NAN;
}
return acos(x);
2020-10-29 05:16:50 +01:00
`,iX=hr+`
2020-10-12 20:28:19 +02:00
return atan(x);
2020-10-29 05:16:50 +01:00
`,rX=`
2020-10-12 20:28:19 +02:00
float e2x = exp(x);
return (e2x - 1.0 / e2x) / 2.0;
2020-10-29 05:16:50 +01:00
`,oX=`
2020-10-12 20:28:19 +02:00
float e2x = exp(-x);
return (e2x + 1.0 / e2x) / 2.0;
2020-10-29 05:16:50 +01:00
`,aX=`
2020-10-12 20:28:19 +02:00
float e2x = exp(-2.0 * abs(x));
return sign(x) * (1.0 - e2x) / (1.0 + e2x);
2020-10-29 05:16:50 +01:00
`,cX=hr+"return log(x + sqrt(x * x + 1.0));",lX=hr+`
2020-10-12 20:28:19 +02:00
if (x < 1.0) return NAN;
2020-10-29 05:16:50 +01:00
return log(x + sqrt(x * x - 1.0));`,hX=hr+`
2020-10-12 20:28:19 +02:00
if ((x < -1.0) || (x > 1.0)) return NAN;
2020-10-29 05:16:50 +01:00
return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,uX=`
2020-10-12 20:28:19 +02:00
// Error function is calculated approximately with elementary function.
// See "Handbook of Mathematical Functions with Formulas,
// Graphs, and Mathematical Tables", Abramowitz and Stegun.
2020-10-29 05:16:50 +01:00
float p = ${ew};
float a1 = ${tw};
float a2 = ${nw};
float a3 = ${sw};
float a4 = ${iw};
float a5 = ${rw};
2020-10-12 20:28:19 +02:00
float sign = sign(x);
x = abs(x);
float t = 1.0 / (1.0 + p * x);
return sign * (1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x));
2020-10-29 05:16:50 +01:00
`,dX="return 1.0 / x;",pX="return float(!(x >= 1.0));",Fm="return x;";const mX="return x;",fX=`
2020-10-12 20:28:19 +02:00
vec4 result = log(x);
vec4 isNaN = vec4(lessThan(x, vec4(0.0)));
result.r = isNaN.r == 1.0 ? NAN : result.r;
result.g = isNaN.g == 1.0 ? NAN : result.g;
result.b = isNaN.b == 1.0 ? NAN : result.b;
result.a = isNaN.a == 1.0 ? NAN : result.a;
return result;
2020-10-29 05:16:50 +01:00
`,DC=`
2020-10-12 20:28:19 +02:00
vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));
bvec4 isNaN = isnan(x);
result.r = isNaN.r ? x.r : result.r;
result.g = isNaN.g ? x.g : result.g;
result.b = isNaN.b ? x.b : result.b;
result.a = isNaN.a ? x.a : result.a;
return result;
2020-10-29 05:16:50 +01:00
`,kC=`
2020-10-12 20:28:19 +02:00
vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));
bvec4 isNaN = isnan(x);
result.r = isNaN.r ? x.r : result.r;
result.g = isNaN.g ? x.g : result.g;
result.b = isNaN.b ? x.b : result.b;
result.a = isNaN.a ? x.a : result.a;
return result;
2020-10-29 05:16:50 +01:00
`,FC=`
2020-10-12 20:28:19 +02:00
vec4 result;
result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);
result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);
result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);
result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);
return result;
2020-10-29 05:16:50 +01:00
`;class fu{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.userCode=`
2020-10-12 20:28:19 +02:00
vec4 unaryOperation(vec4 x) {
${t}
}
void main() {
vec4 x = getAAtOutCoords();
vec4 y = unaryOperation(x);
setOutput(y);
}
2020-10-29 05:16:50 +01:00
`}}class gX{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e;const t=e.length,n=Mn("rc",t),s=Rt(t),i=r5(t,n),o=n.slice(-2),a=t<=1?"rc":`vec2(${o.join(",")})`;this.userCode=`
2020-10-12 20:28:19 +02:00
void main() {
2020-10-13 22:57:06 +02:00
${s} rc = getOutputCoords();
2020-10-12 20:28:19 +02:00
vec4 packedInput = getA(${i});
2020-10-13 22:57:06 +02:00
setOutput(getChannel(packedInput, ${a}));
2020-10-12 20:28:19 +02:00
}
2020-10-29 05:16:50 +01:00
`}}const{segment_util:_C}=cw,yX=lw,bX=hw,wX=uw,LX=Ap,SX=1e-7,IX=1e-4,_m={};function xX(e){return e in _m||(_m[e]={}),_m[e]}function Wm(e,t=!1){if(e==="linear")return t?mX:z6;if(e==="relu")return t?DC:TC;if(e==="elu")return t?FC:vC;if(e==="relu6")return t?kC:AC;if(e==="prelu")return t?iC:sC;throw new Error(`Activation ${e} has not been implemented for the WebGL backend.`)}const TX=128,AX=600;function vX(){return oe().global.screen==null?1024:oe().global.screen.height*oe().global.screen.width*window.devicePixelRatio*AX/1024/1024}const WC=1e3;class NX extends y{constructor(e){super();if(this.pendingRead=new WeakMap,this.pendingDisposal=new WeakSet,this.dataRefCount=new WeakMap,this.numBytesInGPU=0,this.uploadWaitMs=0,this.downloadWaitMs=0,this.warnedAboutMemory=!1,this.warnedAboutCPUBackend=!1,this.pendingDeletes=0,this.disposed=!1,!oe().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");if(e==null){const t=ki(oe().getNumber("WEBGL_VERSION"));this.binaryCache=xX(oe().getNumber("WEBGL_VERSION")),this.gpgpu=new n6(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 W6(this.gpgpu),this.numMBBeforeWarning=vX(),this.texData=new p(this,Ki())}numDataIds(){return this.texData.numDataIds()+(this.cpuBackend?this.cpuBackend.numDataIds():0)-this.pendingDeletes}write(e,t,n){if((oe().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||oe().getBool("DEBUG"))&&this.checkNumericalProblems(e),n==="complex64"&&e!=null)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");const s={};return this.texData.set(s,{shape:t,dtype:n,values:e,usage:Ns.UPLOAD,refCount:1,complexParentRefCount:0}),s}incRef(e){const t=this.texData.get(e);t.refCount++}decRef(e){if(this.texData.has(e)){const t=this.texData.get(e);t.refCount--}}move(e,t,n,s){if(oe().getBool("DEBUG")&&this.checkNumericalProblems(t),s==="complex64")throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(e,{shape:n,dtype:s,values:t,usage:Ns.UPLOAD,refCount:1,complexParentRefCount:0})}disposeIntermediateTensorInfo(e){const t=e.dataId;if(this.texData.has(t)){const n=this.texData.get(t);n.refCount--,n.refCount<1&&this.disposeData(t)}}readSync(e){const t=this.texData.get(e),{values:n,dtype:s,complexTensorInfos:i,slice:o,shape:a,isPacked:c}=t;if(o!=null){let f;c?f=new fu(a,Fm):f=new st(a,Fm);const b=this.runWebGLProgram(f,[{dataId:e,shape:a,dtype:s}],s),w=this.readSync(b.dataId);return this.disposeIntermediateTensorInfo(b),w}if(n!=null)return this.convertAndCacheOnCPU(e);if(s==="string")return n;const h=this.activeTimers!=null;let d;h&&(d=jn());let m;if(s==="complex64"){const f=this.readSync(i.real.dataId),b=this.readSync(i.imag.dataId);m=tr(f,b)}else m=this.getValuesFromTexture(e);return h&&(this.downloadWaitMs+=jn()-d),this.convertAndCacheOnCPU(e,m)}async read(e){if(this.pendingRead.has(e)){const w=this.pendingRead.get(e);return new Promise(L=>w.push(L))}const t=this.texData.get(e),{values:n,shape:s,slice:i,dtype:o,complexTensorInfos:a,isPacked:c}=t;if(i!=null){let w;c?w=new fu(s,Fm):w=new st(s,Fm);const L=this.runWebGLProgram(w,[{dataId:e,shape:s,dtype:o}],o),x=this.read(L.dataId);return this.disposeIntermediateTensorInfo(L),x}if(n!=null)return this.convertAndCacheOnCPU(e);if(!oe().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&oe().getNumber("WEBGL_VERSION")===2)throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");let h=null,d;if(o!=="complex64"&&oe().get("WEBGL_BUFFER_SUPPORTED")){d=this.decode(e);const w=this.texData.get(d.dataId);h=this.gpgpu.createBufferFromTexture(w.texture,...uu(s))}this.pendingRead.set(e,[]),o!=="complex64"&&await this.gpgpu.createAndWaitForFence();let m;if(o==="complex64"){const w=await Promise.all([this.read(a.real.dataId),this.read(a.imag.dataId)]),L=w[0],x=w[1];m=tr(L,x)}else if(h==null)m=this.getValuesFromTexture(e);else{const w=P(s);m=this.gpgpu.downloadFloat32MatrixFromBuffer(h,w)}d!=null&&this.d
2020-10-12 20:28:19 +02:00
if (isnan(a)) return a;
if (isnan(b)) return b;
2020-10-29 05:16:50 +01:00
`,FX=`
2020-10-12 20:28:19 +02:00
result.r = isNaN.r > 0. ? NAN : result.r;
result.g = isNaN.g > 0. ? NAN : result.g;
result.b = isNaN.b > 0. ? NAN : result.b;
result.a = isNaN.a > 0. ? NAN : result.a;
2020-10-29 05:16:50 +01:00
`;function $m(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 Sc({opSnippet:e,packedOpSnippet:t,checkOutOfBounds:n=!1,supportsComplex:s=!1,cpuKernelImpl:i,dtype:o}){return({inputs:a,backend:c})=>{const{a:h,b:d}=a,m=c;if(s&&h.dtype==="complex64"){const L=m.texData.get(h.dataId),x=m.texData.get(d.dataId),[v,N]=[[L.complexTensorInfos.real,x.complexTensorInfos.real],[L.complexTensorInfos.imag,x.complexTensorInfos.imag]].map(E=>{const[k,F]=E,U={dataId:k.dataId,dtype:k.dtype,shape:h.shape},$={dataId:F.dataId,dtype:F.dtype,shape:d.shape},Y=new _n(e,h.shape,d.shape);return m.runWebGLProgram(Y,[U,$],$n(k.dtype,F.dtype))}),O=Lc({inputs:{real:v,imag:N},backend:m});return m.disposeIntermediateTensorInfo(v),m.disposeIntermediateTensorInfo(N),O}const f=o||$n(h.dtype,d.dtype);if(m.shouldExecuteOnCPU([h,d])&&i!=null){const L=m.texData.get(h.dataId),x=m.texData.get(d.dataId),[v,N]=i(h.shape,d.shape,L.values,x.values,f),O=m.makeTensorInfo(N,f),E=m.texData.get(O.dataId);return E.values=v,O}const b=oe().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&t!=null;let w;return b?w=new lr(t,h.shape,d.shape,n):w=new _n(e,h.shape,d.shape),m.runWebGLProgram(w,[h,d],f)}}const UC="return a + b;",_X=Sc({opSnippet:UC,packedOpSnippet:UC,supportsComplex:!0,cpuKernelImpl:GK}),WX={kernelName:wo,backendName:"webgl",kernelFunc:_X};const $X=kX+`
2020-10-12 20:28:19 +02:00
return atan(a, b);
2020-10-29 05:16:50 +01:00
`,UX=`
2020-10-12 20:28:19 +02:00
vec4 result = atan(a, b);
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
2020-10-29 05:16:50 +01:00
`+FX+`
2020-10-12 20:28:19 +02:00
return result;
2020-10-29 05:16:50 +01:00
`,BX=Sc({opSnippet:$X,packedOpSnippet:UX}),MX={kernelName:nd,backendName:"webgl",kernelFunc:BX};function PX(e){const{inputs:t,backend:n,attrs:s}=e,{x:i}=t;du(i,"avgPool");const{filterSize:o,strides:a,pad:c,dimRoundingMode:h}=s,d=1;A(cn(a,d),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${d}'`);const m=Un(i.shape,o,a,d,c,h);if(m.filterWidth===1&&m.filterHeight===1&&ae(m.inShape,m.outShape))return ur({inputs:{x:i},backend:n});const f=new mu(m,"avg",!1);return n.runWebGLProgram(f,[i],"float32")}const zX={kernelName:dl,backendName:"webgl",kernelFunc:PX};function VX(e){const{inputs:t,backend:n,attrs:s}=e,{dy:i,input:o}=t,a=o;du([i,o],"avgPoolBackprop");const{filterSize:c,strides:h,pad:d}=s,m=Un(a.shape,c,h,1,d),f=new V5(m);return n.runWebGLProgram(f,[i],a.dtype)}const GX={kernelName:sd,backendName:"webgl",kernelFunc:VX};class YX{constructor(e,t,n,s,i,o){this.outputShape=[],this.variableNames=["x","mean","variance"],nt(e,t),nt(e,n);let a="0.0";s!=null&&(nt(e,s),this.variableNames.push("offset"),a="getOffsetAtOutCoords()");let c="1.0";i!=null&&(nt(e,i),this.variableNames.push("scale"),c="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`
2020-10-12 20:28:19 +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-12 20:28:19 +02:00
setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));
}
2020-10-29 05:16:50 +01:00
`}}class HX{constructor(e,t,n,s,i,o){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],nt(e,t),nt(e,n);let a="vec4(0.0)";s!=null&&(nt(e,s),this.variableNames.push("offset"),a="getOffsetAtOutCoords()");let c="vec4(1.0)";i!=null&&(nt(e,i),this.variableNames.push("scale"),c="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`
2020-10-12 20:28:19 +02:00
void main() {
2020-10-13 22:57:06 +02:00
vec4 offset = ${a};
vec4 scale = ${c};
2020-10-12 20:28:19 +02:00
vec4 x = getXAtOutCoords();
vec4 mean = getMeanAtOutCoords();
vec4 variance = getVarianceAtOutCoords();
2020-10-11 18:41:17 +02:00
2020-10-13 22:57:06 +02:00
vec4 inv = scale * inversesqrt(variance + vec4(${o}));
2020-10-12 20:28:19 +02:00
setOutput((x - mean) * inv + offset);
}
2020-10-29 05:16:50 +01:00
`}}const qX=({inputs:e,backend:t,attrs:n})=>{const{x:s,mean:i,variance:o,offset:a,scale:c}=e;A(i.shape.length===o.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),A(a==null||i.shape.length===a.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),A(c==null||i.shape.length===c.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let{varianceEpsilon:h}=n;h==null&&(h=.001);const d=[s,i,o];let m=null;a!=null&&(m=a.shape,d.push(a));let f=null;c!=null&&(f=c.shape,d.push(c));const b=oe().getBool("WEBGL_PACK_NORMALIZATION")?new HX(s.shape,i.shape,o.shape,m,f,h):new YX(s.shape,i.shape,o.shape,m,f,h),w=t.runWebGLProgram(b,d,d[0].dtype);return w},jX={kernelName:Il,backendName:"webgl",kernelFunc:qX};const KX="return float(a != b);",BC=Sc({opSnippet:KX,dtype:"bool"}),XX={kernelName:Dl,backendName:"webgl",kernelFunc:BC};function vS(e){const{inputs:t,backend:n}=e,{input:s}=t,i=n.texData.get(s.dataId);return ur({inputs:{x:i.complexTensorInfos.real},backend:n})}const JX={kernelName:Td,backendName:"webgl",kernelFunc:vS};const ZX="return float(int(x));";function QX(e,t){const n=new st(e.shape,ZX),s=t.runWebGLProgram(n,[e],"int32");return{dataId:s.dataId,shape:s.shape,dtype:s.dtype}}function NS(e){const{inputs:t,backend:n,attrs:s}=e,{x:i}=t,{dtype:o}=s;if(o==="complex64"){if(i.dtype==="complex64")return ur({inputs:{x:i},backend:n});const a=dt(i.shape),c=NS({inputs:{x:i},backend:n,attrs:{dtype:"float32"}}),h=Lc({inputs:{real:c,imag:a},backend:n});return a.dispose(),n.disposeIntermediateTensorInfo(c),h}if(i.dtype==="complex64"){const a=vS({inputs:{input:i},backend:n}),c=NS({inputs:{x:a},backend:n,attrs:{dtype:o}});return n.disposeIntermediateTensorInfo(a),c}if(!ba(i.dtype,o)){const a=ur({inputs:{x:i},backend:n});return{dataId:a.dataId,shape:a.shape,dtype:o}}if(o==="int32")return QX(i,n);if(o==="bool"){const a=n.makeTensorInfo([],"bool",bt("bool",1)),c={a:i,b:a},h=BC({inputs:c,backend:n});return n.disposeIntermediateTensorInfo(a),h}throw new Error(`Error in Cast: failed to cast ${i.dtype} to ${o}`)}const e7={kernelName:Sa,backendName:"webgl",kernelFunc:NS};class t7{constructor(e){this.outputShape=[],this.outputShape=Xi(e,1),this.variableNames=e.map((o,a)=>`T${a}`);const t=new Array(e.length-1);t[0]=e[0][1];for(let o=1;o<t.length;o++)t[o]=t[o-1]+e[o][1];const n=[`if (yC < ${t[0]}) setOutput(getT0(yR, yC));`];for(let o=1;o<t.length;o++){const a=t[o-1];n.push(`else if (yC < ${t[o]}) setOutput(getT${o}(yR, yC-${a}));`)}const s=t.length,i=t[t.length-1];n.push(`else setOutput(getT${s}(yR, yC-${i}));`),this.userCode=`
void main() {
ivec2 coords = getOutputCoords();
int yR = coords.x;
int yC = coords.y;
${n.join(`
`)}
}
`}}class n7{constructor(e,t){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=Xi(e,t);const n=this.outputShape,s=n.length,i=Rt(s),o=Mn("coords",s),a=["x","y","z","w","u","v"].slice(0,s);this.variableNames=e.map((L,x)=>`T${x}`);const c=new Array(e.length-1);c[0]=e[0][t];for(let L=1;L<c.length;L++)c[L]=c[L-1]+e[L][t];const h=a[t],d=a.slice(-2),m=a.join();let f=`if (${h} < ${c[0]}) {
return getChannel(
getT0(${m}), vec2(${d.join()}));
}`;for(let L=1;L<c.length;L++){const x=c[L-1];f+=`
if (${h} < ${c[L]} && ${h} >= ${c[L-1]}) {
return getChannel(
getT${L}(${Um(a,h,x)}),
vec2(${Um(d,h,x)}));
}`}const b=c.length,w=c[c.length-1];f+=`
return getChannel(
getT${b}(${Um(a,h,w)}),
vec2(${Um(d,h,w)}));`,this.userCode=`
float getValue(${a.map(L=>"int "+L)}) {
${f}
}
void main() {
${i} coords = getOutputCoords();
vec4 result = vec4(getValue(${o}), 0., 0., 0.);
${o[s-1]} = ${o[s-1]} + 1;
if (${o[s-1]} < ${n[s-1]}) {
result.g = getValue(${o});
}
${o[s-2]} = ${o[s-2]} + 1;
if (${o[s-2]} < ${n[s-2]}) {
result.a = getValue(${o});
}
${o[s-1]} = ${o[s-1]} - 1;
if (${o[s-2]} < ${n[s-2]} &&
${o[s-1]} < ${n[s-1]}) {
result.b = getValue(${o});
}
setOutput(result);
}
`}}function Um(e,t,n){const s=e.indexOf(t),i=e.map((o,a)=>a===s?`${o} - ${n}`:o);return i.join()}function MC(e){const{inputs:t,backend:n}=e,{input:s}=t,i=n.texData.get(s.dataId);return ur({inputs:{x:i.complexTensorInfos.imag},backend:n})}const s7={kernelName:gd,backendName:"webgl",kernelFunc:MC};function i7(e,t,n){const s=[mc(e.shape),...fc(e.shape)],i={dtype:e.dtype,shape:s,dataId:e.dataId},o=[mc(t),...fc(t)],a=new bC(o,s),c=!0,h=n.runWebGLProgram(a,[i],e.dtype,null,c);return{dataId:h.dataId,shape:t,dtype:h.dtype}}function dr(e){const{inputs:t,backend:n,attrs:s}=e,{x:i}=t,{shape:o}=s,a=n,c=P(i.shape),h=Vt(o,c),d=P(h);A(c===d,()=>`The new shape (${h}) has ${d} elements and the old shape (${i.shape}) has ${c} elements. The new shape and old shape must have the same number of elements.`);const m=a.texData.get(i.dataId);return m.isPacked&&!Rm(i.shape,h)&&!(m.texture!==null&&Rm(m.shape,h))?i7(i,h,a):(a.incRef(i.dataId),{dataId:i.dataId,shape:h,dtype:i.dtype})}const r7={kernelName:_l,backendName:"webgl",kernelFunc:dr};function Ic(e,t,n){const s=e[0].dtype;if(s==="complex64"){const d=e.map(L=>vS({inputs:{input:L},backend:n})),m=e.map(L=>MC({inputs:{input:L},backend:n})),f=Ic(d,t,n),b=Ic(m,t,n),w=Lc({inputs:{real:f,imag:b},backend:n});return d.forEach(L=>n.disposeIntermediateTensorInfo(L)),m.forEach(L=>n.disposeIntermediateTensorInfo(L)),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(b),w}if(e.length>oe().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){const d=Math.floor(e.length/2),m=Ic(e.slice(0,d),t,n),f=Ic(e.slice(d),t,n),b=Ic([m,f],t,n);return n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(f),b}if(oe().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&e[0].shape.length>1){const d=new n7(e.map(m=>m.shape),t);return n.runWebGLProgram(d,e,s)}const i=Xi(e.map(d=>d.shape),t),o=e.map(d=>dr({inputs:{x:d},attrs:{shape:[-1,P(d.shape.slice(t))]},backend:n})),a=new t7(o.map(d=>d.shape)),c=n.runWebGLProgram(a,o,s);o.forEach(d=>n.disposeIntermediateTensorInfo(d));const h=dr({inputs:{x:c},attrs:{shape:i},backend:n});return n.disposeIntermediateTensorInfo(c),h}function o7(e){const{inputs:t,backend:n,attrs:s}=e,{axis:i}=s,o=qe(i,t[0].shape)[0],a=Xi(t.map(d=>d.shape),o);if(P(a)===0)return n.makeTensorInfo(a,t[0].dtype,[]);const c=t.filter(d=>P(d.shape)>0);if(c.length===1)return c[0];const h=c.map(d=>d.shape);return np(h,o),Ic(c,o,n)}const a7={kernelName:fl,backendName:"webgl",kernelFunc:o7};const c7=$C+`
2020-10-12 20:28:19 +02:00
return cos(x);
2020-10-29 05:16:50 +01:00
`,l7=$m(c7),h7={kernelName:Ia,backendName:"webgl",kernelFunc:l7};const u7=`
2020-10-12 20:28:19 +02:00
if (a == b) {
return 1.0;
2020-08-29 20:56:29 +02:00
};
2020-10-29 05:16:50 +01:00
return a / b;`,d7=`
2020-10-12 20:28:19 +02:00
// vec4 one = vec4(equal(a, b));
// return one + (vec4(1.0) - one) * a / b;
vec4 result = a / b;
if(a.x == b.x) {
result.x = 1.;
}
if(a.y == b.y) {
result.y = 1.;
}
if(a.z == b.z) {
result.z = 1.;
}
if(a.w == b.w) {
result.w = 1.;
}
return result;
2020-10-29 05:16:50 +01:00
`,p7=Sc({opSnippet:u7,packedOpSnippet:d7,checkOutOfBounds:!0}),m7={kernelName:xa,backendName:"webgl",kernelFunc:p7};class PC{constructor(e,t,n){this.variableNames=["real","imag"];const s=t[1];this.outputShape=t;const i=n?`2.0 * ${Math.PI}`:`-2.0 * ${Math.PI}`,o=n?`${s}.0`:"1.0";let a;if(e==="real")a="return real * expR - imag * expI;";else if(e==="imag")a="return real * expI + imag * expR;";else throw new Error(`FFT component must be either "real" or "imag", got ${e}.`);this.userCode=`
const float exponentMultiplier = ${i};
float unaryOpComplex(float real, float expR, float imag, float expI) {
${a}
}
float mulMatDFT(int batch, int index) {
float indexRatio = float(index) / float(${s});
float exponentMultiplierTimesIndexRatio =
exponentMultiplier * indexRatio;
float result = 0.0;
for (int i = 0; i < ${s}; i++) {
// x = (-2|2 * PI / N) * index * i;
float x = exponentMultiplierTimesIndexRatio * float(i);
float expR = cos(x);
float expI = sin(x);
float real = getReal(batch, i);
float imag = getImag(batch, i);
result +=
unaryOpComplex(real, expR, imag, expI) / ${o};
}
return result;
}
void main() {
ivec2 coords = getOutputCoords();
setOutput(mulMatDFT(coords[0], coords[1]));
}
`}}function zC(e,t,n){const s=n.texData.get(e.dataId),i=P(e.shape),o=e.shape[e.shape.length-1],a=i/o,c=dr({inputs:{x:e},backend:n,attrs:{shape:[a,o]}}),h=c.shape,d=new PC("real",h,t),m=new PC("imag",h,t),f=[{dataId:s.complexTensorInfos.real.dataId,dtype:s.complexTensorInfos.real.dtype,shape:h},{dataId:s.complexTensorInfos.imag.dataId,dtype:s.complexTensorInfos.imag.dtype,shape:h}],b=n.runWebGLProgram(d,f,"float32"),w=n.runWebGLProgram(m,f,"float32"),L=Lc({inputs:{real:b,imag:w},backend:n});n.disposeIntermediateTensorInfo(b),n.disposeIntermediateTensorInfo(w);const x=dr({inputs:{x:L},backend:n,attrs:{shape:e.shape}});return n.disposeIntermediateTensorInfo(x),x}function f7(e){const{inputs:t,backend:n}=e,{input:s}=t;return zC(s,!1,n)}const g7={kernelName:pd,backendName:"webgl",kernelFunc:f7};class y7{constructor(e){this.variableNames=["Image"],this.outputShape=[];const t=e[2];this.outputShape=e,this.userCode=`
2020-10-12 20:28:19 +02:00
void main() {
ivec4 coords = getOutputCoords();
int x = coords[2];
int coordX = ${t} - x;
float outputValue;
if(coordX >= 0 && coordX < ${t}) {
outputValue = getImage(coords[0], coords[1], coordX, coords[3]);
} else {
outputValue = getImage(coords[0], coords[1], coords[2], coords[3]);
}
setOutput(outputValue);
}
2020-10-29 05:16:50 +01:00
`}}const b7={kernelName:md,backendName:"webgl",kernelFunc:({inputs:e,backend:t})=>{const{image:n}=e,s=t,i=new y7(n.shape),o=s.runWebGLProgram(i,[n],n.dtype);return o}};class w7{constructor(e){this.variableNames=["A"];const t=Pn(),[n,s]=e;this.outputShape=e,this.userCode=`
2020-10-12 20:28:19 +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-12 20:28:19 +02:00
vec4 values = ${t.texture2D}(A, uv);
float value;
if (depth == 0) {
value = values.r;
} else if (depth == 1) {
value = values.g;
} else if (depth == 2) {
value = values.b;
} else if (depth == 3) {
value = values.a;
}
setOutput(floor(value * 255.0 + 0.5));
}
2020-10-29 05:16:50 +01:00
`}}class L7{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;const t=Pn(),[n,s]=e;this.outputShape=e,this.userCode=`
2020-10-12 20:28:19 +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-12 20:28:19 +02:00
vec4 values = ${t.texture2D}(A, uv);
float value;
if (depth == 0) {
value = values.r;
} else if (depth == 1) {
value = values.g;
} else if (depth == 2) {
value = values.b;
} else if (depth == 3) {
value = values.a;
}
result[row * 2 + col] = floor(value * 255.0 + 0.5);
}
}
${t.output} = result;
}
2020-10-29 05:16:50 +01:00
`}}const S7={kernelName:Rd,backendName:"webgl",kernelFunc:I7};let xc;function I7(e){const{inputs:t,backend:n,attrs:s}=e;let{pixels:i}=t;const{numChannels:o}=s,a=typeof HTMLVideoElement!="undefined"&&i instanceof HTMLVideoElement,c=typeof HTMLImageElement!="undefined"&&i instanceof HTMLImageElement,[h,d]=a?[i.videoWidth,i.videoHeight]:[i.width,i.height],m=[d,h],f=[d,h,o];(c||a)&&(xc==null&&(xc=document.createElement("canvas").getContext("2d")),xc.canvas.width=h,xc.canvas.height=d,xc.drawImage(i,0,0,h,d),i=xc.canvas);const b=n.makeTensorInfo(m,"int32");n.texData.get(b.dataId).usage=Ns.PIXELS,n.gpgpu.uploadPixelDataToTexture(n.getTexture(b.dataId),i);const w=oe().getBool("WEBGL_PACK")?new L7(f):new w7(f),L=n.runWebGLProgram(w,[b],"int32");return n.disposeData(b.dataId),L}function x7(e){const{inputs:t,backend:n}=e,{input:s}=t;return zC(s,!0,n)}const T7={kernelName:fd,backendName:"webgl",kernelFunc:x7};class VC{constructor(e,t){this.variableNames=["x"];const{windowSize:n,batchSize:s,inSize:i,outSize:o}=e;this.outputShape=[s,o];const a=Math.floor(n/4)*4,c=n%4;let h="sumValue += dot(values, ones);";if(t!=null){const m=1/t;h=`sumValue += dot(values * ${Le(m)?m.toPrecision(2):m}, ones);`}let d="";i%n>0&&(d=`
if (inIdx < 0 || inIdx >= ${i}) {
return 0.0;
}
`),this.userCode=`
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
float getValue(int batch, int inIdx) {
${d}
return getX(batch, inIdx);
}
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
int inOffset = outIdx * ${n};
float sumValue = 0.0;
for (int i = 0; i < ${a}; i += 4) {
int inIdx = inOffset + i;
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
getValue(batch, inIdx + 3)
);
${h}
}
int inIdx = inOffset + ${a};
if (${c===1}) {
vec4 values = vec4(getValue(batch, inIdx), 0.0, 0.0, 0.0);
${h}
} else if (${c===2}) {
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1), 0.0, 0.0);
${h}
} else if (${c===3}) {
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2), 0.0);
${h}
}
setOutput(sumValue);
}
`}}function A7(e){const t=[];for(;t.length===0||t[t.length-1].outSize!==1;){const n=t.length?t[t.length-1].outSize:e[1],s=uh(n);t.push({inSize:n,windowSize:s,outSize:Math.ceil(n/s)})}return t}function GC(e,t,n,s){const i=A7(e.shape);let o=e;for(let a=0;a<i.length;a++){const{inSize:c,windowSize:h,outSize:d}=i[a];let m,f;n==="mean"?m=a===0?new VC({windowSize:h,inSize:c,batchSize:e.shape[0],outSize:d},c):new VC({windowSize:h,inSize:c,batchSize:e.shape[0],outSize:d}):m=new yC({windowSize:h,inSize:c,batchSize:e.shape[0],outSize:d},n),f=o,o=s.runWebGLProgram(m,[o],t),f.dataId!==e.dataId&&s.disposeIntermediateTensorInfo(f)}return o}function v7(e,t,n,s){const i=P(t),o=P(e.shape),a=o/i,c=dr({inputs:{x:e},attrs:{shape:[a,i]},backend:s}),h=GC(c,e.dtype,"max",s),d=dr({inputs:{x:h},attrs:{shape:n},backend:s});return s.disposeIntermediateTensorInfo(c),s.disposeIntermediateTensorInfo(h),d}class N7{constructor(e,t){this.variableNames=["A"];const n=new Array(e.length);for(let o=0;o<n.length;o++)n[o]=e[t[o]];this.outputShape=n,this.rank=n.length;const s=Rt(this.rank),i=C7(t);this.userCode=`
2020-10-12 20:28:19 +02:00
void main() {
2020-10-13 22:57:06 +02:00
${s} resRC = getOutputCoords();
2020-10-12 20:28:19 +02:00
setOutput(getA(${i}));
}
2020-10-29 05:16:50 +01:00
`}}function C7(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 R7{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0;const n=new Array(e.length);for(let d=0;d<n.length;d++)n[d]=e[t[d]];if(this.outputShape=n,this.rank=n.length,this.rank>6)throw Error(`Packed transpose for rank ${this.rank} is not yet supported.`);const s=Rt(this.rank),i=J0("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-12 20:28:19 +02:00
void main() {
2020-10-13 22:57:06 +02:00
${s} rc = getOutputCoords();
2020-10-12 20:28:19 +02:00
vec4 result = vec4(0.);
2020-10-13 22:57:06 +02:00
result[0] = ${h};
if(${c}) {
result[1] = ${h};
2020-10-12 20:28:19 +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-12 20:28:19 +02:00
}
}
setOutput(result);
}
2020-10-29 05:16:50 +01:00
`}}function CS(e,t,n){const s=oe().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new R7(e.shape,t):new N7(e.shape,t);return n.runWebGLProgram(s,[e],e.dtype)}const O7={kernelName:Rl,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:s}=e,{reductionIndices:i,keepDims:o}=t,a=n,c=s.shape.length,h=qe(i,s.shape);let d=h;const m=Xn(d,c),f=m!=null,b=a.shouldExecuteOnCPU([s]);let w=s;if(f){if(b){const O=a.texData.get(w.dataId),E=O.values,k=new Array(c);for(let $=0;$<k.length;$++)k[$]=s.shape[m[$]];const F=SS(E,s.shape,s.dtype,m,k);w=a.makeTensorInfo(k,s.dtype);const U=a.texData.get(w.dataId);U.values=F}else w=CS(s,m,a);d=as(d.length,c)}Kn("max",d,c);const[L,x]=An(w.shape,d);let v=L;o&&(v=vn(L,h));let N;if(b){const O=a.texData.get(w.dataId),E=O.values,k=XK(E,P(x),v,s.dtype);N=a.makeTensorInfo(v,s.dtype);const F=a.texData.get(N.dataId);F.values=k}else N=v7(w,x,v,a);return f&&a.disposeIntermediateTensorInfo(w),N}};function E7(e){const{inputs:t,backend:n,attrs:s}=e,{x:i}=t;du(i,"maxPool");const{filterSize:o,strides:a,pad:c,dimRoundingMode:h}=s,d=1;A(cn(a,d),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${d}'`);const m=Un(i.shape,o,a,d,c,h);if(m.filterWidth===1&&m.filterHeight===1&&ae(m.inShape,m.outShape))return ur({inputs:{x:i},backend:n});const f=new mu(m,"max",!1);return n.runWebGLProgram(f,[i],i.dtype)}const D7={kernelName:Ol,backendName:"webgl",kernelFunc:E7};function k7(e){const{inputs:t,backend:n,attrs:s}=e,{dy:i,input:o,output:a}=t,c=o;du([o,a],"maxPoolBackprop");const{filterSize:h,strides:d,pad:m,dimRoundingMode:f}=s,b=Un(c.shape,h,d,1,m,f),w=!0,L=new mu(b,"max",w),x=n.runWebGLProgram(L,[c],c.dtype),v=new u6(b),N=n.runWebGLProgram(v,[i,x],c.dtype);return n.disposeIntermediateTensorInfo(x),N}const F7={kernelName:bd,backendName:"webgl",kernelFunc:k7};function _7(e,t,n,s){let i=new mu(n,"max",!1);const o=s.runWebGLProgram(i,[e],"float32");i=new mu(n,"max",!0,!0,t);const a=s.runWebGLProgram(i,[e],"float32");return[o,a]}const W7={kernelName:wd,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:s}=e,{filterSize:i,strides:o,pad:a,includeBatchInIndex:c}=t,h=n;A(s.shape.length===4,()=>`Error in maxPool: input must be rank 4 but got rank ${s.shape.length}.`);const d=[1,1];A(cn(o,d),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${o} and dilations '${d}'`);const m=Un(s.shape,i,o,d,a),[f,b]=_7(s,c,m,h);return[f,b]}};function $7(e,t,n,s){const i=P(t),o=P(e.shape),a=o/i,c=dr({inputs:{x:e},attrs:{shape:[a,i]},backend:s}),h=GC(c,"float32","mean",s),d=dr({inputs:{x:h},attrs:{shape:n},backend:s});return s.disposeIntermediateTensorInfo(c),s.disposeIntermediateTensorInfo(h),d}const U7={kernelName:hy,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:s}=e,{keepDims:i,axis:o}=t,a=n,c=s.shape.length,h=qe(o,s.shape);let d=h;const m=Xn(d,c),f=m!=null,b=a.shouldExecuteOnCPU([s]),w=[];let L=s;if(f){if(b){const E=a.texData.get(L.dataId),k=E.values,F=new Array(c);for(let Y=0;Y<F.length;Y++)F[Y]=s.shape[m[Y]];const U=SS(k,s.shape,s.dtype,m,F);L=a.makeTensorInfo(F,s.dtype);const $=a.texData.get(L.dataId);$.values=U}else L=CS(s,m,a);w.push(L),d=as(d.length,c)}Kn("sum",d,c);const[x,v]=An(L.shape,d);let N=x;i&&(N=vn(x,h));const O=$7(L,v,N,a);for(const E of w)a.disposeIntermediateTensorInfo(E);return O}};class B7{constructor(e,t,n){this.variableNames=["x"],this.outputShape=t.map((d,m)=>d[0]+e[m]+d[1]);const s=e.length,i=Rt(s),o=t.map(d=>d[0]).join(","),a=t.map((d,m)=>d[0]+e[m]).join(","),c=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,s),h=n==="reflect"?0:1;if(s===1){this.userCode=`
int start = ${o};
int end = ${a};
void main() {
int outC = getOutputCoords();
if (outC < start) {
outC = start * 2 - outC - ${h};
} else if(outC >= end) {
outC = (end - 1) * 2 - outC + ${h};
}
setOutput(getX(outC - start));
}
`;return}this.userCode=`
${i} start = ${i}(${o});
${i} end = ${i}(${a});
void main() {
${i} outC = getOutputCoords();
for (int i = 0; i < ${s}; i++) {
if (outC[i] < start[i]) {
outC[i] = start[i] * 2 - outC[i] - ${h};
} else if(outC[i] >= end[i]) {
outC[i] = (end[i] - 1) * 2 - outC[i] + ${h};
}
}
${i} coords = outC - start;
setOutput(getX(${c}));
}
`}}class M7{constructor(e,t,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.map((w,L)=>w[0]+e[L]+w[1]);const s=e.length,i=Rt(s),o=t.map(w=>w[0]).join(","),a=t.map((w,L)=>w[0]+e[L]).join(","),c=Mn("rc",s),h=Mn("source",s),d=`${c[s-1]} < ${this.outputShape[s-1]}`,m=s===1?"source":`vec2(${h.slice(-2).join()})`,f=n==="reflect"?0:1;let b="";if(s===1){const w=`
${i} source = rc;
if (source < start) {
source = start * 2 - source - ${f};
} else if (source >= end) {
source = (end - 1) * 2 - source + ${f};
}
source -= start;
`;b=`
${i} rc = outputLoc;
${w}
result[0] = getChannel(getX(${h.join()}), ${m});
${c[s-1]} += 1;
if(${d}) {
${w}
result[1] = getChannel(getX(${h.join()}), ${m});
}
`}else{const w=`
${i} source = rc;
${i} lt = ${i}(lessThan(source, start));
${i} gte = ${i}(greaterThanEqual(source, end));
${i} orig = 1 - (lt + gte);
source = orig * source +
lt * (start * 2 - source - ${f}) +
gte * ((end - 1) * 2 - source + ${f});
source -= start;
`;b=`
${i} rc = outputLoc;
${w}
result[0] = getChannel(getX(${h.join()}), ${m});
${c[s-1]} += 1;
if(${d}) {
${w}
result[1] = getChannel(getX(${h.join()}), ${m});
}
rc = outputLoc;
${c[s-2]} += 1;
if(${c[s-2]} < ${this.outputShape[s-2]}) {
${w}
result[2] = getChannel(getX(${h.join()}), ${m});
${c[s-1]} += 1;
if(${d}) {
${w}
result[3] = getChannel(getX(${h.join()}), ${m});
}
}
`}this.userCode=`
const ${i} start = ${i}(${o});
const ${i} end = ${i}(${a});
void main() {
${i} outputLoc = getOutputCoords();
vec4 result = vec4(0.);
${b}
setOutput(result);
}
`}}const P7=({inputs:e,backend:t,attrs:n})=>{const{x:s}=e,{paddings:i,mode:o}=n,a=oe().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new M7(s.shape,i,o):new B7(s.shape,i,o),c=t.runWebGLProgram(a,[s],s.dtype);return c},z7={kernelName:El,backendName:"webgl",kernelFunc:P7};const YC={REAL:"return areal * breal - aimag * bimag;",IMAG:"return areal * bimag + aimag * breal;"};class HC{constructor(e,t,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=nt(t,n),this.userCode=`
float binaryOpComplex(
float areal, float aimag, float breal, float bimag) {
${e}
}
void main() {
float areal = getARealAtOutCoords();
float aimag = getAImagAtOutCoords();
float breal = getBRealAtOutCoords();
float bimag = getBImagAtOutCoords();
setOutput(binaryOpComplex(areal, aimag, breal, bimag));
}
`}}const qC="return a * b;";function V7(e){const{inputs:t,backend:n}=e,{a:s,b:i}=t,o=$n(s.dtype,i.dtype);if(s.dtype==="complex64"){const c=n.texData.get(s.dataId),h=n.texData.get(i.dataId),d=new HC(YC.REAL,s.shape,i.shape),m=new HC(YC.IMAG,s.shape,i.shape),f=[{dataId:c.complexTensorInfos.real.dataId,dtype:c.complexTensorInfos.real.dtype,shape:s.shape},{dataId:c.complexTensorInfos.imag.dataId,dtype:c.complexTensorInfos.imag.dtype,shape:s.shape},{dataId:h.complexTensorInfos.real.dataId,dtype:h.complexTensorInfos.real.dtype,shape:i.shape},{dataId:h.complexTensorInfos.imag.dataId,dtype:h.complexTensorInfos.imag.dtype,shape:i.shape}],b=n.runWebGLProgram(d,f,"float32"),w=n.runWebGLProgram(m,f,"float32"),L=Lc({inputs:{real:b,imag:w},backend:n});return n.disposeIntermediateTensorInfo(b),n.disposeIntermediateTensorInfo(w),L}if(n.shouldExecuteOnCPU([s,i])){const c=n.texData.get(s.dataId),h=n.texData.get(i.dataId),[d,m]=JK(s.shape,i.shape,c.values,h.values,o),f=n.makeTensorInfo(m,o),b=n.texData.get(f.dataId);return b.values=d,f}let a;return oe().getBool("WEBGL_PACK_BINARY_OPERATIONS")?a=new lr(qC,s.shape,i.shape):a=new _n(qC,s.shape,i.shape),n.runWebGLProgram(a,[s,i],o)}const G7={kernelName:Ta,backendName:"webgl",kernelFunc:V7};const Y7={kernelName:fy,backendName:"webgl",kernelFunc:({inputs:e,backend:t,attrs:n})=>{Za("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{boxes:s,scores:i}=e,{maxOutputSize:o,iouThreshold:a,scoreThreshold:c}=n,h=t,d=h.readSync(s.dataId),m=h.readSync(i.dataId),f=o,b=a,w=c;return Dp(d,m,f,b,w)}};const H7=kp,q7={kernelName:Ld,backendName:"webgl",kernelFunc:({inputs:e,backend:t,attrs:n})=>{Za("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{boxes:s,scores:i}=e,{maxOutputSize:o,iouThreshold:a,scoreThreshold:c,padToMaxOutputSize:h}=n,d=t,m=d.readSync(s.dataId),f=d.readSync(i.dataId),{selectedIndices:b,validOutputs:w}=H7(m,f,o,a,c,h);return[b,w]}};const j7=Fp,K7={kernelName:Sd,backendName:"webgl",kernelFunc:({inputs:e,backend:t,attrs:n})=>{Za("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{boxes:s,scores:i}=e,{maxOutputSize:o,iouThreshold:a,scoreThreshold:c,softNmsSigma:h}=n,d=t,m=d.readSync(s.dataId),f=d.readSync(i.dataId),b=o,w=a,L=c,x=h,{selectedIndices:v,selectedScores:N}=j7(m,f,b,w,L,x);return[v,N]}};class X7{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]=Jb(s,i,o),m=h.toFixed(3),f=d.toFixed(3);let b="";typeof n=="number"?b=`float outputValue = ${n.toFixed(2)};`:b=`
2020-10-13 22:57:06 +02:00
vec3 fill = vec3(${n.join(",")});
2020-10-12 20:28:19 +02:00
float outputValue = fill[coords[3]];`,this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int x = coords[2];
int y = coords[1];
2020-10-29 05:16:50 +01:00
float coordXFloat = (float(x) - ${m}) * ${c} - (float(y) - ${f}) * ${a};
float coordYFloat = (float(x) - ${m}) * ${a} + (float(y) - ${f}) * ${c};
2020-10-13 22:57:06 +02:00
int coordX = int(round(coordXFloat + ${m}));
2020-10-29 05:16:50 +01:00
int coordY = int(round(coordYFloat + ${f}));
2020-10-13 22:57:06 +02:00
${b}
if(coordX >= 0 && coordX < ${o} && coordY >= 0 && coordY < ${i}) {
2020-10-12 20:28:19 +02:00
outputValue = getImage(coords[0], coordY, coordX, coords[3]);
}
setOutput(outputValue);
}
2020-10-29 05:16:50 +01:00
`}}const J7={kernelName:Od,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{image:s}=e,{radians:i,fillValue:o,center:a}=t,c=n,h=new X7(s.shape,i,o,a),d=c.runWebGLProgram(h,[s],s.dtype);return d}};const Z7=$C+`
2020-10-12 20:28:19 +02:00
return sin(x);
2020-10-29 05:16:50 +01:00
`,Q7=$m(Z7),eJ={kernelName:Aa,backendName:"webgl",kernelFunc:Q7};const tJ="return x * x;",nJ=$m(tJ),sJ={kernelName:Nd,backendName:"webgl",kernelFunc:nJ};const jC="return (a - b) * (a - b);",iJ=Sc({opSnippet:jC,packedOpSnippet:jC}),rJ={kernelName:va,backendName:"webgl",kernelFunc:iJ};const KC="return a - b;",oJ=Sc({opSnippet:KC,packedOpSnippet:KC,supportsComplex:!0,cpuKernelImpl:e5}),aJ={kernelName:Na,backendName:"webgl",kernelFunc:oJ};const cJ="return tan(x);",lJ=$m(cJ),hJ={kernelName:Ca,backendName:"webgl",kernelFunc:lJ};const uJ={kernelName:Hl,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:s}=e,{perm:i}=t,o=n,a=s.shape.length,c=new Array(a);for(let d=0;d<c.length;d++)c[d]=s.shape[i[d]];let h;if(o.shouldExecuteOnCPU([s])){const d=o.texData.get(s.dataId),m=d.values,f=SS(m,s.shape,s.dtype,i,c);h=o.makeTensorInfo(c,s.dtype);const b=o.texData.get(h.dataId);b.values=f}else h=CS(s,i,o);return h}};function dJ(e){const{inputs:t,attrs:n,backend:s}=e,{axis:i}=n,{x:o}=t;du(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}=t5(a,i,o.shape,o.dtype);return[s.makeTensorInfo(h,o.dtype,c),s.makeTensorInfo([d.length],"int32",d)]}const pJ={kernelName:Cd,backendName:"webgl",kernelFunc:dJ};const mJ=[WX,MX,zX,GX,jX,e7,DX,a7,h7,m7,g7,b7,S7,EX,T7,s7,O7,D7,F7,W7,U7,z7,G7,Y7,q7,K7,XX,JX,r7,J7,eJ,sJ,aJ,rJ,hJ,uJ,pJ];for(const e of mJ)_d(e);const fJ="2.7.0";const gJ={"tfjs-core":zT,"tfjs-backend-cpu":Dq,"tfjs-backend-webgl":RX,"tfjs-data":y0,"tfjs-layers":lm,"tfjs-converter":KN,tfjs:fJ};r.Abs=td,r.Acos=ol,r.Acosh=al,r.AdadeltaOptimizer=Th,r.AdagradOptimizer=Ah,r.AdamOptimizer=vh,r.AdamaxOptimizer=Nh,r.Add=wo,r.AddN=Gg,r.All=Rx,r.Any=Ox,r.ArgMax=Yg,r.ArgMin=Hg,r.Asin=cl,r.Asinh=ll,r.Atan=hl,r.Atan2=nd,r.Atanh=ul,r.AvgPool=dl,r.AvgPool3D=qg,r.AvgPool3DBackprop=Ex,r.AvgPoolBackprop=sd,r.BatchMatMul=id,r.BatchToSpaceND=jg,r.BroadcastTo=Kg,r.Callback=FN,r.CallbackList=Cv,r.Cast=Sa,r.Ceil=pl,r.ClipByValue=ml,r.Complex=rd,r.Concat=fl,r.Conv2D=od,r.Conv2DBackpropFilter=Xg,r.Conv2DBackpropInput=ad,r.Conv3D=cd,r.Conv3DBackpropFilterV2=Jg,r.Conv3DBackpropInputV2=Zg,r.Cos=Ia,r.Cosh=gl,r.CropAndResize=Dx,r.Cumsum=Qg,r.CustomCallback=Ov,r.DataStorage=p,r.DepthToSpace=kx,r.DepthwiseConv2dNative=ld,r.DepthwiseConv2dNativeBackpropFilter=ey,r.DepthwiseConv2dNativeBackpropInput=ty,r.Diag=Fx,r.Dilation2D=hd,r.Dilation2DBackpropFilter=dd,r.Dilation2DBackpropInput=ud,r.Div=xa,r.EarlyStopping=WN,r.Elu=yl,r.EluGrad=_x,r.Environment=vx,r.Equal=Wx,r.Erf=bl,r.Exp=wl,r.Expm1=Ll,r.FFT=pd,r.Fill=ny,r.FlipLeftRight=md,r.Floor=Sl,r.FloorDiv=sy,r.FromPixels=Rd,r.FusedBatchNorm=Il,r.FusedConv2D=Dd,r.FusedDepthwiseConv2D=kd,r.GatherNd=$x,r.GatherV2=iy,r.GraphModel=jN,r.Greater=Ux,r.GreaterEqual=ry,r.History=Rv,r.IFFT=fd,r.Identity=xl,r.Imag=gd,r.InputSpec=Ln,r.IsFinite=Tl,r.IsInf=Al,r.IsNan=vl,r.KernelBackend=y,r.LRN=ay,r.LRNBackprop=Gx,r.LayerVariable=si,r.LayersModel=rr,r.Less=Bx,r.LessEqual=Mx,r.LinSpace=Px,r.Log=Nl,r.Log1p=Cl,r.LogSoftmax=oy,r.LogicalAnd=zx,r.LogicalNot=yd,r.LogicalOr=Vx,r.Max=Rl,r.MaxPool=Ol,r.MaxPool3D=ly,r.MaxPool3DBackprop=Yx,r.MaxPoolBackprop=bd,r.MaxPoolWithArgmax=wd,r.Maximum=cy,r.Mean=hy,r.Min=uy,r.Minimum=dy,r.MirrorPad=El,r.Mod=py,r.MomentumOptimizer=Ch,r.Multiply=Ta,r.Negate=my,r.NonMaxSuppressionV3=fy,r.NonMaxSuppressionV4=Ld,r.NonMaxSuppressionV5=Sd,r.NotEqual=Dl,r.OP_SCOPE_SUFFIX=pT,r.OneHot=yy,r.OnesLike=gy,r.Optimizer=er,r.PadV2=Id,r.Pool=qD,r.Pow=by,r.Prelu=xd,r.Prod=Hx,r.RMSPropOptimizer=Rh,r.RNN=Ei,r.Range=qx,r.Real=Td,r.Reciprocal=kl,r.Relu=Fl,r.Relu6=Wl,r.Reshape=_l,r.ResizeBilinear=Ly,r.ResizeBilinearGrad=Kx,r.ResizeNearestNeighbor=wy,r.ResizeNearestNeighborGrad=jx,r.Reverse=Sy,r.RotateWithOffset=Od,r.Round=$l,r.Rsqrt=Ul,r.SGDOptimizer=Ja,r.ScatterNd=Xx,r.SelectV2=Iy,r.Selu=Bl,r.Sequential=rc,r.Sigmoid=zl,r.Sign=Pl,r.Sin=Aa,r.Sinh=Ml,r.Slice=Ad,r.Softmax=Ay,r.Softplus=Vl,r.SpaceToBatchND=vd,r.SparseToDense=Jx,r.SplitV=Ty,r.Sqrt=Gl,r.Square=Nd,r.SquaredDifference=va,r.Step=ql,r.StridedSlice=Zx,r.Sub=
`)),T.join(`
`)}function jJ(r,l,u,p){const y=Zt(l),g=p[p.length-1],I=new Array(g).fill(0),S=l.length,T=u==="complex64"?Cu(r):r;if(S>1)for(let C=0;C<y/g;C++){const D=C*g;for(let _=0;_<g;_++)I[_]=Math.max(I[_],Nu(T[D+_],0,u).length)}return I}function Nu(r,l,u){let p;return Array.isArray(r)?p=`${parseFloat(r[0].toFixed(aI))} + ${parseFloat(r[1].toFixed(aI))}j`:xu(r)?p=`'${r}'`:u==="bool"?p=XR(r):p=parseFloat(r.toFixed(aI)).toString(),Ec(p,l)}function XR(r){return r===0?"false":"true"}function Qf(r,l,u,p,y,g=!0){const I=u==="complex64"?2:1,S=l[0],T=l.length;if(T===0){if(u==="complex64"){const te=Cu(r);return[Nu(te[0],0,u)]}return u==="bool"?[XR(r[0])]:[r[0].toString()]}if(T===1){if(S>jR){const P=vu*I;let ge=Array.from(r.slice(0,P)),ae=Array.from(r.slice((S-vu)*I,S*I));return u==="complex64"&&(ge=Cu(ge),ae=Cu(ae)),["["+ge.map((Le,ve)=>Nu(Le,y[ve],u)).join(", ")+", ..., "+ae.map((Le,ve)=>Nu(Le,y[S-vu+ve],u)).join(", ")+"]"]}const te=u==="complex64"?Cu(r):Array.from(r);return["["+te.map((P,ge)=>Nu(P,y[ge],u)).join(", ")+"]"]}const C=l.slice(1),D=p.slice(1),_=p[0]*I,A=[];if(S>jR){for(let te=0;te<vu;te++){const P=te*_,ge=P+_;A.push(...Qf(r.slice(P,ge),C,u,D,y,!1))}A.push("...");for(let te=S-vu;te<S;te++){const P=te*_,ge=P+_;A.push(...Qf(r.slice(P,ge),C,u,D,y,te===S-1))}}else for(let te=0;te<S;te++){const P=te*_,ge=P+_;A.push(...Qf(r.slice(P,ge),C,u,D,y,te===S-1))}const B=T===2?",":"";A[0]="["+A[0]+B;for(let te=1;te<A.length-1;te++)A[te]=" "+A[te]+B;let ne=`,
`;for(let te=2;te<T;te++)ne+=`
`;return A[A.length-1]=" "+A[A.length-1]+"]"+(g?"":ne),A}function Cu(r){const l=[];for(let u=0;u<r.length;u+=2)l.push([r[u],r[u+1]]);return l}class JR{constructor(r,l,u){if(this.dtype=l,this.shape=r.slice(),this.size=Zt(r),u!=null){const p=u.length;J(p===this.size,()=>`Length of values '${p}' does not match the size inferred by the shape '${this.size}'.`)}if(l==="complex64")throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=u||a2(l,this.size),this.strides=Au(r)}set(r,...l){l.length===0&&(l=[0]),J(l.length===this.rank,()=>`The number of provided coordinates (${l.length}) must match the rank (${this.rank})`);const u=this.locToIndex(l);this.values[u]=r}get(...r){r.length===0&&(r=[0]);let l=0;for(const p of r){if(p<0||p>=this.shape[l]){const y=`Requested out of range element at ${r}. Buffer shape=${this.shape}`;throw new Error(y)}l++}let u=r[r.length-1];for(let p=0;p<r.length-1;++p)u+=this.strides[p]*r[p];return this.values[u]}locToIndex(r){if(this.rank===0)return 0;if(this.rank===1)return r[0];let l=r[r.length-1];for(let u=0;u<r.length-1;++u)l+=this.strides[u]*r[u];return l}indexToLoc(r){if(this.rank===0)return[];if(this.rank===1)return[r];const l=new Array(this.shape.length);for(let u=0;u<l.length-1;++u)l[u]=Math.floor(r/this.strides[u]),r-=l[u]*this.strides[u];return l[l.length-1]=r,l}get rank(){return this.shape.length}toTensor(){return Bi().makeTensor(this.values,this.shape,this.dtype)}}let Bi=null,Fc=null,KJ=null;function ZR(r){Bi=r}function QR(r){Fc=r}function eO(r){KJ=r}class En{constructor(r,l,u,p){this.kept=!1,this.isDisposedInternal=!1,this.shape=r.slice(),this.dtype=l||"float32",this.size=Zt(r),this.strides=Au(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 Fc.buffer(this.shape,this.dtype,r)}bufferSync(){return Fc.buffer(this.shape,this.dtype,this.dataSync())}async array(){const r=await this.data();return JS(this.shape,r)}arraySync(){return JS(this.shape,this.dataSync())}async data(){this.throwIfDisposed();const r=Bi().read(this.dataId);if(this.dtype==="string"){const l=await r;try{return l.map(u=>oI(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=Bi().readSync(this.dataId);if(this.dtype==="string")try{return r.map(l=>oI(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 Bi().read(this.dataId);return this.dtype==="string"?r:new Uint8Array(r.buffer)}dispose(){if(this.isDisposed)return;Bi().disposeTensor(this),this.isDisposedInternal=!0}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(r=!1){return Fc.print(this,r)}clone(){return this.throwIfDisposed(),Fc.clone(this)}toString(r=!1){const l=this.dataSync();return KR(l,this.shape,this.dtype,r)}cast(r){return this.throwIfDisposed(),Fc.cast(this,r)}variable(r=!0,l,u){return this.throwIfDisposed(),Bi().makeVariable(this,r,l,u)}}Object.defineProperty(En,Symbol.hasInstance,{value:r=>!!r&&r.data!=null&&r.dataSync!=null&&r.throwIfDisposed!=null});class eg extends En{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(!Iu(r.shape,this.shape))throw new Error(`shape of the new value (${r.shape}) and previous value (${this.shape}) must match`);Bi().disposeTensor(this),this.dataId=r.dataId,Bi().incRef(this,null)}dispose(){Bi().disposeVariable(this),this.isDisposedInternal=!0}}Object.defineProperty(eg,Symbol.hasInstance,{value:r=>r instanceof En&&r.assign!=null&&r.assign instanceof Function});var tO;(function(r){r.R0="R0",
with dtype ${I.dtype}. `)});const p=(I,S)=>{const T=ft(l,u[0].shape)[0],C=fO(u.map(A=>A.shape),T);if(Zt(C)===0)return pI([],C);if(u=u.filter(A=>A.size>0),u.length===1)return u[0];const D=u.map(A=>A.shape);mO(D,T);const _=I.concat(u,T);return S(u),_},y=u,g={axis:l};return H.runKernelFunc(p,y,null,rf,g)}const Tn=V({concat_:I9});function x9(r){const l=M(r,"x","sigmoid"),u={x:l};return H.runKernelFunc((p,y)=>{const g=p.sigmoid(l);return y([g]),g},u,null,Uf)}const wI=V({sigmoid_:x9});function T9(r,l,u){const p=M(r,"x","slice");if(p.rank===0)throw new Error("Slicing scalar is not possible");const y=(S,T)=>{const[C,D]=sg(p,l,u);return lO(p,C,D),T([p]),S.slice(p,C,D)},g={x:p},I={begin:l,size:u};return H.runKernelFunc(y,g,null,_f,I)}const Tt=V({slice_:T9});function A9(r,l,u){const p=M(r,"x","batchToSpaceND"),y=l.reduce((T,C)=>T*C);J(p.rank>=1+l.length,()=>`input rank is ${p.rank} but should be > than blockShape.length ${l.length}`),J(u.length===l.length,()=>`crops.length is ${u.length} but should be equal to blockShape.length ${l.length}`),J(p.shape[0]%y===0,()=>`input tensor batch is ${p.shape[0]} but is not divisible by the product of the elements of blockShape ${l.join(" * ")} === ${y}`);const g=T=>T.batchToSpaceND(p,l,u),I={x:p},S={blockShape:l,crops:u};return H.runKernelFunc(g,I,null,nf,S)}const LI=V({batchToSpaceND_:A9});function v9(r,l){let u=M(r,"broadcastTo","x");const p=u.shape;if(l.some(D=>!(D>0)||D%1!==0))throw new Error(`broadcastTo(): Invalid broadcast shape [${l}].`);if(l.length<u.rank)throw new Error(`broadcastTo(): shape.length=${l.length} < input.rank=${u.rank}.`);if(l.length>u.rank){const D=u.shape.slice();for(;D.length<l.length;)D.unshift(1);u=re(u,D)}const y=u.shape,g=Array.from(l);for(let D=l.length-1;D>=0;D--)if(y[D]===l[D])g[D]=1;else if(u.shape[D]!==1)throw new Error(`broadcastTo(): [${p}] cannot be broadcast to [${l}].`);const I=g.map((D,_)=>D>1?_:-1).filter(D=>D>=0);if(I.length===0)return pi(u);const S=D=>D.tile(u,g),T={x:u},C={shape:l,inputShape:y};return H.runKernelFunc(S,T,null,sf,C)}const ag=V({broadcastTo_:v9});function N9(r,l,u,p,y="NHWC",g=[1,1],I){const S=M(r,"x","conv2d"),T=M(l,"filter","conv2d");let C=S,D=!1;S.rank===3&&(D=!0,C=re(S,[1,S.shape[0],S.shape[1],S.shape[2]])),J(C.rank===4,()=>`Error in conv2d: input must be rank 4, but got rank ${C.rank}.`),J(T.rank===4,()=>`Error in conv2d: filter must be rank 4, but got rank ${T.rank}.`),I!=null&&J(nn(p),()=>`Error in conv2d: pad must be an integer when using, dimRoundingMode ${I} but got pad ${p}.`);const _=y==="NHWC"?C.shape[3]:C.shape[1];J(_===T.shape[2],()=>`Error in conv2d: depth of input (${_}) must match input depth for filter ${T.shape[2]}.`),J(oo(u,g),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${u} and dilations '${g}'`);const A=(P,ge)=>{const ae=Uc(y),Le=mi(C.shape,T.shape,u,g,p,I,!1,ae),ve=P.conv2d(C,T,Le);return ge([C,T]),ve},B={x:C,filter:T},ne={strides:u,pad:p,dataFormat:y,dilations:g,dimRoundingMode:I},te=H.runKernelFunc(A,B,null,of,ne);return D?re(te,[te.shape[1],te.shape[2],te.shape[3]]):te}const SI=V({conv2d_:N9});function C9(r,l,u,p,y,g="NHWC",I){J(r.length===l.rank,()=>`Length of inShape (${r.length}) and rank of dy (${l.rank}) must match`);let S=r,T=l,C=!1;l.rank===3&&(C=!0,T=re(l,[1,l.shape[0],l.shape[1],l.shape[2]]),S=[1,r[0],r[1],r[2]]),J(S.length===4,()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${S.length}.`),J(T.rank===4,()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${T.rank}`),J(u.rank===4,()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${u.rank}`);const D=g==="NHWC"?S[3]:S[1],_=g==="NHWC"?T.shape[3]:T.shape[1];J(D===u.shape[2],()=>`Error in conv2dDerInput: depth of input (${D}) must match input depth for filter ${u.shape[2]}.`),J(_===u.shape[3],()=>`Error in conv2dDerInput: depth of output (${_}) must match output depth for filter ${u.shape[3]}.`),I!=null&&J(nn(y),()=>`Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode ${I} but got pad ${y}.`);const A=(P,ge)=>{const ae=1,Le=Uc(g),ve=mi(S,u.shap
2020-10-12 20:28:19 +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.esm.js.map