face-api/dist/face-api.js

3977 lines
935 KiB
JavaScript
Raw Normal View History

2020-10-11 18:41:17 +02:00
var faceapi=(()=>{var Ku=Object.defineProperty,ZE=Object.prototype.hasOwnProperty,qs=(e,t)=>()=>(t||(t={exports:{}},e(t.exports,t)),t.exports),yL=e=>Ku(e,"__esModule",{value:!0}),Ee=(e,t)=>{yL(e);for(var s in t)Ku(e,s,{get:t[s],enumerable:!0})},QE=(e,t)=>{if(yL(e),typeof t=="object"||typeof t=="function")for(let s in t)!ZE.call(e,s)&&s!=="default"&&Ku(e,s,{get:()=>t[s],enumerable:!0});return e},vc=e=>e&&e.__esModule?e:QE(Ku({},"default",{value:e,enumerable:!0}),e);var wL=qs((bL,Ug)=>{(function(e,t,s){function n(a){var l=this,c=o();l.next=function(){var p=2091639*l.s0+l.c*23283064365386963e-26;return l.s0=l.s1,l.s1=l.s2,l.s2=p-(l.c=p|0)},l.c=1,l.s0=c(" "),l.s1=c(" "),l.s2=c(" "),l.s0-=c(a),l.s0<0&&(l.s0+=1),l.s1-=c(a),l.s1<0&&(l.s1+=1),l.s2-=c(a),l.s2<0&&(l.s2+=1),c=null}function i(a,l){return l.c=a.c,l.s0=a.s0,l.s1=a.s1,l.s2=a.s2,l}function r(a,l){var c=new n(a),p=l&&l.state,u=c.next;return u.int32=function(){return c.next()*4294967296|0},u.double=function(){return u()+(u()*2097152|0)*11102230246251565e-32},u.quick=u,p&&(typeof p=="object"&&i(p,c),u.state=function(){return i(c,{})}),u}function o(){var a=4022871197,l=function(c){c=c.toString();for(var p=0;p<c.length;p++){a+=c.charCodeAt(p);var u=.02519603282416938*a;a=u>>>0,u-=a,u*=a,a=u>>>0,u-=a,a+=u*4294967296}return(a>>>0)*23283064365386963e-26};return l}t&&t.exports?t.exports=r:s&&s.amd?s(function(){return r}):this.alea=r})(bL,typeof Ug=="object"&&Ug,typeof define=="function"&&define)});var LL=qs((xL,$g)=>{(function(e,t,s){function n(o){var a=this,l="";a.x=0,a.y=0,a.z=0,a.w=0,a.next=function(){var p=a.x^a.x<<11;return a.x=a.y,a.y=a.z,a.z=a.w,a.w^=a.w>>>19^p^p>>>8},o===(o|0)?a.x=o:l+=o;for(var c=0;c<l.length+64;c++)a.x^=l.charCodeAt(c)|0,a.next()}function i(o,a){return a.x=o.x,a.y=o.y,a.z=o.z,a.w=o.w,a}function r(o,a){var l=new n(o),c=a&&a.state,p=function(){return(l.next()>>>0)/4294967296};return p.double=function(){do var u=l.next()>>>11,h=(l.next()>>>0)/4294967296,d=(u+h)/(1<<21);while(d===0);return d},p.int32=l.next,p.quick=p,c&&(typeof c=="object"&&i(c,l),p.state=function(){return i(l,{})}),p}t&&t.exports?t.exports=r:s&&s.amd?s(function(){return r}):this.xor128=r})(xL,typeof $g=="object"&&$g,typeof define=="function"&&define)});var IL=qs((SL,Wg)=>{(function(e,t,s){function n(o){var a=this,l="";a.next=function(){var p=a.x^a.x>>>2;return a.x=a.y,a.y=a.z,a.z=a.w,a.w=a.v,(a.d=a.d+362437|0)+(a.v=a.v^a.v<<4^(p^p<<1))|0},a.x=0,a.y=0,a.z=0,a.w=0,a.v=0,o===(o|0)?a.x=o:l+=o;for(var c=0;c<l.length+64;c++)a.x^=l.charCodeAt(c)|0,c==l.length&&(a.d=a.x<<10^a.x>>>4),a.next()}function i(o,a){return a.x=o.x,a.y=o.y,a.z=o.z,a.w=o.w,a.v=o.v,a.d=o.d,a}function r(o,a){var l=new n(o),c=a&&a.state,p=function(){return(l.next()>>>0)/4294967296};return p.double=function(){do var u=l.next()>>>11,h=(l.next()>>>0)/4294967296,d=(u+h)/(1<<21);while(d===0);return d},p.int32=l.next,p.quick=p,c&&(typeof c=="object"&&i(c,l),p.state=function(){return i(l,{})}),p}t&&t.exports?t.exports=r:s&&s.amd?s(function(){return r}):this.xorwow=r})(SL,typeof Wg=="object"&&Wg,typeof define=="function"&&define)});var TL=qs((vL,zg)=>{(function(e,t,s){function n(o){var a=this;a.next=function(){var c=a.x,p=a.i,u,h,d;return u=c[p],u^=u>>>7,h=u^u<<24,u=c[p+1&7],h^=u^u>>>10,u=c[p+3&7],h^=u^u>>>3,u=c[p+4&7],h^=u^u<<7,u=c[p+7&7],u=u^u<<13,h^=u^u<<9,c[p]=h,a.i=p+1&7,h};function l(c,p){var u,h,d=[];if(p===(p|0))h=d[0]=p;else for(p=""+p,u=0;u<p.length;++u)d[u&7]=d[u&7]<<15^p.charCodeAt(u)+d[u+1&7]<<13;for(;d.length<8;)d.push(0);for(u=0;u<8&&d[u]===0;++u);for(u==8?h=d[7]=-1:h=d[u],c.x=d,c.i=0,u=256;u>0;--u)c.next()}l(a,o)}function i(o,a){return a.x=o.x.slice(),a.i=o.i,a}function r(o,a){o==null&&(o=+new Date);var l=new n(o),c=a&&a.state,p=function(){return(l.next()>>>0)/4294967296};return p.double=function(){do var u=l.next()>>>11,h=(l.next()>>>0)/4294967296,d=(u+h)/(1<<21);while(d===0);return d},p.int32=l.next,p.quick=p,c&&(c.x&&i(c,l),p.state=function(){return i(l,{})}),p}t&&t.exports?t.exports=r:s&&s.amd?s(function(){return r}):this.xorshift7=r})(vL,typeof zg=="object"&&zg,typeof define=="function"&&define)});var NL=qs((AL,P
`)),l.join(`
`)}function W_(e,t,s,n){const i=We(t),r=n[n.length-1],o=new Array(r).fill(0),a=t.length,l=s==="complex64"?Fp(e):e;if(a>1)for(let c=0;c<i/r;c++){const p=c*r;for(let u=0;u<r;u++)o[u]=Math.max(o[u],Dp(l[p+u],0,s).length)}return o}function Dp(e,t,s){let n;return Array.isArray(e)?n=`${parseFloat(e[0].toFixed(Py))} + ${parseFloat(e[1].toFixed(Py))}j`:Un(e)?n=`'${e}'`:s==="bool"?n=kS(e):n=parseFloat(e.toFixed(Py)).toString(),Yo(n,t)}function kS(e){return e===0?"false":"true"}function _h(e,t,s,n,i,r=!0){const o=s==="complex64"?2:1,a=t[0],l=t.length;if(l===0){if(s==="complex64"){const f=Fp(e);return[Dp(f[0],0,s)]}return s==="bool"?[kS(e[0])]:[e[0].toString()]}if(l===1){if(a>ES){const g=kp*o;let y=Array.from(e.slice(0,g)),w=Array.from(e.slice((a-kp)*o,a*o));return s==="complex64"&&(y=Fp(y),w=Fp(w)),["["+y.map((x,T)=>Dp(x,i[T],s)).join(", ")+", ..., "+w.map((x,T)=>Dp(x,i[a-kp+T],s)).join(", ")+"]"]}const f=s==="complex64"?Fp(e):Array.from(e);return["["+f.map((g,y)=>Dp(g,i[y],s)).join(", ")+"]"]}const c=t.slice(1),p=n.slice(1),u=n[0]*o,h=[];if(a>ES){for(let f=0;f<kp;f++){const g=f*u,y=g+u;h.push(..._h(e.slice(g,y),c,s,p,i,!1))}h.push("...");for(let f=a-kp;f<a;f++){const g=f*u,y=g+u;h.push(..._h(e.slice(g,y),c,s,p,i,f===a-1))}}else for(let f=0;f<a;f++){const g=f*u,y=g+u;h.push(..._h(e.slice(g,y),c,s,p,i,f===a-1))}const d=l===2?",":"";h[0]="["+h[0]+d;for(let f=1;f<h.length-1;f++)h[f]=" "+h[f]+d;let m=`,
`;for(let f=2;f<l;f++)m+=`
`;return h[h.length-1]=" "+h[h.length-1]+"]"+(r?"":m),h}function Fp(e){const t=[];for(let s=0;s<e.length;s+=2)t.push([e[s],e[s+1]]);return t}class dn{constructor(e,t,s){if(this.dtype=t,this.shape=e.slice(),this.size=We(e),s!=null){const n=s.length;I(n===this.size,()=>`Length of values '${n}' 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=s||My(t,this.size),this.strides=oi(e)}set(e,...t){t.length===0&&(t=[0]),I(t.length===this.rank,()=>`The number of provided coordinates (${t.length}) must match the rank (${this.rank})`);const s=this.locToIndex(t);this.values[s]=e}get(...e){e.length===0&&(e=[0]);let t=0;for(const n of e){if(n<0||n>=this.shape[t]){const i=`Requested out of range element at ${e}. Buffer shape=${this.shape}`;throw new Error(i)}t++}let s=e[e.length-1];for(let n=0;n<e.length-1;++n)s+=this.strides[n]*e[n];return this.values[s]}locToIndex(e){if(this.rank===0)return 0;if(this.rank===1)return e[0];let t=e[e.length-1];for(let s=0;s<e.length-1;++s)t+=this.strides[s]*e[s];return t}indexToLoc(e){if(this.rank===0)return[];if(this.rank===1)return[e];const t=new Array(this.shape.length);for(let s=0;s<t.length-1;++s)t[s]=Math.floor(e/this.strides[s]),e-=t[s]*this.strides[s];return t[t.length-1]=e,t}get rank(){return this.shape.length}toTensor(){return li().makeTensor(this.values,this.shape,this.dtype)}}let li=null,il=null,z_=null;function DS(e){li=e}function FS(e){il=e}function MS(e){z_=e}class me{constructor(e,t,s,n){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=We(e),this.strides=oi(e),this.dataId=s,this.id=n,this.rankType=this.rank<5?this.rank.toString():"higher"}get rank(){return this.shape.length}async buffer(){const e=await this.data();return il.buffer(this.shape,this.dtype,e)}bufferSync(){return il.buffer(this.shape,this.dtype,this.dataSync())}async array(){const e=await this.data();return Ko(this.shape,e)}arraySync(){return Ko(this.shape,this.dataSync())}async data(){this.throwIfDisposed();const e=li().read(this.dataId);if(this.dtype==="string"){const t=await e;try{return t.map(s=>Eh(s))}catch(s){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=li().readSync(this.dataId);if(this.dtype==="string")try{return e.map(t=>Eh(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 li().read(this.dataId);return this.dtype==="string"?e:new Uint8Array(e.buffer)}dispose(){if(this.isDisposed)return;li().disposeTensor(this),this.isDisposedInternal=!0}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return il.print(this,e)}clone(){return this.throwIfDisposed(),il.clone(this)}toString(e=!1){const t=this.dataSync();return _S(t,this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),il.cast(this,e)}variable(e=!0,t,s){return this.throwIfDisposed(),li().makeVariable(this,e,t,s)}}Object.defineProperty(me,Symbol.hasInstance,{value:e=>!!e&&e.data!=null&&e.dataSync!=null&&e.throwIfDisposed!=null});class ci extends me{constructor(e,t,s,n){super(e.shape,e.dtype,e.dataId,n);this.trainable=t,this.name=s}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(!Nt(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);li().disposeTensor(this),this.dataId=e.dataId,li().incRef(this,null)}dispose(){li().disposeVariable(this),this.isDisposedInternal=!0}}Object.defineProperty(ci,Symbol.hasInstance,{value:e=>e instanceof me&&e.assign!=null&&e.assign instanceof Function});var By;(function(e){e.R0="R0",e
Manifest JSON has weights with names: ${a.join(", ")}.`)}const l=i.reduce((d,m,f)=>(m&&d.push(f),d),[]),c=[];l.forEach(d=>{t[d].paths.forEach(m=>{const f=s+(s.endsWith("/")?"":"/")+m;c.push(f)})});const p=await e(c),u={};let h=0;return l.forEach(d=>{const m=t[d].paths.length;let f=0;for(let T=0;T<m;T++)f+=p[h+T].byteLength;const g=new ArrayBuffer(f),y=new Uint8Array(g);let w=0;for(let T=0;T<m;T++){const A=new Uint8Array(p[h+T]);y.set(A,w),w+=A.byteLength}const x=r[d];x.forEach(T=>{const A=g.slice(T.groupOffset,T.groupOffset+T.sizeBytes),_=Jy(A,[T.manifestEntry]);for(const E in _)u[E]=_[E]}),h+=m}),u}}const yk="application/octet-stream",bk="application/json";class tb{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?(I(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=W().platform.fetch,I(e!=null&&e.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(e)&&I(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 s=[{paths:["./model.weights.bin"],weights:e.weightSpecs}],n={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,userDefinedMetadata:e.userDefinedMetadata,weightsManifest:s};t.body.append("model.json",new Blob([JSON.stringify(n)],{type:bk}),"model.json"),e.weightData!=null&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:yk}),"model.weights.bin");const i=await this.fetch(this.path,t);if(i.ok)return{modelArtifactsInfo:Pp(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(h){let d=`Failed to parse model JSON of response from ${this.path}.`;throw this.path.endsWith(".pb")?d+=" 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.":d+=" Please make sure the server is serving valid JSON for this request.",new Error(d)}const s=t.modelTopology,n=t.weightsManifest,i=t.generatedBy,r=t.convertedBy,o=t.format,a=t.userDefinedMetadata;if(s==null&&n==null)throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`);let l,c;if(n!=null){const h=await this.loadWeights(n);[l,c]=h}const p={modelTopology:s,weightSpecs:l,weightData:c,userDefinedMetadata:a,generatedBy:i,convertedBy:r,format:o},u=t.modelInitializer;return u&&(p.modelInitializer=u),p}async loadWeights(e){const t=Array.isArray(this.path)?this.path[1]:this.path,[s,n]=wk(t),i=this.weightPathPrefix||s,r=[];for(const c of e)r.push(...c.weights);const o=[],a=[];for(const c of e)for(const p of c.paths)this.weightUrlConverter!=null?a.push(this.weightUrlConverter(p)):o.push(i+p+n);this.weightUrlConverter&&o.push(...await Promise.all(a));const l=await eb(o,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress});return[r,zp(l)]}}tb.URL_SCHEME_REGEX=/^https?:\/\//;function w
Actual: ${i}.
Expected: ${r}.`);for(let o=0;o<r.length;++o){const a=i[o],l=r[o];if(!s(a,l))throw new Error(`Arrays differ: actual[${o}] = ${a}, expected[${o}] = ${l}.
Actual: ${i}.
Expected: ${r}.`)}}function Uk(e,t){e().then(()=>t.fail(),()=>t())}function $k(e,t){const s=typeof t=="string"||typeof t=="number"||typeof t=="boolean"?[t]:t;return Un(e)||Un(e[0])||Un(t)||Un(t[0])?ub(e,s,(n,i)=>n==i):ub(e,t,(n,i)=>hb(n,i,0))}function Wk(e,t,s){if(s==null&&(s=pb()),!hb(e,t,s))throw new Error(`Numbers differ: actual === ${e}, expected === ${t}`)}function hb(e,t,s){return!isFinite(e)&&!isFinite(t)?!0:!(isNaN(e)||isNaN(t)||Math.abs(e-t)>s)}function zk(e,t,s){for(let n=0;n<e.length;n++)if(e[n]<t||e[n]>s)throw new Error(`Value out of range:${e[n]} low: ${t}, high: ${s}`)}function Pk(e,t){expect(new Float32Array(e)).toEqual(new Float32Array(t))}const db="2.6.0";function Bk(){W().set("PROD",!0)}function jk(){W().set("DEBUG",!0)}function Vk(){W().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function It(e){W().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(e+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}MS(It);function Gk(){v.disposeVariables()}function Us(){return v}function pl(){return v.memory()}function qk(e){return v.profile(e)}function C(e,t){return v.tidy(e,t)}function ce(e){const t=Up(e);t.forEach(s=>s.dispose())}function pt(e){return v.keep(e)}function Hk(e){return v.time(e)}function uI(e){return v.setBackend(e)}function Yk(){return v.ready()}function Kk(){return v.backendName}function Xk(e){v.removeBackend(e)}function Jk(e){return v.findBackend(e)}function Zk(e){return v.findBackendFactory(e)}function Vp(e,t,s=1){return v.registerBackend(e,t,s)}function mb(){return v.backend}function Qk(e,t){W().setPlatform(e,t)}function eD(e,t){let s=b(e,"a","add"),n=b(t,"b","add");[s,n]=Ce(s,n);const i=(o,a)=>{const l=o.add(s,n);return a([s,n]),l},r={a:s,b:n};return v.runKernelFunc(i,r,null,Zn)}const $=S({add_:eD});function tD(e,t){let s=b(e,"a","floorDiv"),n=b(t,"b","floorDiv");[s,n]=Ce(s,n);const i=(o,a)=>{const l=o.floorDiv(s,n);return a([s,n]),l},r={a:s,b:n};return v.runKernelFunc(i,r,null,Xc)}const ul=S({floorDiv_:tD});function sD(e,t){let s=b(e,"a","div"),n=b(t,"b","div");if([s,n]=Ce(s,n),s.dtype==="int32"&&n.dtype==="int32")return ul(s,n);const i=(a,l)=>{const c=a.realDivide(s,n);return l([s,n]),c},r={a:s,b:n},o={};return v.runKernelFunc(i,r,null,ei,o)}const Z=S({div_:sD});function nD(e,t){let s=b(e,"a","mul"),n=b(t,"b","mul");[s,n]=Ce(s,n);const i=(o,a)=>{const l=o.multiply(s,n);return a([s,n]),l},r={a:s,b:n};return v.runKernelFunc(i,r,null,_r)}const R=S({mul_:nD});function iD(e){const t=b(e,"x","abs"),s={x:t};return v.runKernelFunc((n,i)=>(i([t]),t.dtype==="complex64"?n.complexAbs(t):n.abs(t)),s,null,_o)}const et=S({abs_:iD});function rD(e){const t=b(e,"x","acos"),s={x:t};return v.runKernelFunc((n,i)=>{const r=n.acos(t);return i([t]),r},s,null,dr)}const Uh=S({acos_:rD});function oD(e){const t=b(e,"x","acosh"),s={x:t};return v.runKernelFunc((n,i)=>{const r=n.acosh(t);return i([t]),r},s,null,mr)}const $h=S({acosh_:oD});function aD(e){I(Array.isArray(e),()=>"The argument passed to tf.addN() must be a list of tensors"),I(e.length>=1,()=>`Must pass at least one tensor to tf.addN(), but got ${e.length}`);const t=e.map((r,o)=>b(r,`tensors${o}`,"addN")),s=t[0];t.forEach(r=>{if(r.dtype!==s.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),t.forEach(r=>{if(!Nt(r.shape,s.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});const n=(r,o)=>{const a=r.addN(t);return o(t),a},i=t;return v.runKernelFunc(n,i,null,Mc)}const Wh=S({addN_:aD});function fb(e,t){for(let s=0;s<e.length;++s)if(e[e.length-s-1]!==t-1-s)return!1;return!0}function hI(e,t,s){const n=e.length+t.length,i=[];let r=0,o=0;for(let a=0;a<n;a++)s.indexOf(a)===-1?i.push(e[r++]):i.push(t[o++]);return i}function gb(e,t){const s=[],n=e.length;for(let r=0;r<n;r++)t.indexOf(r)===-1&&s.push(e[r]);const i=t.map(r=>e[r]);return[s,i]}function wt(e,t){const s=t.map(n=>1);return hI(e,s,t)}function lD(e,t,s){I(fb(t,s),()=>`${e} supports only inner-most axes for now. Got axes ${t} and rank-${s} input.`)}funct
with dtype ${o.dtype}. `)});const n=(o,a)=>{const l=Ne(t,s[0].shape)[0],c=xb(s.map(h=>h.shape),l);if(We(c)===0)return ze([],c);if(s=s.filter(h=>h.size>0),s.length===1)return s[0];const p=s.map(h=>h.shape);wb(p,l);const u=o.concat(s,l);return a(s),u},i=s,r={axis:t};return v.runKernelFunc(n,i,null,Fo,r)}const be=S({concat_:TD});function AD(e){const t=b(e,"x","sigmoid"),s={x:t};return v.runKernelFunc((n,i)=>{const r=n.sigmoid(t);return i([r]),r},s,null,Wr)}const os=S({sigmoid_:AD});function ND(e,t,s){const n=b(e,"x","slice");if(n.rank===0)throw new Error("Slicing scalar is not possible");const i=(a,l)=>{const[c,p]=jp(n,t,s);return ob(n,c,p),l([n]),a.slice(n,c,p)},r={x:n},o={begin:t,size:s};return v.runKernelFunc(i,r,null,jo,o)}const he=S({slice_:ND});function CD(e){const t=b(e,"x","tanh"),s={x:t};return v.runKernelFunc((n,i)=>{const r=n.tanh(t);return i([r]),r},s,null,jr)}const Mi=S({tanh_:CD});function RD(e,t,s,n,i,r){const o=b(e,"forgetBias","basicLSTMCell"),a=b(t,"lstmKernel","basicLSTMCell"),l=b(s,"lstmBias","basicLSTMCell"),c=b(n,"data","basicLSTMCell"),p=b(i,"c","basicLSTMCell"),u=b(r,"h","basicLSTMCell"),h=be([c,u],1),d=Te(h,a),m=$(d,l),f=m.shape[0],g=m.shape[1]/4,y=[f,g],w=he(m,[0,0],y),x=he(m,[0,g],y),T=he(m,[0,g*2],y),A=he(m,[0,g*3],y),_=$(R(os(w),Mi(x)),R(p,os($(o,T)))),E=R(Mi(_),os(A));return[_,E]}const dI=S({basicLSTMCell_:RD});function OD(e,t,s){const n=b(e,"x","batchToSpaceND"),i=t.reduce((l,c)=>l*c);I(n.rank>=1+t.length,()=>`input rank is ${n.rank} but should be > than blockShape.length ${t.length}`),I(s.length===t.length,()=>`crops.length is ${s.length} but should be equal to blockShape.length ${t.length}`),I(n.shape[0]%i===0,()=>`input tensor batch is ${n.shape[0]} but is not divisible by the product of the elements of blockShape ${t.join(" * ")} === ${i}`);const r=l=>l.batchToSpaceND(n,t,s),o={x:n},a={blockShape:t,crops:s};return v.runKernelFunc(r,o,null,Pc,a)}const Yr=S({batchToSpaceND_:OD});function mI(e){let t;return e.rank===0||e.rank===1?t=O(e,[1,1,1,e.size]):e.rank===2?t=O(e,[1,1,e.shape[0],e.shape[1]]):e.rank===3?t=O(e,[1,e.shape[0],e.shape[1],e.shape[2]]):t=e,t}function ED(e,t,s,n,i,r){r==null&&(r=.001);const o=b(e,"x","batchNorm"),a=b(t,"mean","batchNorm"),l=b(s,"variance","batchNorm");let c;i!=null&&(c=b(i,"scale","batchNorm"));let p;n!=null&&(p=b(n,"offset","batchNorm")),I(a.rank===l.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),I(p==null||a.rank===p.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),I(c==null||a.rank===c.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");const u=mI(o),h=(g,y)=>(y([u,a,l,c]),g.batchNorm(u,Hh(a),Hh(l),Hh(p),Hh(c),r)),d={x:u,scale:c,offset:p,mean:a,variance:l},m={varianceEpsilon:r},f=v.runKernelFunc(h,d,null,Ni,m);return O(f,o.shape)}function Hh(e){return e==null?null:e.rank===0?O(e,[e.size]):e.rank===1?e:e.rank===2?O(e,[1,1,e.shape[0],e.shape[1]]):e.rank===3?O(e,[1,e.shape[0],e.shape[1],e.shape[2]]):e}const Xs=S({batchNorm_:ED});function _D(e,t,s,n,i,r){const o=b(e,"x","batchNorm"),a=b(t,"mean","batchNorm"),l=b(s,"variance","batchNorm");let c;i!=null&&(c=b(i,"scale","batchNorm"));let p;return n!=null&&(p=b(n,"offset","batchNorm")),I(o.rank===2,()=>`Error in batchNorm2D: x must be rank 2 but got rank ${o.rank}.`),I(a.rank===2||a.rank===1,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${a.rank}.`),I(l.rank===2||l.rank===1,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${l.rank}.`),c!=null&&I(c.rank===2||c.rank===1,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${c.rank}.`),p!=null&&I(p.rank===2||p.rank===1,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${p.rank}.`),Xs(o,a,l,p,c,r)}const Yh=S({batchNorm2d_:_D});function kD(e,t,s,n,i,r){const o=b(e,"x","batchNorm"),a=b(t,"mean","batchNorm"),l=b(s,"variance","batchNorm");let c;i!=null&&(c=b(i,"scale","batchNorm"));let p;return n!=null&&(p=b(n,"offset","batchNorm")),I(o.rank===3,()=>`Error in batc
${i} and ${t} for depthToSpace with input shape
${n.shape}`),I(r*t>=0,()=>`Negative dimension size caused by overflow when multiplying
${r} and ${t} for depthToSpace with input shape
${n.shape}`),I(o%(t*t)===0,()=>`Dimension size must be evenly divisible by ${t*t} but is ${o} for depthToSpace with input shape ${n.shape}`);const a=p=>p.depthToSpace(n,t,s),l={x:n},c={blockSize:t,dataFormat:s};return v.runKernelFunc(a,l,null,ly,c)}const nd=S({depthToSpace_:ZD});function QD(e,t,s,n,i="NHWC",r=[1,1],o){const a=b(e,"x","depthwiseConv2d"),l=b(t,"filter","depthwiseConv2d");let c=a,p=!1;a.rank===3&&(p=!0,c=O(a,[1,a.shape[0],a.shape[1],a.shape[2]])),I(c.rank===4,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${c.rank}.`),I(l.rank===4,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${l.rank}.`),I(c.shape[3]===l.shape[2],()=>`Error in depthwiseConv2d: number of input channels (${c.shape[3]}) must match the inChannels dimension in filter ${l.shape[2]}.`),o!=null&&I(De(n),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${n}.`);const u=(f,g)=>{r==null&&(r=[1,1]),I(tt(s,r),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${s} and dilations '${r}'`);const y=rs(c.shape,l.shape,s,r,n,o,!0),w=f.depthwiseConv2D(c,l,y);return g([c,l]),w},h={x:c,filter:l},d={strides:s,pad:n,dataFormat:i,dilations:r,dimRoundingMode:o},m=v.runKernelFunc(u,h,null,Yc,d);return p?O(m,[m.shape[1],m.shape[2],m.shape[3]]):m}const fn=S({depthwiseConv2d_:QD});function eF(e){const t=b(e,"x","diag"),s=i=>{const r=O(t,[t.size]),o=i.diag(r),a=[...e.shape,...e.shape];return O(o,a)},n={x:t};return v.runKernelFunc(s,n,null,uy)}const gI=S({diag_:eF});function tF(e,t,s,n,i=[1,1],r="NHWC"){const o=b(e,"x","dilation2d"),a=b(t,"filter","dilation2d");I(o.rank===3||o.rank===4,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${o.rank}.`),I(a.rank===3,()=>`Error in dilation2d: filter must be rank 3, but got rank ${a.rank}.`),I(r==="NHWC",()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${r}`);let l=o,c=!1;o.rank===3&&(l=O(o,[1,o.shape[0],o.shape[1],o.shape[2]]),c=!0);const p={x:l,filter:a},u={strides:s,pad:n,dilations:i},h=v.runKernel(Mo,p,u);return c?O(h,[h.shape[1],h.shape[2],h.shape[3]]):h}const id=S({dilation2d_:tF});function sF(e,t){const s=e.length,n=[];for(let i=0;i<s;i++){const r=s-1-i,o=e[r]||1,a=t[t.length-1-i]||1;a>1&&o===1&&n.unshift(r)}return n}function Ke(e,t){const s=[];for(let n=0;n<t.length;n++){const i=e[e.length-n-1],r=t.length-n-1,o=t[r];(i==null||i===1&&o>1)&&s.unshift(r)}return s}function Ie(e,t){const s=[],n=Math.max(e.length,t.length);for(let i=0;i<n;i++){let r=e[e.length-i-1];r==null&&(r=1);let o=t[t.length-i-1];if(o==null&&(o=1),r===1)s.unshift(o);else if(o===1)s.unshift(r);else if(r!==o){const a=`Operands could not be broadcast together with shapes ${e} and ${t}.`;throw Error(a)}else s.unshift(r)}return s}function nF(e,t){let s=b(e,"a","equal"),n=b(t,"b","equal");[s,n]=Ce(s,n),Ie(s.shape,n.shape);const i=o=>o.equal(s,n),r={a:s,b:n};return v.runKernelFunc(i,r,null,dy)}const as=S({equal_:nF});function iF(e,t,s){const n=b(t,"a","where"),i=b(s,"b","where"),r=b(e,"condition","where","bool"),o=Ie(n.shape,i.shape),a=ta(n,o),l=ta(i,o);r.rank===1&&I(r.shape[0]===n.shape[0],()=>"The first dimension of `a` must match the size of `condition`."),r.rank!==1&&Se(r.shape,l.shape,"Error in where: ");const c=(u,h)=>{const d=u.select(r,a,l);return h([r]),d},p={condition:r,t:a,e:l};return v.runKernelFunc(c,p,null,xp)}const mt=S({where_:iF});function rF(e){const t=b(e,"x","zerosLike"),s={x:t};return v.runKernelFunc(n=>n.zerosLike(t),s,null,Np)}const re=S({zerosLike_:rF});function oF(e,t){let s=b(e,"a","div"),n=b(t,"b","div");[s,n]=Ce(s,n);const i=Z(s,n),r=re(i),o=as(n,r);return mt(o,r,i)}const rd=S({divNoNan_:oF});function aF(e,t){const s=b(e,"t1","dot"),n=b(t,"t2","dot");I((s.rank===1||s.rank===2)&&(n.rank===1||n.rank===2),()=>`Error in dot: inputs must all be rank 1 or 2, but got ranks ${s.rank} and ${n.rank}.`);const i=s.rank===1?s.size:s.shape[1],r=n.rank===1?n.size:n.shape[0];if(I(i===r,()=>`Error in dot: inner dimensions of inputs must match, but got ${i} and ${r}.`),s.rank==
rank ${r.rank}.`),I(De(t),()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`);let o=r,a=!1;r.rank===3&&(a=!0,o=O(r,[1,r.shape[0],r.shape[1],r.shape[2]]));const l=(h,d)=>{const m=h.localResponseNormalization4D(o,t,s,n,i);return d([o,m]),m},c={x:o},p={depthRadius:t,bias:s,alpha:n,beta:i},u=v.runKernelFunc(l,c,null,sp,p);return a?O(u,[u.shape[1],u.shape[2],u.shape[3]]):u}const pd=S({localResponseNormalization_:OF});function EF(e){const t=b(e,"x","log"),s={x:t};return v.runKernelFunc((n,i)=>{const r=n.log(t);return i([t]),r},s,null,Or)}const zt=S({log_:EF});function _F(e){const t=b(e,"x","log1p"),s={x:t};return v.runKernelFunc((n,i)=>{const r=n.log1p(t);return i([t]),r},s,null,Er)}const Sl=S({log1p_:_F});function kF(e){return I(ri(e),()=>"The f passed in grad(f) must be a function"),(t,s)=>{const n=b(t,"x","tf.grad",null),i=s!=null?b(s,"dy","tf.grad"):null;return v.tidy(()=>{const{value:r,grads:o}=v.gradients(()=>e(n),[n],i);return i!=null&&Se(r.shape,i.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),ud(o),o[0]})}}function DF(e){return I(ri(e),()=>"The f passed in grads(f) must be a function"),(t,s)=>{I(Array.isArray(t),()=>"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s");const n=Di(t,"args","tf.grads",null),i=s!=null?b(s,"dy","tf.grads"):null;return v.tidy(()=>{const{value:r,grads:o}=v.gradients(()=>e(...n),n,i);return i!=null&&Se(r.shape,i.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),ud(o),o})}}function FF(e){return I(ri(e),()=>"The f passed in valueAndGrad(f) must be a function"),(t,s)=>{I(t instanceof me,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),I(s==null||s instanceof me,()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");const{grads:n,value:i}=v.gradients(()=>e(t),[t],s);return ud(n),{grad:n[0],value:i}}}function MF(e){return I(ri(e),()=>"The f passed in valueAndGrads(f) must be a function"),(t,s)=>{I(Array.isArray(t)&&t.every(i=>i instanceof me),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),I(s==null||s instanceof me,()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");const n=v.gradients(()=>e(...t),t,s);return s!=null&&Se(n.value.shape,s.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),ud(n.grads),n}}function hd(e,t){I(ri(e),()=>"The f passed in variableGrads(f) must be a function"),I(t==null||Array.isArray(t)&&t.every(c=>c instanceof ci),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");const s=t!=null;if(!s){t=[];for(const c in v.registeredVariables)t.push(v.registeredVariables[c])}const n=s?t.filter(c=>!c.trainable):null,i=t.length;t=t.filter(c=>c.trainable),I(t.length>0,()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${i} variables is trainable.`);const r=!0,{value:o,grads:a}=v.gradients(e,t,null,r);I(a.some(c=>c!=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()."),I(o.rank===0,()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${o.rank} tensor`);const l={};return t.forEach((c,p)=>{a[p]!=null&&(l[c.name]=a[p])}),n!=null&&n.forEach(c=>l[c.name]=null),{value:o,grads:l}}function fs(e){return v.customGrad(e)}function ud(e){const t=e.filter(s=>s==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 UF(e){const t=b(e,"x","neg"),s={x:t};return v.runKernelFunc(n=>n.neg(t),s,null,lp)}const ke=S({neg_:UF});function $F(e){const t=b(e,"x","softplus"),s={x:t};return v.runKernelFunc((n,i)=>{const r=n.softplus(t);return i([t]),r},s,null,zr)}const di=S({softplus_:$F});function WF(e){const t=b(e,"x","logSigmoid"),s=fs(n=>{const i=ke(di(ke(n))),r=o=>{const a=R(o,os(ke(n)));return a};return{value:i,gradFunc:r}});return s(t)}const SI=S({logSigmoid_:WF});function zF(e,t=null,s=!1){const n=b(e,"x","max"),i=(a,l)=>{const c=Ne(t,n.shape);let p=c;const u=dt(p,n.rank);let h=n;u!=null&&(h=se(n,u),p=qt(p.length,h.rank));const d=a.max(h,p);u!=null&&h.dispose();let m=d;if(s){const f=wt(m.shape,Ne(t,n.shape));m=O(m,f),d.dispose()}return l([n,m]),m},r={x:n},o={reductionIndices:t,keepDims:s};return v.runKernelFunc(i,r,null,Ri,o)}const Lt=S({max_:zF});function PF(e,t){let s=b(e,"a","sub"),n=b(t,"b","sub");[s,n]=Ce(s,n);const i=(o,a)=>{const l=o.subtract(s,n);return a([s,n]),l},r={a:s,b:n};return v.runKernelFunc(i,r,null,Br)}const X=S({sub_:PF});function BF(e,t=null,s=!1){let n=b(e,"x","sum");n.dtype==="bool"&&(n=G(n,"int32"));const i=(a,l)=>{l([n]);const c=Ne(t,n.shape),p=dt(c,n.rank);let u=c,h=n;p!=null&&(h=se(n,p),u=qt(u.length,n.rank));let d=a.sum(h,u);if(s){const m=wt(d.shape,c);d=O(d,m)}return d},r={x:n},o={axis:t,keepDims:s};return v.runKernelFunc(i,r,null,Lp,o)}const te=S({sum_:BF});function jF(e,t=-1){const s=b(e,"logits","logSoftmax");if(t===-1&&(t=s.rank-1),t!==s.rank-1)throw Error(`Log Softmax along a non-last dimension is not yet supported. Logits was rank ${s.rank} and axis was ${t}`);const n=(o,a)=>{const l=!0,c=Lt(e,t,!0),p=X(e,c),u=X(G(p,"float32"),zt(te(ut(p),t,l)));return a([u]),u},i={logits:s},r={axis:t};return v.runKernelFunc(n,i,null,tp,r)}const Il=S({logSoftmax_:jF});function VF(e,t=null,s=!1){const n=b(e,"x","logSumExp"),i=Ne(t,n.shape),r=Lt(n,i,!0),o=X(n,r),a=ut(o),l=te(a,i),c=zt(l),p=$(O(r,c.shape),c);if(s){const u=wt(p.shape,i);return O(p,u)}return p}const dd=S({logSumExp_:VF});function GF(e,t){const s=b(e,"a","logicalAnd","bool"),n=b(t,"b","logicalAnd","bool");Ie(s.shape,n.shape);const i={a:s,b:n};return v.runKernelFunc(r=>r.logicalAnd(s,n),i,null,xy)}const Yt=S({logicalAnd_:GF});function qF(e){const t=b(e,"x","logicalNot","bool"),s={x:t};return v.runKernelFunc(n=>n.logicalNot(t),s,null,Ya)}const Jr=S({logicalNot_:qF});function HF(e,t){const s=b(e,"a","logicalOr","bool"),n=b(t,"b","logicalOr","bool");Ie(s.shape,n.shape);const i={a:s,b:n};return v.runKernelFunc(r=>r.logicalOr(s,n),i,null,Ly)}const vl=S({logicalOr_:HF});function YF(e,t){const s=b(e,"a","logicalXor","bool"),n=b(t,"b","logicalXor","bool");return Ie(s.shape,n.shape),Yt(vl(e,t),Jr(Yt(e,t)))}const II=S({logicalXor_:YF});function KF(e,t,s,n,i){const r=b(e,"x","maxPool"),o=1;let a=r,l=!1;r.rank===3&&(l=!0,a=O(r,[1,r.shape[0],r.shape[1],r.shape[2]])),I(a.rank===4,()=>`Error in maxPool: input must be rank 4 but got rank ${a.rank}.`),I(tt(s,o),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${s} and dilations '${o}'`),i!=null&&I(De(n),()=>`Error in maxPool: pad must be an integer when using, dimRoundingMode ${i} but got pad ${n}.`);const c=(d,m)=>{const f=Wn(a.shape,t,s,1,n,i);let g;return f.filterWidth===1&&f.filterHeight===1&&Nt(f.inShape,f.outShape)?g=a.clone():g=d.maxPool(a,f),m([a,g]),g},p={x:a},u={filterSize:t,strides:s,pad:n,dimRoundingMode:i},h=v.runKernelFunc(c,p,null,Oi,u);return l?O(h,[h.shape[1],h.shape[2],h.shape[3]]):h}const ft=S({maxPool_:KF});function XF(e,t=[1,1,1],s,n,i,r="NDHWC",o){o==null?o=[1,1,1]:It("dilations is deprecated, this field will be gone in v3.0.0.");const a=b(e,"x","maxPool3d");let l=a,c=!1;a.rank===4&&(c=!0,l=O(a,[1,a.shape[0],a.shape[1],a.shape[2],a.shape[3]])),I(l.rank===5,()=>`Error in maxPool3d: x must be rank 5 but got rank ${l.rank}.`),I(r==="NDHWC",()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${r}`),I(tt(s,o),()=>`Error in maxPool3d: Either strides or dilations must be 1. Got stri
1. The ${n} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
2. The custom ${n} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);return o}else{const r=e;if(r.className==null||r.config==null)throw new k(`${n}: Improper config format: ${JSON.stringify(r)}.
'className' and 'config' must set.`);const o=r.className;let a,l;if(o in s?[a,l]=s[o]:o in Tn?[a,l]=Tn.className:o in t&&([a,l]=t[o]),a==null)throw new k(`Unknown ${n}: ${o}. This may be due to one of the following reasons:
1. The ${n} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
2. The custom ${n} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);if(l!=null){const c={};for(const d of Object.keys(Tn))c[d]=Tn[d];for(const d of Object.keys(s))c[d]=s[d];const p=r.config;p.customObjects=c;const u=Object.assign({},Tn);for(const d of Object.keys(s))Tn[d]=s[d];$b(r.config);const h=l(a,r.config,s,i);return Tn=Object.assign({},u),h}else{const c=Object.assign({},Tn);for(const u of Object.keys(s))Tn[u]=s[u];const p=new a(r.config);return Tn=Object.assign({},c),p}}}function TW(e,t){return e<t?-1:e>t?1:0}function Qp(e,t){return-1*TW(e,t)}function An(e){if(e==null)return e;const t=[];for(const s of e)t.indexOf(s)===-1&&t.push(s);return t}function pA(e){if(e==null)throw new k(`Invalid value in obj: ${JSON.stringify(e)}`);for(const t in e)if(e.hasOwnProperty(t))return!1;return!0}function Bi(e,t,s){if(s==null)return;if(e.indexOf(s)<0)throw new k(`${s} is not a valid ${t}. Valid values are ${e} or null/undefined.`)}function Md(e,t,s=0,n=Infinity){return tn(s>=0),tn(n>=s),Array.isArray(e)&&e.length>=s&&e.length<=n&&e.every(i=>typeof i===t)}function yt(e,t){Array.isArray(e)?(N.assert(e.length>0,()=>`${t} is unexpectedly an empty array.`),e.forEach((s,n)=>yt(s,`element ${n+1} of ${t}`))):N.assert(Number.isInteger(e)&&e>0,()=>`Expected ${t} to be a positive integer, but got ${uA(e)}.`)}function uA(e){return e===null?"null":Array.isArray(e)?"["+e.map(t=>uA(t)).join(",")+"]":typeof e=="string"?`"${e}"`:`${e}`}function hA(e,t){let s=N.now(),n;const i=(...r)=>{const o=N.now();return o-s<t||(s=o,n=e(...r)),n};return i}function Ud(e){return e==="relu"?"relu":e==="linear"?"linear":e==="elu"?"elu":null}function Wb(e,t){return C(()=>Je(te(R(e,e),t,!0)))}class eu extends V.Serializable{getConfig(){return{}}}class $d extends eu{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 C(()=>{const t=Wb(e,this.axis),s=xt(t,0,this.maxValue);return R(e,Z(s,$(Tt(),t)))})}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}}$d.className="MaxNorm";V.registerClass($d);class Wd extends eu{constructor(e){super();this.defaultAxis=0,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return C(()=>Z(e,$(Tt(),Wb(e,this.axis))))}getConfig(){return{axis:this.axis}}}Wd.className="UnitNorm";V.registerClass(Wd);class zd extends eu{apply(e){return Fe(e)}}zd.className="NonNeg";V.registerClass(zd);class Pd extends eu{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 C(()=>{const t=Wb(e,this.axis),s=$(R(this.rate,xt(t,this.minValue,this.maxValue)),R(1-this.rate,t));return R(e,Z(s,$(Tt(),t)))})}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}}Pd.className="MinMaxNorm";V.registerClass(Pd);const dA={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function ot(e){return Ml(e)}function mA(e,t={}){return fi(e,V.SerializationMap.getMap().classNameMap,t,"constraint")}function at(e){if(e==null)return null;if(typeof e=="string"){const t=e in dA?dA[e]:e,s={className:t,config:{}};return mA(s)}else return e instanceof eu?e:mA(e)}const zb={};Ee(zb,{maxNorm:()=>AW,minMaxNorm:()=>RW,nonNeg:()=>CW,unitNorm:()=>NW});function AW(e){return new $d(e)}function NW(e){return new Wd(e)}function CW(){return new zd}function RW(e){return new Pd(e)}const fA=["channelsFirst","channelsLast"],gA=["valid","same","causal"],yA=["max","avg"],bA=["sum","mul","concat","ave"];const Ul=new Map;function lt(e){Bi(fA,"DataFormat",e)}function bs(e){Bi(gA,"PaddingMode",e)}function Pb(e){Bi(yA,"PoolMode",e)}const tu=[],wA="/";function zn(e,t){tu.push(e);try{const s=t();return tu.pop(),s}catch(s){throw tu.pop(),s}}function OW(){return tu.lengt
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),Bs(this.elementShape,t.shape,`TensorArray ${this.name}: Could not write to TensorArray index ${e}.`),s.read)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been read.`);if(s.written)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been written.`);s.tensor=t,pt(t),s.written=!0,this.tensors[e]=s}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((s,n)=>this.write(s,t[n]))}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 n=0;n<this.size();n++)e.push(n)}if(e.length===0)return ze([],[0].concat(this.elementShape));const s=this.readMany(e);return Bs(this.elementShape,s[0].shape,"TensorArray shape mismatch: "),Ge(s,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 ze([],[0].concat(this.elementShape));const t=[];for(let n=0;n<this.size();n++)t.push(n);const s=this.readMany(t);return Bs(this.elementShape,s[0].shape,`TensorArray shape mismatch: tensor array shape (${this.elementShape}) vs first tensor shape (${s[0].shape})`),be(s,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 s=Math.max(...e);if(!this.dynamicSize&&s>=this.maxSize)throw new Error(`Max index must be < array size (${s} vs. ${this.maxSize})`);this.writeMany(e,qe(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 s=0;const n=e.map(a=>(s+=a,s));if(s!==t.shape[0])throw new Error(`Expected sum of lengths to be equal to
tensor.shape[0], but sum of lengths is
${s}, 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=s===0?0:t.size/s,r=[];C(()=>{t=O(t,[1,s,i]);for(let a=0;a<e.length;++a){const l=a===0?0:n[a-1],c=[0,l,0],p=[1,e[a],i];r[a]=O(he(t,c,p),this.elementShape)}return r});const o=[];for(let a=0;a<e.length;a++)o[a]=a;this.writeMany(o,r)}}class Ou{constructor(e,t,s,n=-1){this.tensors=e,this.elementShape=t,this.elementDtype=s,e!=null&&e.forEach(i=>{if(s!==i.dtype)throw new Error(`Invalid data types; op elements ${s}, but list elements ${i.dtype}`);Bs(t,i.shape,"TensorList shape mismatch: "),pt(i)}),this.idTensor=j(0),this.maxNumElements=n,pt(this.idTensor)}get id(){return this.idTensor.id}copy(){return new Ou([...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,s=-1){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);if(s!==-1&&this.tensors.length!==s)throw new Error(`Operation expected a list with ${s} elements but got a list with ${this.tensors.length} elements.`);return Bs(e,this.elementShape,"TensorList shape mismatch: "),C(()=>{const n=this.tensors.map(i=>O(i,e));return Ge(n,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 s=this.tensors.pop();return Bs(s.shape,e,"TensorList shape mismatch: "),O(s,e)}pushBack(e){if(e.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${this.elementDtype}`);if(Bs(e.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");pt(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,s){if(s!==this.elementDtype)throw new Error(`Invalid data types; op elements ${s}, 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 Bs(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.`);Bs(this.elementShape,t.shape,"TensorList shape mismatch: "),pt(t),this.tensors[e]=t}gather(e,t,s){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);return Bs(this.elementShape,s,"TensorList shape mismatch: "),e=e.slice(0,this.size()),e.length===0?ze([],[0].concat(this.elementShape)):C(()=>{const n=e.map(i=>O(this.tensors[i],s));return Ge(n,0)})}concat(e,t){if(!!e&&e!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${e}`);return Bs(this.elementShape,t,"TensorList shape mismatch: "),this.size()===0?ze([],[0].concat(this.elementShape)):C(()=>{const s=this.tensors.map(n=>O(n,t));return be(s,0)})}}function JN(e,t,s){const n=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!==s)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${s}`);const i=e.shape.
tensor.shape[0], but sum of lengths is
${n}, and tensor's shape is: ${e.shape}`);const r=n===0?0:e.size/n,o=C(()=>{const l=[];e=O(e,[1,n,r]);for(let c=0;c<t.length;++c){const p=c===0?0:i[c-1],u=[0,p,0],h=[1,t[c],r];l[c]=O(he(e,u,h),s)}return e.dispose(),l}),a=new Ou([],s,e.dtype,t.length);for(let l=0;l<o.length;l++)a.setItem(l,o[l]);return a}const tC=async(e,t,s)=>{switch(e.op){case"If":case"StatelessIf":{const n=L("thenBranch",e,t,s),i=L("elseBranch",e,t,s),r=L("cond",e,t,s),o=L("args",e,t,s),a=await r.data();return a[0]?s.functionMap[n].executeFunctionAsync(o,s.tensorArrayMap,s.tensorListMap):s.functionMap[i].executeFunctionAsync(o,s.tensorArrayMap,s.tensorListMap)}case"While":case"StatelessWhile":{const n=L("body",e,t,s),i=L("cond",e,t,s),r=L("args",e,t,s),o=await s.functionMap[i].executeFunctionAsync(r,s.tensorArrayMap,s.tensorListMap),a=r.map(p=>p.id);let l=await o[0].data();o.forEach(p=>{!p.kept&&a.indexOf(p.id)===-1&&p.dispose()});let c=r;for(;l[0];){const p=c;c=await s.functionMap[n].executeFunctionAsync(c,s.tensorArrayMap,s.tensorListMap);const u=c.map(d=>d.id);p.forEach(d=>{!d.kept&&a.indexOf(d.id)===-1&&u.indexOf(d.id)===-1&&d.dispose()});const h=await s.functionMap[i].executeFunctionAsync(c,s.tensorArrayMap,s.tensorListMap);l=await h[0].data(),h.forEach(d=>{!d.kept&&a.indexOf(d.id)===-1&&u.indexOf(d.id)===-1&&d.dispose()})}return c}case"LoopCond":{const n=L("pred",e,t,s);return[qn(n)]}case"Switch":{const n=L("pred",e,t,s);let i=L("data",e,t,s);return i.kept||(i=qn(i)),(await n.data())[0]?[void 0,i]:[i,void 0]}case"Merge":{const n=e.inputNames.find(i=>Vt(i,t,s)!==void 0);if(n){const i=Vt(n,t,s);return[qn(i)]}return}case"Enter":{const n=L("frameName",e,t,s),i=L("tensor",e,t,s);return s.enterFrame(n),[qn(i)]}case"Exit":{const n=L("tensor",e,t,s);return s.exitFrame(),[qn(n)]}case"NextIteration":{const n=L("tensor",e,t,s);return s.nextIteration(),[qn(n)]}case"TensorArrayV3":{const n=L("size",e,t,s),i=L("dtype",e,t,s),r=L("elementShape",e,t,s),o=L("dynamicSize",e,t,s),a=L("clearAfterRead",e,t,s),l=L("identicalElementShapes",e,t,s),c=L("name",e,t,s),p=new XN(c,i,n,r,l,o,a);return s.addTensorArray(p),[p.idTensor,j(1)]}case"TensorArrayWriteV3":{const n=L("tensorArrayId",e,t,s),i=L("index",e,t,s),r=L("tensor",e,t,s),o=s.getTensorArray(n.id);return o.write(i,r),[o.idTensor]}case"TensorArrayReadV3":{const n=L("tensorArrayId",e,t,s),i=L("index",e,t,s),r=s.getTensorArray(n.id);return[r.read(i)]}case"TensorArrayGatherV3":{const n=L("tensorArrayId",e,t,s),i=L("indices",e,t,s),r=L("dtype",e,t,s),o=s.getTensorArray(n.id);return[o.gather(i,r)]}case"TensorArrayScatterV3":{const n=L("tensorArrayId",e,t,s),i=L("indices",e,t,s),r=L("tensor",e,t,s),o=s.getTensorArray(n.id);return o.scatter(i,r),[o.idTensor]}case"TensorArrayConcatV3":{const n=L("tensorArrayId",e,t,s),i=s.getTensorArray(n.id),r=L("dtype",e,t,s);return[i.concat(r)]}case"TensorArraySplitV3":{const n=L("tensorArrayId",e,t,s),i=L("tensor",e,t,s),r=L("lengths",e,t,s),o=s.getTensorArray(n.id);return o.split(r,i),[o.idTensor]}case"TensorArraySizeV3":{const n=L("tensorArrayId",e,t,s),i=s.getTensorArray(n.id);return[j(i.size(),"int32")]}case"TensorArrayCloseV3":{const n=L("tensorArrayId",e,t,s),i=s.getTensorArray(n.id);return i.clearAndClose(),[i.idTensor]}case"TensorListSetItem":{const n=L("tensorListId",e,t,s),i=L("index",e,t,s),r=L("tensor",e,t,s),o=s.getTensorList(n.id);return o.setItem(i,r),[o.idTensor]}case"TensorListGetItem":{const n=L("tensorListId",e,t,s),i=L("index",e,t,s),r=L("elementShape",e,t,s),o=L("elementDType",e,t,s),a=s.getTensorList(n.id);return[a.getItem(i,r,o)]}case"TensorListScatterV2":case"TensorListScatter":{const n=L("indices",e,t,s),i=L("tensor",e,t,s),r=L("elementShape",e,t,s),o=L("numElements",e,t,s),a=QN(i,n,r,o);return s.addTensorList(a),[a.idTensor]}case"TensorListReserve":{const n=L("elementShape",e,t,s),i=L("elementDType",e,t,s),r=L("numElements",e,t,s),o=ZN(n,i,r);return s.addTensorList(o),[o.idTensor]}case"TensorListGather":{const n=L("tensorListId",e,t,s),i=L("indices",e,t,s),r=L("elementShape",e,t,s),o=L("elementDType",e,t,s),a=s.getTensorList(n.id);return[a.gather(i,o,
${e}`);let n;return this.size===Infinity||this.size==null?n=this.size:t?n=Math.ceil(this.size/e):n=Math.floor(this.size/e),Os(async()=>(await s.iterator()).columnMajorBatch(e,t,pj),n)}concatenate(e){const t=this;let s;return this.size===Infinity||e.size===Infinity?s=Infinity:this.size!=null&&e.size!=null?s=this.size+e.size:s=null,Os(async()=>(await t.iterator()).concatenate(await e.iterator()),s)}filter(e){const t=this;let s;return this.size===Infinity?s=Infinity:s=null,Os(async()=>(await t.iterator()).filter(n=>C(()=>e(n))),s)}async forEachAsync(e){return(await this.iterator()).forEachAsync(e)}map(e){const t=this;return Os(async()=>(await t.iterator()).map(s=>C(()=>e(s))),this.size)}mapAsync(e){const t=this;return Os(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 Os(async()=>(await t.iterator()).prefetch(e),this.size)}repeat(e){const t=this;let s;return this.size!=null&&e>0?s=this.size*e:e===0?s=0:this.size!=null&&(e===void 0||e<0)?s=Infinity:s=null,Os(async()=>{const n=Eu(async()=>({value:await t.iterator(),done:!1}));return TC(n.take(e))},s)}skip(e){const t=this;let s;return this.size!=null&&e>=0&&this.size>=e?s=this.size-e:this.size!=null&&(this.size<e||e===void 0||e<0)?s=0:s=null,Os(async()=>(await t.iterator()).skip(e),s)}shuffle(e,t,s=!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 n=this,i=RC.alea(t||N.now().toString());return Os(async()=>{let r=i.int32();return s&&(r+=i.int32()),(await n.iterator()).shuffle(e,r.toString())},this.size)}take(e){const t=this;let s;return this.size!=null&&this.size>e?s=e:this.size!=null&&this.size<=e?s=this.size:s=null,Os(async()=>(await t.iterator()).take(e),s)}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()}}Xi.MAX_BUFFER_SIZE=1e4;function Os(e,t=null){return new class extends Xi{constructor(){super(...arguments);this.size=t}async iterator(){return e()}}}function OC(e){return Os(async()=>jw(e),e.length)}function EC(e){if(!yo(e))throw new Error("The argument to zip() must be an object or array.");let t;if(Array.isArray(e))for(let s=0;s<e.length;s++)t=t==null?e[s].size:Math.min(t,e[s].size);else if(e instanceof Object)for(const s in e)t=t==null?e[s].size:Math.min(t,e[s].size);return Os(async()=>{const s=await Ff(e,n=>{if(n instanceof Xi)return{value:n.iterator(),recurse:!1};if(yo(n))return{value:null,recurse:!0};throw new Error("Leaves of the structure passed to zip() must be Datasets, not primitives.")});return AC(s,Ki.SHORTEST)},t)}function pj(e){if(e===null)return null;const t=e[0];if(LC(t)){const s=uj(e);return{value:s,recurse:!1}}return{value:null,recurse:!0}}function uj(e){if(e.length===0)throw new Error("Can't make a batch of zero elements.");return e[0]instanceof me?Ge(e):ze(e)}class $f extends Xi{constructor(e){super();this.input=e}async iterator(){const e=await this.input.iterator(),t=e.decodeUTF8(),s=t.split(`
`).map(n=>(n.endsWith("\r")&&(n=n.slice(0,-1)),n));return s}}const Wf='"',ku=Symbol("out"),_C=Symbol("field"),zf=Symbol("quote"),Vw=Symbol("quoteafterquote"),kC=Symbol("quoteinquote");class Pf extends Xi{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 $f(e),t||(t={}),this.hasHeader=!(t.hasHeader===!1),this.fullColumnNames=t.columnNames,this.columnConfigs=t.columnConfigs,this.configuredColumnsOnly=t.configuredColumnsOnly,t.delimWhitespace?(N.assert(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&&N.assert(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((n,i)=>(n[i]=n[i]+1||1,n),{}),s=Object.keys(t).filter(n=>t[n]>1);if(N.assert(s.length===0,()=>"Duplicate column names found: "+s.toString()),this.columnConfigs)for(const n of Object.keys(this.columnConfigs)){const i=this.fullColumnNames.indexOf(n);if(i===-1)throw new Error('The key "'+n+'" 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 s=t.value,n=this.parseRow(s,!1);return n}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),s={},n={};for(let i=0;i<this.fullColumnNames.length;i++){const r=this.fullColumnNames[i],o=this.columnConfigs?this.columnConfigs[r]:null;if(this.configuredColumnsOnly&&!o)continue;{const a=t[i];let l=null;if(a==="")if(o&&o.default!==void 0)l=o.default;else{if(o&&(o.required||o.isLabel))throw new Error(`Required column ${r} is empty in this line: ${e}`);l=void 0}else{const c=Number(a);if(isNaN(c))o&&o.dtype==="bool"?l=this.getBoolean(a):l=a;else if(!o||!o.dtype)l=c;else switch(o.dtype){case"float32":l=c;break;case"int32":l=Math.floor(c);break;case"bool":l=this.getBoolean(a);break;default:l=c}}o&&o.isLabel?n[r]=l:s[r]=l}}return Object.keys(n).length===0?s:{xs:s,ys:n}}getBoolean(e){return e==="1"||e.toLowerCase()==="true"?1:0}parseRow(e,t=!0){const s=[];let n=0;const i=e.length;let r=ku;for(let o=0;o<i;o++)switch(r){case ku:switch(e.charAt(o)){case Wf:n=o+1,r=zf;break;case this.delimiter:if(n=o+1,this.delimiter===" "&&this.delimWhitespace)break;s.push(""),r=ku;break;default:r=_C,n=o;break}break;case _C:switch(e.charAt(o)){case this.delimiter:s.push(e.substring(n,o)),r=ku,n=o+1;break;default:}break;case zf:switch(e.charAt(o)){case Wf:r=Vw;break;default:}break;case Vw:switch(e.charAt(o)){case this.delimiter:s.push(e.substring(n,o-1)),r=ku,n=o+1;break;case Wf:r=zf;break;default:r=kC;break}break;case kC:switch(e.charAt(o)){case Wf:r=zf;break;default:}break;default:}if(r===Vw?s.push(e.substring(n,i-1)):s.push(e.substring(n)),t&&s.length!==this.fullColumnNames.length)throw new Error(`Invalid row in csv file. Should have ${this.fullColumnNames.length} elements in a row, but got ${s}`);return s}}class Gw extends At{constructor(e){super();this.microphoneConfig=e,this.isClosed=!1,this.fftSize=e.fftSize||1024;const t=Math.log2(this.fftSize);if
============================
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.
============================`));const n={};return this.data.set(n,{values:e,dtype:s,refCount:1}),n}makeTensorInfo(e,t,s){const n=this.write(s,e,t);return{dataId:n,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,s,n){this.data.set(e,{values:t,dtype:n,refCount:1})}numDataIds(){return this.data.numDataIds()}async read(e){return this.readSync(e)}readSync(e){const{dtype:t,complexTensorInfos:s}=this.data.get(e);if(t==="complex64"){const n=this.readSync(s.real.dataId),i=this.readSync(s.imag.dataId);return U.mergeRealAndImagArrays(n,i)}return this.data.get(e).values}bufferSync(e){const t=this.readSync(e.dataId);let s=t;if(e.dtype==="string")try{s=t.map(n=>N.decodeString(n))}catch(n){throw new Error("Failed to decode encoded string bytes into utf-8")}return ge(e.shape,e.dtype,s)}makeOutput(e,t,s){const n=this.write(e,t,s);return Us().makeTensorFromDataId(n,t,s,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 s=this.data.get(t);s.refCount--,s.refCount<1&&this.disposeData(t)}}async time(e){const t=N.now();e();const s=N.now()-t;return{kernelMs:s}}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,s,n){ee(e,"stridedSlice");const i=Ms.computeOutShape(t,s,n);if(i.some(a=>a===0))return ze([],i);const r=ge(i,e.dtype),o=this.bufferSync(e);for(let a=0;a<r.size;a++){const l=r.indexToLoc(a),c=new Array(l.length);for(let p=0;p<c.length;p++)c[p]=l[p]*n[p]+t[p];r.set(o.get(...c),...l)}return r.toTensor()}diag(e){const t=this.readSync(e.dataId),s=ge([e.size,e.size],e.dtype),n=s.values;for(let i=0;i<t.length;i++)n[i*e.size+i]=t[i];return s.toTensor()}unstack(e,t){const s=e.shape[t],n=new Array(e.rank-1);let i=0;for(let l=0;l<e.rank;l++)l!==t&&(n[i++]=e.shape[l]);const r=new Array(e.rank).fill(0),o=e.shape.slice();o[t]=1;const a=new Array(s);for(let l=0;l<a.length;l++)r[t]=l,a[l]=he(e,r,o).reshape(n);return a}reverse(e,t){ee(e,"reverse");const s=ge(e.shape,e.dtype),n=this.bufferSync(e);for(let i=0;i<s.size;i++){const r=s.indexToLoc(i),o=r.slice();t.forEach(a=>o[a]=e.shape[a]-1-o[a]),s.set(n.get(...o),...r)}return s.toTensor()}neg(e){return ee(e,"neg"),R(j(-1),e)}addN(e){ee(e,"addN");const t=e.map(i=>this.readSync(i.dataId)),s=ge(e[0].shape,e[0].dtype),n=s.values;for(let i=0;i<e.length;i++){const r=t[i];for(let o=0;o<n.length;o++)n[o]+=r[o]}return s.toTensor()}softmax(e,t){const s=N.parseAxisParam([t],e.shape),n=Lt(e,s),i=U.expandShapeToKeepDim(n.shape,s),r=X(e,n.reshape(i)),o=ut(r),a=this.sum(o,s).reshape(i);return Z(o,a)}pow(e,t){return ee([e,t],"pow"),this.broadcastedBinaryOp(e,t,e.dtype,(s,n)=>Math.pow(s,n))}batchMatMul(e,t,s,n){ee([e,t],"matMul");const i=s?e.shape[1]:e.shape[2],r=s?e.shape[2]:e.shape[1],o=n?t.shape[1]:t.shape[2],a=e.shape[0],l=this.readSync(e.dataId),c=this.readSync(t.dataId),[p,u,h]=s?[e.strides[0],1,e.strides[1]]:[e.strides[0],e.strides[1],1],[d,m,f]=n?[1,t.strides[1],t.strides[0]]:[t.strides[1],1,t.strides[0]],g=r*o,y=ge([a,r,o],e.dtype),w=y.values,x=this.blockSize;for(let T=0;T<a;T++)for(let A=0;A<r;A+=x)for(let _=0;_<o;_+=x)for(let E=0;E<i;E+=x){const F=Math.min(A+x,r),D=Math.min(_+x,o),M=Math.min(E+x,i);for(let P=A;P<F;P++)for(let B=_;B<D;B++){let Y=0;for(let q=E;q<M;q++)Y+=l[T*p+P*u+q*h]*c[q*d+B*m+T*f];w[T*g+(P*o+B)]+=Y}}return y.toTensor()}fusedBatchMatMul({a:e,b:t,transposeA:s,transposeB:n,bias:i,activation:r,preluActivationWeights:o}){let a=this.batchMatMul(e,t,s,n);return i&&(a=$(a,i)),r&&(a=Kw(this,a,r,o)),a}floorDiv(e,t){ee([e,t],"floorDiv");const s=(i,r)=>Math.floor(i/r),n="int32";return this.broadcastedBinaryOp(e,t,n,s)}sum(e,t){ee(e,"sum"),U.assertAxesAreInnerMostDims("sum",t,e.rank);const[s,n]=U.computeOutAndReduceShapes(e.shape,t),i=Ft(e.dtype,"int32"),r=ye(s,i),o=N.sizeFromShape(n),a=
`),r=i.length.toString().length+2,o=i.map((u,h)=>N.rightPad((h+1).toString(),r)+u);let a=0;for(let u=0;u<o.length;u++)a=Math.max(o[u].length,a);const l=o.slice(0,n-1),c=o.slice(n-1,n),p=o.slice(n);console.log(l.join(`
`)),console.log(t.split(`
`)[0]),console.log(`%c ${N.rightPad(c[0],a)}`,"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(p.join(`
`))}function cR(e){return Ji(e,()=>e.createProgram(),"Unable to create WebGLProgram.")}function pR(e,t){if(pe(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 eg(e,t){if(pe(e,()=>e.validateProgram(t)),e.getProgramParameter(t,e.VALIDATE_STATUS)===!1)throw console.log(e.getProgramInfoLog(t)),new Error("Shader program validation failed.")}function uR(e,t){const s=Ji(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return pe(e,()=>e.bindBuffer(e.ARRAY_BUFFER,s)),pe(e,()=>e.bufferData(e.ARRAY_BUFFER,t,e.STATIC_DRAW)),s}function hR(e,t){const s=Ji(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return pe(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,s)),pe(e,()=>e.bufferData(e.ELEMENT_ARRAY_BUFFER,t,e.STATIC_DRAW)),s}function dR(e){return Ji(e,()=>e.createTexture(),"Unable to create WebGLTexture.")}function mR(e,t){const s=W().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(e<=0||t<=0){const n=`[${e}x${t}]`;throw new Error("Requested texture size "+n+" is invalid.")}if(e>s||t>s){const n=`[${e}x${t}]`,i=`[${s}x${s}]`;throw new Error("Requested texture size "+n+" greater than WebGL maximum on this browser / GPU "+i+".")}}function fR(e){return Ji(e,()=>e.createFramebuffer(),"Unable to create WebGLFramebuffer.")}function yx(e,t,s,n,i,r,o){const a=e.getAttribLocation(t,s);return a===-1?!1:(pe(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n)),pe(e,()=>e.vertexAttribPointer(a,i,e.FLOAT,!1,r,o)),pe(e,()=>e.enableVertexAttribArray(a)),!0)}function q3(e,t,s){G3(e,s),pe(e,()=>e.activeTexture(e.TEXTURE0+s)),pe(e,()=>e.bindTexture(e.TEXTURE_2D,t))}function gR(e,t,s){return Ji(e,()=>e.getUniformLocation(t,s),'uniform "'+s+'" not present in program.')}function yR(e,t,s){return e.getUniformLocation(t,s)}function bR(e,t,s,n){pe(e,()=>q3(e,t,n)),pe(e,()=>e.uniform1i(s,n))}function tg(e,t,s){pe(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,s)),pe(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0))}function bx(e,t){pe(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,t)),pe(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0))}function Uu(e){const t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+H3(e,t))}function H3(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 Ji(e,t,s){const n=pe(e,()=>t());if(n==null)throw new Error(s);return n}function G3(e,t){const s=e.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,n=t+e.TEXTURE0;if(n<e.TEXTURE0||n>s){const i=`[gl.TEXTURE0, gl.TEXTURE${s}]`;throw new Error(`textureUnit must be in ${i}.`)}}function Lo(e,t=2){return N.sizeFromShape(e.slice(0,e.length-t))}function So(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 sg(e){let t=[1,1,1];const s=e.length===0||e.length===1&&e[0]===1;return s||(t=[Lo(e),...So(e)]),t}function wR(e,t=!1){let s=W().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(t&&(s=s*2,e=e.map((i,r)=>r>=e.length-2?N.nearestLargerEven(e[r]):e[r]),e.length===1&&(e=[2,e[0]])),e.length!==2){const i=N.squeezeShape(e);e=i.newShape}let n=N.sizeFromShape(e);if(e.length<=1&&n<=s)return[1,n];if(e.length===2&&e[0]<=s&&e[1]<=s)return e;if(e.length===3&&e[0]*e[1]<=s&&e[2]<=s)return[e[0]*e[1],e[2]];if(e.length===3&&e[0]<=s&&e[1]*e[2]<=s)return[e[0],e[1]*e[2]];if(e.length===4&&e[0]*e[1]*e[2]<=s&&e[3]<=s)return[e[0]*e[1]*e[2],e[3]];if(e.length===4&&e[0]<=s&&e[1]*e[2]*e[3]<=s)return[e[0],e[1]*e[2]*e[3]];if(t){const i=Lo(e);let r=2,o=2;return e.length&&([r,o]=So(e)),n=i*(r/2)*(o/2),N.sizeToSquarishShape(n).map(a=>a*2)}return N.sizeToSquarishShape(n)}function ng(e){return e%2===0}functio
void main() {
${s.join(`
`)}
float result = ${n};
setOutput(result);
}
`}}class zR{constructor(e,t){this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.variableNames=t.map((i,r)=>`T${r}`);const s=[];this.variableNames.forEach(i=>{s.push(`vec4 v${i} = get${i}AtOutCoords();`)});const n=this.variableNames.map(i=>`v${i}`).join(" + ");this.userCode=`
void main() {
${s.join(`
`)}
vec4 result = ${n};
setOutput(result);
}
`}}class PR{constructor(e,t,s){this.variableNames=["A"];const{windowSize:n,batchSize:i,outSize:r}=e;s||this.variableNames.push("bestIndicesA"),this.outputShape=[i,r];const o=t==="max"?">":"<",a=s?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode=`
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
int inOffset = outIdx * ${n};
int bestIndex = inOffset;
float bestValue = getA(batch, bestIndex);
for (int i = 0; i < ${n}; i++) {
int inIdx = ${a};
float candidate = getA(batch, inIdx);
if (candidate ${o} bestValue) {
bestValue = candidate;
bestIndex = inIdx;
}
}
setOutput(float(bestIndex));
}
`}}function Ix(e,t){return["x","y","z","w","u","v"].slice(0,t).map(s=>`${e}.${s}`)}function _t(e,t){return t===1?[e]:Ix(e,t)}function BR(e,t){if(e===1)return"rc";let s="";for(let n=0;n<e;n++)s+=t[n],n<e-1&&(s+=",");return s}function ct(){let e,t,s,n,i,r,o,a,l,c;return W().getNumber("WEBGL_VERSION")===2?(e="#version 300 es",t="in",s="out",n="in",i="texture",r="outputColor",o="out vec4 outputColor;",a=`
bool isnan_custom(float val) {
return (val > 0.0 || val < 0.0) ? false : val != 0.0;
}
bvec4 isnan_custom(vec4 val) {
return bvec4(isnan_custom(val.x),
isnan_custom(val.y), isnan_custom(val.z), isnan_custom(val.w));
}
#define isnan(value) isnan_custom(value)
`,l="",c=`
#define round(value) newRound(value)
int newRound(float value) {
return int(floor(value + 0.5));
}
ivec4 newRound(vec4 value) {
return ivec4(floor(value + vec4(0.5)));
}
`):(e="",t="attribute",s="varying",n="varying",i="texture2D",r="gl_FragColor",o="",a=`
#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));
}
`,l=`
uniform float INFINITY;
bool isinf(float val) {
return abs(val) == INFINITY;
}
bvec4 isinf(vec4 val) {
return equal(abs(val), vec4(INFINITY));
}
`,c=`
int round(float value) {
return int(floor(value + 0.5));
}
ivec4 round(vec4 value) {
return ivec4(floor(value + vec4(0.5)));
}
`),{version:e,attribute:t,varyingVs:s,varyingFs:n,texture2D:i,output:r,defineOutput:o,defineSpecialNaN:a,defineSpecialInf:l,defineRound:c}}function Hn(e,t,s="index"){const n=N.computeStrides(t);return n.map((i,r)=>{const o=`int ${e[r]} = ${s} / ${i}`,a=r===n.length-1?`int ${e[r+1]} = ${s} - ${e[r]} * ${i}`:`index -= ${e[r]} * ${i}`;return`${o}; ${a};`}).join("")}function nc(e){const t=N.computeStrides(e).map(s=>s.toString());return`
int getFlatIndex(ivec3 coords) {
return coords.x * ${t[0]} + coords.y * ${t[1]} + coords.z;
}
`}const rg=`
const float FLOAT_MAX = 1.70141184e38;
const float FLOAT_MIN = 1.17549435e-38;
lowp vec4 encode_float(highp float v) {
if (isnan(v)) {
return vec4(255, 255, 255, 255);
}
highp float av = abs(v);
if(av < FLOAT_MIN) {
return vec4(0.0, 0.0, 0.0, 0.0);
} else if(v > FLOAT_MAX) {
return vec4(0.0, 0.0, 128.0, 127.0) / 255.0;
} else if(v < -FLOAT_MAX) {
return vec4(0.0, 0.0, 128.0, 255.0) / 255.0;
}
highp vec4 c = vec4(0,0,0,0);
highp float e = floor(log2(av));
highp float m = exp2(fract(log2(av))) - 1.0;
c[2] = floor(128.0 * m);
m -= c[2] / 128.0;
c[1] = floor(32768.0 * m);
m -= c[1] / 32768.0;
c[0] = floor(8388608.0 * m);
highp float ebias = e + 127.0;
c[3] = floor(ebias / 2.0);
ebias -= c[3] * 2.0;
c[2] += floor(ebias) * 128.0;
c[3] += 128.0 * step(0.0, -v);
return c / 255.0;
}
`;const{getBroadcastDims:jR}=U;function VR(e,t,s,n){const i=[];e.forEach(m=>{const f=N.sizeFromShape(m.shapeInfo.logicalShape);m.shapeInfo.isUniform?i.push(`uniform float ${m.name}${f>1?`[${f}]`:""};`):(i.push(`uniform sampler2D ${m.name};`),i.push(`uniform int offset${m.name};`))});const r=i.join(`
`),o=e.map(m=>K3(m,t,n)).join(`
`),a=t.texShape,l=ct(),c=Z3(l);let p,u,h=tV(l);t.isPacked?(p=X3(t.logicalShape,a),u=eV(l)):(p=J3(t.logicalShape,a),u=Q3(l)),n&&(h+=sV);const d=[h,c,u,r,p,o,s].join(`
`);return d}function ic(e){const t=e.shapeInfo.logicalShape;switch(t.length){case 0:return nV(e);case 1:return iV(e);case 2:return rV(e);case 3:return oV(e);case 4:return aV(e);case 5:return lV(e);case 6:return cV(e);default:throw new Error(`${t.length}-D input sampling is not yet supported`)}}function GR(e){const t=e.shapeInfo.logicalShape;switch(t.length){case 0:return pV(e);case 1:return uV(e);case 2:return hV(e);case 3:return dV(e);default:return mV(e)}}function K3(e,t,s=!1){let n="";s?n+=GR(e):n+=ic(e);const i=e.shapeInfo.logicalShape,r=t.logicalShape;return i.length<=r.length&&(s?n+=fV(e,t):n+=gV(e,t)),n}function X3(e,t){switch(e.length){case 0:return qR();case 1:return yV(e,t);case 2:return xV(e,t);case 3:return bV(e,t);default:return wV(e,t)}}function J3(e,t){switch(e.length){case 0:return qR();case 1:return LV(e,t);case 2:return AV(e,t);case 3:return SV(e,t);case 4:return IV(e,t);case 5:return vV(e,t);case 6:return TV(e,t);default:throw new Error(`${e.length}-D output sampling is not yet supported`)}}function Z3(e){return`
float sampleTexture(sampler2D textureSampler, vec2 uv) {
return ${e.texture2D}(textureSampler, uv).r;
}
`}function Q3(e){return`
void setOutput(float val) {
${e.output} = vec4(val, 0, 0, 0);
}
`}function eV(e){return`
void setOutput(vec4 val) {
${e.output} = val;
}
`}function tV(e){const t=`${e.version}
precision highp float;
precision highp int;
precision highp sampler2D;
${e.varyingFs} vec2 resultUV;
${e.defineOutput}
const vec2 halfCR = vec2(0.5, 0.5);
struct ivec5
{
int x;
int y;
int z;
int w;
int u;
};
struct ivec6
{
int x;
int y;
int z;
int w;
int u;
int v;
};
uniform float NAN;
${e.defineSpecialNaN}
${e.defineSpecialInf}
${e.defineRound}
int imod(int x, int y) {
return x - y * (x / y);
}
int idiv(int a, int b, float sign) {
int res = a / b;
int mod = imod(a, b);
if (sign < 0. && mod != 0) {
res -= 1;
}
return res;
}
//Based on the work of Dave Hoskins
//https://www.shadertoy.com/view/4djSRW
#define HASHSCALE1 443.8975
float random(float seed){
vec2 p = resultUV * seed;
vec3 p3 = fract(vec3(p.xyx) * HASHSCALE1);
p3 += dot(p3, p3.yzx + 19.19);
return fract((p3.x + p3.y) * p3.z);
}
${NV}
${CV}
${RV}
`;return t}const NV=`
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);
}
`,CV=`
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);
}
`,RV=`
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);
}
`,sV=`
float getChannel(vec4 frag, vec2 innerDims) {
vec2 modCoord = mod(innerDims, 2.);
return modCoord.x == 0. ?
(modCoord.y == 0. ? frag.r : frag.g) :
(modCoord.y == 0. ? frag.b : frag.a);
}
float getChannel(vec4 frag, int dim) {
float modCoord = mod(float(dim), 2.);
return modCoord == 0. ? frag.r : frag.g;
}
`;function qR(){return`
int getOutputCoords() {
return 0;
}
`}function yV(e,t){const s=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];return s[0]===1?`
int getOutputCoords() {
return 2 * int(resultUV.x * ${s[1]}.0);
}
`:s[1]===1?`
int getOutputCoords() {
return 2 * int(resultUV.y * ${s[0]}.0);
}
`:`
int getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${s[0]}, ${s[1]}));
return 2 * (resTexRC.x * ${s[1]} + resTexRC.y);
}
`}function LV(e,t){return t[0]===1?`
int getOutputCoords() {
return int(resultUV.x * ${t[1]}.0);
}
`:t[1]===1?`
int getOutputCoords() {
return int(resultUV.y * ${t[0]}.0);
}
`:`
int getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
return resTexRC.x * ${t[1]} + resTexRC.y;
}
`}function bV(e,t){const s=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],n=Math.ceil(e[2]/2),i=n*Math.ceil(e[1]/2);return`
ivec3 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${s[0]}, ${s[1]}));
int index = resTexRC.x * ${s[1]} + resTexRC.y;
int b = index / ${i};
index -= b * ${i};
int r = 2 * (index / ${n});
int c = imod(index, ${n}) * 2;
return ivec3(b, r, c);
}
`}function SV(e,t){const s=Hn(["r","c","d"],e);return`
ivec3 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
${s}
return ivec3(r, c, d);
}
`}function wV(e,t){const s=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],n=Math.ceil(e[e.length-1]/2),i=n*Math.ceil(e[e.length-2]/2);let r=i,o="",a="b, r, c";for(let l=2;l<e.length-1;l++)r*=e[e.length-l-1],o=`
int b${l} = index / ${r};
index -= b${l} * ${r};
`+o,a=`b${l}, `+a;return`
ivec${e.length} getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${s[0]}, ${s[1]}));
int index = resTexRC.x * ${s[1]} + resTexRC.y;
${o}
int b = index / ${i};
index -= b * ${i};
int r = 2 * (index / ${n});
int c = imod(index, ${n}) * 2;
return ivec${e.length}(${a});
}
`}function IV(e,t){const s=Hn(["r","c","d","d2"],e);return`
ivec4 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
${s}
return ivec4(r, c, d, d2);
}
`}function vV(e,t){const s=Hn(["r","c","d","d2","d3"],e);return`
ivec5 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx * vec2(${t[0]},
${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
${s}
ivec5 outShape = ivec5(r, c, d, d2, d3);
return outShape;
}
`}function TV(e,t){const s=Hn(["r","c","d","d2","d3","d4"],e);return`
ivec6 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
${s}
ivec6 result = ivec6(r, c, d, d2, d3, d4);
return result;
}
`}function xV(e,t){const s=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(N.arraysEqual(e,t))return`
ivec2 getOutputCoords() {
return 2 * ivec2(resultUV.yx * vec2(${s[0]}, ${s[1]}));
}
`;const n=Math.ceil(e[1]/2);return`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${s[0]}, ${s[1]}));
int index = resTexRC.x * ${s[1]} + resTexRC.y;
int r = 2 * (index / ${n});
int c = imod(index, ${n}) * 2;
return ivec2(r, c);
}
`}function AV(e,t){return N.arraysEqual(e,t)?`
ivec2 getOutputCoords() {
return ivec2(resultUV.yx * vec2(${t[0]}, ${t[1]}));
}
`:e[1]===1?`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
return ivec2(index, 0);
}
`:e[0]===1?`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
return ivec2(0, index);
}
`:`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
int r = index / ${e[1]};
int c = index - r * ${e[1]};
return ivec2(r, c);
}
`}function Aa(e){return`offset${e}`}function pV(e){const t=e.name,s="get"+t.charAt(0).toUpperCase()+t.slice(1),n=ct();return`
vec4 ${s}() {
return ${n.texture2D}(${t}, halfCR);
}
`}function nV(e){const t=e.name,s="get"+t.charAt(0).toUpperCase()+t.slice(1);if(e.shapeInfo.isUniform)return`float ${s}() {return ${t};}`;const[n,i]=e.shapeInfo.texShape;if(n===1&&i===1)return`
float ${s}() {
return sampleTexture(${t}, halfCR);
}
`;const[r,o]=e.shapeInfo.texShape,a=Aa(t);return`
float ${s}() {
vec2 uv = uvFromFlat(${r}, ${o}, ${a});
return sampleTexture(${t}, uv);
}
`}function uV(e){const t=e.name,s="get"+t.charAt(0).toUpperCase()+t.slice(1),n=e.shapeInfo.texShape,i=[Math.ceil(n[0]/2),Math.ceil(n[1]/2)],r=ct();return`
vec4 ${s}(int index) {
vec2 uv = packedUVfrom1D(
${i[0]}, ${i[1]}, index);
return ${r.texture2D}(${t}, uv);
}
`}function iV(e){const t=e.name,s="get"+t.charAt(0).toUpperCase()+t.slice(1);if(e.shapeInfo.isUniform)return`
float ${s}(int index) {
${rc(e)}
}
`;const n=e.shapeInfo.texShape,i=n[0],r=n[1];if(r===1&&i===1)return`
float ${s}(int index) {
return sampleTexture(${t}, halfCR);
}
`;const o=Aa(t);return r===1?`
float ${s}(int index) {
vec2 uv = vec2(0.5, (float(index + ${o}) + 0.5) / ${i}.0);
return sampleTexture(${t}, uv);
}
`:i===1?`
float ${s}(int index) {
vec2 uv = vec2((float(index + ${o}) + 0.5) / ${r}.0, 0.5);
return sampleTexture(${t}, uv);
}
`:`
float ${s}(int index) {
vec2 uv = uvFromFlat(${i}, ${r}, index + ${o});
return sampleTexture(${t}, uv);
}
`}function hV(e){const t=e.shapeInfo.logicalShape,s=e.name,n="get"+s.charAt(0).toUpperCase()+s.slice(1),i=e.shapeInfo.texShape,r=i[0],o=i[1],a=ct();if(i!=null&&N.arraysEqual(t,i))return`
vec4 ${n}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${o}.0, ${r}.0);
return ${a.texture2D}(${s}, uv);
}
`;const l=[Math.ceil(i[0]/2),Math.ceil(i[1]/2)],c=Math.ceil(t[1]/2);return`
vec4 ${n}(int row, int col) {
vec2 uv = packedUVfrom2D(${c}, ${l[0]}, ${l[1]}, row, col);
return ${a.texture2D}(${s}, uv);
}
`}function rV(e){const t=e.shapeInfo.logicalShape,s=e.name,n="get"+s.charAt(0).toUpperCase()+s.slice(1),i=e.shapeInfo.texShape;if(i!=null&&N.arraysEqual(t,i)){const u=i[0],h=i[1];return`
float ${n}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${h}.0, ${u}.0);
return sampleTexture(${s}, uv);
}
`}const{newShape:r,keptDims:o}=N.squeezeShape(t),a=r;if(a.length<t.length){const u=oc(e,a),h=["row","col"];return`
${ic(u)}
float ${n}(int row, int col) {
return ${n}(${ac(h,o)});
}
`}if(e.shapeInfo.isUniform)return`
float ${n}(int row, int col) {
int index = round(dot(vec2(row, col), vec2(${t[1]}, 1)));
${rc(e)}
}
`;const l=i[0],c=i[1],p=Aa(s);return c===1?`
float ${n}(int row, int col) {
float index = dot(vec3(row, col, ${p}), vec3(${t[1]}, 1, 1));
vec2 uv = vec2(0.5, (index + 0.5) / ${l}.0);
return sampleTexture(${s}, uv);
}
`:l===1?`
float ${n}(int row, int col) {
float index = dot(vec3(row, col, ${p}), vec3(${t[1]}, 1, 1));
vec2 uv = vec2((index + 0.5) / ${c}.0, 0.5);
return sampleTexture(${s}, uv);
}
`:`
float ${n}(int row, int col) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${t[1]} + col + ${p};
vec2 uv = uvFromFlat(${l}, ${c}, index);
return sampleTexture(${s}, uv);
}
`}function dV(e){const t=e.shapeInfo.logicalShape,s=e.name,n="get"+s.charAt(0).toUpperCase()+s.slice(1),i=e.shapeInfo.texShape,r=[Math.ceil(i[0]/2),Math.ceil(i[1]/2)];if(t[0]===1){const u=t.slice(1),h=[1,2],d=oc(e,u),m=["b","row","col"];return`
${GR(d)}
vec4 ${n}(int b, int row, int col) {
return ${n}(${ac(m,h)});
}
`}const o=r[0],a=r[1],l=Math.ceil(t[2]/2),c=l*Math.ceil(t[1]/2),p=ct();return`
vec4 ${n}(int b, int row, int col) {
vec2 uv = packedUVfrom3D(
${o}, ${a}, ${c}, ${l}, b, row, col);
return ${p.texture2D}(${s}, uv);
}
`}function oV(e){const t=e.shapeInfo.logicalShape,s=e.name,n="get"+s.charAt(0).toUpperCase()+s.slice(1),i=t[1]*t[2],r=t[2],{newShape:o,keptDims:a}=N.squeezeShape(t),l=o;if(l.length<t.length){const m=oc(e,l),f=["row","col","depth"];return`
${ic(m)}
float ${n}(int row, int col, int depth) {
return ${n}(${ac(f,a)});
}
`}if(e.shapeInfo.isUniform)return`
float ${n}(int row, int col, int depth) {
int index = round(dot(vec3(row, col, depth),
vec3(${i}, ${r}, 1)));
${rc(e)}
}
`;const c=e.shapeInfo.texShape,p=c[0],u=c[1],h=e.shapeInfo.flatOffset;if(u===i&&h==null)return`
float ${n}(int row, int col, int depth) {
float texR = float(row);
float texC = dot(vec2(col, depth), vec2(${r}, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${u}.0, ${p}.0);
return sampleTexture(${s}, uv);
}
`;if(u===r&&h==null)return`
float ${n}(int row, int col, int depth) {
float texR = dot(vec2(row, col), vec2(${t[1]}, 1));
float texC = float(depth);
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${u}.0, ${p}.0);
return sampleTexture(${s}, uv);
}
`;const d=Aa(s);return`
float ${n}(int row, int col, int depth) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${i} + col * ${r} + depth + ${d};
vec2 uv = uvFromFlat(${p}, ${u}, index);
return sampleTexture(${s}, uv);
}
`}function mV(e){const t=e.shapeInfo.logicalShape,s=t.length,n=e.name,i="get"+n.charAt(0).toUpperCase()+n.slice(1),r=e.shapeInfo.texShape,o=[Math.ceil(r[0]/2),Math.ceil(r[1]/2)],a=o[0],l=o[1],c=Math.ceil(t[s-1]/2);let p=c*Math.ceil(t[s-2]/2),u="int b, int row, int col",h=`b * ${p} + (row / 2) * ${c} + (col / 2)`;for(let m=2;m<s-1;m++)u=`int b${m}, `+u,p*=t[s-m-1],h=`b${m} * ${p} + `+h;const d=ct();return`
vec4 ${i}(${u}) {
int index = ${h};
int texR = index / ${l};
int texC = index - texR * ${l};
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${l}, ${a});
return ${d.texture2D}(${n}, uv);
}
`}function aV(e){const t=e.shapeInfo.logicalShape,s=e.name,n="get"+s.charAt(0).toUpperCase()+s.slice(1),i=t[3],r=t[2]*i,o=t[1]*r,{newShape:a,keptDims:l}=N.squeezeShape(t);if(a.length<t.length){const m=oc(e,a),f=["row","col","depth","depth2"];return`
${ic(m)}
float ${n}(int row, int col, int depth, int depth2) {
return ${n}(${ac(f,l)});
}
`}if(e.shapeInfo.isUniform)return`
float ${n}(int row, int col, int depth, int depth2) {
int index = round(dot(vec4(row, col, depth, depth2),
vec4(${o}, ${r}, ${i}, 1)));
${rc(e)}
}
`;const c=e.shapeInfo.flatOffset,p=e.shapeInfo.texShape,u=p[0],h=p[1];if(h===o&&c==null)return`
float ${n}(int row, int col, int depth, int depth2) {
float texR = float(row);
float texC =
dot(vec3(col, depth, depth2),
vec3(${r}, ${i}, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${h}.0, ${u}.0);
return sampleTexture(${s}, uv);
}
`;if(h===i&&c==null)return`
float ${n}(int row, int col, int depth, int depth2) {
float texR = dot(vec3(row, col, depth),
vec3(${t[1]*t[2]}, ${t[2]}, 1));
float texC = float(depth2);
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${h}.0, ${u}.0);
return sampleTexture(${s}, uv);
}
`;const d=Aa(s);return`
float ${n}(int row, int col, int depth, int depth2) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${o} + col * ${r} +
depth * ${i} + depth2;
vec2 uv = uvFromFlat(${u}, ${h}, index + ${d});
return sampleTexture(${s}, uv);
}
`}function lV(e){const t=e.shapeInfo.logicalShape,s=e.name,n="get"+s.charAt(0).toUpperCase()+s.slice(1),i=t[4],r=t[3]*i,o=t[2]*r,a=t[1]*o,{newShape:l,keptDims:c}=N.squeezeShape(t);if(l.length<t.length){const f=oc(e,l),g=["row","col","depth","depth2","depth3"];return`
${ic(f)}
float ${n}(int row, int col, int depth, int depth2, int depth3) {
return ${n}(${ac(g,c)});
}
`}if(e.shapeInfo.isUniform)return`
float ${n}(int row, int col, int depth, int depth2, int depth3) {
float index = dot(
vec4(row, col, depth, depth2),
vec4(${a}, ${o}, ${r}, ${i})) +
depth3;
${rc(e)}
}
`;const p=e.shapeInfo.flatOffset,u=e.shapeInfo.texShape,h=u[0],d=u[1];if(d===a&&p==null)return`
float ${n}(int row, int col, int depth, int depth2, int depth3) {
int texR = row;
float texC = dot(vec4(col, depth, depth2, depth3),
vec4(${o}, ${r}, ${i}, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${d}.0, ${h}.0);
return sampleTexture(${s}, uv);
}
`;if(d===i&&p==null)return`
float ${n}(int row, int col, int depth, int depth2, int depth3) {
float texR = dot(
vec4(row, col, depth, depth2),
vec4(${t[1]*t[2]*t[3]},
${t[2]*t[3]}, ${t[3]}, 1));
int texC = depth3;
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${d}.0, ${h}.0);
return sampleTexture(${s}, uv);
}
`;const m=Aa(s);return`
float ${n}(int row, int col, int depth, int depth2, int depth3) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${a} + col * ${o} + depth * ${r} +
depth2 * ${i} + depth3 + ${m};
vec2 uv = uvFromFlat(${h}, ${d}, index);
return sampleTexture(${s}, uv);
}
`}function cV(e){const t=e.shapeInfo.logicalShape,s=e.name,n="get"+s.charAt(0).toUpperCase()+s.slice(1),{newShape:i,keptDims:r}=N.squeezeShape(t);if(i.length<t.length){const g=oc(e,i),y=["row","col","depth","depth2","depth3","depth4"];return`
${ic(g)}
float ${n}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
return ${n}(${ac(y,r)});
}
`}const o=t[5],a=t[4]*o,l=t[3]*a,c=t[2]*l,p=t[1]*c;if(e.shapeInfo.isUniform)return`
float ${n}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
int index = round(dot(
vec4(row, col, depth, depth2),
vec4(${p}, ${c}, ${l}, ${a})) +
dot(
vec2(depth3, depth4),
vec2(${o}, 1)));
${rc(e)}
}
`;const u=e.shapeInfo.flatOffset,h=e.shapeInfo.texShape,d=h[0],m=h[1];if(m===p&&u==null)return`
float ${n}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
int texR = row;
float texC = dot(vec4(col, depth, depth2, depth3),
vec4(${c}, ${l}, ${a}, ${o})) +
float(depth4);
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${m}.0, ${d}.0);
return sampleTexture(${s}, uv);
}
`;if(m===o&&u==null)return`
float ${n}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
float texR = dot(vec4(row, col, depth, depth2),
vec4(${t[1]*t[2]*t[3]*t[4]},
${t[2]*t[3]*t[4]},
${t[3]*t[4]},
${t[4]})) + float(depth3);
int texC = depth4;
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${m}.0, ${d}.0);
return sampleTexture(${s}, uv);
}
`;const f=Aa(s);return`
float ${n}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${p} + col * ${c} + depth * ${l} +
depth2 * ${a} + depth3 * ${o} + depth4 + ${f};
vec2 uv = uvFromFlat(${d}, ${m}, index);
return sampleTexture(${s}, uv);
}
`}function rc(e){const t=e.name,s=N.sizeFromShape(e.shapeInfo.logicalShape);return s<2?`return ${t};`:`
for (int i = 0; i < ${s}; i++) {
if (i == index) {
return ${t}[i];
}
}
`}function fV(e,t){const s=e.name,n=s.charAt(0).toUpperCase()+s.slice(1),i="get"+n+"AtOutCoords",r=e.shapeInfo.logicalShape.length,o=t.logicalShape.length,a=jR(e.shapeInfo.logicalShape,t.logicalShape),l=Re(o),c=o-r;let p;const u=["x","y","z","w","u","v"];r===0?p="":o<2&&a.length>=1?p="coords = 0;":p=a.map(w=>`coords.${u[w+c]} = 0;`).join(`
`);let h="";o<2&&r>0?h="coords":h=e.shapeInfo.logicalShape.map((w,x)=>`coords.${u[x+c]}`).join(", ");let d="return outputValue;";const m=N.sizeFromShape(e.shapeInfo.logicalShape),f=m===1,g=N.sizeFromShape(t.logicalShape),y=g===1;if(r===1&&!f&&!y)d=`
return vec4(outputValue.xy, outputValue.xy);
`;else if(f&&!y)o===1?d=`
return vec4(outputValue.x, outputValue.x, 0., 0.);
`:d=`
return vec4(outputValue.x);
`;else if(a.length){const w=r-2,x=r-1;a.indexOf(w)>-1&&a.indexOf(x)>-1?d="return vec4(outputValue.x);":a.indexOf(w)>-1?d="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":a.indexOf(x)>-1&&(d="return vec4(outputValue.xx, outputValue.zz);")}return`
vec4 ${i}() {
${l} coords = getOutputCoords();
${p}
vec4 outputValue = get${n}(${h});
${d}
}
`}function gV(e,t){const s=e.name,n=s.charAt(0).toUpperCase()+s.slice(1),i="get"+n+"AtOutCoords",r=t.texShape,o=e.shapeInfo.texShape,a=e.shapeInfo.logicalShape.length,l=t.logicalShape.length;if(!e.shapeInfo.isUniform&&a===l&&e.shapeInfo.flatOffset==null&&N.arraysEqual(o,r))return`
float ${i}() {
return sampleTexture(${s}, resultUV);
}
`;const c=Re(l),p=jR(e.shapeInfo.logicalShape,t.logicalShape),u=l-a;let h;const d=["x","y","z","w","u","v"];a===0?h="":l<2&&p.length>=1?h="coords = 0;":h=p.map(f=>`coords.${d[f+u]} = 0;`).join(`
`);let m="";return l<2&&a>0?m="coords":m=e.shapeInfo.logicalShape.map((f,g)=>`coords.${d[g+u]}`).join(", "),`
float ${i}() {
${c} coords = getOutputCoords();
${h}
return get${n}(${m});
}
`}function Re(e){if(e<=1)return"int";if(e===2)return"ivec2";if(e===3)return"ivec3";if(e===4)return"ivec4";if(e===5)return"ivec5";if(e===6)return"ivec6";throw Error(`GPU for rank ${e} is not yet supported`)}function oc(e,t){const s=JSON.parse(JSON.stringify(e));return s.shapeInfo.logicalShape=t,s}function ac(e,t){return t.map(s=>e[s]).join(", ")}class HR{constructor(e,t,s,n){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,N.assert(e.length>2,()=>`Packed arg${s.charAt(0).toUpperCase()+s.slice(1)} supports only inputs with rank above 2.`);const i=e[e.length-1],r=Math.ceil(i/t);this.outputShape=e.slice(0,-1),r>1&&this.outputShape.push(r),n||this.variableNames.push("bestIndicesA");const o=this.outputShape,a=o.length,l=Re(a),c=_t("coords",a);let p,u;if(r===1){u=a+1;const E=Re(u);p=`
${E} sourceLocR = ${E}(${c.join()}, 0);
++${c[a-1]};
${E} sourceLocG = ${E}(${c.join()}, 0);
++${c[a-2]};
${E} sourceLocA = ${E}(${c.join()}, 0);
--${c[a-1]};
${E} sourceLocB = ${E}(${c.join()}, 0);
--${c[a-2]};`}else u=a,p=`
${l} sourceLocR = coords;
++${c[a-1]};
${l} sourceLocG = coords;
++${c[a-2]};
${l} sourceLocA = coords;
--${c[a-1]};
${l} sourceLocB = coords;
--${c[a-2]};`;const h=["x","y","z","w","u","v"].slice(0,u),d="."+h[u-1],m=h.map(E=>"int "+E),f=_t("sourceLocR",u-1).concat("inIdx.r"),g=_t("sourceLocG",u-1).concat("inIdx.g"),y=_t("sourceLocB",u-1).concat("inIdx.b"),w=_t("sourceLocA",u-1).concat("inIdx.a"),x=s==="max"?"greaterThan":"lessThan",T=n?"":`
inIdx = round(vec4(getBestIndicesAChannel(${f.join()}),
getBestIndicesAChannel(${g.join()}),
getBestIndicesAChannel(${y.join()}),
getBestIndicesAChannel(${w.join()})));`,A=`vec4(
getAChannel(${f.join()}),
hasNextCol ? getAChannel(${g.join()}) : 0.,
hasNextRow ? getAChannel(${y.join()}) : 0.,
hasNextRow && hasNextCol ? getAChannel(${w.join()}) : 0.)`,_=n?"":`
float getBestIndicesAChannel(${m.join()}) {
return getChannel(getBestIndicesA(${h.join()}),
vec2(${h.slice(-2).join()}));
}`;this.userCode=`
float getAChannel(${m.join()}) {
return getChannel(getA(${h.join()}),
vec2(${h.slice(-2).join()}));
}
${_}
void main() {
${l} coords = getOutputCoords();
bool hasNextCol = ${c[a-1]} < ${o[a-1]-1};
bool hasNextRow = ${c[a-2]} < ${o[a-2]-1};
${p}
ivec4 srcIdx = ivec4(sourceLocR${d}, sourceLocG${d},
sourceLocB${d}, sourceLocA${d}) * ${t};
ivec4 inIdx = srcIdx;
vec4 bestIndex = vec4(inIdx);
vec4 bestValue = ${A};
for (int i = 0; i < ${t}; i++) {
inIdx = srcIdx;
${T}
vec4 candidate = ${A};
bvec4 nan = isnan(candidate);
bvec4 replace = bvec4(
vec4(${x}(candidate, bestValue)) * (vec4(1.0) - vec4(nan)));
bestValue = vec4(replace.x ? candidate.x : bestValue.x,
replace.y ? candidate.y : bestValue.y,
replace.z ? candidate.z : bestValue.z,
replace.w ? candidate.w : bestValue.w);
bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace));
srcIdx++;
}
setOutput(bestIndex);
}
`}}class YR{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;const t=e.filterHeight,s=e.filterWidth,n=e.strideHeight,i=e.strideWidth,r=e.dilationHeight,o=e.dilationWidth,a=e.effectiveFilterHeight,l=e.effectiveFilterWidth,c=a-1-e.padInfo.top,p=l-1-e.padInfo.left,u=1/(t*s);this.userCode=`
const ivec2 pads = ivec2(${c}, ${p});
const float avgMultiplier = float(${u});
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 < ${a};
wR += ${r}) {
float dyR = float(dyRCorner + wR) / ${n}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
for (int wC = 0; wC < ${l};
wC+= ${o}) {
float dyC = float(dyCCorner + wC) / ${i}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
float dyValue = getDy(b, idyR, idyC, d);
dotProd += dyValue * avgMultiplier;
}
}
setOutput(dotProd);
}
`}}class KR{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;const t=e.filterDepth,s=e.filterHeight,n=e.filterWidth,i=e.strideDepth,r=e.strideHeight,o=e.strideWidth,a=e.dilationDepth,l=e.dilationHeight,c=e.dilationWidth,p=e.effectiveFilterDepth,u=e.effectiveFilterHeight,h=e.effectiveFilterWidth,d=p-1-e.padInfo.front,m=u-1-e.padInfo.top,f=h-1-e.padInfo.left,g=1/(t*s*n);this.userCode=`
const ivec3 pads = ivec3(${d}, ${m}, ${f});
const float avgMultiplier = float(${g});
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int ch = coords.u;
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
int dyDCorner = dyCorner.x;
int dyRCorner = dyCorner.y;
int dyCCorner = dyCorner.z;
// Convolve dy(?, ?, ?, d) with pos mask(:, :, :, ch) to get
// dx(xD, xR, xC, ch).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wD = 0; wD < ${p};
wD += ${a}) {
float dyD = float(dyDCorner + wD) / ${i}.0;
if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) {
continue;
}
int idyD = int(dyD);
for (int wR = 0; wR < ${u};
wR += ${l}) {
float dyR = float(dyRCorner + wR) / ${r}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
for (int wC = 0; wC < ${h};
wC += ${c}) {
float dyC = float(dyCCorner + wC) / ${o}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
float dyValue = getDy(batch, idyD, idyR, idyC, ch);
dotProd += dyValue * avgMultiplier;
}
}
}
setOutput(dotProd);
}
`}}const vx={REAL:"return areal * breal - aimag * bimag;",IMAG:"return areal * bimag + aimag * breal;"};class Tx{constructor(e,t,s){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=U.assertAndGetBroadcastShape(t,s),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 XR=`
if (isnan(a)) return a;
if (isnan(b)) return b;
`,og="return a + b;",ag="return a - b;",Ax="return a * b;",JR=`
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;
}
`,ZR=`
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);
`,QR="return float(a == b);",e2="return float(a != b);",t2="return float(a < b);",s2="return float(a <= b);",n2="return float(a > b);",i2="return float(a >= b);",r2="return float(a >= 1.0 && b >= 1.0);",o2="return float(a >= 1.0 || b >= 1.0);",a2=XR+`
return max(a, b);
`,l2=XR+`
return min(a, b);
`,c2=`if (b == 0.0) return NAN;
return mod(a, b);`,p2="return (b >= 1.0) ? a : a * (b + 1.0);",Nx="return (a < 0.) ? b * a : a;";class kt{constructor(e,t,s){this.variableNames=["A","B"],this.outputShape=U.assertAndGetBroadcastShape(t,s),this.userCode=`
float binaryOperation(float a, float b) {
${e}
}
void main() {
float a = getAAtOutCoords();
float b = getBAtOutCoords();
setOutput(binaryOperation(a, b));
}
`}}const lg=`
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;
`,u2=`
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);
`,h2=`
// 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));
`+lg+`
return result;
`,Cx=`
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
`,d2=`
vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));
return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));
`,m2=`
return vec4(equal(a, b));
`,f2=`
return vec4(notEqual(a, b));
`,g2=`
return vec4(lessThan(a, b));
`,y2=`
return vec4(lessThanEqual(a, b));
`,b2=`
return vec4(greaterThan(a, b));
`,w2=`
return vec4(greaterThanEqual(a, b));
`,x2=`
return vec4(
vec4(greaterThanEqual(a, vec4(1.0))) *
vec4(greaterThanEqual(b, vec4(1.0))));
`,L2=`
return min(
vec4(greaterThanEqual(a, vec4(1.0))) +
vec4(greaterThanEqual(b, vec4(1.0))),
vec4(1.0));
`,S2=`
vec4 result = vec4(max(a, b));
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
`+lg+`
return result;
`,I2=`
vec4 result = vec4(min(a, b));
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
`+lg+`
return result;
`,v2=`
vec4 result = mod(a, b);
vec4 isNaN = vec4(equal(b, vec4(0.0)));
`+lg+`
return result;
`;class Li{constructor(e,t,s,n=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=U.assertAndGetBroadcastShape(t,s);const i=this.outputShape.length;let r="";if(n)if(i===0||N.sizeFromShape(this.outputShape)===1)r=`
result.y = 0.;
result.z = 0.;
result.w = 0.;
`;else{const o=Re(i);if(r=`
${o} coords = getOutputCoords();
`,i===1)r+=`
result.y = (coords + 1) >= ${this.outputShape[0]} ? 0. : result.y;
result.z = 0.;
result.w = 0.;
`;else{const a=_t("coords",i);r+=`
bool nextRowOutOfBounds =
(${a[i-2]} + 1) >= ${this.outputShape[i-2]};
bool nextColOutOfBounds =
(${a[i-1]} + 1) >= ${this.outputShape[i-1]};
result.y = nextColOutOfBounds ? 0. : result.y;
result.z = nextRowOutOfBounds ? 0. : result.z;
result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;
`}}this.userCode=`
vec4 binaryOperation(vec4 a, vec4 b) {
${e}
}
void main() {
vec4 a = getAAtOutCoords();
vec4 b = getBAtOutCoords();
vec4 result = binaryOperation(a, b);
${r}
setOutput(result);
}
`}}class T2{constructor(e){this.variableNames=["A"],this.outputShape=e,this.userCode=`
uniform float minVal;
uniform float maxVal;
void main() {
float value = getAAtOutCoords();
if (isnan(value)) {
setOutput(value);
return;
}
setOutput(clamp(value, minVal, maxVal));
}
`}getCustomSetupFunc(e,t){return(s,n)=>{this.minLoc==null&&(this.minLoc=s.getUniformLocationNoThrow(n,"minVal"),this.maxLoc=s.getUniformLocationNoThrow(n,"maxVal")),s.gl.uniform1f(this.minLoc,e),s.gl.uniform1f(this.maxLoc,t)}}}class A2{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.userCode=`
uniform float minVal;
uniform float maxVal;
void main() {
vec4 value = getAAtOutCoords();
if (any(isnan(value))) {
setOutput(value);
return;
}
setOutput(clamp(value, vec4(minVal), vec4(maxVal)));
}
`}getCustomSetupFunc(e,t){return(s,n)=>{this.minLoc==null&&(this.minLoc=s.getUniformLocationNoThrow(n,"minVal"),this.maxLoc=s.getUniformLocationNoThrow(n,"maxVal")),s.gl.uniform1f(this.minLoc,e),s.gl.uniform1f(this.maxLoc,t)}}}class N2{constructor(e){this.variableNames=["real","imag"],this.outputShape=e,this.userCode=`
void main() {
float re = abs(getRealAtOutCoords());
float im = abs(getImagAtOutCoords());
float mx = max(re, im);
// sadly the length function in glsl is not underflow-safe
// (at least not on Intel GPUs). So the safe solution is
// to ensure underflow-safety in all cases.
setOutput(
mx == 0.0 ? 0.0 : mx * length(vec2(1, min(re, im)/mx))
);
}
`}}class C2{constructor(e){this.outputShape=[],this.outputShape=U.computeOutShape(e,1),this.variableNames=e.map((r,o)=>`T${o}`);const t=new Array(e.length-1);t[0]=e[0][1];for(let r=1;r<t.length;r++)t[r]=t[r-1]+e[r][1];const s=[`if (yC < ${t[0]}) setOutput(getT0(yR, yC));`];for(let r=1;r<t.length;r++){const o=t[r-1];s.push(`else if (yC < ${t[r]}) setOutput(getT${r}(yR, yC-${o}));`)}const n=t.length,i=t[t.length-1];s.push(`else setOutput(getT${n}(yR, yC-${i}));`),this.userCode=`
void main() {
ivec2 coords = getOutputCoords();
int yR = coords.x;
int yC = coords.y;
${s.join(`
`)}
}
`}}class R2{constructor(e,t){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=U.computeOutShape(e,t);const s=this.outputShape,n=s.length,i=Re(n),r=_t("coords",n),o=["x","y","z","w","u","v"].slice(0,n);this.variableNames=e.map((m,f)=>`T${f}`);const a=new Array(e.length-1);a[0]=e[0][t];for(let m=1;m<a.length;m++)a[m]=a[m-1]+e[m][t];const l=o[t],c=o.slice(-2),p=o.join();let u=`if (${l} < ${a[0]}) {
return getChannel(
getT0(${p}), vec2(${c.join()}));
}`;for(let m=1;m<a.length;m++){const f=a[m-1];u+=`
if (${l} < ${a[m]} && ${l} >= ${a[m-1]}) {
return getChannel(
getT${m}(${cg(o,l,f)}),
vec2(${cg(c,l,f)}));
}`}const h=a.length,d=a[a.length-1];u+=`
return getChannel(
getT${h}(${cg(o,l,d)}),
vec2(${cg(c,l,d)}));`,this.userCode=`
float getValue(${o.map(m=>"int "+m)}) {
${u}
}
void main() {
${i} coords = getOutputCoords();
vec4 result = vec4(getValue(${r}), 0., 0., 0.);
${r[n-1]} = ${r[n-1]} + 1;
if (${r[n-1]} < ${s[n-1]}) {
result.g = getValue(${r});
}
${r[n-2]} = ${r[n-2]} + 1;
if (${r[n-2]} < ${s[n-2]}) {
result.a = getValue(${r});
}
${r[n-1]} = ${r[n-1]} - 1;
if (${r[n-2]} < ${s[n-2]} &&
${r[n-1]} < ${s[n-1]}) {
result.b = getValue(${r});
}
setOutput(result);
}
`}}function cg(e,t,s){const n=e.indexOf(t),i=e.map((r,o)=>o===n?`${r} - ${s}`:r);return i.join()}class O2{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;const t=e.strideHeight,s=e.strideWidth,n=e.padInfo.top,i=e.padInfo.left,r=e.dataFormat==="channelsLast";this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int wR = coords.x;
int wC = coords.y;
int d1 = coords.z;
int d2 = coords.w;
// Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int b = 0; b < ${e.batchSize}; b++) {
for (int yR = 0; yR < ${e.outHeight}; yR++) {
int xR = wR + yR * ${t} - ${n};
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int yC = 0; yC < ${e.outWidth}; yC++) {
int xC = wC + yC * ${s} - ${i};
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
if (${r}) {
float dyValue = getDy(b, yR, yC, d2);
float xValue = getX(b, xR, xC, d1);
dotProd += (xValue * dyValue);
} else {
float dyValue = getDy(b, d2, yR, yC);
float xValue = getX(b, d1, xR, xC);
dotProd += (xValue * dyValue);
}
}
}
}
setOutput(dotProd);
}
`}}class E2{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterHeight,s=e.filterWidth,n=e.strideHeight,i=e.strideWidth,r=e.dataFormat==="channelsLast",o=t-1-e.padInfo.top,a=s-1-e.padInfo.left,l=r?1:2,c=r?2:3,p=r?3:1;this.userCode=`
const ivec2 pads = ivec2(${o}, ${a});
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d1 = coords[${p}];
ivec2 dyCorner = ivec2(coords[${l}], coords[${c}]) - pads;
int dyRCorner = dyCorner.x;
int dyCCorner = dyCorner.y;
// Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wR = 0; wR < ${t}; wR++) {
float dyR = float(dyRCorner + wR) / ${n}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
int wRPerm = ${t} - 1 - wR;
for (int wC = 0; wC < ${s}; wC++) {
float dyC = float(dyCCorner + wC) / ${i}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
int wCPerm = ${s} - 1 - wC;
for (int d2 = 0; d2 < ${e.outChannels}; d2++) {
if (${r}) {
float xValue = getDy(batch, idyR, idyC, d2);
float wValue = getW(wRPerm, wCPerm, d1, d2);
dotProd += xValue * wValue;
} else {
float xValue = getDy(batch, d2, idyR, idyC);
float wValue = getW(wRPerm, wCPerm, d1, d2);
dotProd += xValue * wValue;
}
}
}
}
setOutput(dotProd);
}
`}}class _2{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;const t=e.strideDepth,s=e.strideHeight,n=e.strideWidth,i=e.padInfo.front,r=e.padInfo.top,o=e.padInfo.left;this.userCode=`
void main() {
ivec5 coords = getOutputCoords();
int wF = coords.x;
int wR = coords.y;
int wC = coords.z;
int d1 = coords.w;
int d2 = coords.u;
float dotProd = 0.0;
for (int b = 0; b < ${e.batchSize}; b++) {
for (int yF = 0; yF < ${e.outDepth}; yF++) {
int xF = wF + yF * ${t} - ${i};
if (xF < 0 || xF >= ${e.inDepth}) {
continue;
}
for (int yR = 0; yR < ${e.outHeight}; yR++) {
int xR = wR + yR * ${s} - ${r};
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int yC = 0; yC < ${e.outWidth}; yC++) {
int xC = wC + yC * ${n} - ${o};
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
float dyValue = getDy(b, yF, yR, yC, d2);
float xValue = getX(b, xF, xR, xC, d1);
dotProd += (xValue * dyValue);
}
}
}
}
setOutput(dotProd);
}
`}}class k2{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterDepth,s=e.filterHeight,n=e.filterWidth,i=e.strideDepth,r=e.strideHeight,o=e.strideWidth,a=t-1-e.padInfo.front,l=s-1-e.padInfo.top,c=n-1-e.padInfo.left;this.userCode=`
const ivec3 pads = ivec3(${a}, ${l}, ${c});
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int d1 = coords.u;
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
int dyFCorner = dyCorner.x;
int dyRCorner = dyCorner.y;
int dyCCorner = dyCorner.z;
float dotProd = 0.0;
for (int wF = 0; wF < ${t}; wF++) {
float dyF = float(dyFCorner + wF) / ${i}.0;
if (dyF < 0.0 || dyF >= ${e.outDepth}.0 || fract(dyF) > 0.0) {
continue;
}
int idyF = int(dyF);
int wFPerm = ${t} - 1 - wF;
for (int wR = 0; wR < ${s}; wR++) {
float dyR = float(dyRCorner + wR) / ${r}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
int wRPerm = ${s} - 1 - wR;
for (int wC = 0; wC < ${n}; wC++) {
float dyC = float(dyCCorner + wC) / ${o}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
int wCPerm = ${n} - 1 - wC;
for (int d2 = 0; d2 < ${e.outChannels}; d2++) {
float xValue = getDy(batch, idyF, idyR, idyC, d2);
float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);
dotProd += xValue * wValue;
}
}
}
}
setOutput(dotProd);
}
`}}class D2{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;const t=e.strideHeight,s=e.strideWidth,n=e.padInfo.top,i=e.padInfo.left,r=e.outChannels/e.inChannels;this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int wR = coords.x;
int wC = coords.y;
int d1 = coords.z;
int dm = coords.w;
int d2 = d1 * ${r} + dm;
float dotProd = 0.0;
// TO DO: Vec4 over the batch size
for (int b = 0; b < ${e.batchSize}; b++) {
for (int yR = 0; yR < ${e.outHeight}; yR++) {
int xR = wR + yR * ${t} - ${n};
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int yC = 0; yC < ${e.outWidth}; yC++) {
int xC = wC + yC * ${s} - ${i};
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
float dyValue = getDy(b, yR, yC, d2);
float xValue = getX(b, xR, xC, d1);
dotProd += (xValue * dyValue);
}
}
}
setOutput(dotProd);
}
`}}class F2{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterHeight,s=e.filterWidth,n=e.strideHeight,i=e.strideWidth,r=t-1-e.padInfo.top,o=s-1-e.padInfo.left,a=e.outChannels/e.inChannels;this.userCode=`
const ivec2 pads = ivec2(${r}, ${o});
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d1 = coords[3];
ivec2 dyCorner = coords.yz - pads;
int dyRCorner = dyCorner.x;
int dyCCorner = dyCorner.y;
float dotProd = 0.0;
for (int wR = 0; wR < ${t}; wR++) {
float dyR = float(dyRCorner + wR) / ${n}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
int wRPerm = ${t} - 1 - wR;
for (int wC = 0; wC < ${s}; wC++) {
float dyC = float(dyCCorner + wC) / ${i}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
int wCPerm = ${s} - 1 - wC;
// TO DO: Vec4 over the channelMul
for (int dm = 0; dm < ${a}; dm++) {
int d2 = d1 * ${a} + dm;
float xValue = getDy(batch, idyR, idyC, d2);
float wValue = getW(wRPerm, wCPerm, d1, dm);
dotProd += xValue * wValue;
}
}
}
setOutput(dotProd);
}
`}}class Rx{constructor(e,t=!1,s=null,n=!1){this.variableNames=["x","W"],this.outputShape=e.outShape;const i=e.padInfo.top,r=e.padInfo.left,o=e.strideHeight,a=e.strideWidth,l=e.dilationHeight,c=e.dilationWidth,p=e.filterHeight,u=e.filterWidth,h=Math.floor(e.inChannels/4)*4,d=e.inChannels%4,m=e.dataFormat==="channelsLast",f=m?1:2,g=m?2:3,y=m?3:1;let w="",x="";s&&(n?w=`float activation(float a) {
float b = getPreluActivationWeightsAtOutCoords();
${s}
}`:w=`
float activation(float x) {
${s}
}
`,x="result = activation(result);");const T=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),n&&this.variableNames.push("preluActivationWeights"),this.userCode=`
${w}
const ivec2 strides = ivec2(${o}, ${a});
const ivec2 pads = ivec2(${i}, ${r});
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d2 = coords[${y}];
ivec2 xRCCorner =
ivec2(coords[${f}], coords[${g}]) * strides - pads;
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
// Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wR = 0; wR < ${p}; wR++) {
int xR = xRCorner + wR * ${l};
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int wC = 0; wC < ${u}; wC++) {
int xC = xCCorner + wC * ${c};
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
for (int d1 = 0; d1 < ${h}; d1 += 4) {
vec4 wValues = vec4(
getW(wR, wC, d1, d2),
getW(wR, wC, d1 + 1, d2),
getW(wR, wC, d1 + 2, d2),
getW(wR, wC, d1 + 3, d2)
);
if (${m}) {
vec4 xValues = vec4(
getX(batch, xR, xC, d1),
getX(batch, xR, xC, d1 + 1),
getX(batch, xR, xC, d1 + 2),
getX(batch, xR, xC, d1 + 3)
);
dotProd += dot(xValues, wValues);
} else {
vec4 xValues = vec4(
getX(batch, d1, xR, xC),
getX(batch, d1 + 1, xR, xC),
getX(batch, d1 + 2, xR, xC),
getX(batch, d1 + 3, xR, xC)
);
dotProd += dot(xValues, wValues);
}
}
if (${d===1}) {
if (${m}) {
dotProd +=
getX(batch, xR, xC, ${h}) *
getW(wR, wC, ${h}, d2);
} else {
dotProd +=
getX(batch, ${h}, xR, xC) *
getW(wR, wC, ${h}, d2);
}
} else if (${d===2}) {
vec2 wValues = vec2(
getW(wR, wC, ${h}, d2),
getW(wR, wC, ${h} + 1, d2)
);
if (${m}) {
vec2 xValues = vec2(
getX(batch, xR, xC, ${h}),
getX(batch, xR, xC, ${h} + 1)
);
dotProd += dot(xValues, wValues);
} else {
vec2 xValues = vec2(
getX(batch, ${h}, xR, xC),
getX(batch, ${h} + 1, xR, xC)
);
dotProd += dot(xValues, wValues);
}
} else if (${d===3}) {
vec3 wValues = vec3(
getW(wR, wC, ${h}, d2),
getW(wR, wC, ${h} + 1, d2),
getW(wR, wC, ${h} + 2, d2)
);
if (${m}) {
vec3 xValues = vec3(
getX(batch, xR, xC, ${h}),
getX(batch, xR, xC, ${h} + 1),
getX(batch, xR, xC, ${h} + 2)
);
dotProd += dot(xValues, wValues);
} else {
vec3 xValues = vec3(
getX(batch, ${h}, xR, xC),
getX(batch, ${h} + 1, xR, xC),
getX(batch, ${h} + 2, xR, xC)
);
dotProd += dot(xValues, wValues);
}
}
}
}
float result = dotProd;
${T}
${x}
setOutput(result);
}
`}}class M2{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;const t=e.padInfo.front,s=e.padInfo.top,n=e.padInfo.left,i=e.strideDepth,r=e.strideHeight,o=e.strideWidth,a=e.dilationDepth,l=e.dilationHeight,c=e.dilationWidth,p=e.filterDepth,u=e.filterHeight,h=e.filterWidth,d=Math.floor(e.inChannels/4)*4,m=e.inChannels%4;this.userCode=`
const ivec3 strides = ivec3(${i}, ${r}, ${o});
const ivec3 pads = ivec3(${t}, ${s}, ${n});
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int d2 = coords.u;
ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
int xFCorner = xFRCCorner.x;
int xRCorner = xFRCCorner.y;
int xCCorner = xFRCCorner.z;
// Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get
// y(yF, yR, yC, d2). ? = to be determined. : = across all
// values in that axis.
float dotProd = 0.0;
for (int wF = 0; wF < ${p}; wF++) {
int xF = xFCorner + wF * ${a};
if (xF < 0 || xF >= ${e.inDepth}) {
continue;
}
for (int wR = 0; wR < ${u}; wR++) {
int xR = xRCorner + wR * ${l};
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int wC = 0; wC < ${h}; wC++) {
int xC = xCCorner + wC * ${c};
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
for (int d1 = 0; d1 < ${d}; d1 += 4) {
vec4 xValues = vec4(
getX(batch, xF, xR, xC, d1),
getX(batch, xF, xR, xC, d1 + 1),
getX(batch, xF, xR, xC, d1 + 2),
getX(batch, xF, xR, xC, d1 + 3)
);
vec4 wValues = vec4(
getW(wF, wR, wC, d1, d2),
getW(wF, wR, wC, d1 + 1, d2),
getW(wF, wR, wC, d1 + 2, d2),
getW(wF, wR, wC, d1 + 3, d2)
);
dotProd += dot(xValues, wValues);
}
if (${m===1}) {
dotProd +=
getX(batch, xF, xR, xC, ${d}) *
getW(wF, wR, wC, ${d}, d2);
} else if (${m===2}) {
vec2 xValues = vec2(
getX(batch, xF, xR, xC, ${d}),
getX(batch, xF, xR, xC, ${d} + 1)
);
vec2 wValues = vec2(
getW(wF, wR, wC, ${d}, d2),
getW(wF, wR, wC, ${d} + 1, d2)
);
dotProd += dot(xValues, wValues);
} else if (${m===3}) {
vec3 xValues = vec3(
getX(batch, xF, xR, xC, ${d}),
getX(batch, xF, xR, xC, ${d} + 1),
getX(batch, xF, xR, xC, ${d} + 2)
);
vec3 wValues = vec3(
getW(wF, wR, wC, ${d}, d2),
getW(wF, wR, wC, ${d} + 1, d2),
getW(wF, wR, wC, ${d} + 2, d2)
);
dotProd += dot(xValues, wValues);
}
}
}
}
setOutput(dotProd);
}
`}}class Ox{constructor(e,t=!1,s=null,n=!1){this.variableNames=["x","W"],this.outputShape=e.outShape;const i=e.inHeight,r=e.inWidth,o=e.padInfo.top,a=e.padInfo.left,l=e.strideHeight,c=e.strideWidth,p=e.dilationHeight,u=e.dilationWidth,h=e.filterHeight,d=e.filterWidth,m=e.outChannels/e.inChannels;let f="",g="";s&&(n?f=`float activation(float a) {
float b = getPreluActivationWeightsAtOutCoords();
${s}
}`:f=`
float activation(float x) {
${s}
}
`,g="result = activation(result);");const y=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),n&&this.variableNames.push("preluActivationWeights"),this.userCode=`
${f}
const ivec2 strides = ivec2(${l}, ${c});
const ivec2 pads = ivec2(${o}, ${a});
void main() {
ivec4 coords = getOutputCoords();
int batch = coords.x;
ivec2 xRCCorner = coords.yz * strides - pads;
int d2 = coords.w;
int d1 = d2 / ${m};
int q = d2 - d1 * ${m};
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
// Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
// TO DO(dsmilkov): Flatten the two for loops and vec4 the operations.
for (int wR = 0; wR < ${h}; wR++) {
int xR = xRCorner + wR * ${p};
if (xR < 0 || xR >= ${i}) {
continue;
}
for (int wC = 0; wC < ${d}; wC++) {
int xC = xCCorner + wC * ${u};
if (xC < 0 || xC >= ${r}) {
continue;
}
float xVal = getX(batch, xR, xC, d1);
float wVal = getW(wR, wC, d1, q);
dotProd += xVal * wVal;
}
}
float result = dotProd;
${y}
${g}
setOutput(result);
}
`}}class Ex{constructor(e,t=!1,s=null,n=!1){this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e.outShape;const i=e.inHeight,r=e.inWidth,o=e.padInfo.top,a=e.padInfo.left,l=e.strideHeight,c=e.strideWidth,p=e.dilationHeight,u=e.dilationWidth,h=e.filterHeight,d=e.filterWidth,m=d;let f="int xR; int xC; int xCOffset;";for(let x=0;x<h;x++)for(let T=0;T<d;T++)f+=`
vec4 xTexelR${x}C${T*2} = vec4(0.);
vec4 wR${x}C${T} = vec4(0.);
vec4 xR${x}C${T} = vec4(0.);`;for(let x=0;x<h;x++)for(let T=0;T<m;T++){const A=T*2;if(f+=`
xR = xRCorner + ${x*p};
xC = xCCorner + ${A*u};
`,c===1){if(A<d&&(a%2===1?f+=`
xCOffset = xC + 1;
if(xR >= 0 && xR < ${i} && xCOffset >= 0 && xCOffset < ${r}) {
xTexelR${x}C${A} = getX(batch, xR, xCOffset, d1);
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if(xCOffset + 1 >= ${r}) {
xTexelR${x}C${A}.zw = vec2(0.);
}
} else {
xTexelR${x}C${A} = vec4(0.);
}
xCOffset = xC + 1 - 2;
if(xR >= 0 && xR < ${i} && xCOffset >= 0 && xCOffset < ${r}) {
vec4 previous = getX(batch, xR, xCOffset, d1);
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if(xCOffset + 1 >= ${r}) {
previous.zw = vec2(0.);
}
xR${x}C${A} = vec4(previous.zw, xTexelR${x}C${A}.xy);
} else {
xR${x}C${A} = vec4(0, 0, xTexelR${x}C${A}.xy);
}
`:f+=`
if(xR >= 0 && xR < ${i} && xC >= 0 && xC < ${r}) {
xTexelR${x}C${A} = getX(batch, xR, xC, d1);
} else {
xTexelR${x}C${A} = vec4(0.);
}
xR${x}C${A} = xTexelR${x}C${A};
`,A+1<d)){const _=a%2===0?N.nearestLargerEven(u):u;u%2===0&&a%2===1||u%2!==0&&a%2!==1?(f+=`
xCOffset = xC + ${a%2} + ${_};
if(xR >= 0 && xR < ${i} &&
xCOffset >= 0 && xCOffset < ${r}) {
xTexelR${x}C${A+2} = getX(batch, xR, xCOffset, d1);
}
`,u>1&&(f+=`
xCOffset -= 2;
if(xR >= 0 && xR < ${i} &&
xCOffset >= 0 && xCOffset < ${r}) {
xTexelR${x}C${A} = getX(batch, xR, xCOffset, d1);
} else {
xTexelR${x}C${A} = vec4(0.);
}
`),f+=`
xR${x}C${A+1} = vec4(
xTexelR${x}C${A}.zw, xTexelR${x}C${A+2}.xy);
`):f+=`
xCOffset = xC + ${_};
if(xR >= 0 && xR < ${i} &&
xCOffset >= 0 && xCOffset < ${r}) {
xTexelR${x}C${A+2} = getX(batch, xR, xCOffset, d1);
}
xR${x}C${A+1} = xTexelR${x}C${A+2};
`}}else A<d&&(f+=`
if(xR >= 0 && xR < ${i}) {
`,a%2===1?(f+=`
xCOffset = xC + 1 - ${c};
if(xCOffset >= 0 && xCOffset < ${r}) {
xTexelR${x}C${A} = getX(batch, xR, xCOffset, d1);
} else {
xTexelR${x}C${A} = vec4(0.);
}
if(xC + 1 >= 0 && xC + 1 < ${r}) {
xTexelR${x}C${A+2} = getX(batch, xR, xC + 1, d1);
} else {
xTexelR${x}C${A+2} = vec4(0.);
}
xR${x}C${A} = vec4(
xTexelR${x}C${A}.zw, xTexelR${x}C${A+2}.zw);
`,A+1<d&&(f+=`
vec4 final = vec4(0.);
xCOffset = xC + 1 + ${c};
if(xCOffset >= 0 && xCOffset < ${r}) {
final = getX(batch, xR, xCOffset, d1);
}
xR${x}C${A+1} = vec4(xTexelR${x}C${A+2}.xy, final.xy);
`)):(f+=`
if(xC >= 0 && xC < ${r}) {
xTexelR${x}C${A} = getX(batch, xR, xC, d1);
} else {
xTexelR${x}C${A} = vec4(0.);
}
xCOffset = xC + ${c};
if(xCOffset >= 0 && xCOffset < ${r}) {
xTexelR${x}C${A+2} = getX(batch, xR, xCOffset, d1);
} else {
xTexelR${x}C${A+2} = vec4(0.);
}
xR${x}C${A} = vec4(
xTexelR${x}C${A}.xy, xTexelR${x}C${A+2}.xy);
`,A+1<d&&(f+=`
xR${x}C${A+1} = vec4(
xTexelR${x}C${A}.zw, xTexelR${x}C${A+2}.zw);
`)),f+="}");A<d&&(f+=`
vec4 wTexelR${x}C${A} = getW(${x}, ${A}, d1, q);
wR${x}C${A} = vec4(wTexelR${x}C${A}.xz, wTexelR${x}C${A}.xz);
`,A+1<d&&(f+=`
vec4 wTexelR${x}C${A+1} = getW(${x}, ${A+1}, d1, q);
wR${x}C${A+1} =
vec4(wTexelR${x}C${A+1}.xz, wTexelR${x}C${A+1}.xz);`))}for(let x=0;x<h;x++)for(let T=0;T<d;T++)f+=`dotProd += xR${x}C${T} * wR${x}C${T};`;let g="",y="";s&&(n?g=`vec4 activation(vec4 a) {
vec4 b = getPreluActivationWeightsAtOutCoords();
${s}
}`:g=`vec4 activation(vec4 x) {
${s}
}`,y="result = activation(result);");const w=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),n&&this.variableNames.push("preluActivationWeights"),this.userCode=`
${g}
const ivec2 strides = ivec2(${l}, ${c});
const ivec2 pads = ivec2(${o}, ${a});
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.);
${f}
vec4 result = dotProd;
${w}
${y}
setOutput(result);
}
`}}class U2{constructor(e,t,s,n,i){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];const[r,o,a,l]=e,[c]=t,[p,u]=s;this.outputShape=[c,p,u,l];const h=n==="bilinear"?1:0,[d,m]=[`${o-1}.0`,`${a-1}.0`],[f,g,y]=p>1?[`${(o-1)/(p-1)}`,"(y2-y1) * height_ratio",`y1*${d} + float(y)*(height_scale)`]:["0.0","0.0",`0.5 * (y1+y2) * ${d}`],[w,x,T]=u>1?[`${(a-1)/(u-1)}`,"(x2-x1) * width_ratio",`x1*${m} + float(x)*(width_scale)`]:["0.0","0.0",`0.5 * (x1+x2) * ${m}`];this.userCode=`
const float height_ratio = float(${f});
const float width_ratio = float(${w});
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int y = coords[1];
int x = coords[2];
int d = coords[3];
// get box vals
float y1 = getBoxes(b,0);
float x1 = getBoxes(b,1);
float y2 = getBoxes(b,2);
float x2 = getBoxes(b,3);
// get image in batch index
int bInd = round(getBoxInd(b));
if(bInd < 0 || bInd >= ${r}) {
return;
}
float height_scale = ${g};
float width_scale = ${x};
float in_y = ${y};
if( in_y < 0.0 || in_y > ${d} ) {
setOutput(float(${i}));
return;
}
float in_x = ${T};
if( in_x < 0.0 || in_x > ${m} ) {
setOutput(float(${i}));
return;
}
vec2 sourceFracIndexCR = vec2(in_x,in_y);
if(${h} == 1) {
// Compute the four integer indices.
ivec2 sourceFloorCR = ivec2(sourceFracIndexCR);
ivec2 sourceCeilCR = ivec2(ceil(sourceFracIndexCR));
float topLeft = getImage(b, sourceFloorCR.y, sourceFloorCR.x, d);
float bottomLeft = getImage(b, sourceCeilCR.y, sourceFloorCR.x, d);
float topRight = getImage(b, sourceFloorCR.y, sourceCeilCR.x, d);
float bottomRight = getImage(b, sourceCeilCR.y, sourceCeilCR.x, d);
vec2 fracCR = sourceFracIndexCR - vec2(sourceFloorCR);
float top = topLeft + (topRight - topLeft) * fracCR.x;
float bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x;
float newValue = top + (bottom - top) * fracCR.y;
setOutput(newValue);
} else {
// Compute the coordinators of nearest neighbor point.
ivec2 sourceNearestCR = ivec2(floor(
sourceFracIndexCR + vec2(0.5,0.5)));
float newValue = getImage(b, sourceNearestCR.y, sourceNearestCR.x, d);
setOutput(newValue);
}
}
`}}class _x{constructor(e,t,s){this.variableNames=["x"],this.outputShape=e;const n=e.length,i=t?"0.0":`getX(${$2(n,"coords")})`,r=e[e.length-1];let o="",a="";t?(o=s?`end != ${r-1}`:"end != 0",a=s?"end + 1":"end - 1"):(o=s?`end + pow2 < ${r}`:"end >= pow2",a=s?"end + pow2":"end - pow2"),this.userCode=`
uniform float index;
void main() {
${Re(n)} coords = getOutputCoords();
int end = ${W2(n,"coords")};
float val = ${i};
int pow2 = int(pow(2.0, index));
if (${o}) {
int idx = ${a};
${W2(n,"coords")} = idx;
val += getX(${$2(n,"coords")});
}
setOutput(val);
}
`}getCustomSetupFunc(e){return(t,s)=>{this.index==null&&(this.index=t.getUniformLocation(s,"index")),t.gl.uniform1f(this.index,e)}}}function $2(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 W2(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 z2{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=wo.DENSE;const t=xo(e),s=ct();this.outputShape=e,this.userCode=`
ivec3 outCoordsFromFlatIndex(int index) {
${Hn(["r","c","d"],e)}
return ivec3(r, c, d);
}
void main() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = 4 * (resTexRC.x * ${t[1]} + resTexRC.y);
vec4 result = vec4(0.);
for (int i=0; i<4; i++) {
int flatIndex = index + i;
ivec3 rc = outCoordsFromFlatIndex(flatIndex);
result[i] = getA(rc.x, rc.y, rc.z);
}
${s.output} = result;
}
`}}class P2{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=wo.DENSE;const t=xo(e),s=ct();this.outputShape=e,this.userCode=`
ivec3 outCoordsFromFlatIndex(int index) {
${Hn(["r","c","d"],e)}
return ivec3(r, c, d);
}
void main() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = 4 * (resTexRC.x * ${t[1]} + resTexRC.y);
vec4 result = vec4(0.);
for (int i=0; i<4; i++) {
int flatIndex = index + i;
ivec3 rc = outCoordsFromFlatIndex(flatIndex);
result[i] = getChannel(getA(rc.x, rc.y, rc.z), vec2(rc.y, rc.z));
}
${s.output} = result;
}
`}}class B2{constructor(e,t,s){this.variableNames=["x"],this.outputShape=[],this.outputShape=e,this.blockSize=t,this.dataFormat=s,this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int h = ${this.getHeightCoordString()};
int w = ${this.getWidthCoordString()};
int d = ${this.getDepthCoordString()};
int in_h = h / ${t};
int offset_h = imod(h, ${t});
int in_w = w / ${t};
int offset_w = imod(w, ${t});
int offset_d = (offset_h * ${t} + offset_w) *
${this.getOutputDepthSize()};
int in_d = d + offset_d;
float result = ${this.getInputSamplingString()};
setOutput(result);
}
`}getHeightCoordString(){return this.dataFormat==="NHWC"?"coords[1]":"coords[2]"}getWidthCoordString(){return this.dataFormat==="NHWC"?"coords[2]":"coords[3]"}getDepthCoordString(){return this.dataFormat==="NHWC"?"coords[3]":"coords[1]"}getOutputDepthSize(){return this.dataFormat==="NHWC"?this.outputShape[3]:this.outputShape[1]}getInputSamplingString(){return this.dataFormat==="NHWC"?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"}}class j2{constructor(e){this.variableNames=["X"],this.outputShape=[e,e],this.userCode=`
void main() {
ivec2 coords = getOutputCoords();
float val = coords[0] == coords[1] ? getX(coords[0]) : 0.0;
setOutput(val);
}
`}}class V2{constructor(e){this.variableNames=["A"],this.outTexUsage=is.DOWNLOAD;const t=ct();this.outputShape=e,this.userCode=`
${rg}
void main() {
float x = getAAtOutCoords();
${t.output} = encode_float(x);
}
`}}class G2{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=is.DOWNLOAD;const t=ct();this.outputShape=e,this.userCode=`
${rg}
void main() {
ivec3 coords = getOutputCoords();
float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));
${t.output} = encode_float(x);
}
`}}class q2{constructor(e,t,s=!1){this.variableNames=["A"];const n=ct(),[i,r]=t;this.outputShape=e;let o="result";s&&(o="floor(result * 255. + 0.5)"),this.userCode=`
${nc(e)}
void main() {
ivec3 coords = getOutputCoords();
int flatIndex = getFlatIndex(coords);
int offset = imod(flatIndex, 4);
flatIndex = idiv(flatIndex, 4, 1.);
int r = flatIndex / ${r};
int c = imod(flatIndex, ${r});
vec2 uv = (vec2(c, r) + halfCR) / vec2(${r}.0, ${i}.0);
vec4 values = ${n.texture2D}(A, uv);
float result;
if(offset == 0) {
result = values[0];
} else if(offset == 1) {
result = values[1];
} else if(offset == 2) {
result = values[2];
} else {
result = values[3];
}
${n.output} = vec4(${o}, 0., 0., 0.);
}
`}}class H2{constructor(e,t,s=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;const n=ct(),[i,r]=t;this.outputShape=e;let o="",a="result";s&&(a="floor(result * 255. + 0.5)");for(let l=0;l<=1;l++)for(let c=0;c<=1;c++){const p=l*2+c;o+=`
localCoords = coords;
if(localCoords[2] + ${c} < ${e[2]}) {
localCoords[2] += ${c};
if(localCoords[1] + ${l} < ${e[1]}) {
localCoords[1] += ${l};
flatIndex = getFlatIndex(localCoords);
offset = imod(flatIndex, 4);
flatIndex = idiv(flatIndex, 4, 1.);
r = flatIndex / ${r};
c = imod(flatIndex, ${r});
uv = (vec2(c, r) + halfCR) / vec2(${r}.0, ${i}.0);
values = ${n.texture2D}(A, uv);
if(offset == 0) {
result[${p}] = values[0];
} else if(offset == 1) {
result[${p}] = values[1];
} else if(offset == 2) {
result[${p}] = values[2];
} else {
result[${p}] = values[3];
}
}
}
`}this.userCode=`
${nc(e)}
void main() {
ivec3 coords = getOutputCoords();
vec4 result = vec4(0.);
int flatIndex, r, c, offset;
ivec3 localCoords;
vec2 uv;
vec4 values;
${o}
${n.output} = ${a};
}
`}}const kx={REAL:"return real * expR - imag * expI;",IMAG:"return real * expI + imag * expR;"};class Dx{constructor(e,t,s){this.variableNames=["real","imag"];const n=t[1];this.outputShape=t;const i=s?`2.0 * ${Math.PI}`:`-2.0 * ${Math.PI}`,r=s?`${n}.0`:"1.0";this.userCode=`
const float exponentMultiplier = ${i};
float unaryOpComplex(float real, float expR, float imag, float expI) {
${e}
}
float mulMatDFT(int batch, int index) {
float indexRatio = float(index) / float(${n});
float exponentMultiplierTimesIndexRatio =
exponentMultiplier * indexRatio;
float result = 0.0;
for (int i = 0; i < ${n}; 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) / ${r};
}
return result;
}
void main() {
ivec2 coords = getOutputCoords();
setOutput(mulMatDFT(coords[0], coords[1]));
}
`}}class Y2{constructor(e,t){this.outputShape=[],this.variableNames=["x"],this.outputShape=e,this.userCode=`
uniform float value;
void main() {
// Input can be obtained from uniform value.
setOutput(value);
}
`}getCustomSetupFunc(e){return(t,s)=>{this.valueLoc==null&&(this.valueLoc=t.getUniformLocationNoThrow(s,"value")),t.gl.uniform1f(this.valueLoc,e)}}}class K2{constructor(e,t,s){this.variableNames=["A","indices"];const n=e.slice();n[s]=t,this.outputShape=n,this.rank=n.length;const i=Re(this.rank),r=OV(e,s);this.userCode=`
void main() {
${i} resRC = getOutputCoords();
setOutput(getA(${r}));
}
`}}function OV(e,t){const s=e.length;if(s>4)throw Error(`Gather for rank ${s} is not yet supported`);if(s===1)return"int(getIndices(resRC))";const n=["resRC.x","resRC.y","resRC.z","resRC.w"],i=[];for(let r=0;r<e.length;r++)r===t?i.push(`int(getIndices(${n[r]}))`):i.push(`${n[r]}`);return i.join()}class X2{constructor(e,t,s){this.sliceDim=e,this.strides=t,this.variableNames=["x","indices"],this.outputShape=s;const n=Re(t.length),i=Re(s.length),r=this.sliceDim>1?"strides[j]":"strides";this.userCode=`
${n} strides = ${n}(${this.strides});
void main() {
${i} coords = getOutputCoords();
int flattenIndex = 0;
for (int j = 0; j < ${this.sliceDim}; j++) {
int index = round(getIndices(coords[0], j));
flattenIndex += index * ${r};
}
setOutput(getX(flattenIndex, coords[1]));
}
`}}function J2(e){const t=ct(),s=`${t.version}
precision highp float;
${t.attribute} vec3 clipSpacePos;
${t.attribute} vec2 uv;
${t.varyingVs} vec2 resultUV;
void main() {
gl_Position = vec4(clipSpacePos, 1);
resultUV = uv;
}`;return aR(e,s)}function Z2(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 uR(e,t)}function Q2(e){const t=new Uint16Array([0,1,2,2,1,3]);return hR(e,t)}function $u(e,t,s,n,i,r){mR(t,s);const o=dR(e),a=e.TEXTURE_2D;return pe(e,()=>e.bindTexture(a,o)),pe(e,()=>e.texParameteri(a,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE)),pe(e,()=>e.texParameteri(a,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)),pe(e,()=>e.texParameteri(a,e.TEXTURE_MIN_FILTER,e.NEAREST)),pe(e,()=>e.texParameteri(a,e.TEXTURE_MAG_FILTER,e.NEAREST)),pe(e,()=>e.texImage2D(a,0,n,t,s,0,i,r,null)),pe(e,()=>e.bindTexture(e.TEXTURE_2D,null)),o}function Fx(e){return e.internalFormatFloat}function eO(e,t,s,n){const[i,r]=Ta(t,s);return $u(e,i,r,Fx(n),n.textureFormatFloat,e.FLOAT)}function Mx(e){return e.internalFormatHalfFloat}function tO(e,t,s,n){const[i,r]=Ta(t,s);return $u(e,i,r,Mx(n),n.textureFormatFloat,n.textureTypeHalfFloat)}function Ux(e){return e.downloadTextureFormat}function sO(e,t,s,n){const[i,r]=Ta(t,s);return $u(e,i,r,Ux(n),e.RGBA,e.UNSIGNED_BYTE)}function $x(e){return e.internalFormatPackedFloat}function nO(e,t,s,n){const[i,r]=wi(t,s);return $u(e,i,r,$x(n),e.RGBA,e.FLOAT)}function Wx(e){return e.internalFormatPackedHalfFloat}function iO(e,t,s,n){const[i,r]=wi(t,s);return $u(e,i,r,Wx(n),e.RGBA,n.textureTypeHalfFloat)}function rO(e,t,s){const n=0,i=3*4,r=3*4+2*4;pe(e,()=>e.bindBuffer(e.ARRAY_BUFFER,s));const o=yx(e,t,"clipSpacePos",s,3,r,n);return o&&yx(e,t,"uv",s,2,r,i)}function oO(e,t,s,n,i,r){pe(e,()=>e.bindTexture(e.TEXTURE_2D,t));let o,a,l;i instanceof Uint8Array?(o=new Uint8Array(s*n*4),a=e.UNSIGNED_BYTE,l=e.RGBA):(o=new Float32Array(s*n*4),a=e.FLOAT,l=r.internalFormatPackedFloat),o.set(i),pe(e,()=>e.texImage2D(e.TEXTURE_2D,0,l,s,n,0,e.RGBA,a,o)),pe(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function aO(e,t,s){pe(e,()=>e.bindTexture(e.TEXTURE_2D,t)),s.data instanceof Uint8Array?pe(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,s.width,s.height,0,e.RGBA,e.UNSIGNED_BYTE,s.data)):pe(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,s)),pe(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function lO(e,t,s,n){const i=e.createBuffer();pe(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,i));const r=4,o=4,a=r*o*t*s;return pe(e,()=>e.bufferData(e.PIXEL_PACK_BUFFER,a,e.STREAM_READ)),pe(e,()=>e.readPixels(0,0,s,t,e.RGBA,e.FLOAT,0)),pe(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,null)),i}function cO(e,t,s){const n=e,i=new Float32Array(s);return n.bindBuffer(n.PIXEL_PACK_BUFFER,t),n.getBufferSubData(n.PIXEL_PACK_BUFFER,0,i),n.bindBuffer(n.PIXEL_PACK_BUFFER,null),i}function pO(e,t,s,n){const[i,r]=Ta(t,s),o=4,a=new Uint8Array(iR(t*s,o));return pe(e,()=>e.readPixels(0,0,i,r,n.downloadTextureFormat,e.UNSIGNED_BYTE,a)),new Float32Array(a.buffer)}function uO(e,t,s,n,i,r,o,a){const l=e,c=new Float32Array(rR(r,o));return l.bindBuffer(l.PIXEL_PACK_BUFFER,t),l.getBufferSubData(l.PIXEL_PACK_BUFFER,0,c),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),c}function hO(e,t,s){const n=new Float32Array(t*s*4);return pe(e,()=>e.readPixels(0,0,s,t,e.RGBA,e.FLOAT,n)),n}class zx{constructor(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];const t=W().getNumber("WEBGL_VERSION");e!=null?(this.gl=e,gx(t,e)):this.gl=on(t);let s="WEBGL_color_buffer_float";const n="EXT_color_buffer_half_float";if(W().getNumber("WEBGL_VERSION")===1){const i="OES_texture_float",r="OES_texture_half_float";if(this.textureFloatExtension=Mu(this.gl,i),an(this.gl,r))this.textureHalfFloatExtension=Mu(this.gl,r);else if(W().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(s),an(this.gl,n))this.colorBufferHalfFloatExtension=Mu(this.gl,n);else if(W().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(s="EXT_color_buffer_float",an(this.gl,s))this.colorBufferFloatExtensi
blockIndex = rc.y + ${A};
pos = rc.x + ${T};
if(blockIndex < ${e[1]} && pos < ${e[0]}) {
offsetY = int(blockIndex / (${l})) * ${o} - ${d};
d0 = offsetY + ${p} * (pos / ${m});
if(d0 < ${t[y]} && d0 >= 0) {
offsetX = int(mod(float(blockIndex), ${l}.) * ${r}. - ${h}.);
d1 = offsetX + ${c} * (int(mod(float(pos), ${m}.) / ${i}.));
if(d1 < ${t[w]} && d1 >= 0) {
ch = int(mod(float(pos), ${i}.));
if (${g}) {
innerDims = vec2(d1, ch);
result[${T*2+A}] = getChannel(
getA(d0, int(innerDims.x),
int(innerDims.y)), innerDims);
} else {
innerDims = vec2(d0, d1);
result[${T*2+A}] = getChannel(
getA(ch, int(innerDims.x),
int(innerDims.y)), innerDims);
}
}
}
}
`;this.userCode=`
void main() {
ivec2 rc = getOutputCoords();
vec4 result = vec4(0);
int blockIndex, pos, offsetY, d0, offsetX, d1, ch;
vec2 innerDims;
${x}
${f.output} = result;
}
`}}class bO{constructor(e,t,s,n,i){this.variableNames=["x"],this.outputShape=[];const r=t,o=e[3]-1;this.outputShape=e;let a;const l=`float(${s}) + float(${n}) * sum`;i===.5?a=`inversesqrt(${l})`:i===1?a=`1.0/(${l})`:a=`exp(log(${l}) * float(-${i}));`,this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int r = coords[1];
int c = coords[2];
int d = coords[3];
float x = getX(b, r, c, d);
float sum = 0.0;
for (int j = -${r}; j <= ${r}; j++) {
int idx = d + j;
if (idx >= 0 && idx <= ${o}) {
float z = getX(b, r, c, idx);
sum += z * z;
}
}
float val = x * ${a};
setOutput(val);
}
`}}class wO{constructor(e,t,s,n,i){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=e,this.depth=e[3],this.depthRadius=t,this.bias=s,this.alpha=n,this.beta=i,this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int r = coords[1];
int c = coords[2];
float result = 0.0;
for (int d = 0; d < ${this.depth}; ++d) {
int depthBegin = int(max(0.0, float(d - ${t})));
int depthEnd = int(min(float(${this.depth}),
float(d + ${t} + 1)));
const int MIN_DEPTH_BEGIN = 0;
const int MAX_DEPTH_END = ${this.depth};
float norm = 0.0;
for (int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k) {
if (k < depthBegin){
continue;
}
else if (k >= depthBegin && k < depthEnd) {
norm += getInputImage(b, r, c, k) * getInputImage(b, r, c, k);
}
else {
break;
}
}
norm = float(${n}) * norm + float(${s});
for(int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k){
if (k < depthBegin){
continue;
}
else if (k >= depthBegin && k < depthEnd){
float dyi = -2.0 * float(${n})
* float(${i})
* getInputImage(b ,r ,c, k) * getOutputImage(b, r, c, d)
/ norm;
if (k == d) {
dyi += pow(norm, -1.0 * ${i});
}
if (k == coords[3]) {
dyi *= getDy(b, r, c, d);
result += dyi;
}
}
else {
break;
}
}
}
setOutput(result);
}
`}}class xO{constructor(e,t,s,n,i){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;const r=t,o=e[3]-1;this.outputShape=e;let a;const l=`float(${s}) + float(${n}) * sum`;i===.5?a=`inversesqrt(${l})`:i===1?a=`1.0/(${l})`:a=`exp(log(${l}) * float(-${i}));`,this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int b = coords.x;
int r = coords.y;
int c = coords.z;
int d = coords.w;
bool hasNextCol = d < ${this.outputShape[3]};
bool hasNextRow = c < ${this.outputShape[2]};
vec4 sum = vec4(0.);
vec4 xFragAtOutputCoords = getX(b, r, c, d);
vec4 xAtOutputCoords = vec4(
getChannel(xFragAtOutputCoords, vec2(c, d)),
hasNextCol ?
getChannel(xFragAtOutputCoords, vec2(c, d + 1)) : 0.0,
hasNextRow ?
getChannel(xFragAtOutputCoords , vec2(c + 1, d)) : 0.0,
(hasNextRow && hasNextCol) ?
getChannel(xFragAtOutputCoords, vec2(c + 1, d + 1)) : 0.0
);
int firstChannel = d - ${r};
vec2 cache = vec2(0.);
if(firstChannel >= 0){
vec4 firstChannelFrag = getX(b, r, c, firstChannel);
cache.x = getChannel(firstChannelFrag, vec2(c, firstChannel));
if(hasNextRow){
cache.y = getChannel(firstChannelFrag, vec2(c + 1, firstChannel));
}
}
ivec2 depth = ivec2(d, d + 1);
for (int j = - ${r}; j <= ${r}; j++) {
ivec2 idx = depth + j;
bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));
bvec2 belowUpperBound = lessThanEqual(idx, ivec2(${o}));
bool depthInRange = aboveLowerBound.x && belowUpperBound.x;
bool depthPlusOneInRange = aboveLowerBound.y && belowUpperBound.y;
if(depthInRange || depthPlusOneInRange){
vec4 z = vec4(0.);
vec4 xFragAtCurrentDepth;
z.xz = cache.xy;
if(depthPlusOneInRange && hasNextCol){
xFragAtCurrentDepth = idx.y != d ?
getX(b, r, c, idx.y) : xFragAtOutputCoords;
z.y = getChannel(xFragAtCurrentDepth, vec2(c, idx.y));
if(hasNextRow){
z.w = getChannel(xFragAtCurrentDepth, vec2(c + 1, idx.y));
}
}
cache.xy = z.yw;
sum += z * z;
}
}
vec4 result = xAtOutputCoords * ${a};
setOutput(result);
}
`}}class LO{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;const t=e.strideHeight,s=e.strideWidth,n=e.dilationHeight,i=e.effectiveFilterHeight,r=e.effectiveFilterWidth,o=i-1-e.padInfo.top,a=r-1-e.padInfo.left,l=i*r-1;this.userCode=`
const ivec2 pads = ivec2(${o}, ${a});
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 dyRCCorner = coords.yz - pads;
int dyRCorner = dyRCCorner.x;
int dyCCorner = dyRCCorner.y;
// Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wR = 0; wR < ${i};
wR += ${n}) {
float dyR = float(dyRCorner + wR) / ${t}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
for (int wC = 0; wC < ${r}; wC++) {
float dyC = float(dyCCorner + wC) / ${s}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
float dyValue = getDy(b, idyR, idyC, d);
int maxPosValue = ${l} - int(getMaxPos(b, idyR, idyC, d));
// Get the current value, check it against the value from the
// position matrix.
int curPosValue = wR * ${r} + wC;
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
dotProd += dyValue * mask;
}
}
setOutput(dotProd);
}
`}}class SO{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;const t=e.strideDepth,s=e.strideHeight,n=e.strideWidth,i=e.dilationDepth,r=e.dilationHeight,o=e.dilationWidth,a=e.effectiveFilterDepth,l=e.effectiveFilterHeight,c=e.effectiveFilterWidth,p=a-1-e.padInfo.front,u=l-1-e.padInfo.top,h=c-1-e.padInfo.left,d=a*l*c-1;this.userCode=`
const ivec3 pads = ivec3(${p}, ${u}, ${h});
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int ch = coords.u;
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
int dyDCorner = dyCorner.x;
int dyRCorner = dyCorner.y;
int dyCCorner = dyCorner.z;
// Convolve dy(?, ?, ?, ch) with pos mask(:, :, :, d) to get
// dx(xD, xR, xC, ch).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wD = 0; wD < ${a};
wD += ${i}) {
float dyD = float(dyDCorner + wD) / ${t}.0;
if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) {
continue;
}
int idyD = int(dyD);
for (int wR = 0; wR < ${l};
wR += ${r}) {
float dyR = float(dyRCorner + wR) / ${s}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
for (int wC = 0; wC < ${c};
wC += ${o}) {
float dyC = float(dyCCorner + wC) / ${n}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
float dyValue = getDy(batch, idyD, idyR, idyC, ch);
int maxPosValue = ${d} -
int(getMaxPos(batch, idyD, idyR, idyC, ch));
// Get the current value, check it against the value from the
// position matrix.
int curPosValue =
wD * ${l} * ${c} +
wR * ${c} + wC;
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
dotProd += dyValue * mask;
}
}
}
setOutput(dotProd);
}
`}}class pg{constructor(e,t,s=!1,n=!1,i=!1,r=null,o=!1){this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t;const a=s?e[1]:e[2],l=Math.ceil(a/2),c=s?"i * 2, rc.y":"rc.y, i * 2",p=n?"rc.z, i * 2":"i * 2, rc.z",u=s?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],h=n?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"];let d="",m="";r&&(o?d=`vec4 activation(vec4 a) {
vec4 b = getPreluActivationWeightsAtOutCoords();
${r}
}`:d=`vec4 activation(vec4 x) {
${r}
}`,m="result = activation(result);");const f=i?"result += getBiasAtOutCoords();":"";i&&this.variableNames.push("bias"),o&&this.variableNames.push("preluActivationWeights"),this.userCode=`
${d}
const float sharedDimension = ${l}.0;
vec4 dot2x2ARowBCol(ivec3 rc) {
vec4 result = vec4(0);
for (int i = 0; i < ${l}; i++) {
vec4 a = getMatrixA(rc.x, ${c});
vec4 b = getMatrixB(rc.x, ${p});
// These swizzled products need to be separately added.
// See: https://github.com/tensorflow/tfjs/issues/1735
result += (${u[0]} * ${h[0]});
result += (${u[1]} * ${h[1]});
}
return result;
}
void main() {
ivec3 rc = getOutputCoords();
vec4 result = dot2x2ARowBCol(rc);
${f}
${m}
setOutput(result);
}
`}}class IO{constructor(e,t,s){this.variableNames=["probs"],this.outputShape=[e,s],this.userCode=`
uniform float seed;
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
float r = random(seed);
float cdf = 0.0;
for (int i = 0; i < ${t-1}; i++) {
cdf += getProbs(batch, i);
if (r < cdf) {
setOutput(float(i));
return;
}
}
// If no other event happened, last event happened.
setOutput(float(${t-1}));
}
`}getCustomSetupFunc(e){return(t,s)=>{this.seedLoc==null&&(this.seedLoc=t.getUniformLocation(s,"seed")),t.gl.uniform1f(this.seedLoc,e)}}}class vO{constructor(e,t,s,n){this.variableNames=["indices"],this.outputShape=[e,t],this.userCode=`
void main() {
ivec2 coords = getOutputCoords();
int index = round(getIndices(coords.x));
setOutput(mix(float(${n}), float(${s}),
float(index == coords.y)));
}
`}}class TO{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outputShape=e;const t=e.length;if(t===0)this.userCode=`
void main() {
setOutput(vec4(getA(), 0., 0., 0.));
}
`;else{const s=_t("rc",t),n=Re(t),i=_V(t,e,s),r=kV(t,e[e.length-1],e[e.length-2],s),o=DV(e,s);this.userCode=`
void main() {
${n} rc = getOutputCoords();
if(${i}) {
setOutput(vec4(0));
} else {
${r}
setOutput(vec4(${o}));
}
}
`}}}function FV(e,t){const s=[];for(let n=0;n<=1;n++)for(let i=0;i<=1;i++){let r=`${n===0?"r":"rp1"}, ${i===0?"c":"cp1"}`;for(let o=2;o<e;o++)r=`${t[t.length-1-o]},`+r;s.push(r)}return s}function _V(e,t,s){if(e===1)return`rc > ${t[0]}`;let n="";for(let i=e-2;i<e;i++)n+=`${s[i]} >= ${t[i]}`,i<e-1&&(n+="||");return n}function kV(e,t,s,n){if(e===1)return"";const i=n.slice(-2);return`
int r = ${i[0]};
int c = ${i[1]};
int rp1 = r + 1;
int cp1 = c + 1;
bool cEdge = cp1 >= ${t};
bool rEdge = rp1 >= ${s};
`}function DV(e,t){const s=e.length,n=FV(s,t);return s===1?`getA(rc),
rc + 1 >= ${e[0]} ? 0. : getA(rc + 1),
0, 0`:`getA(${n[0]}),
cEdge ? 0. : getA(${n[1]}),
rEdge ? 0. : getA(${n[2]}),
rEdge || cEdge ? 0. : getA(${n[3]})`}class AO{constructor(e,t,s){this.variableNames=["x"],this.outputShape=t.map((l,c)=>l[0]+e[c]+l[1]);const n=e.length,i=Re(n),r=t.map(l=>l[0]).join(","),o=t.map((l,c)=>l[0]+e[c]).join(","),a=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,n);if(n===1){this.userCode=`
int start = ${r};
int end = ${o};
void main() {
int outC = getOutputCoords();
if (outC < start || outC >= end) {
setOutput(float(${s}));
} else {
setOutput(getX(outC - start));
}
}
`;return}this.userCode=`
${i} start = ${i}(${r});
${i} end = ${i}(${o});
void main() {
${i} outC = getOutputCoords();
if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {
setOutput(float(${s}));
} else {
${i} coords = outC - start;
setOutput(getX(${a}));
}
}
`}}class NO{constructor(e,t,s){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.map((m,f)=>m[0]+e[f]+m[1]);const n=e.length,i=Re(n),r=t.map(m=>m[0]).join(","),o=t.map((m,f)=>m[0]+e[f]).join(","),a=_t("rc",n),l=_t("source",n),c=`${a[n-1]} < ${this.outputShape[n-1]}`,p=n===1?"source":`vec2(${l.slice(-2).join()})`,u=[`${i} rc = outputLoc;`,`${a[n-1]} += 1;
if(${c}) {
`,n===1?"":`}
rc = outputLoc;
${a[n-2]} += 1;
if(${a[n-2]} < ${this.outputShape[n-2]}) {`,n===1?"":` ${a[n-1]} += 1;
if(${c}) {`],h=n===1?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))";let d="";for(let m=0,f=n===1?2:4;m<f;m++)d+=`
${u[m]}
if (${h}) {
result[${m}] = float(${s});
} else {
${i} source = rc - start;
result[${m}] = getChannel(getX(${l.join()}), ${p});
}
`;d+=n===1?"} ":"}}",this.userCode=`
const ${i} start = ${i}(${r});
const ${i} end = ${i}(${o});
void main() {
${i} outputLoc = getOutputCoords();
vec4 result = vec4(0.);
${d}
setOutput(result);
}
`}}class Zi{constructor(e,t,s,n=!1,i=!1){if(this.variableNames=["x"],t==="avg"&&s)throw new Error("Cannot compute positions for average pool.");const r=e.filterWidth,o=e.strideHeight,a=e.strideWidth,l=e.dilationHeight,c=e.dilationWidth,p=e.effectiveFilterHeight,u=e.effectiveFilterWidth,h=e.padInfo.top,d=e.padInfo.left;this.outputShape=e.outShape;const m=t==="avg",f=`((batch * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + d`,g=`(xR * ${e.inWidth} + xC) * ${e.inChannels} + d`;let y="0.0";if(m||(y="-1.0 / 1e-20"),s){const E=">=";this.userCode=`
const ivec2 strides = ivec2(${o}, ${a});
const ivec2 pads = ivec2(${h}, ${d});
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d = coords[3];
ivec2 xRCCorner = coords.yz * strides - pads;
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
// max/min x(?, ?, d) to get y(yR, yC, d).
// ? = to be determined
float minMaxValue = 0.0;
float minMaxValueFound = 0.0;
int minMaxPosition = 0;
float avgValue = 0.0;
for (int wR = 0; wR < ${p};
wR += ${l}) {
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int wC = 0; wC < ${u};
wC += ${c}) {
int xC = xCCorner + wC;
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
float value = getX(batch, xR, xC, d);
// If a min / max value has already been found, use it. If not,
// use the current value.
float currMinMaxValue = mix(
value, minMaxValue, minMaxValueFound);
if (value ${E} currMinMaxValue) {
minMaxValue = value;
minMaxValueFound = 1.0;
minMaxPosition = ${n?i?f:g:`wR * ${u} + wC`};
}
}
}
setOutput(float(minMaxPosition));
}
`;return}const w="max";let x=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(x="avgValue / count");const T=Math.floor(r/4)*4,A=r%4,_=`
if (${m}) {
avgValue += dot(values, ones);
} else {
minMaxValue = ${w}(values, minMaxValue);
}
`;this.userCode=`
const ivec2 strides = ivec2(${o}, ${a});
const ivec2 pads = ivec2(${h}, ${d});
const float initializationValue = ${y};
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
float count = 0.0;
float getValue(int batch, int xR, int xC, int d) {
if (xC < 0 || xC >= ${e.inWidth}) {
return initializationValue;
}
count += 1.0;
return getX(batch, xR, xC, d);
}
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d = coords[3];
ivec2 xRCCorner = coords.yz * strides - pads;
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
// max/min x(?, ?, d) to get y(yR, yC, d).
// ? = to be determined
vec4 minMaxValue = vec4(${y});
float avgValue = 0.0;
count = 0.0;
for (int wR = 0; wR < ${p};
wR += ${l}) {
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int wC = 0; wC < ${T}; wC += 4) {
int xC = xCCorner + wC * ${c};
vec4 values = vec4(
getValue(batch, xR, xC, d),
getValue(batch, xR, xC + ${c}, d),
getValue(batch, xR, xC + 2 * ${c}, d),
getValue(batch, xR, xC + 3 * ${c}, d)
);
${_}
}
int xC = xCCorner + ${T};
if (${A===1}) {
vec4 values = vec4(
getValue(batch, xR, xC, d),
initializationValue,
initializationValue,
initializationValue
);
${_}
} else if (${A===2}) {
vec4 values = vec4(
getValue(batch, xR, xC, d),
getValue(batch, xR, xC + ${c}, d),
initializationValue,
initializationValue
);
${_}
} else if (${A===3}) {
vec4 values = vec4(
getValue(batch, xR, xC, d),
getValue(batch, xR, xC + ${c}, d),
getValue(batch, xR, xC + 2 * ${c}, d),
initializationValue
);
${_}
}
}
setOutput(${x});
}
`}}class ug{constructor(e,t,s,n=!1,i=!1){if(this.variableNames=["x"],t==="avg"&&s)throw new Error("Cannot compute positions for average pool.");const r=e.filterWidth,o=e.strideDepth,a=e.strideHeight,l=e.strideWidth,c=e.dilationDepth,p=e.dilationHeight,u=e.dilationWidth,h=e.effectiveFilterDepth,d=e.effectiveFilterHeight,m=e.effectiveFilterWidth,f=e.padInfo.front,g=e.padInfo.top,y=e.padInfo.left;this.outputShape=e.outShape;const w=t==="avg";let x="0.0";if(w||(x="-1.0 / 1e-20"),s){const D=">=";this.userCode=`
const ivec3 strides =
ivec3(${o}, ${a}, ${l});
const ivec3 pads = ivec3(${f}, ${g}, ${y});
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int ch = coords.u;
ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
int xDCorner = xCorner.x;
int xRCorner = xCorner.y;
int xCCorner = xCorner.z;
// max/min x(?, ?, ?, ch) to get y(yD, yR, yC, ch).
// ? = to be determined
float minMaxValue = 0.0;
float minMaxValueFound = 0.0;
int minMaxPosition = 0;
for (int wD = 0; wD < ${h};
wD += ${c}) {
int xD = xDCorner + wD;
if (xD < 0 || xD >= ${e.inDepth}) {
continue;
}
for (int wR = 0; wR < ${d};
wR += ${p}) {
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int wC = 0; wC < ${m};
wC += ${u}) {
int xC = xCCorner + wC;
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
float value = getX(batch, xD, xR, xC, ch);
// If a min / max value has already been found, use it. If not,
// use the current value.
float currMinMaxValue = mix(
value, minMaxValue, minMaxValueFound);
if (value ${D} currMinMaxValue) {
minMaxValue = value;
minMaxValueFound = 1.0;
minMaxPosition = ${n?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 * ${d} * ${m} +
wR * ${m} + wC`};
}
}
}
}
setOutput(float(minMaxPosition));
}
`;return}const T="max";let A=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(A="avgValue / count");const _=Math.floor(r/4)*4,E=r%4,F=`
if (${w}) {
avgValue += dot(values, ones);
} else {
minMaxValue = ${T}(values, minMaxValue);
}
`;this.userCode=`
const ivec3 strides =
ivec3(${o}, ${a}, ${l});
const ivec3 pads = ivec3(${f}, ${g}, ${y});
const float initializationValue = ${x};
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
float count = 0.0;
float getValue(int batch, int xD, int xR, int xC, int ch) {
if (xC < 0 || xC >= ${e.inWidth}) {
return initializationValue;
}
count += 1.0;
return getX(batch, xD, xR, xC, ch);
}
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int ch = coords.u;
ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
int xDCorner = xCorner.x;
int xRCorner = xCorner.y;
int xCCorner = xCorner.z;
// max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch).
// ? = to be determined
vec4 minMaxValue = vec4(${x});
float avgValue = 0.0;
count = 0.0;
for (int wD = 0; wD < ${h};
wD += ${c}) {
int xD = xDCorner + wD;
if (xD < 0 || xD >= ${e.inDepth}) {
continue;
}
for (int wR = 0; wR < ${d};
wR += ${p}) {
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int wC = 0; wC < ${_}; wC += 4) {
int xC = xCCorner + wC * ${u};
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
getValue(batch, xD, xR, xC + ${u}, ch),
getValue(batch, xD, xR, xC + 2 * ${u}, ch),
getValue(batch, xD, xR, xC + 3 * ${u}, ch)
);
${F}
}
int xC = xCCorner + ${_};
if (${E===1}) {
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
initializationValue,
initializationValue,
initializationValue
);
${F}
} else if (${E===2}) {
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
getValue(batch, xD, xR, xC + ${u}, ch),
initializationValue,
initializationValue
);
${F}
} else if (${E===3}) {
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
getValue(batch, xD, xR, xC + ${u}, ch),
getValue(batch, xD, xR, xC + 2 * ${u}, ch),
initializationValue
);
${F}
}
}
setOutput(${A});
}
}
`}}class hg{constructor(e,t){this.variableNames=["x"];const{windowSize:s,batchSize:n,inSize:i,outSize:r}=e;this.outputShape=[n,r];let o="0.0",a="";t==="prod"?o="1.0":t==="min"?(o="1.0 / 1e-20",a="min"):t==="max"&&(o="-1.0 / 1e-20",a="max");let l=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="sum"?l="sumValue":t==="prod"?l="prodValue":t==="all"?l="allValue":t==="any"&&(l="anyValue");const c=Math.floor(s/4)*4,p=s%4;let u=`
if (${t==="sum"}) {
sumValue += dot(values, ones);
} else if (${t==="prod"}) {
vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);
prodValue *= tmp[0] * tmp[1];
} else {
minMaxValue = ${a}(values, minMaxValue);
}
`,h="vec4";t==="all"?(o="1.0",u=`
bool reducedAllValue = all(values);
float floatedReducedAllValue = float(reducedAllValue);
allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);
`,h="bvec4"):t==="any"&&(o="0.0",u=`
bool reducedAnyValue = any(values);
float floatedReducedAnyValue = float(reducedAnyValue);
anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);
`,h="bvec4");let d="";i%s>0&&(d=`
if (inIdx < 0 || inIdx >= ${i}) {
return initializationValue;
}
`),this.userCode=`
const float initializationValue = ${o};
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 * ${s};
vec4 minMaxValue = vec4(${o});
float prodValue = 1.0;
float sumValue = 0.0;
float allValue = 1.0;
float anyValue = 0.0;
for (int i = 0; i < ${c}; i += 4) {
int inIdx = inOffset + i;
${h} values = ${h}(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
getValue(batch, inIdx + 3)
);
${u}
}
int inIdx = inOffset + ${c};
if (${p===1}) {
${h} values = ${h}(
getValue(batch, inIdx),
initializationValue,
initializationValue,
initializationValue
);
${u}
} else if (${p===2}) {
${h} values = ${h}(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
initializationValue,
initializationValue
);
${u}
} else if (${p===3}) {
${h} values = ${h}(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
initializationValue
);
${u}
}
setOutput(${l});
}
`}}class dg{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e;let s="";for(let n=0;n<4;n++){let i="thisRC = rc;";n%2===1&&(i+="thisRC.z += 1;"),n>1&&(i+="thisRC.y += 1;"),s+=`
${i}
${n>0?"if(thisRC.y < rows && thisRC.z < cols){":""}
int flatIndex = getFlatIndex(thisRC);
ivec3 inputRC = inputCoordsFromReshapedOutCoords(flatIndex);
vec2 inputRCInnerDims = vec2(float(inputRC.y),float(inputRC.z));
result[${n}] =
getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);
${n>0?"}":""}
`}this.userCode=`
${MV(t)}
${nc(e)}
void main() {
ivec3 rc = getOutputCoords();
vec4 result = vec4(0.);
ivec3 thisRC;
int rows = ${e[1]};
int cols = ${e[2]};
${s}
setOutput(result);
}
`}}function MV(e){const t=Hn(["r","c","d"],e);return`
ivec3 inputCoordsFromReshapedOutCoords(int index) {
${t}
return ivec3(r, c, d);
}
`}class CO{constructor(e,t,s){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t.shape;const[,n,i]=t.shape,[,r,o]=e.shape,a=[s&&r>1?n-1:n,s&&o>1?i-1:i],l=[s&&r>1?r-1:r,s&&o>1?o-1:o],c=a[0]/l[0],p=a[1]/l[1],u=1/c,h=1/p,d=Math.ceil(u)*2+2,m=Math.ceil(h)*2+2;this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
int r = coords[1];
int c = coords[2];
float accumulator = 0.0;
const float heightScale = float(${c});
const float widthScale = float(${p});
const float invHeightScale = float(${u});
const float invWidthScale = float(${h});
const int winHeight = int(${d});
const int winWidth = int(${m});
// Compute bounds for where in dy we will look
float startRLerp = floor(float(r) * invHeightScale);
int startDyR = int(startRLerp - float(winHeight / 2));
float startCLerp = floor(float(c) * invWidthScale);
int startDyC = int(startCLerp - float(winWidth / 2));
// Loop over dy
for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {
int dyR = dyROffset + startDyR;
// Guard against the window exceeding the bounds of dy
if (dyR < 0 || dyR >= ${r}) {
continue;
}
for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {
int dyC = dyCOffset + startDyC;
// Guard against the window exceeding the bounds of dy
if (dyC < 0 || dyC >= ${o}) {
continue;
}
float dxR = float(dyR) * heightScale;
int topDxRIndex = int(floor(dxR));
int bottomDxRIndex = int(min(ceil(dxR), ${n-1}.0));
float dxRLerp = dxR - float(topDxRIndex);
float inverseDxRLerp = 1.0 - dxRLerp;
float dxC = float(dyC) * widthScale;
int leftDxCIndex = int(floor(dxC));
int rightDxCIndex = int(min(ceil(dxC), ${i-1}.0));
float dxCLerp = dxC - float(leftDxCIndex);
float inverseDxCLerp = 1.0 - dxCLerp;
if (r == topDxRIndex && c == leftDxCIndex) {
// topLeft
accumulator +=
getDy(b, dyR, dyC, d) * inverseDxRLerp * inverseDxCLerp;
}
if (r == topDxRIndex && c == rightDxCIndex) {
// topRight
accumulator += getDy(b, dyR, dyC, d) * inverseDxRLerp * dxCLerp;
}
if (r == bottomDxRIndex && c == leftDxCIndex) {
// bottomLeft
accumulator += getDy(b, dyR, dyC, d) * dxRLerp * inverseDxCLerp;
}
if (r == bottomDxRIndex && c == rightDxCIndex) {
// bottomRight
accumulator += getDy(b, dyR, dyC, d) * dxRLerp * dxCLerp;
}
}
}
// End loop over dy
setOutput(accumulator);
}
`}}class RO{constructor(e,t,s,n){this.variableNames=["A"],this.outputShape=[];const[i,r,o,a]=e;this.outputShape=[i,t,s,a];const l=[n&&t>1?r-1:r,n&&s>1?o-1:o],c=[n&&t>1?t-1:t,n&&s>1?s-1:s];this.userCode=`
const vec2 effectiveInputOverOutputRatioRC = vec2(
${l[0]/c[0]},
${l[1]/c[1]});
const vec2 inputShapeRC = vec2(${r}.0, ${o}.0);
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 yRC = coords.yz;
// Fractional source index.
vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;
// Compute the four integer indices.
ivec2 sourceFloorRC = ivec2(sourceFracIndexRC);
ivec2 sourceCeilRC = ivec2(
min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));
float topLeft = getA(b, sourceFloorRC.x, sourceFloorRC.y, d);
float bottomLeft = getA(b, sourceCeilRC.x, sourceFloorRC.y, d);
float topRight = getA(b, sourceFloorRC.x, sourceCeilRC.y, d);
float bottomRight = getA(b, sourceCeilRC.x, sourceCeilRC.y, d);
vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC);
float top = topLeft + (topRight - topLeft) * fracRC.y;
float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;
float newValue = top + (bottom - top) * fracRC.x;
setOutput(newValue);
}
`}}class OO{constructor(e,t,s,n){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];const[i,r,o,a]=e;this.outputShape=[i,t,s,a];const l=[n&&t>1?r-1:r,n&&s>1?o-1:o],c=[n&&t>1?t-1:t,n&&s>1?s-1:s];this.userCode=`
const vec3 effectiveInputOverOutputRatioRC = vec3(
${l[0]/c[0]},
${l[1]/c[1]},
${l[1]/c[1]});
const vec3 inputShapeRC = vec3(${r}.0, ${o}.0,
${o}.0);
float getAValue(int b, int r, int c, int d) {
return getChannel(getA(b, r, c, d), vec2(c, d));
}
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
// Calculate values for next column in yRC.z.
ivec3 yRC = coords.yzz + ivec3(0, 0, 1);
// Fractional source index.
vec3 sourceFracIndexRC = vec3(yRC) * effectiveInputOverOutputRatioRC;
// Compute the four integer indices.
ivec3 sourceFloorRC = ivec3(sourceFracIndexRC);
ivec3 sourceCeilRC = ivec3(
min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));
// Should we calculate next column and row elements in 2x2 packed cell.
bool hasNextCol = d < ${a-1};
bool hasNextRow = coords.z < ${s-1};
// In parallel, construct four corners for all four components in
// packed 2x2 cell.
vec4 topLeft = vec4(
getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d),
hasNextCol ? getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d + 1)
: 0.0,
hasNextRow ? getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d)
: 0.0,
(hasNextRow && hasNextCol) ?
getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d + 1) : 0.0);
vec4 bottomLeft = vec4(
getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d),
hasNextCol ? getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d + 1)
: 0.0,
hasNextRow ? getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d)
: 0.0,
(hasNextRow && hasNextCol) ?
getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d + 1) : 0.0);
vec4 topRight = vec4(
getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d),
hasNextCol ? getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d + 1)
: 0.0,
hasNextRow ? getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d)
: 0.0,
(hasNextRow && hasNextCol) ?
getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d + 1) : 0.0);
vec4 bottomRight = vec4(
getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d),
hasNextCol ? getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d + 1)
: 0.0,
hasNextRow ? getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d)
: 0.0,
(hasNextRow && hasNextCol) ?
getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d + 1) : 0.0);
vec3 fracRC = sourceFracIndexRC - vec3(sourceFloorRC);
vec4 top = mix(topLeft, topRight, fracRC.yyzz);
vec4 bottom = mix(bottomLeft, bottomRight, fracRC.yyzz);
vec4 newValue = mix(top, bottom, fracRC.x);
setOutput(newValue);
}
`}}class EO{constructor(e,t,s){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t.shape;const[,n,i]=t.shape,[,r,o]=e.shape,a=[s&&r>1?n-1:n,s&&o>1?i-1:i],l=[s&&r>1?r-1:r,s&&o>1?o-1:o],c=a[0]/l[0],p=a[1]/l[1],u=1/c,h=1/p,d=Math.ceil(u)*2+2,m=Math.ceil(h)*2+2;this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
int r = coords[1];
int c = coords[2];
float accumulator = 0.0;
const float heightScale = float(${c});
const float widthScale = float(${p});
const float invHeightScale = float(${u});
const float invWidthScale = float(${h});
const int winHeight = int(${d});
const int winWidth = int(${m});
// Compute bounds for where in dy we will look
float startRLerp = floor(float(r) * invHeightScale);
int startDyR = int(floor(startRLerp - float(winHeight / 2)));
float startCLerp = floor(float(c) * invWidthScale);
int startDyC = int(floor(startCLerp - float(winWidth / 2)));
// Loop over dy
for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {
int dyR = dyROffset + startDyR;
// Guard against the window exceeding the bounds of dy
if (dyR < 0 || dyR >= ${r}) {
continue;
}
for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {
int dyC = dyCOffset + startDyC;
// Guard against the window exceeding the bounds of dy
if (dyC < 0 || dyC >= ${o}) {
continue;
}
float sourceFracRow =
float(${a[0]}) *
(float(dyR) / float(${l[0]}));
float sourceFracCol =
float(${a[1]}) *
(float(dyC) / float(${l[1]}));
int sourceNearestRow = int(min(
float(int(${n}) - 1),
${s} ? float(round(sourceFracRow)) :
float(floor(sourceFracRow))));
int sourceNearestCol = int(min(
float(int(${i}) - 1),
${s} ? float(round(sourceFracCol)) :
float(floor(sourceFracCol))));
if (r == sourceNearestRow && c == sourceNearestCol) {
accumulator += getDy(b, dyR, dyC, d);
}
}
}
// End loop over dy
setOutput(accumulator);
}
`}}class _O{constructor(e,t,s,n){this.variableNames=["A"],this.outputShape=[];const[i,r,o,a]=e;this.outputShape=[i,t,s,a];const l=[n&&t>1?r-1:r,n&&s>1?o-1:o],c=[n&&t>1?t-1:t,n&&s>1?s-1:s],p=n?"0.5":"0.0";this.userCode=`
const vec2 effectiveInputOverOutputRatioRC = vec2(
${l[0]/c[0]},
${l[1]/c[1]});
const vec2 inputShapeRC = vec2(${r}.0, ${o}.0);
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 yRC = coords.yz;
// Fractional source index.
vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;
// Compute the coordinators of nearest neighbor point.
ivec2 sourceNearestRC = ivec2(
min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${p})));
float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);
setOutput(newValue);
}
`}}class kO{constructor(e,t){this.variableNames=["x"];const s=e.length;if(s>4)throw new Error(`WebGL backend: Reverse of rank-${s} tensor is not yet supported`);if(this.outputShape=e,s===1){this.userCode=`
void main() {
int coord = getOutputCoords();
setOutput(getX(${e[0]} - coord - 1));
}
`;return}const n=o=>t.indexOf(o)!==-1&&e[o]!==1?`${e[o]} - coords[${o}] - 1`:`coords[${o}]`,i=e.map((o,a)=>n(a)).join(","),r=Re(s);this.userCode=`
void main() {
${r} coords = getOutputCoords();
setOutput(getX(${i}));
}
`}}class DO{constructor(e,t){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;const s=e.length;if(s>4)throw new Error(`WebGL backend: Reverse of rank-${s} tensor is not yet supported`);this.outputShape=e;const n=_t("rc",s),i=`${n[s-1]} + 1 < ${this.outputShape[s-1]}`,r=`${n[s-2]} + 1 < ${this.outputShape[s-2]}`,o=Re(s);s===1?this.userCode=`
void main(){
int rc = getOutputCoords();
vec4 result = vec4(0.);
result.r = getChannel(getX(${e[0]} - rc - 1),
${e[0]} - rc - 1);
if(${i}){
result.g = getChannel(getX(${e[0]} - (rc + 1) - 1),
${e[0]} - (rc + 1) - 1);
}
setOutput(result);
}
`:this.userCode=`
void main() {
${o} rc = getOutputCoords();
vec4 result = vec4(0.);
result.r = ${a(n.slice())};
if(${i}){
result.g = ${l(n.slice())};
}
if(${r}) {
result.b = ${c(n.slice())};
if(${i}) {
result.a = ${p(n.slice())};
}
}
setOutput(result);
}
`;function a(d){return u(d)}function l(d){return d[s-1]="("+d[s-1]+" + 1)",u(d)}function c(d){return d[s-2]="("+d[s-2]+" + 1)",u(d)}function p(d){return d[s-1]="("+d[s-1]+" + 1)",d[s-2]="("+d[s-2]+" + 1)",u(d)}function u(d){const m=e.map((y,w)=>h(w,d)),f=m.join(","),g=m.slice(-2).join(",");return`getChannel(getX(${f}), vec2(${g}))`}function h(d,m){return t.indexOf(d)!==-1&&e[d]!==1?`${e[d]} - ${m[d]} - 1`:`${m[d]}`}}}class Px{constructor(e,t,s,n,i,r,o=!0){this.variableNames=["updates","indices","defaultValue"],this.outputShape=r;const a=Re(i.length),l=Re(r.length);let c="";s===1?c="i":s===2&&(c="i, j");const p=`getIndices(${c})`;let u="";n===1?u="i":n===2&&(u="i, coords[1]");const h=`getUpdates(${u})`,d=t>1?"strides[j]":"strides";this.userCode=`
${a} strides = ${a}(${i});
void main() {
${l} coords = getOutputCoords();
float sum = 0.0;
bool found = false;
for (int i = 0; i < ${e}; i++) {
int flattenedIndex = 0;
for (int j = 0; j < ${t}; j++) {
int index = round(${p});
flattenedIndex += index * ${d};
}
if (flattenedIndex == coords[0]) {
sum += ${h};
found = true;
}
}
setOutput(mix(getDefaultValue(), sum, float(found)));
}
`}}class FO{constructor(e,t){this.variableNames=["x","segmentIds"];const s=e.windowSize,n=e.batchSize,i=e.inSize,r=e.numSegments,o=r*Math.ceil(i/s);this.outputShape=[n,o];const a="0.0",l="sumValue",c=Math.floor(s/4)*4,p=s%4,u=`
sumValue += dot(values, segFilter);
`;let h="";i%s>0&&(h=`
if (inIdx < 0 || inIdx >= ${i}) {
return initializationValue;
}
`);let d="";i%s>0&&(d=`
if (inIdx < 0 || inIdx >= ${i}) {
return -1.0;
}
`),this.userCode=`
const float initializationValue = ${a};
float getValue(int batch, int inIdx) {
${h}
return getX(batch, inIdx);
}
float getSegmentIdAtIndex(int inIdx) {
${d}
return getSegmentIds(inIdx);
}
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
int inOffset = int(floor(float(outIdx) / float(
${r})) * float(${s}));
int currentSeg = int(mod(float(outIdx), float(${r})));
float sumValue = 0.0;
for (int i = 0; i < ${c}; i += 4) {
int inIdx = inOffset + i;
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
getValue(batch, inIdx + 3)
);
vec4 segFilter = vec4(
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 3)) == currentSeg ? 1 : 0
);
${u}
}
int inIdx = inOffset + ${c};
if (${p===1}) {
vec4 values = vec4(
getValue(batch, inIdx),
initializationValue,
initializationValue,
initializationValue
);
int inIdxSeg = int(getSegmentIdAtIndex(inIdx));
vec4 segFilter = vec4(
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
0,
0,
0
);
${u}
} else if (${p===2}) {
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
initializationValue,
initializationValue
);
vec4 segFilter = vec4(
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
0,
0
);
${u}
} else if (${p===3}) {
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
initializationValue
);
vec4 segFilter = vec4(
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,
0
);
${u}
}
setOutput(${l});
}
`}}class MO{constructor(e,t,s){this.variableNames=["c","a","b"],this.outputShape=t;let n,i;if(s>4)throw Error(`Where for rank ${s} is not yet supported`);if(s===1)i="resRC",n="resRC";else{const o=["resRC.x","resRC.y","resRC.z","resRC.w"],a=[],l=[];for(let c=0;c<t.length;c++)l.push(`${o[c]}`),c<e&&a.push(`${o[c]}`);n=a.join(),i=l.join()}const r=Re(s);this.userCode=`
void main() {
${r} resRC = getOutputCoords();
float cVal = getC(${n});
if (cVal >= 1.0) {
setOutput(getA(${i}));
} else {
setOutput(getB(${i}));
}
}
`}}class UO{constructor(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;const t=Re(this.rank),s=`uniform int start[${this.rank}];`,n=UV(this.rank);let i;const r=e.map((o,a)=>`sourceLoc.${Bx[a]} = start[${a}] + coords.${Bx[a]};`);i=`
${t} sourceLoc;
${t} coords = getOutputCoords();
${r.join(`
`)}
`,this.userCode=`
${s}
void main() {
${i}
setOutput(getSource(${n}));
}
`}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,s)=>{if(this.startLoc==null&&(this.startLoc=t.getUniformLocationNoThrow(s,"start"),this.startLoc==null))return;t.gl.uniform1iv(this.startLoc,e)}}}const Bx=["x","y","z","w","u","v"];function UV(e){if(e===1)return"sourceLoc";if(e<=6)return Bx.slice(0,e).map(t=>"sourceLoc."+t).join(",");throw Error(`Slicing for rank ${e} is not yet supported`)}class $O{constructor(e){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.rank=e.length;const t=Re(this.rank),s=_t("coords",this.rank),n=_t("sourceLoc",this.rank),i=this.rank===1?"sourceLoc":`vec2(${n.slice(-2).join()})`,r=`getChannel(getSource(${n.join()}), ${i})`,o=`
result.x = ${r};
if (++${s[this.rank-1]} < ${e[this.rank-1]}) {
++${n[this.rank-1]};
result.y = ${r};
--${n[this.rank-1]};
}
`,a=this.rank===1?"":`
--${s[this.rank-1]};
if (++${s[this.rank-2]} < ${e[this.rank-2]}) {
++${n[this.rank-2]};
result.z = ${r};
if (++${s[this.rank-1]} < ${e[this.rank-1]}) {
++${n[this.rank-1]};
result.w = ${r};
}
}
`,l=this.rank<=4?`sourceLoc = coords +
${t}(${e.map((c,p)=>`start[${p}]`).join()});`:e.map((c,p)=>`${n[p]} = ${s[p]} + start[${p}];`).join(`
`);this.userCode=`
uniform int start[${this.rank}];
void main() {
${t} coords = getOutputCoords();
${t} sourceLoc;
${l}
vec4 result = vec4(0.);
${o}
${a}
setOutput(result);
}
`}getCustomSetupFunc(e){if(e.length!==this.rank)throw Error(`The rank (${this.rank}) of the program must match the length of start (${e.length})`);return(t,s)=>{if(this.startLoc==null&&(this.startLoc=t.getUniformLocationNoThrow(s,"start"),this.startLoc==null))return;t.gl.uniform1iv(this.startLoc,e)}}}class WO{constructor(e,t,s){this.variableNames=["x"],this.outputShape=s;const n=s.length,i=Re(s.length),r=Re(s.length);let o="";if(n===1)o="coords * strides + begin";else{let a=0;o=s.map((l,c)=>(a++,s.length===1?`coords * strides[${c}] + begin[${c}]`:`coords[${a-1}] * strides[${c}] + begin[${c}]`)).join(",")}this.userCode=`
${i} begin = ${i}(${e});
${i} strides = ${i}(${t});
void main() {
${r} coords = getOutputCoords();
setOutput(getX(${o}));
}
`}}class jO{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,s){const n=PO(t,s),i=BO(e,n,s);i in this.freeTextures||(this.freeTextures[i]=[]),i in this.usedTextures||(this.usedTextures[i]=[]);const r=zO(e,n,this.gpgpu.gl,this.gpgpu.textureConfig,s);if(this.freeTextures[i].length>0){this.numFreeTextures--,this.numUsedTextures++,this._numBytesFree-=r,this.log();const a=this.freeTextures[i].shift();return this.usedTextures[i].push(a),a}let o;return n===Xt.PACKED_2X2_FLOAT32?o=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):n===Xt.PACKED_2X2_FLOAT16?o=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):n===Xt.UNPACKED_FLOAT32?o=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):n===Xt.UNPACKED_FLOAT16?o=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):n===Xt.PACKED_4X1_UNSIGNED_BYTE&&(o=this.gpgpu.createUnsignedBytesMatrixTexture(e[0],e[1])),this.usedTextures[i].push(o),this.numUsedTextures++,this._numBytesAllocated+=r,this.log(),o}releaseTexture(e,t,s,n){if(this.freeTextures==null)return;const i=PO(s,n),r=BO(t,i,n);r in this.freeTextures||(this.freeTextures[r]=[]);const o=zO(t,i,this.gpgpu.gl,this.gpgpu.textureConfig,n),a=W().get("WEBGL_DELETE_TEXTURE_THRESHOLD");a!==-1&&this._numBytesAllocated>a?(this.gpgpu.deleteMatrixTexture(e),this._numBytesAllocated-=o):(this.freeTextures[r].push(e),this.numFreeTextures++,this._numBytesFree+=o),this.numUsedTextures--;const l=this.usedTextures[r],c=l.indexOf(e);if(c<0)throw new Error("Cannot release a texture that was never provided by this texture manager");l.splice(c,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 $V(e,t){const s=e;if(t===s.R32F)return 4;if(t===s.R16F)return 2;if(t===s.RGBA32F)return 16;if(t===e.RGBA)return 16;if(t===s.RGBA16F)return 8;throw new Error(`Unknown internal format ${t}`)}function zO(e,t,s,n,i){const r=WV(t,n);let o;if(i){const[l,c]=wi(e[0],e[1]);o=l*c}else{const[l,c]=Ta(e[0],e[1]);o=l*c}const a=$V(s,r);return o*a}function WV(e,t){switch(e){case Xt.PACKED_2X2_FLOAT32:return $x(t);case Xt.PACKED_2X2_FLOAT16:return Wx(t);case Xt.UNPACKED_FLOAT32:return Fx(t);case Xt.UNPACKED_FLOAT16:return Mx(t);case Xt.PACKED_4X1_UNSIGNED_BYTE:return Ux(t);default:throw new Error(`Unknown physical texture type ${e}`)}}function zV(e){return W().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?Xt.PACKED_2X2_FLOAT32:Xt.UNPACKED_FLOAT32:e?Xt.PACKED_2X2_FLOAT16:Xt.UNPACKED_FLOAT16}function PO(e,t){if(e===is.UPLOAD)return Xt.PACKED_2X2_FLOAT32;if(e===is.RENDER||e==null)return zV(t);if(e===is.DOWNLOAD||e===is.PIXELS)return Xt.PACKED_4X1_UNSIGNED_BYTE;throw new Error(`Unknown logical texture type ${e}`)}function BO(e,t,s){return`${e[0]}_${e[1]}_${t}_${s}`}class VO{constructor(e,t){this.variableNames=["A"];const s=new Array(e.length);for(let r=0;r<s.length;r++)s[r]=e[r]*t[r];this.outputShape=s,this.rank=s.length;const n=Re(this.rank),i=PV(e);this.userCode=`
void main() {
${n} resRC = getOutputCoords();
setOutput(getA(${i}));
}
`}}function PV(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 s=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],n=[];for(let i=0;i<e.length;i++)n.push(`imod(${s[i]}, ${e[i]})`);return n.join()}class $e{constructor(e,t){this.variableNames=["A"],this.outputShape=e,this.userCode=`
float unaryOperation(float x) {
${t}
}
void main() {
float x = getAAtOutCoords();
float y = unaryOperation(x);
setOutput(y);
}
`}}const Qi="if (isnan(x)) return x;",GO="return x;",jx="return abs(x);",Vx=Qi+`
return (x < 0.0) ? 0.0 : x;
`,Gx=Qi+`
return (x < 0.0) ? 0.0 : min(6.0, x);
`,qx="return (x >= 0.0) ? x : (exp(x) - 1.0);",qO=`
// Stable and Attracting Fixed Point (0, 1) for Normalized Weights.
// see: https://arxiv.org/abs/1706.02515
float scaleAlpha = ${U.SELU_SCALEALPHA};
float scale = ${U.SELU_SCALE};
return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);
`;function HO(e=0){return Qi+`
return x > 0.0 ? 1.0 : float(${e});
`}const Hx="return -x;",Yx="return ceil(x);",Kx="return floor(x);",YO=`
if (isnan(x)) { return 0.0; }
return sign(x);
`,KO="return float(isnan(x));",XO="return float(isinf(x));",JO="return float(!isnan(x) && !isinf(x));",ZO=`
// 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;
}
}
`,Xx="return exp(x);",Jx="return exp(x) - 1.0;",QO=`if (x < 0.0) return NAN;
return log(x);`,e1="return log(1.0 + x);",t1="return sqrt(x);",s1="return inversesqrt(x);",n1="return 1.0 / (1.0 + exp(-1.0 * x));",i1=`
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;
`,r1=Qi+`
if (abs(x) > 1.) {
return NAN;
}
return asin(x);
`,o1=Qi+`
if (abs(x) > 1.) {
return NAN;
}
return acos(x);
`,a1=Qi+`
return atan(x);
`,l1=`
float e2x = exp(x);
return (e2x - 1.0 / e2x) / 2.0;
`,c1=`
float e2x = exp(-x);
return (e2x + 1.0 / e2x) / 2.0;
`,p1=`
float e2x = exp(-2.0 * abs(x));
return sign(x) * (1.0 - e2x) / (1.0 + e2x);
`,u1=Qi+"return log(x + sqrt(x * x + 1.0));",h1=Qi+`
if (x < 1.0) return NAN;
return log(x + sqrt(x * x - 1.0));`,d1=Qi+`
if ((x < -1.0) || (x > 1.0)) return NAN;
return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,m1=`
// Error function is calculated approximately with elementary function.
// See "Handbook of Mathematical Functions with Formulas,
// Graphs, and Mathematical Tables", Abramowitz and Stegun.
float p = ${U.ERF_P};
float a1 = ${U.ERF_A1};
float a2 = ${U.ERF_A2};
float a3 = ${U.ERF_A3};
float a4 = ${U.ERF_A4};
float a5 = ${U.ERF_A5};
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));
`,f1="return 1.0 / x;",g1="return float(!(x >= 1.0));",y1="return float(int(x));",Wu="return x;";const b1="return x;",w1=`
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;
`,Zx=`
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;
`,Qx=`
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;
`,eL=`
vec4 result;
result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);
result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);
result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);
result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);
return result;
`;class lc{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.userCode=`
vec4 unaryOperation(vec4 x) {
${t}
}
void main() {
vec4 x = getAAtOutCoords();
vec4 y = unaryOperation(x);
setOutput(y);
}
`}}class x1{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e;const t=e.length,s=_t("rc",t),n=Re(t),i=BR(t,s),r=s.slice(-2),o=t<=1?"rc":`vec2(${r.join(",")})`;this.userCode=`
void main() {
${n} rc = getOutputCoords();
vec4 packedInput = getA(${i});
setOutput(getChannel(packedInput, ${o}));
}
`}}const{segment_util:L1}=U,BV=vt.split,jV=vt.tile,VV=vt.topkImpl,GV=vt.whereImpl,qV=1e-7,HV=1e-4,mg={};function YV(e){return e in mg||(mg[e]={}),mg[e]}function fg(e,t=!1){if(e==="linear")return t?b1:GO;if(e==="relu")return t?Zx:Vx;if(e==="elu")return t?eL:qx;if(e==="relu6")return t?Qx:Gx;if(e==="prelu")return t?Cx:Nx;throw new Error(`Activation ${e} has not been implemented for the WebGL backend.`)}const KV=128,XV=600;function JV(){return W().global.screen==null?1024:W().global.screen.height*W().global.screen.width*window.devicePixelRatio*XV/1024/1024}const S1=1e3;class tL extends Eo{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,!W().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");if(e==null){const t=on(W().getNumber("WEBGL_VERSION"));this.binaryCache=YV(W().getNumber("WEBGL_VERSION")),this.gpgpu=new zx(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 jO(this.gpgpu),this.numMBBeforeWarning=JV(),this.texData=new Fc(this,Us())}numDataIds(){return this.texData.numDataIds()+(this.cpuBackend?this.cpuBackend.numDataIds():0)-this.pendingDeletes}write(e,t,s){if((W().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||W().getBool("DEBUG"))&&this.checkNumericalProblems(e),s==="complex64"&&e!=null)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");const n={};return this.texData.set(n,{shape:t,dtype:s,values:e,usage:is.UPLOAD,refCount:1}),n}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,s,n){if(W().getBool("DEBUG")&&this.checkNumericalProblems(t),n==="complex64")throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(e,{shape:s,dtype:n,values:t,usage:is.UPLOAD,refCount:1})}disposeIntermediateTensorInfo(e){const t=e.dataId;if(this.texData.has(t)){const s=this.texData.get(t);s.refCount--,s.refCount<1&&this.disposeData(t)}}readSync(e){const t=this.texData.get(e),{values:s,dtype:n,complexTensors:i,slice:r,shape:o,isPacked:a}=t;if(r!=null){let u;a?u=new lc(o,Wu):u=new $e(o,Wu);const h=this.runWebGLProgram(u,[{dataId:e,shape:o,dtype:n}],n),d=this.readSync(h.dataId);return this.disposeIntermediateTensorInfo(h),d}if(s!=null)return this.convertAndCacheOnCPU(e);if(n==="string")return s;const l=this.activeTimers!=null;let c;l&&(c=N.now());let p;if(n==="complex64"){const u=i.real.dataSync(),h=i.imag.dataSync();p=U.mergeRealAndImagArrays(u,h)}else p=this.getValuesFromTexture(e);return l&&(this.downloadWaitMs+=N.now()-c),this.convertAndCacheOnCPU(e,p)}async read(e){if(this.pendingRead.has(e)){const d=this.pendingRead.get(e);return new Promise(m=>d.push(m))}const t=this.texData.get(e),{values:s,shape:n,slice:i,dtype:r,complexTensors:o,isPacked:a}=t;if(i!=null){let d;a?d=new lc(n,Wu):d=new $e(n,Wu);const m=this.runWebGLProgram(d,[{dataId:e,shape:n,dtype:r}],r),f=this.read(m.dataId);return this.disposeIntermediateTensorInfo(m),f}if(s!=null)return this.convertAndCacheOnCPU(e);if(!W().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&W().getNumber("WEBGL_VERSION")===2)throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");let l=null,c;if(r!=="complex64"&&W().get("WEBGL_BUFFER_SUPPORTED")){c=this.decode(e);const d=this.texData.get(c.dataId);l=this.gpgpu.createBufferFromTexture(d.texture,...xo(n))}this.pendingRead.set(e,[]),r!=="complex64"&&await this.gpgpu.createAndWaitForFence();let p;if(r==="complex64"){const d=await Promise.all([o.real.data(),o.imag.data()]),m=d[0],f=d[1];p=U.mergeRealAndImagArrays(m,f)}else if(l==null)p=this.getValuesFromTexture(e);else{const d=N.sizeFromShape(n);p=this.gpgpu.downloadFloat32MatrixFromBuffer(l,d)}c!=null&&this.disposeIntermediat
if (isnan(a)) return a;
if (isnan(b)) return b;
`,T1=`
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;
`;function Io(e){return({inputs:t,backend:s})=>{const{x:n}=t,i=s,r=new $e(n.shape,e);return i.runWebGLProgram(r,[n],n.dtype)}}function cc(e,t,s,n){return({inputs:i,backend:r})=>{const{a:o,b:a}=i,l=r,c=W().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Li(t,o.shape,a.shape,!!s):new kt(e,o.shape,a.shape),p=n||o.dtype,u=l.runWebGLProgram(c,[o,a],p);return u}}const QV=v1+`
return atan(a, b);
`,eG=`
vec4 result = atan(a, b);
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
`+T1+`
return result;
`,tG=cc(QV,eG),A1={kernelName:ko,backendName:"webgl",kernelFunc:tG};function zu(e){const{inputs:t,backend:s}=e,{x:n}=t;return s.incRef(n.dataId),{dataId:n.dataId,shape:n.shape,dtype:n.dtype}}const N1={kernelName:Ci,backendName:"webgl",kernelFunc:zu};function sG(e){const{inputs:t,backend:s,attrs:n}=e,{x:i}=t;xi(i,"avgPool");const{filterSize:r,strides:o,pad:a,dimRoundingMode:l}=n,c=1;N.assert(U.eitherStridesOrDilationsAreOne(o,c),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${o} and dilations '${c}'`);const p=U.computePool2DInfo(i.shape,r,o,c,a,l);if(p.filterWidth===1&&p.filterHeight===1&&N.arraysEqual(p.inShape,p.outShape))return zu({inputs:{x:i},backend:s});const u=new Zi(p,"avg",!1);return s.runWebGLProgram(u,[i],"float32")}const C1={kernelName:Ti,backendName:"webgl",kernelFunc:sG};function nG(e){const{inputs:t,backend:s,attrs:n}=e,{dy:i,input:r}=t,o=r;xi([i,r],"avgPoolBackprop");const{filterSize:a,strides:l,pad:c}=n,p=U.computePool2DInfo(o.shape,a,l,1,c),u=new YR(p);return s.runWebGLProgram(u,[i],o.dtype)}const R1={kernelName:Do,backendName:"webgl",kernelFunc:nG};class O1{constructor(e,t,s,n,i,r){this.outputShape=[],this.variableNames=["x","mean","variance"],U.assertAndGetBroadcastShape(e,t),U.assertAndGetBroadcastShape(e,s);let o="0.0";n!=null&&(U.assertAndGetBroadcastShape(e,n),this.variableNames.push("offset"),o="getOffsetAtOutCoords()");let a="1.0";i!=null&&(U.assertAndGetBroadcastShape(e,i),this.variableNames.push("scale"),a="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`
void main() {
float x = getXAtOutCoords();
float mean = getMeanAtOutCoords();
float variance = getVarianceAtOutCoords();
float offset = ${o};
float scale = ${a};
float inv = scale * inversesqrt(variance + float(${r}));
setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));
}
`}}class E1{constructor(e,t,s,n,i,r){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],U.assertAndGetBroadcastShape(e,t),U.assertAndGetBroadcastShape(e,s);let o="vec4(0.0)";n!=null&&(U.assertAndGetBroadcastShape(e,n),this.variableNames.push("offset"),o="getOffsetAtOutCoords()");let a="vec4(1.0)";i!=null&&(U.assertAndGetBroadcastShape(e,i),this.variableNames.push("scale"),a="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`
void main() {
vec4 offset = ${o};
vec4 scale = ${a};
vec4 x = getXAtOutCoords();
vec4 mean = getMeanAtOutCoords();
vec4 variance = getVarianceAtOutCoords();
vec4 inv = scale * inversesqrt(variance + vec4(${r}));
setOutput((x - mean) * inv + offset);
}
`}}const iG=({inputs:e,backend:t,attrs:s})=>{const{x:n,mean:i,variance:r,offset:o,scale:a}=e;N.assert(i.shape.length===r.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),N.assert(o==null||i.shape.length===o.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),N.assert(a==null||i.shape.length===a.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let{varianceEpsilon:l}=s;l==null&&(l=.001);const c=[n,i,r];let p=null;o!=null&&(p=o.shape,c.push(o));let u=null;a!=null&&(u=a.shape,c.push(a));const h=W().getBool("WEBGL_PACK_NORMALIZATION")?new E1(n.shape,i.shape,r.shape,p,u,l):new O1(n.shape,i.shape,r.shape,p,u,l),d=t.runWebGLProgram(h,c,c[0].dtype);return d},_1={kernelName:Ni,backendName:"webgl",kernelFunc:iG};const rG=gg+`
return cos(x);
`,oG=Io(rG),k1={kernelName:Qn,backendName:"webgl",kernelFunc:oG};const aG=`
if (a == b) {
return 1.0;
};
return a / b;`,lG=`
// 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;
`,cG=cc(aG,lG,!0),D1={kernelName:ei,backendName:"webgl",kernelFunc:cG};class F1{constructor(e){this.variableNames=["Image"],this.outputShape=[];const t=e[2];this.outputShape=e,this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int x = coords[2];
int coordX = ${t} - x;
float outputValue;
if(coordX >= 0 && coordX < ${t}) {
outputValue = getImage(coords[0], coords[1], coordX, coords[3]);
} else {
outputValue = getImage(coords[0], coords[1], coords[2], coords[3]);
}
setOutput(outputValue);
}
`}}const M1={kernelName:Uo,backendName:"webgl",kernelFunc:({inputs:e,backend:t})=>{const{image:s}=e,n=t,i=new F1(s.shape),r=n.runWebGLProgram(i,[s],s.dtype);return r}};class U1{constructor(e){this.variableNames=["A"];const t=ct(),[s,n]=e;this.outputShape=e,this.userCode=`
void main() {
ivec3 coords = getOutputCoords();
int texR = coords[0];
int texC = coords[1];
int depth = coords[2];
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${n}.0, ${s}.0);
vec4 values = ${t.texture2D}(A, uv);
float value;
if (depth == 0) {
value = values.r;
} else if (depth == 1) {
value = values.g;
} else if (depth == 2) {
value = values.b;
} else if (depth == 3) {
value = values.a;
}
setOutput(floor(value * 255.0 + 0.5));
}
`}}class $1{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;const t=ct(),[s,n]=e;this.outputShape=e,this.userCode=`
void main() {
ivec3 coords = getOutputCoords();
int texR = coords[0];
int texC = coords[1];
int depth = coords[2];
vec4 result = vec4(0.);
for(int row=0; row<=1; row++) {
for(int col=0; col<=1; col++) {
texC = coords[1] + row;
depth = coords[2] + col;
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${n}.0, ${s}.0);
vec4 values = ${t.texture2D}(A, uv);
float value;
if (depth == 0) {
value = values.r;
} else if (depth == 1) {
value = values.g;
} else if (depth == 2) {
value = values.b;
} else if (depth == 3) {
value = values.a;
}
result[row * 2 + col] = floor(value * 255.0 + 0.5);
}
}
${t.output} = result;
}
`}}const W1={kernelName:Xa,backendName:"webgl",kernelFunc:pG};let pc;function pG(e){const{inputs:t,backend:s,attrs:n}=e;let{pixels:i}=t;const{numChannels:r}=n,o=typeof HTMLVideoElement!="undefined"&&i instanceof HTMLVideoElement,a=typeof HTMLImageElement!="undefined"&&i instanceof HTMLImageElement,[l,c]=o?[i.videoWidth,i.videoHeight]:[i.width,i.height],p=[c,l],u=[c,l,r];(a||o)&&(pc==null&&(pc=document.createElement("canvas").getContext("2d")),pc.canvas.width=l,pc.canvas.height=c,pc.drawImage(i,0,0,l,c),i=pc.canvas);const h=s.makeTensorInfo(p,"int32");s.texData.get(h.dataId).usage=is.PIXELS,s.gpgpu.uploadPixelDataToTexture(s.getTexture(h.dataId),i);const d=W().getBool("WEBGL_PACK")?new $1(u):new U1(u),m=s.runWebGLProgram(d,[h],"int32");return s.disposeData(h.dataId),m}function uG(e){const t=[];for(;t.length===0||t[t.length-1].outSize!==1;){const s=t.length?t[t.length-1].outSize:e[1],n=U.computeOptimalWindowSize(s);t.push({inSize:s,windowSize:n,outSize:Math.ceil(s/n)})}return t}function z1(e,t,s,n){const i=uG(e.shape);let r=e;for(let o=0;o<i.length;o++){const{inSize:a,windowSize:l,outSize:c}=i[o],p=new hg({windowSize:l,inSize:a,batchSize:e.shape[0],outSize:c},s),u=r;r=n.runWebGLProgram(p,[r],t),u.dataId!==e.dataId&&n.disposeData(u.dataId)}return r}function P1(e,t,s){const n=[Lo(e.shape),...So(e.shape)],i={dtype:e.dtype,shape:n,dataId:e.dataId},r=[Lo(t),...So(t)],o=new dg(r,n),a=!0,l=s.runWebGLProgram(o,[i],e.dtype,null,a);return{dataId:l.dataId,shape:t,dtype:l.dtype}}function yg(e){const{inputs:t,backend:s,attrs:n}=e,{x:i}=t,{shape:r}=n,o=s,a=N.sizeFromShape(i.shape),l=N.inferFromImplicitShape(r,a),c=N.sizeFromShape(l);N.assert(a===c,()=>`The new shape (${l}) has ${c} elements and the old shape (${i.shape}) has ${a} elements. The new shape and old shape must have the same number of elements.`);const p=o.texData.get(i.dataId);return p.isPacked&&!sc(i.shape,l)&&!(p.texture!==null&&sc(p.shape,l))?P1(i,l,o):(o.incRef(i.dataId),{dataId:i.dataId,shape:l,dtype:i.dtype})}const B1={kernelName:Ei,backendName:"webgl",kernelFunc:yg};function j1(e,t,s,n){const i=N.sizeFromShape(t),r=N.sizeFromShape(e.shape),o=r/i,a=yg({inputs:{x:e},attrs:{shape:[o,i]},backend:n}),l=z1(a,e.dtype,"max",n),c=yg({inputs:{x:l},attrs:{shape:s},backend:n});return n.disposeIntermediateTensorInfo(a),n.disposeIntermediateTensorInfo(l),c}class V1{constructor(e,t){this.variableNames=["A"];const s=new Array(e.length);for(let r=0;r<s.length;r++)s[r]=e[t[r]];this.outputShape=s,this.rank=s.length;const n=Re(this.rank),i=hG(t);this.userCode=`
void main() {
${n} resRC = getOutputCoords();
setOutput(getA(${i}));
}
`}}function hG(e){const t=e.length;if(t>6)throw Error(`Transpose for rank ${t} is not yet supported`);const s=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],n=new Array(t);for(let i=0;i<e.length;i++)n[e[i]]=s[i];return n.join()}class G1{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0;const s=new Array(e.length);for(let c=0;c<s.length;c++)s[c]=e[t[c]];if(this.outputShape=s,this.rank=s.length,this.rank>6)throw Error(`Packed transpose for rank ${this.rank} is not yet supported.`);const n=Re(this.rank),i=Ix("rc",this.rank),r=new Array(this.rank);for(let c=0;c<t.length;c++)r[t[c]]=i[c];const o=`vec2(${r.slice(-2).join()})`,a=`++${i[this.rank-1]} < ${s[this.rank-1]}`,l=`getChannel(getA(${r.join()}), ${o})`;this.userCode=`
void main() {
${n} rc = getOutputCoords();
vec4 result = vec4(0.);
result[0] = ${l};
if(${a}) {
result[1] = ${l};
}
--${i[this.rank-1]};
if(++${i[this.rank-2]} < ${s[this.rank-2]}) {
result[2] = ${l};
if(${a}) {
result[3] = ${l};
}
}
setOutput(result);
}
`}}function bg(e,t,s){const n=W().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new G1(e.shape,t):new V1(e.shape,t);return s.runWebGLProgram(n,[e],e.dtype)}const q1={kernelName:Ri,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:s})=>{const{x:n}=e,{reductionIndices:i,keepDims:r}=t,o=s,a=n.shape.length,l=N.parseAxisParam(i,n.shape);let c=l;const p=U.getAxesPermutation(c,a),u=p!=null,h=o.shouldExecuteOnCPU([n]);let d=n;if(u){if(h){const w=o.texData.get(d.dataId),x=w.values,T=new Array(a);for(let E=0;E<T.length;E++)T[E]=n.shape[p[E]];const A=ig(x,n.shape,n.dtype,p,T);d=o.makeTensorInfo(T,n.dtype);const _=o.texData.get(d.dataId);_.values=A}else d=bg(n,p,o);c=U.getInnerMostAxes(c.length,a)}U.assertAxesAreInnerMostDims("max",c,a);const[m,f]=U.computeOutAndReduceShapes(d.shape,c);let g=m;r&&(g=U.expandShapeToKeepDim(m,l));let y;if(h){const w=o.texData.get(d.dataId),x=w.values,T=kR(x,N.sizeFromShape(f),g,n.dtype);y=o.makeTensorInfo(g,n.dtype);const A=o.texData.get(y.dataId);A.values=T}else y=j1(d,f,g,o);return u&&o.disposeIntermediateTensorInfo(d),y}};function dG(e){const{inputs:t,backend:s,attrs:n}=e,{x:i}=t;xi(i,"maxPool");const{filterSize:r,strides:o,pad:a,dimRoundingMode:l}=n,c=1;N.assert(U.eitherStridesOrDilationsAreOne(o,c),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${o} and dilations '${c}'`);const p=U.computePool2DInfo(i.shape,r,o,c,a,l);if(p.filterWidth===1&&p.filterHeight===1&&N.arraysEqual(p.inShape,p.outShape))return zu({inputs:{x:i},backend:s});const u=new Zi(p,"max",!1);return s.runWebGLProgram(u,[i],i.dtype)}const H1={kernelName:Oi,backendName:"webgl",kernelFunc:dG};function mG(e){const{inputs:t,backend:s,attrs:n}=e,{dy:i,input:r,output:o}=t,a=r;xi([r,o],"maxPoolBackprop");const{filterSize:l,strides:c,pad:p,dimRoundingMode:u}=n,h=U.computePool2DInfo(a.shape,l,c,1,p,u),d=!0,m=new Zi(h,"max",d),f=s.runWebGLProgram(m,[a],a.dtype),g=new LO(h),y=s.runWebGLProgram(g,[i,f],a.dtype);return s.disposeIntermediateTensorInfo(f),y}const Y1={kernelName:$o,backendName:"webgl",kernelFunc:mG};function K1(e,t,s,n){let i=new Zi(s,"max",!1);const r=n.runWebGLProgram(i,[e],"float32");i=new Zi(s,"max",!0,!0,t);const o=n.runWebGLProgram(i,[e],"float32");return[r,o]}const X1={kernelName:Wo,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:s})=>{const{x:n}=e,{filterSize:i,strides:r,pad:o,includeBatchInIndex:a}=t,l=s;N.assert(n.shape.length===4,()=>`Error in maxPool: input must be rank 4 but got rank ${n.shape.length}.`);const c=[1,1];N.assert(U.eitherStridesOrDilationsAreOne(r,c),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${r} and dilations '${c}'`);const p=U.computePool2DInfo(n.shape,i,r,c,o),[u,h]=K1(n,a,p,l);return[u,h]}};const J1={kernelName:cp,backendName:"webgl",kernelFunc:({inputs:e,backend:t,attrs:s})=>{U.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{boxes:n,scores:i}=e,{maxOutputSize:r,iouThreshold:o,scoreThreshold:a}=s,l=t,c=l.readSync(n.dataId),p=l.readSync(i.dataId),u=r,h=o,d=a;return vt.nonMaxSuppressionV3Impl(c,p,u,h,d)}};const fG=vt.nonMaxSuppressionV4Impl,Z1={kernelName:zo,backendName:"webgl",kernelFunc:({inputs:e,backend:t,attrs:s})=>{U.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{boxes:n,scores:i}=e,{maxOutputSize:r,iouThreshold:o,scoreThreshold:a,padToMaxOutputSize:l}=s,c=t,p=c.readSync(n.dataId),u=c.readSync(i.dataId),{selectedIndices:h,validOutputs:d}=fG(p,u,r,o,a,l);return[h,d]}};const gG=vt.nonMaxSuppressionV5Impl,Q1={kernelName:Po,backendName:"webgl",kernelFunc:({inputs:e,backend:t,attrs:s})=>{U.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{boxes:n,scores:i}=e,{maxOutputSize:r,iouThreshold:o,scoreThreshold:a,softNmsSigma:l}=s,c=t,p=c.readSync(n.dataId),u=c.readSync(i.dataId),h=r,d=o,m=a,f=l,{selectedIndices:g,selectedScores:y}=gG(p,u,h,d,m,f);return[g,y]}};class eE{constructor(e,t,s,n){this.variableNames=["Image"],this.outputShape=[];const i=e[1],r=e[2],o=
vec3 fill = vec3(${s.join(",")});
float outputValue = fill[coords[3]];`,this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int x = coords[2];
int y = coords[1];
float coordXFloat = (float(x) - ${p}) * ${a} - (float(y) - ${u}) * ${o};
float coordYFloat = (float(x) - ${p}) * ${o} + (float(y) - ${u}) * ${a};
int coordX = int(round(coordXFloat + ${p}));
int coordY = int(round(coordYFloat + ${u}));
${h}
if(coordX >= 0 && coordX < ${r} && coordY >= 0 && coordY < ${i}) {
outputValue = getImage(coords[0], coordY, coordX, coords[3]);
}
setOutput(outputValue);
}
`}}const tE={kernelName:Ho,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:s})=>{const{image:n}=e,{radians:i,fillValue:r,center:o}=t,a=s,l=new eE(n.shape,i,r,o),c=a.runWebGLProgram(l,[n],n.dtype);return c}};const yG=gg+`
return sin(x);
`,bG=Io(yG),sE={kernelName:ti,backendName:"webgl",kernelFunc:bG};const wG="return x * x;",xG=Io(wG),nE={kernelName:Go,backendName:"webgl",kernelFunc:xG};const iE="return (a - b) * (a - b);",LG=cc(iE,iE),rE={kernelName:si,backendName:"webgl",kernelFunc:LG};const SG="return tan(x);",IG=Io(SG),oE={kernelName:ni,backendName:"webgl",kernelFunc:IG};const aE={kernelName:_i,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:s})=>{const{x:n}=e,{perm:i}=t,r=s,o=n.shape.length,a=new Array(o);for(let c=0;c<a.length;c++)a[c]=n.shape[i[c]];let l;if(r.shouldExecuteOnCPU([n])){const c=r.texData.get(n.dataId),p=c.values,u=ig(p,n.shape,n.dtype,i,a);l=r.makeTensorInfo(a,n.dtype);const h=r.texData.get(l.dataId);h.values=u}else l=bg(n,i,r);return l}};function vG(e){const{inputs:t,attrs:s,backend:n}=e,{axis:i}=s,{x:r}=t;xi(r,"unique"),console.warn("WARNING: ","UI might be locked temporarily as data is being downloaded");const o=n.readSync(r.dataId),{outputValues:a,outputShape:l,indices:c}=$R(o,i,r.shape,r.dtype);return[n.makeTensorInfo(l,r.dtype,a),n.makeTensorInfo([c.length],"int32",c)]}const lE={kernelName:qo,backendName:"webgl",kernelFunc:vG};const TG=[A1,C1,R1,_1,k1,D1,M1,W1,N1,q1,H1,Y1,X1,J1,Z1,Q1,B1,tE,sE,nE,rE,oE,aE,lE];for(const e of TG)Za(e);const cE="2.6.0";const Ju={};Ee(Ju,{Abs:()=>_o,Acos:()=>dr,Acosh:()=>mr,AdadeltaOptimizer:()=>ca,AdagradOptimizer:()=>pa,AdamOptimizer:()=>ua,AdamaxOptimizer:()=>ha,Add:()=>Zn,AddN:()=>Mc,All:()=>ty,Any:()=>sy,ArgMax:()=>Uc,ArgMin:()=>$c,Asin:()=>fr,Asinh:()=>gr,Atan:()=>yr,Atan2:()=>ko,Atanh:()=>br,AvgPool:()=>Ti,AvgPool3D:()=>Wc,AvgPool3DBackprop:()=>ny,AvgPoolBackprop:()=>Do,BatchMatMul:()=>zc,BatchToSpaceND:()=>Pc,BroadcastTo:()=>Bc,Callback:()=>fw,CallbackList:()=>Hb,Cast:()=>Ai,Ceil:()=>wr,ClipByValue:()=>xr,Complex:()=>jc,Concat:()=>Fo,Conv2D:()=>Vc,Conv2DBackpropFilter:()=>iy,Conv2DBackpropInput:()=>Gc,Conv3D:()=>qc,Conv3DBackpropFilterV2:()=>ry,Conv3DBackpropInputV2:()=>oy,Cos:()=>Qn,Cosh:()=>Lr,CropAndResize:()=>ay,Cumsum:()=>Hc,CustomCallback:()=>Kb,DataStorage:()=>Fc,DepthToSpace:()=>ly,DepthwiseConv2dNative:()=>Yc,DepthwiseConv2dNativeBackpropFilter:()=>cy,DepthwiseConv2dNativeBackpropInput:()=>py,Diag:()=>uy,Dilation2D:()=>Mo,Dilation2DBackpropFilter:()=>Ha,Dilation2DBackpropInput:()=>qa,Div:()=>ei,ENV:()=>Jg,EarlyStopping:()=>gw,Elu:()=>Sr,EluGrad:()=>hy,Environment:()=>Xg,Equal:()=>dy,Erf:()=>Ir,Exp:()=>vr,Expm1:()=>Tr,FFT:()=>Kc,Fill:()=>my,FlipLeftRight:()=>Uo,Floor:()=>Ar,FloorDiv:()=>Xc,FromPixels:()=>Xa,FusedBatchNorm:()=>Ni,FusedConv2D:()=>Ah,FusedDepthwiseConv2D:()=>Nh,GatherNd:()=>fy,GatherV2:()=>Jc,GraphModel:()=>Pw,Greater:()=>gy,GreaterEqual:()=>Zc,History:()=>Yb,IFFT:()=>Qc,Identity:()=>Ci,Imag:()=>ep,InputSpec:()=>st,IsFinite:()=>Nr,IsInf:()=>Cr,IsNan:()=>Rr,KernelBackend:()=>Eo,LRN:()=>sp,LRNBackprop:()=>Sy,LayerVariable:()=>nm,LayersModel:()=>nn,Less:()=>yy,LessEqual:()=>by,LinSpace:()=>wy,Log:()=>Or,Log1p:()=>Er,LogSoftmax:()=>tp,LogicalAnd:()=>xy,LogicalNot:()=>Ya,LogicalOr:()=>Ly,Max:()=>Ri,MaxPool:()=>Oi,MaxPool3D:()=>ip,MaxPool3DBackprop:()=>Iy,MaxPoolBackprop:()=>$o,MaxPoolWithArgmax:()=>Wo,Maximum:()=>np,Mean:()=>y_,Min:()=>rp,Minimum:()=>op,Mod:()=>ap,MomentumOptimizer:()=>da,Multiply:()=>_r,Negate:()=>lp,NonMaxSuppressionV3:()=>cp,NonMaxSuppressionV4:()=>zo,NonMaxSuppressionV5:()=>Po,NotEqual:()=>Ka,OP_SCOPE_SUFFIX:()=>Xy,OneHot:()=>up,OnesLike:()=>pp,Optimizer:()=>gs,PadV2:()=>Bo,Pool:()=>b_,Pow:()=>hp,Prelu:()=>dp,Prod:()=>vy,RMSPropOptimizer:()=>ma,RNN:()=>rn,Range:()=>Ty,Rank:()=>By,Real:()=>mp,Reciprocal:()=>kr,Reduction:()=>gt,Relu:()=>fp,Relu6:()=>bp,Reshape:()=>Ei,ResizeBilinear:()=>yp,ResizeBilinearGrad:()=>Ny,ResizeNearestNeighbor:()=>gp,ResizeNearestNeighborGrad:()=>Ay,Reverse:()=>wp,RotateWithOffset:()=>Ho,Round:()=>Dr,Rsqrt:()=>Fr,SGDOptimizer:()=>zi,ScatterNd:()=>Cy,SelectV2:()=>xp,Selu:()=>Mr,Sequential:()=>mo,Sigmoid:()=>Wr,Sign:()=>$r,Sin:()=>ti,Sinh:()=>Ur,Slice:()=>jo,Softmax:()=>Ip,Softplus:()=>zr,SpaceToBatchND:()=>Vo,SparseToDense:()=>Ry,SplitV:()=>Sp,Sqrt:()=>Pr,Square:()=>Go,SquaredDifference:()=>si,Step:()=>Vr,StridedSlice:(
/**
* @license
* Copyright 2017 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* =============================================================================
*/
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @license
* Copyright 2019 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* =============================================================================
*/
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @license
* Copyright 2020 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/** @license See the LICENSE file. */
//# sourceMappingURL=face-api.js.map