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

4122 lines
1.1 MiB

var rf=Object.defineProperty,n9=Object.prototype.hasOwnProperty,XS=(r,l)=>()=>(l||(l={exports:{}},r(l.exports,l)),l.exports),T2=r=>rf(r,"__esModule",{value:!0}),$c=(r,l)=>{T2(r);for(var u in l)rf(r,u,{get:l[u],enumerable:!0})},s9=(r,l)=>{if(T2(r),typeof l=="object"||typeof l=="function")for(let u in l)!n9.call(r,u)&&u!=="default"&&rf(r,u,{get:()=>l[u],enumerable:!0});return r},He=r=>r&&r.__esModule?r:s9(rf({},"default",{value:r,enumerable:!0}),r);var F2=XS(i9=>{$c(i9,{FetchError:()=>Gn,Headers:()=>fi,Request:()=>ra,Response:()=>Mi,default:()=>g9});const qs=He(require("stream")),JS=He(require("http")),of=He(require("url")),A2=He(require("https")),uo=He(require("zlib")),r9=qs.default.Readable,Lr=Symbol("buffer"),ZS=Symbol("type");class Ou{constructor(){this[ZS]="";const r=arguments[0],l=arguments[1],u=[];let d=0;if(r){const g=r,I=Number(g.length);for(let S=0;S<I;S++){const x=g[S];let N;x instanceof Buffer?N=x:ArrayBuffer.isView(x)?N=Buffer.from(x.buffer,x.byteOffset,x.byteLength):x instanceof ArrayBuffer?N=Buffer.from(x):x instanceof Ou?N=x[Lr]:N=Buffer.from(typeof x=="string"?x:String(x)),d+=N.length,u.push(N)}}this[Lr]=Buffer.concat(u);let f=l&&l.type!==void 0&&String(l.type).toLowerCase();f&&!/[^\u0020-\u007E]/.test(f)&&(this[ZS]=f)}get size(){return this[Lr].length}get type(){return this[ZS]}text(){return Promise.resolve(this[Lr].toString())}arrayBuffer(){const r=this[Lr],l=r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength);return Promise.resolve(l)}stream(){const r=new r9;return r._read=function(){},r.push(this[Lr]),r.push(null),r}toString(){return"[object Blob]"}slice(){const r=this.size,l=arguments[0],u=arguments[1];let d,f;l===void 0?d=0:l<0?d=Math.max(r+l,0):d=Math.min(l,r),u===void 0?f=r:u<0?f=Math.max(r+u,0):f=Math.min(u,r);const g=Math.max(f-d,0),I=this[Lr],S=I.slice(d,d+g),x=new Ou([],{type:arguments[2]});return x[Lr]=S,x}}Object.defineProperties(Ou.prototype,{size:{enumerable:!0},type:{enumerable:!0},slice:{enumerable:!0}});Object.defineProperty(Ou.prototype,Symbol.toStringTag,{value:"Blob",writable:!1,enumerable:!1,configurable:!0});function Gn(r,l,u){Error.call(this,r),this.message=r,this.type=l,u&&(this.code=this.errno=u.code),Error.captureStackTrace(this,this.constructor)}Gn.prototype=Object.create(Error.prototype);Gn.prototype.constructor=Gn;Gn.prototype.name="FetchError";let QS;try{QS=require("encoding").convert}catch(r){}const Sr=Symbol("Body internals"),v2=qs.default.PassThrough;function Dn(r){var l=this,u=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},d=u.size;let f=d===void 0?0:d;var g=u.timeout;let I=g===void 0?0:g;r==null?r=null:N2(r)?r=Buffer.from(r.toString()):Eu(r)||(Buffer.isBuffer(r)||(Object.prototype.toString.call(r)==="[object ArrayBuffer]"?r=Buffer.from(r):ArrayBuffer.isView(r)?r=Buffer.from(r.buffer,r.byteOffset,r.byteLength):r instanceof qs.default||(r=Buffer.from(String(r))))),this[Sr]={body:r,disturbed:!1,error:null},this.size=f,this.timeout=I,r instanceof qs.default&&r.on("error",function(S){const x=S.name==="AbortError"?S:new Gn(`Invalid response body while trying to fetch ${l.url}: ${S.message}`,"system",S);l[Sr].error=x})}Dn.prototype={get body(){return this[Sr].body},get bodyUsed(){return this[Sr].disturbed},arrayBuffer(){return Uc.call(this).then(function(r){return r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength)})},blob(){let r=this.headers&&this.headers.get("content-type")||"";return Uc.call(this).then(function(l){return Object.assign(new Ou([],{type:r.toLowerCase()}),{[Lr]:l})})},json(){var r=this;return Uc.call(this).then(function(l){try{return JSON.parse(l.toString())}catch(u){return Dn.Promise.reject(new Gn(`invalid json response body at ${r.url} reason: ${u.message}`,"invalid-json"))}})},text(){return Uc.call(this).then(function(r){return r.toString()})},buffer(){return Uc.call(this)},textConverted(){var r=this;return Uc.call(this).then(function(l){return o9(l,r.headers)})}};Object.defineProperties(Dn.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0}});Dn.mixIn=function(r){for(const l of Object.getOwnPropertyNames(Dn.prototype))if(!(l in r)){const u=Object.getOwnPropertyDescriptor(Dn.prototype,l);Object.defineProperty(r,l,u)}};function Uc(){var r=this;if(this[Sr].disturbed)return Dn.Promise.reject(new TypeError(`body used already for: ${this.url}`));if(this[Sr].disturbed=!0,this[Sr].error)return Dn.Promise.reject(this[Sr].error);let l=this.body;if(l===null)return Dn.Promise.resolve(Buffer.alloc(0));if(Eu(l)&&(l=l.stream()),Buffer.isBuffer(l))return Dn.Promise.resolve(l);if(!(l instanceof qs.default))return Dn.Promise.resolve(Buffer.alloc(0));let u=[],d=0,f=!1;return new Dn.Promise(function(g,I){let S;r.timeout&&(S=setTimeout(function(){f=!0,I(new Gn(`Response timeout while trying to fetch ${r.url} (over ${r.timeout}ms)`,"body-timeout"))},r.timeout)),l.on("error",function(x){x.name==="AbortError"?(f=!0,I(x)):I(new Gn(`Invalid response body while trying to fetch ${r.url}: ${x.message}`,"system",x))}),l.on("data",function(x){if(f||x===null)return;if(r.size&&d+x.length>r.size){f=!0,I(new Gn(`content size at ${r.url} over limit: ${r.size}`,"max-size"));return}d+=x.length,u.push(x)}),l.on("end",function(){if(f)return;clearTimeout(S);try{g(Buffer.concat(u,d))}catch(x){I(new Gn(`Could not create Buffer from response body for ${r.url}: ${x.message}`,"system",x))}})})}function o9(r,l){if(typeof QS!="function")throw new Error("The package `encoding` must be installed to use the textConverted() function");const u=l.get("content-type");let d="utf-8",f,g;return u&&(f=/charset=([^;]*)/i.exec(u)),g=r.slice(0,1024).toString(),!f&&g&&(f=/<meta.+?charset=(['"])(.+?)\1/i.exec(g)),!f&&g&&(f=/<meta[\s]+?http-equiv=(['"])content-type\1[\s]+?content=(['"])(.+?)\2/i.exec(g),f||(f=/<meta[\s]+?content=(['"])(.+?)\1[\s]+?http-equiv=(['"])content-type\3/i.exec(g),f&&f.pop()),f&&(f=/charset=(.*)/i.exec(f.pop()))),!f&&g&&(f=/<\?xml.+?encoding=(['"])(.+?)\1/i.exec(g)),f&&(d=f.pop(),(d==="gb2312"||d==="gbk")&&(d="gb18030")),QS(r,"UTF-8",d).toString()}function N2(r){return typeof r!="object"||typeof r.append!="function"||typeof r.delete!="function"||typeof r.get!="function"||typeof r.getAll!="function"||typeof r.has!="function"||typeof r.set!="function"?!1:r.constructor.name==="URLSearchParams"||Object.prototype.toString.call(r)==="[object URLSearchParams]"||typeof r.sort=="function"}function Eu(r){return typeof r=="object"&&typeof r.arrayBuffer=="function"&&typeof r.type=="string"&&typeof r.stream=="function"&&typeof r.constructor=="function"&&typeof r.constructor.name=="string"&&/^(Blob|File)$/.test(r.constructor.name)&&/^(Blob|File)$/.test(r[Symbol.toStringTag])}function C2(r){let l,u,d=r.body;if(r.bodyUsed)throw new Error("cannot clone body after it is used");return d instanceof qs.default&&typeof d.getBoundary!="function"&&(l=new v2,u=new v2,d.pipe(l),d.pipe(u),r[Sr].body=l,d=u),d}function R2(r){return r===null?null:typeof r=="string"?"text/plain;charset=UTF-8":N2(r)?"application/x-www-form-urlencoded;charset=UTF-8":Eu(r)?r.type||null:Buffer.isBuffer(r)||(Object.prototype.toString.call(r)==="[object ArrayBuffer]"||ArrayBuffer.isView(r))?null:typeof r.getBoundary=="function"?`multipart/form-data;boundary=${r.getBoundary()}`:r instanceof qs.default?null:"text/plain;charset=UTF-8"}function O2(r){const l=r.body;return l===null?0:Eu(l)?l.size:Buffer.isBuffer(l)?l.length:l&&typeof l.getLengthSync=="function"&&(l._lengthRetrievers&&l._lengthRetrievers.length==0||l.hasKnownLength&&l.hasKnownLength())?l.getLengthSync():null}function a9(r,l){const u=l.body;u===null?r.end():Eu(u)?u.stream().pipe(r):Buffer.isBuffer(u)?(r.write(u),r.end()):u.pipe(r)}Dn.Promise=global.Promise;const E2=/[^\^_`a-zA-Z\-0-9!#$%&'*+.|~]/,eI=/[^\t\x20-\x7e\x80-\xff]/;function Du(r){if(r=`${r}`,E2.test(r)||r==="")throw new TypeError(`${r} is not a legal HTTP header name`)}function D2(r){if(r=`${r}`,eI.test(r))throw new TypeError(`${r} is not a legal HTTP header value`)}function Bc(r,l){l=l.toLowerCase();for(const u in r)if(u.toLowerCase()===l)return u;return}const ln=Symbol("map");class fi{constructor(){let r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:void 0;if(this[ln]=Object.create(null),r instanceof fi){const l=r.raw(),u=Object.keys(l);for(const d of u)for(const f of l[d])this.append(d,f);return}if(!(r==null))if(typeof r=="object"){const l=r[Symbol.iterator];if(l!=null){if(typeof l!="function")throw new TypeError("Header pairs must be iterable");const u=[];for(const d of r){if(typeof d!="object"||typeof d[Symbol.iterator]!="function")throw new TypeError("Each header pair must be iterable");u.push(Array.from(d))}for(const d of u){if(d.length!==2)throw new TypeError("Each header pair must be a name/value tuple");this.append(d[0],d[1])}}else for(const u of Object.keys(r)){const d=r[u];this.append(u,d)}}else throw new TypeError("Provided initializer must be an object")}get(r){r=`${r}`,Du(r);const l=Bc(this[ln],r);return l===void 0?null:this[ln][l].join(", ")}forEach(r){let l=arguments.length>1&&arguments[1]!==void 0?arguments[1]:void 0,u=tI(this),d=0;for(;d<u.length;){var f=u[d];const g=f[0],I=f[1];r.call(l,I,g,this),u=tI(this),d++}}set(r,l){r=`${r}`,l=`${l}`,Du(r),D2(l);const u=Bc(this[ln],r);this[ln][u!==void 0?u:r]=[l]}append(r,l){r=`${r}`,l=`${l}`,Du(r),D2(l);const u=Bc(this[ln],r);u!==void 0?this[ln][u].push(l):this[ln][r]=[l]}has(r){return r=`${r}`,Du(r),Bc(this[ln],r)!==void 0}delete(r){r=`${r}`,Du(r);const l=Bc(this[ln],r);l!==void 0&&delete this[ln][l]}raw(){return this[ln]}keys(){return nI(this,"key")}values(){return nI(this,"value")}[Symbol.iterator](){return nI(this,"key+value")}}fi.prototype.entries=fi.prototype[Symbol.iterator];Object.defineProperty(fi.prototype,Symbol.toStringTag,{value:"Headers",writable:!1,enumerable:!1,configurable:!0});Object.defineProperties(fi.prototype,{get:{enumerable:!0},forEach:{enumerable:!0},set:{enumerable:!0},append:{enumerable:!0},has:{enumerable:!0},delete:{enumerable:!0},keys:{enumerable:!0},values:{enumerable:!0},entries:{enumerable:!0}});function tI(r){let l=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"key+value";const u=Object.keys(r[ln]).sort();return u.map(l==="key"?function(d){return d.toLowerCase()}:l==="value"?function(d){return r[ln][d].join(", ")}:function(d){return[d.toLowerCase(),r[ln][d].join(", ")]})}const sI=Symbol("internal");function nI(r,l){const u=Object.create(iI);return u[sI]={target:r,kind:l,index:0},u}const iI=Object.setPrototypeOf({next(){if(!this||Object.getPrototypeOf(this)!==iI)throw new TypeError("Value of `this` is not a HeadersIterator");var r=this[sI];const l=r.target,u=r.kind,d=r.index,f=tI(l,u),g=f.length;return d>=g?{value:void 0,done:!0}:(this[sI].index=d+1,{value:f[d],done:!1})}},Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())));Object.defineProperty(iI,Symbol.toStringTag,{value:"HeadersIterator",writable:!1,enumerable:!1,configurable:!0});function c9(r){const l=Object.assign({__proto__:null},r[ln]),u=Bc(r[ln],"Host");return u!==void 0&&(l[u]=l[u][0]),l}function l9(r){const l=new fi;for(const u of Object.keys(r)){if(E2.test(u))continue;if(Array.isArray(r[u]))for(const d of r[u]){if(eI.test(d))continue;l[ln][u]===void 0?l[ln][u]=[d]:l[ln][u].push(d)}else eI.test(r[u])||(l[ln][u]=[r[u]])}return l}const po=Symbol("Response internals"),h9=JS.default.STATUS_CODES;class Mi{constructor(){let r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:null,l=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};Dn.call(this,r,l);const u=l.status||200,d=new fi(l.headers);if(r!=null&&!d.has("Content-Type")){const f=R2(r);f&&d.append("Content-Type",f)}this[po]={url:l.url,status:u,statusText:l.statusText||h9[u],headers:d,counter:l.counter}}get url(){return this[po].url||""}get status(){return this[po].status}get ok(){return this[po].status>=200&&this[po].status<300}get redirected(){return this[po].counter>0}get statusText(){return this[po].statusText}get headers(){return this[po].headers}clone(){return new Mi(C2(this),{url:this.url,status:this.status,statusText:this.statusText,headers:this.headers,ok:this.ok,redirected:this.redirected})}}Dn.mixIn(Mi.prototype);Object.defineProperties(Mi.prototype,{url:{enumerable:!0},status:{enumerable:!0},ok:{enumerable:!0},redirected:{enumerable:!0},statusText:{enumerable:!0},headers:{enumerable:!0},clone:{enumerable:!0}});Object.defineProperty(Mi.prototype,Symbol.toStringTag,{value:"Response",writable:!1,enumerable:!1,configurable:!0});const Ir=Symbol("Request internals"),rI=of.default.parse,u9=of.default.format,d9="destroy"in qs.default.Readable.prototype;function af(r){return typeof r=="object"&&typeof r[Ir]=="object"}function p9(r){const l=r&&typeof r=="object"&&Object.getPrototypeOf(r);return!!(l&&l.constructor.name==="AbortSignal")}class ra{constructor(r){let l=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},u;af(r)?u=rI(r.url):(r&&r.href?u=rI(r.href):u=rI(`${r}`),r={});let d=l.method||r.method||"GET";if(d=d.toUpperCase(),(l.body!=null||af(r)&&r.body!==null)&&(d==="GET"||d==="HEAD"))throw new TypeError("Request with GET/HEAD method cannot have body");let f=l.body!=null?l.body:af(r)&&r.body!==null?C2(r):null;Dn.call(this,f,{timeout:l.timeout||r.timeout||0,size:l.size||r.size||0});const g=new fi(l.headers||r.headers||{});if(f!=null&&!g.has("Content-Type")){const S=R2(f);S&&g.append("Content-Type",S)}let I=af(r)?r.signal:null;if("signal"in l&&(I=l.signal),I!=null&&!p9(I))throw new TypeError("Expected signal to be an instanceof AbortSignal");this[Ir]={method:d,redirect:l.redirect||r.redirect||"follow",headers:g,parsedURL:u,signal:I},this.follow=l.follow!==void 0?l.follow:r.follow!==void 0?r.follow:20,this.compress=l.compress!==void 0?l.compress:r.compress!==void 0?r.compress:!0,this.counter=l.counter||r.counter||0,this.agent=l.agent||r.agent}get method(){return this[Ir].method}get url(){return u9(this[Ir].parsedURL)}get headers(){return this[Ir].headers}get redirect(){return this[Ir].redirect}get signal(){return this[Ir].signal}clone(){return new ra(this)}}Dn.mixIn(ra.prototype);Object.defineProperty(ra.prototype,Symbol.toStringTag,{value:"Request",writable:!1,enumerable:!1,configurable:!0});Object.defineProperties(ra.prototype,{method:{enumerable:!0},url:{enumerable:!0},headers:{enumerable:!0},redirect:{enumerable:!0},clone:{enumerable:!0},signal:{enumerable:!0}});function m9(r){const l=r[Ir].parsedURL,u=new fi(r[Ir].headers);if(u.has("Accept")||u.set("Accept","*/*"),!l.protocol||!l.hostname)throw new TypeError("Only absolute URLs are supported");if(!/^https?:$/.test(l.protocol))throw new TypeError("Only HTTP(S) protocols are supported");if(r.signal&&r.body instanceof qs.default.Readable&&!d9)throw new Error("Cancellation of streamed requests with AbortSignal is not supported in node < 8");let d=null;if(r.body==null&&/^(POST|PUT)$/i.test(r.method)&&(d="0"),r.body!=null){const g=O2(r);typeof g=="number"&&(d=String(g))}d&&u.set("Content-Length",d),u.has("User-Agent")||u.set("User-Agent","node-fetch/1.0 (+https://github.com/bitinn/node-fetch)"),r.compress&&!u.has("Accept-Encoding")&&u.set("Accept-Encoding","gzip,deflate");let f=r.agent;return typeof f=="function"&&(f=f(l)),!u.has("Connection")&&!f&&u.set("Connection","close"),Object.assign({},l,{method:r.method,headers:c9(u),agent:f})}function ku(r){Error.call(this,r),this.type="aborted",this.message=r,Error.captureStackTrace(this,this.constructor)}ku.prototype=Object.create(Error.prototype);ku.prototype.constructor=ku;ku.prototype.name="AbortError";const k2=qs.default.PassThrough,f9=of.default.resolve;function mo(r,l){if(!mo.Promise)throw new Error("native promise missing, set fetch.Promise to your favorite alternative");return Dn.Promise=mo.Promise,new mo.Promise(function(u,d){const f=new ra(r,l),g=m9(f),I=(g.protocol==="https:"?A2.default:JS.default).request,S=f.signal;let x=null;const N=function(){let Q=new ku("The user aborted a request.");if(d(Q),f.body&&f.body instanceof qs.default.Readable&&f.body.destroy(Q),!x||!x.body)return;x.body.emit("error",Q)};if(S&&S.aborted){N();return}const E=function(){N(),U()},_=I(g);let A;S&&S.addEventListener("abort",E);function U(){_.abort(),S&&S.removeEventListener("abort",E),clearTimeout(A)}f.timeout&&_.once("socket",function(ne){A=setTimeout(function(){d(new Gn(`network timeout at: ${f.url}`,"request-timeout")),U()},f.timeout)}),_.on("error",function(ne){d(new Gn(`request to ${f.url} failed, reason: ${ne.message}`,"system",ne)),U()}),_.on("response",function(ne){clearTimeout(A);const Q=l9(ne.headers);if(mo.isRedirect(ne.statusCode)){const Ae=Q.get("Location"),Me=Ae===null?null:f9(f.url,Ae);switch(f.redirect){case"error":d(new Gn(`uri requested responds with a redirect, redirect mode is set to error: ${f.url}`,"no-redirect")),U();return;case"manual":if(Me!==null)try{Q.set("Location",Me)}catch(ct){d(ct)}break;case"follow":if(Me===null)break;if(f.counter>=f.follow){d(new Gn(`maximum redirect reached at: ${f.url}`,"max-redirect")),U();return}const et={headers:new fi(f.headers),follow:f.follow,counter:f.counter+1,agent:f.agent,compress:f.compress,method:f.method,body:f.body,signal:f.signal,timeout:f.timeout,size:f.size};if(ne.statusCode!==303&&f.body&&O2(f)===null){d(new Gn("Cannot follow redirect with body being a readable stream","unsupported-redirect")),U();return}(ne.statusCode===303||(ne.statusCode===301||ne.statusCode===302)&&f.method==="POST")&&(et.method="GET",et.body=void 0,et.headers.delete("content-length")),u(mo(new ra(Me,et))),U();return}}ne.once("end",function(){S&&S.removeEventListener("abort",E)});let M=ne.pipe(new k2);const fe={url:f.url,status:ne.statusCode,statusText:ne.statusMessage,headers:Q,size:f.size,timeout:f.timeout,counter:f.counter},ie=Q.get("Content-Encoding");if(!f.compress||f.method==="HEAD"||ie===null||ne.statusCode===204||ne.statusCode===304){x=new Mi(M,fe),u(x);return}const we={flush:uo.default.Z_SYNC_FLUSH,finishFlush:uo.default.Z_SYNC_FLUSH};if(ie=="gzip"||ie=="x-gzip"){M=M.pipe(uo.default.createGunzip(we)),x=new Mi(M,fe),u(x);return}if(ie=="deflate"||ie=="x-deflate"){const Ae=ne.pipe(new k2);Ae.once("data",function(Me){(Me[0]&15)===8?M=M.pipe(uo.default.createInflate()):M=M.pipe(uo.default.createInflateRaw()),x=new Mi(M,fe),u(x)});return}if(ie=="br"&&typeof uo.default.createBrotliDecompress=="function"){M=M.pipe(uo.default.createBrotliDecompress()),x=new Mi(M,fe),u(x);return}x=new Mi(M,fe),u(x)}),a9(_,f)})}mo.isRedirect=function(r){return r===301||r===302||r===303||r===307||r===308};mo.Promise=global.Promise;var g9=mo});var Ze=XS((cf,_2)=>{(function(r,l){typeof cf=="object"&&typeof _2!="undefined"?l(cf):typeof define=="function"&&define.amd?define(["exports"],l):(r=r||self,l(r.tf=r.tf||{}))})(cf,function(r){"use strict";const l=1e-7,u=1e-4;class d{constructor(e,t){this.backend=e,this.dataMover=t,this.data=new WeakMap,this.dataIdsCount=0}get(e){return this.data.has(e)||this.dataMover.moveData(this.backend,e),this.data.get(e)}set(e,t){this.dataIdsCount++,this.data.set(e,t)}has(e){return this.data.has(e)}delete(e){return this.dataIdsCount--,this.data.delete(e)}numDataIds(){return this.dataIdsCount}}class f{time(e){return g("time")}read(e){return g("read")}readSync(e){return g("readSync")}numDataIds(){return g("numDataIds")}disposeData(e){return g("disposeData")}write(e,t,n){return g("write")}move(e,t,n,s){return g("move")}memory(){return g("memory")}floatPrecision(){return g("floatPrecision")}epsilon(){return this.floatPrecision()===32?l:u}batchMatMul(e,t,n,s){return g("batchMatMul")}fusedBatchMatMul({a:e,b:t,transposeA:n,transposeB:s,bias:i,activation:o,preluActivationWeights:a}){return g("fusedBatchMatMul")}slice(e,t,n){return g("slice")}stridedSlice(e,t,n,s){return g("stridedSlice")}unstack(e,t){return g("unstack")}reverse(e,t){return g("reverse")}concat(e,t){return g("concat")}neg(e){return g("neg")}add(e,t){return g("add")}addN(e){return g("addN")}subtract(e,t){return g("subtract")}multiply(e,t){return g("multiply")}realDivide(e,t){return g("realDivide")}floorDiv(e,t){return g("floorDiv")}sum(e,t){return g("sum")}prod(e,t){return g("prod")}unsortedSegmentSum(e,t,n){return g("unsortedSegmentSum")}argMin(e,t){return g("argMin")}argMax(e,t){return g("argMax")}equal(e,t){return g("equal")}notEqual(e,t){return g("notEqual")}less(e,t){return g("less")}lessEqual(e,t){return g("lessEqual")}greater(e,t){return g("greater")}greaterEqual(e,t){return g("greaterEqual")}logicalNot(e){return g("logicalNot")}logicalAnd(e,t){return g("logicalAnd")}logicalOr(e,t){return g("logicalOr")}where(e){return g("where")}select(e,t,n){return g("select")}topk(e,t,n){return g("topk")}min(e,t){return g("min")}minimum(e,t){return g("minimum")}mod(e,t){return g("mod")}max(e,t){return g("max")}maximum(e,t){return g("maximum")}all(e,t){return g("all")}any(e,t){return g("any")}squaredDifference(e,t){return g("squaredDifference")}ceil(e){return g("ceil")}floor(e){return g("floor")}round(e){return g("round")}sign(e){return g("sign")}isNaN(e){return g("isNaN")}isInf(e){return g("isInf")}isFinite(e){return g("isFinite")}pow(e,t){return g("pow")}exp(e){return g("exp")}expm1(e){return g("expm1")}softmax(e,t){return g("softmax")}log(e){return g("log")}log1p(e){return g("log1p")}sqrt(e){return g("sqrt")}rsqrt(e){return g("rsqrt")}square(e){return g("square")}reciprocal(e){return g("reciprocal")}relu(e){return g("relu")}relu6(e){return g("relu6")}prelu(e,t){return g("prelu")}elu(e){return g("elu")}eluDer(e,t){return g("eluDer")}selu(e){return g("selu")}int(e){return g("int")}clip(e,t,n){return g("clip")}abs(e){return g("abs")}complexAbs(e){return g("complexAbs")}sigmoid(e){return g("sigmoid")}softplus(e){return g("softplus")}sin(e){return g("sin")}cos(e){return g("cos")}tan(e){return g("tan")}asin(e){return g("asin")}acos(e){return g("acos")}atan(e){return g("atan")}atan2(e,t){return g("atan2")}sinh(e){return g("sinh")}cosh(e){return g("cosh")}tanh(e){return g("tanh")}asinh(e){return g("asinh")}acosh(e){return g("acosh")}atanh(e){return g("atanh")}erf(e){return g("erf")}step(e,t){return g("step")}fusedConv2d({input:e,filter:t,convInfo:n,bias:s,activation:i,preluActivationWeights:o}){return g("fusedConv2d")}conv2d(e,t,n){return g("conv2d")}conv2dDerInput(e,t,n){return g("conv2dDerInput")}conv2dDerFilter(e,t,n){return g("conv2dDerFilter")}fusedDepthwiseConv2D({input:e,filter:t,convInfo:n,bias:s,activation:i,preluActivationWeights:o}){return g("fusedDepthwiseConv2D")}depthwiseConv2D(e,t,n){return g("depthwiseConv2D")}depthwiseConv2DDerInput(e,t,n){return g("depthwiseConv2DDerInput")}depthwiseConv2DDerFilter(e,t,n){return g("depthwiseConv2DDerFilter")}conv3d(e,t,n){return g("conv3d")}conv3dDerInput(e,t,n){return g("conv3dDerInput")}conv3dDerFilter(e,t,n){return g("conv3dDerFilter")}maxPool(e,t){return g("maxPool")}maxPoolBackprop(e,t,n,s){return g("maxPoolBackprop")}avgPool(e,t){return g("avgPool")}avgPoolBackprop(e,t,n){return g("avgPoolBackprop")}avgPool3d(e,t){return g("avgPool3d")}avgPool3dBackprop(e,t,n){return g("avgPool3dBackprop")}maxPool3d(e,t){return g("maxPool3d")}maxPool3dBackprop(e,t,n,s){return g("maxPool3dBackprop")}reshape(e,t){return g("reshape")}cast(e,t){return g("cast")}tile(e,t){return g("tile")}pad(e,t,n){return g("pad")}transpose(e,t){return g("transpose")}gather(e,t,n){return g("gather")}gatherND(e,t){return g("gatherND")}scatterND(e,t,n){return g("scatterND")}batchToSpaceND(e,t,n){return g("batchToSpaceND")}spaceToBatchND(e,t,n){return g("spaceToBatchND")}resizeBilinear(e,t,n,s){return g("resizeBilinear")}resizeBilinearBackprop(e,t,n){return g("resizeBilinearBackprop")}resizeNearestNeighbor(e,t,n,s){return g("resizeNearestNeighbor")}resizeNearestNeighborBackprop(e,t,n){return g("resizeNearestNeighborBackprop")}batchNorm(e,t,n,s,i,o){return g("batchNorm")}localResponseNormalization4D(e,t,n,s,i){return g("localResponseNormalization4D")}LRNGrad(e,t,n,s,i,o,a){return g("LRNGrad")}multinomial(e,t,n,s){return g("multinomial")}oneHot(e,t,n,s){return g("oneHot")}cumsum(e,t,n,s){return g("cumsum")}nonMaxSuppression(e,t,n,s,i){return g("nonMaxSuppression")}fft(e){return g("fft")}ifft(e){return g("ifft")}complex(e,t){return g("complex")}real(e){return g("real")}imag(e){return g("imag")}cropAndResize(e,t,n,s,i,o){return g("cropAndResize")}depthToSpace(e,t,n){return g("depthToSpace")}split(e,t,n){return g("split")}sparseToDense(e,t,n,s){return g("sparseToDense")}diag(e){return g("diag")}fill(e,t,n){return g("fill")}onesLike(e){return g("onesLike")}zerosLike(e){return g("zerosLike")}linspace(e,t,n){return g("linspace")}dispose(){return g("dispose")}}function g(e){throw new Error(`'${e}' not yet implemented or not found in the registry. This kernel may not be supported by the tfjs backend you have chosen`)}function I(e){let t=e.length,n=0,s=0;for(;t>0;)s=Math.random()*t|0,t--,n=e[t],e[t]=e[s],e[s]=n}function S(e,t,n){return Math.max(e,Math.min(t,n))}function x(e){return e%2===0?e:e+1}function N(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n];return t}function E(e,t){const n=Math.random();return t*n+(1-n)*e}function _(e,t){let n=0;for(let s=0;s<e.length;s++){const i=Number(e[s])-Number(t[s]);n+=i*i}return n}function A(e,t){if(!e)throw new Error(typeof t=="string"?t:t())}function U(e,t,n=""){A(ie(e,t),()=>n+` Shapes ${e} and ${t} must match`)}function ne(e){A(e!=null,()=>"The input to the tensor constructor must be a non-null value.")}function Q(e,t=[],n=!1){if(t==null&&(t=[]),Array.isArray(e)||un(e)&&!n)for(let s=0;s<e.length;++s)Q(e[s],t,n);else t.push(e);return t}function M(e){if(e.length===0)return 1;let t=e[0];for(let n=1;n<e.length;n++)t*=e[n];return t}function fe(e){return e.length===0}function ie(e,t){if(e===t)return!0;if(e==null||t==null)return!1;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function we(e){return e%1===0}function Ae(e){if(Math.tanh!=null)return Math.tanh(e);if(e===Infinity)return 1;if(e===-Infinity)return-1;{const t=Math.exp(2*e);return(t-1)/(t+1)}}function Me(e){const t=Math.ceil(Math.sqrt(e));return[t,Math.ceil(e/t)]}function et(e){const t=new Uint32Array(e);for(let n=0;n<e;++n)t[n]=n;return I(t),t}function ct(e,t){return t<=e.length?e:e+" ".repeat(t-e.length)}function $t(e,t=s=>0,n){return new Promise((s,i)=>{let o=0;const a=()=>{if(e()){s();return}o++;const c=t(o);if(n!=null&&o>=n){i();return}setTimeout(a,c)};a()})}function Vt(e,t){let n=1,s=-1;for(let o=0;o<e.length;++o)if(e[o]>=0)n*=e[o];else if(e[o]===-1){if(s!==-1)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${s} and dim ${o}`);s=o}else if(e[o]<0)throw Error(`Shapes can not be < 0. Found ${e[o]} at dim ${o}`);if(s===-1){if(t>0&&t!==n)throw Error(`Size(${t}) must match the product of shape ${e}`);return e}if(n===0)throw Error(`Cannot infer the missing size in [${e}] when there are 0 elements`);if(t%n!==0)throw Error(`The implicit shape can't be a fractional number. Got ${t} / ${n}`);const i=e.slice();return i[s]=t/n,i}function je(e,t){const n=t.length;return e=e==null?t.map((s,i)=>i):[].concat(e),A(e.every(s=>s>=-n&&s<n),()=>`All values in axis param must be in range [-${n}, ${n}) but got axis ${e}`),A(e.every(s=>we(s)),()=>`All values in axis param must be integers but got axis ${e}`),e.map(s=>s<0?n+s:s)}function hn(e,t){const n=[],s=[],i=t!=null&&Array.isArray(t)&&t.length===0,o=t==null||i?null:je(t,e).sort();let a=0;for(let c=0;c<e.length;++c){if(o!=null){if(o[a]===c&&e[c]!==1)throw new Error(`Can't squeeze axis ${c} since its dim '${e[c]}' is not 1`);(o[a]==null||o[a]>c)&&e[c]===1&&(n.push(e[c]),s.push(c)),o[a]<=c&&a++}e[c]!==1&&(n.push(e[c]),s.push(c))}return{newShape:n,keptDims:s}}function bt(e,t){let n=null;if(e==null||e==="float32")n=new Float32Array(t);else if(e==="int32")n=new Int32Array(t);else if(e==="bool")n=new Uint8Array(t);else throw new Error(`Unknown data type ${e}`);return n}function Is(e,t){let n=null;if(e==null||e==="float32")n=new Float32Array(t);else if(e==="int32")n=new Int32Array(t);else if(e==="bool")n=new Uint8Array(t);else if(e==="string")n=new Array(t);else throw new Error(`Unknown data type ${e}`);return n}function _r(e,t){for(let n=0;n<e.length;n++){const s=e[n];if(isNaN(s)||!isFinite(s))throw Error(`A tensor of type ${t} being uploaded contains ${s}.`)}}function Wr(e){return e==="bool"||e==="complex64"||e==="float32"||e==="int32"||e==="string"}function Oa(e,t){return t==="complex64"||(t==="float32"&&e!=="complex64"||t==="int32"&&e!=="float32"&&e!=="complex64")?!1:!(t==="bool"&&e==="bool")}function un(e){return e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array}function iy(e){if(e==="float32"||e==="int32")return 4;if(e==="complex64")return 8;if(e==="bool")return 1;throw new Error(`Unknown dtype ${e}`)}function Xx(e){if(e==null)return 0;let t=0;return e.forEach(n=>t+=n.length),t}function Ji(e){return typeof e=="string"||e instanceof String}function Jx(e){return typeof e=="boolean"}function yd(e){return typeof e=="number"}function Ea(e){return Array.isArray(e)?Ea(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array?"int32":yd(e)?"float32":Ji(e)?"string":Jx(e)?"bool":"float32"}function $r(e){return!!(e&&e.constructor&&e.call&&e.apply)}function bd(e,t){for(let n=t;n<e;++n)if(e%n===0)return n;return e}function Ke(e){const t=e.length;if(t<2)return[];const n=new Array(t-1);n[t-2]=e[t-1];for(let s=t-3;s>=0;--s)n[s]=n[s+1]*e[s+1];return n}function Zx(e,t,n){const s=new Array;if(t.length===1){const i=t[0];for(let o=0;o<i;o++)s[o]=n[e+o]}else{const i=t[0],o=t.slice(1),a=o.reduce((c,h)=>c*h);for(let c=0;c<i;c++)s[c]=Zx(e+c*a,o,n)}return s}function xs(e,t){if(e.length===0)return t[0];const n=e.reduce((s,i)=>s*i);if(n===0)return[];if(n!==t.length)throw new Error(`[${e}] does not match the input size ${t.length}.`);return Zx(0,e,t)}function ry(e,t){const n=Da(e,t);for(let s=0;s<n.length;s++)n[s]=1;return n}function Da(e,t){if(t==null||t==="float32"||t==="complex64")return new Float32Array(e);if(t==="int32")return new Int32Array(e);if(t==="bool")return new Uint8Array(e);throw new Error(`Unknown data type ${t}`)}function oy(e,t){const n=e.reduce((s,i)=>s*i,1);if(t==null||t==="float32")return xs(e,new Float32Array(n));if(t==="int32")return xs(e,new Int32Array(n));if(t==="bool")return xs(e,new Uint8Array(n));throw new Error(`Unknown data type ${t}`)}function ay(e){e.forEach(t=>{A(Number.isInteger(t)&&t>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`)})}function Us(e,t,n){if(t===0)return 0;if(t===1)return e[0];let s=e[e.length-1];for(let i=0;i<e.length-1;++i)s+=n[i]*e[i];return s}function Co(e,t,n){if(t===0)return[];if(t===1)return[e];const s=new Array(t);for(let i=0;i<s.length-1;++i)s[i]=Math.floor(e/n[i]),e-=s[i]*n[i];return s[s.length-1]=e,s}function Ro(e){return e&&e.then&&typeof e.then=="function"}const Qx="tfjsflags";class eT{constructor(e){this.global=e,this.flags={},this.flagRegistry={},this.urlFlags={},this.populateURLFlags()}setPlatform(e,t){this.platform!=null&&console.warn(`Platform ${this.platformName} has already been set. Overwriting the platform with ${t}.`),this.platformName=e,this.platform=t}registerFlag(e,t,n){if(this.flagRegistry[e]={evaluationFn:t,setHook:n},this.urlFlags[e]!=null){const s=this.urlFlags[e];console.warn(`Setting feature override from URL ${e}: ${s}.`),this.set(e,s)}}async getAsync(e){return e in this.flags?this.flags[e]:(this.flags[e]=await this.evaluateFlag(e),this.flags[e])}get(e){if(e in this.flags)return this.flags[e];const t=this.evaluateFlag(e);if(Ro(t))throw new Error(`Flag ${e} cannot be synchronously evaluated. Please use getAsync() instead.`);return this.flags[e]=t,this.flags[e]}getNumber(e){return this.get(e)}getBool(e){return this.get(e)}getFlags(){return this.flags}get features(){return this.flags}set(e,t){if(this.flagRegistry[e]==null)throw new Error(`Cannot set flag ${e} as it has not been registered.`);this.flags[e]=t,this.flagRegistry[e].setHook!=null&&this.flagRegistry[e].setHook(t)}evaluateFlag(e){if(this.flagRegistry[e]==null)throw new Error(`Cannot evaluate flag '${e}': no evaluation function found.`);return this.flagRegistry[e].evaluationFn()}setFlags(e){this.flags=Object.assign({},e)}reset(){this.flags={},this.urlFlags={},this.populateURLFlags()}populateURLFlags(){if(typeof this.global=="undefined"||typeof this.global.location=="undefined"||typeof this.global.location.search=="undefined")return;const e=Tk(this.global.location.search);if(Qx in e){const t=e[Qx].split(",");t.forEach(n=>{const[s,i]=n.split(":");this.urlFlags[s]=vk(s,i)})}}}function Tk(e){const t={};return e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(n,...s)=>(Ak(t,s[0],s[1]),s.join("="))),t}function Ak(e,t,n){e[decodeURIComponent(t)]=decodeURIComponent(n||"")}function vk(e,t){if(t=t.toLowerCase(),t==="true"||t==="false")return t==="true";if(`${+t}`===t)return+t;throw new Error(`Could not parse value flag value ${t} for flag ${e}.`)}function ae(){return r.ENV}r.ENV=null;function Nk(e){r.ENV=e}let cy;function tT(){if(cy==null){let e;if(typeof window!="undefined")e=window;else if(typeof global!="undefined")e=global;else if(typeof process!="undefined")e=process;else if(typeof self!="undefined")e=self;else throw new Error("Could not find a global object");cy=e}return cy}function Ck(){const e=tT();return e._tfGlobals==null&&(e._tfGlobals=new Map),e._tfGlobals}function nT(e,t){const n=Ck();if(n.has(e))return n.get(e);{const s=t();return n.set(e,s),n.get(e)}}const wd="Abs",Ll="Acos",Sl="Acosh",Oo="Add",ly="AddN",sT="All",iT="Any",hy="ArgMax",uy="ArgMin",Il="Asin",xl="Asinh",Tl="Atan",Al="Atanh",Ld="Atan2",vl="AvgPool",Sd="AvgPoolBackprop",dy="AvgPool3D",rT="AvgPool3DBackprop",Id="BatchMatMul",py="BatchToSpaceND",my="BroadcastTo",ka="Cast",Nl="Ceil",Cl="ClipByValue",xd="Complex",Rl="Concat",Td="Conv2D",fy="Conv2DBackpropFilter",Ad="Conv2DBackpropInput",vd="Conv3D",gy="Conv3DBackpropFilterV2",yy="Conv3DBackpropInputV2",Fa="Cos",Ol="Cosh",by="Cumsum",oT="CropAndResize",aT="DepthToSpace",Nd="DepthwiseConv2dNative",wy="DepthwiseConv2dNativeBackpropFilter",Ly="DepthwiseConv2dNativeBackpropInput",cT="Diag",Cd="Dilation2D",Rd="Dilation2DBackpropInput",Od="Dilation2DBackpropFilter",_a="Div",El="Elu",lT="EluGrad",Dl="Erf",hT="Equal",kl="Exp",Fl="Expm1",Ed="FFT",Sy="Fill",Dd="FlipLeftRight",_l="Floor",Iy="FloorDiv",Wl="FusedBatchNorm",xy="GatherV2",uT="GatherNd",dT="Greater",Ty="GreaterEqual",$l="Identity",kd="IFFT",Fd="Imag",Ul="IsFinite",Bl="IsInf",Ml="IsNan",pT="Less",mT="LessEqual",fT="LinSpace",Pl="Log",zl="Log1p",gT="LogicalAnd",_d="LogicalNot",yT="LogicalOr",Ay="LogSoftmax",vy="LRN",bT="LRNBackprop",Vl="Max",Ny="Maximum",Gl="MaxPool",Wd="MaxPoolBackprop",Cy="MaxPool3D",wT="MaxPool3DBackprop",$d="MaxPoolWithArgmax",Ry="Mean",Oy="Min",Ey="Minimum",Yl="MirrorPad",Dy="Mod",Wa="Multiply",ky="Negate",Hl="NotEqual",Fy="NonMaxSuppressionV3",Ud="NonMaxSuppressionV4",Bd="NonMaxSuppressionV5",_y="OnesLike",Wy="OneHot",Md="PadV2",Rk="Pool",$y="Pow",Pd="Prelu",LT="Prod",ST="Range",zd="Real",ql="Reciprocal",jl="Relu",Kl="Reshape",Uy="ResizeNearestNeighbor",IT="ResizeNearestNeighborGrad",By="ResizeBilinear",xT="ResizeBilinearGrad",Xl="Relu6",My="Reverse",Jl="Round",Zl="Rsqrt",TT="ScatterNd",Py="SelectV2",Ql="Selu",Vd="Slice",$a="Sin",eh="Sinh",th="Sign",nh="Sigmoid",sh="Softplus",ih="Sqrt",zy="Sum",Gd="SpaceToBatchND",Vy="SplitV",Gy="Softmax",Ua="SquaredDifference",Yd="Square",Ba="Sub",AT="SparseToDense",vT="StridedSlice",Ma="Tan",rh="Tanh",Yy="Tile",NT="TopK",oh="Transpose",Hd="Unique",Hy="Unpack",qy="UnsortedSegmentSum",jy="ZerosLike",ah="Step",qd="FromPixels",jd="RotateWithOffset",Kd="_FusedMatMul",Xd="FusedConv2D",Jd="FusedDepthwiseConv2D";const Pa=nT("kernelRegistry",()=>new Map),ch=nT("gradRegistry",()=>new Map);function Ky(e,t){const n=Jy(e,t);return Pa.get(n)}function Xy(e){return ch.get(e)}function Zd(e){const t=Pa.entries(),n=[];for(;;){const{done:s,value:i}=t.next();if(s)break;const[o,a]=i,[c]=o.split("_");c===e&&n.push(a)}return n}function Qd(e){const{kernelName:t,backendName:n}=e,s=Jy(t,n);Pa.has(s)&&console.warn(`The kernel '${t}' for backend '${n}' is already registered`),Pa.set(s,e)}function CT(e){const{kernelName:t}=e;ch.has(t)&&(ae().getBool("DEBUG")&&console.warn(`Overriding the gradient for '${t}'`)),ch.set(t,e)}function Ok(e,t){const n=Jy(e,t);if(!Pa.has(n))throw new Error(`The kernel '${e}' for backend '${t}' is not registered`);Pa.delete(n)}function Ek(e){if(!ch.has(e))throw new Error(`The gradient '${e}' for backend is not registered`);ch.delete(e)}function Dk(e,t){const n=Zd(e);n.forEach(s=>{const i=Object.assign({},s,{backendName:t});Qd(i)})}function Jy(e,t){return`${t}_${e}`}function RT(e,t){return t==="string"?ep(e):Ur([e],t)}function kk(e,t){return e instanceof Float32Array&&t==="float32"||e instanceof Int32Array&&t==="int32"||e instanceof Uint8Array&&t==="bool"}function Ur(e,t){if(t==="string")throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=Q(e)),ae().getBool("DEBUG")&&_r(e,t),kk(e,t))return e;if(t==null||t==="float32"||t==="complex64")return new Float32Array(e);if(t==="int32")return new Int32Array(e);if(t==="bool"){const n=new Uint8Array(e.length);for(let s=0;s<n.length;++s)Math.round(e[s])!==0&&(n[s]=1);return n}else throw new Error(`Unknown data type ${t}`)}function Jn(){return ae().platform.now()}function OT(e,t){return ae().platform.fetch(e,t)}function ep(e,t="utf-8"){return t=t||"utf-8",ae().platform.encode(e,t)}function lh(e,t="utf-8"){return t=t||"utf-8",ae().platform.decode(e,t)}var Fk=Object.freeze({__proto__:null,createScalarValue:RT,toTypedArray:Ur,now:Jn,fetch:OT,encodeString:ep,decodeString:lh,shuffle:I,clamp:S,nearestLargerEven:x,sum:N,randUniform:E,distSquared:_,assert:A,assertShapesMatch:U,assertNonNull:ne,flatten:Q,sizeFromShape:M,isScalarShape:fe,arraysEqual:ie,isInt:we,tanh:Ae,sizeToSquarishShape:Me,createShuffledIndices:et,rightPad:ct,repeatedTry:$t,inferFromImplicitShape:Vt,parseAxisParam:je,squeezeShape:hn,getTypedArrayFromDType:bt,getArrayFromDType:Is,checkConversionForErrors:_r,isValidDtype:Wr,hasEncodingLoss:Oa,isTypedArray:un,bytesPerElement:iy,bytesFromStringArray:Xx,isString:Ji,isBoolean:Jx,isNumber:yd,inferDtype:Ea,isFunction:$r,nearestDivisor:bd,computeStrides:Ke,toNestedArray:xs,makeOnesTypedArray:ry,makeZerosTypedArray:Da,makeZerosNestedTypedArray:oy,assertNonNegativeIntegerDimensions:ay,locToIndex:Us,indexToLoc:Co,isPromise:Ro});class _k{constructor(e,t){this.backendTimer=e,this.logger=t,t==null&&(this.logger=new $k)}profileKernel(e,t,n){let s;const i=()=>{s=n()},o=this.backendTimer.time(i);for(let c=0;c<s.length;c++){const h=s[c];h.data().then(p=>{Wk(p,h.dtype,e)})}const a={kernelName:e,outputs:s,inputs:t,timeMs:o.then(c=>c.kernelMs),extraInfo:o.then(c=>c.getExtraProfileInfo!=null?c.getExtraProfileInfo():"")};return a}logKernelProfile(e){const{kernelName:t,outputs:n,timeMs:s,inputs:i,extraInfo:o}=e;n.forEach(a=>{Promise.all([a.data(),s,o]).then(c=>{this.logger.logKernelProfile(t,a,c[0],c[1],i,c[2])})})}}function Wk(e,t,n){if(t!=="float32")return!1;for(let s=0;s<e.length;s++){const i=e[s];if(isNaN(i)||!isFinite(i))return console.warn(`Found ${i} in the result of '${n}'`),!0}return!1}class $k{logKernelProfile(e,t,n,s,i,o){const a=typeof s=="number"?ct(`${s}ms`,9):s.error,c=ct(e,25),h=t.rank,p=t.size,m=ct(t.shape.toString(),14);let y="";for(const b in i){const w=i[b];if(w!=null){const L=w.shape||t.shape,T=L.length;y+=`${b}: ${T}D ${T>0?L:""} `}}console.log(`%c${c} %c${a} %c${h}D ${m} %c${p} %c${y} %c${o}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}}function Uk(e,t,n){const s={},i={};for(let h=0;h<t.length;h++)s[t[h].id]=!0;for(let h=0;h<e.length;h++){const p=e[h],m=p.inputs;for(const y in m){const b=m[y];let w=!1;for(let L=0;L<t.length;L++)if(s[b.id]){p.outputs.forEach(T=>s[T.id]=!0),w=!0,i[p.id]=!0;break}if(w)break}}const o={};o[n.id]=!0;const a={};for(let h=e.length-1;h>=0;h--){const p=e[h],m=p.inputs;for(let y=0;y<p.outputs.length;y++)if(o[p.outputs[y].id]){for(const b in m)o[m[b].id]=!0,a[p.id]=!0;break}}const c=[];for(let h=0;h<e.length;h++){const p=e[h];if(i[p.id]&&a[p.id]){const m={};for(const b in p.inputs){const w=p.inputs[b];s[w.id]&&(m[b]=w)}const y=Object.assign({},p);y.inputs=m,y.outputs=p.outputs,c.push(y)}}return c}function Bk(e,t,n,s){for(let i=t.length-1;i>=0;i--){const o=t[i],a=[];if(o.outputs.forEach(h=>{const p=e[h.id];p!=null?a.push(p):a.push(null)}),o.gradient==null)throw new Error(`Cannot compute gradient: gradient function not found for ${o.kernelName}.`);const c=o.gradient(a);for(const h in o.inputs){if(!(h in c))throw new Error(`Cannot backprop through input ${h}. Available gradients found: ${Object.keys(c)}.`);const p=n(()=>c[h]());if(p.dtype!=="float32")throw new Error(`Error in gradient for op ${o.kernelName}. The gradient of input ${h} must have 'float32' dtype, but has '${p.dtype}'`);const m=o.inputs[h];if(!ie(p.shape,m.shape))throw new Error(`Error in gradient for op ${o.kernelName}. The gradient of input '${h}' has shape '${p.shape}', which does not match the shape of the input '${m.shape}'`);if(e[m.id]==null)e[m.id]=p;else{const y=e[m.id];e[m.id]=s(y,p),y.dispose()}}}}const ET=20,hh=3,Zy=7;function Mk(e,t,n,s){const i=Ke(t),o=Pk(e,t,n,i),a=t.length,c=tp(e,t,n,i,o),h=["Tensor"];return s&&(h.push(` dtype: ${n}`),h.push(` rank: ${a}`),h.push(` shape: [${t}]`),h.push(" values:")),h.push(c.map(p=>" "+p).join(`
`)),h.join(`
`)}function Pk(e,t,n,s){const i=M(t),o=s[s.length-1],a=new Array(o).fill(0),c=t.length,h=n==="complex64"?dh(e):e;if(c>1)for(let p=0;p<i/o;p++){const m=p*o;for(let y=0;y<o;y++)a[y]=Math.max(a[y],uh(h[m+y],0,n).length)}return a}function uh(e,t,n){let s;return Array.isArray(e)?s=`${parseFloat(e[0].toFixed(Zy))} + ${parseFloat(e[1].toFixed(Zy))}j`:Ji(e)?s=`'${e}'`:n==="bool"?s=DT(e):s=parseFloat(e.toFixed(Zy)).toString(),ct(s,t)}function DT(e){return e===0?"false":"true"}function tp(e,t,n,s,i,o=!0){const a=n==="complex64"?2:1,c=t[0],h=t.length;if(h===0){if(n==="complex64"){const T=dh(e);return[uh(T[0],0,n)]}return n==="bool"?[DT(e[0])]:[e[0].toString()]}if(h===1){if(c>ET){const v=hh*a;let C=Array.from(e.slice(0,v)),O=Array.from(e.slice((c-hh)*a,c*a));return n==="complex64"&&(C=dh(C),O=dh(O)),["["+C.map((D,k)=>uh(D,i[k],n)).join(", ")+", ..., "+O.map((D,k)=>uh(D,i[c-hh+k],n)).join(", ")+"]"]}const T=n==="complex64"?dh(e):Array.from(e);return["["+T.map((v,C)=>uh(v,i[C],n)).join(", ")+"]"]}const p=t.slice(1),m=s.slice(1),y=s[0]*a,b=[];if(c>ET){for(let T=0;T<hh;T++){const v=T*y,C=v+y;b.push(...tp(e.slice(v,C),p,n,m,i,!1))}b.push("...");for(let T=c-hh;T<c;T++){const v=T*y,C=v+y;b.push(...tp(e.slice(v,C),p,n,m,i,T===c-1))}}else for(let T=0;T<c;T++){const v=T*y,C=v+y;b.push(...tp(e.slice(v,C),p,n,m,i,T===c-1))}const w=h===2?",":"";b[0]="["+b[0]+w;for(let T=1;T<b.length-1;T++)b[T]=" "+b[T]+w;let L=`,
`;for(let T=2;T<h;T++)L+=`
`;return b[b.length-1]=" "+b[b.length-1]+"]"+(o?"":L),b}function dh(e){const t=[];for(let n=0;n<e.length;n+=2)t.push([e[n],e[n+1]]);return t}class an{constructor(e,t,n){if(this.dtype=t,this.shape=e.slice(),this.size=M(e),n!=null){const s=n.length;A(s===this.size,()=>`Length of values '${s}' does not match the size inferred by the shape '${this.size}'.`)}if(t==="complex64")throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=n||Is(t,this.size),this.strides=Ke(e)}set(e,...t){t.length===0&&(t=[0]),A(t.length===this.rank,()=>`The number of provided coordinates (${t.length}) must match the rank (${this.rank})`);const n=this.locToIndex(t);this.values[n]=e}get(...e){e.length===0&&(e=[0]);let t=0;for(const s of e){if(s<0||s>=this.shape[t]){const i=`Requested out of range element at ${e}. Buffer shape=${this.shape}`;throw new Error(i)}t++}let n=e[e.length-1];for(let s=0;s<e.length-1;++s)n+=this.strides[s]*e[s];return this.values[n]}locToIndex(e){if(this.rank===0)return 0;if(this.rank===1)return e[0];let t=e[e.length-1];for(let n=0;n<e.length-1;++n)t+=this.strides[n]*e[n];return t}indexToLoc(e){if(this.rank===0)return[];if(this.rank===1)return[e];const t=new Array(this.shape.length);for(let n=0;n<t.length-1;++n)t[n]=Math.floor(e/this.strides[n]),e-=t[n]*this.strides[n];return t[t.length-1]=e,t}get rank(){return this.shape.length}toTensor(){return vi().makeTensor(this.values,this.shape,this.dtype)}}let vi=null,za=null,kT=null;function zk(e){vi=e}function Vk(e){za=e}function Gk(e){kT=e}class te{constructor(e,t,n,s){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=M(e),this.strides=Ke(e),this.dataId=n,this.id=s,this.rankType=this.rank<5?this.rank.toString():"higher"}get rank(){return this.shape.length}async buffer(){const e=await this.data();return za.buffer(this.shape,this.dtype,e)}bufferSync(){return za.buffer(this.shape,this.dtype,this.dataSync())}async array(){const e=await this.data();return xs(this.shape,e)}arraySync(){return xs(this.shape,this.dataSync())}async data(){this.throwIfDisposed();const e=vi().read(this.dataId);if(this.dtype==="string"){const t=await e;try{return t.map(n=>lh(n))}catch(n){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}}return e}dataSync(){this.throwIfDisposed();const e=vi().readSync(this.dataId);if(this.dtype==="string")try{return e.map(t=>lh(t))}catch(t){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}return e}async bytes(){this.throwIfDisposed();const e=await vi().read(this.dataId);return this.dtype==="string"?e:new Uint8Array(e.buffer)}dispose(){if(this.isDisposed)return;vi().disposeTensor(this),this.isDisposedInternal=!0}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return za.print(this,e)}clone(){return this.throwIfDisposed(),za.clone(this)}toString(e=!1){const t=this.dataSync();return Mk(t,this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),za.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),vi().makeVariable(this,e,t,n)}}Object.defineProperty(te,Symbol.hasInstance,{value:e=>!!e&&e.data!=null&&e.dataSync!=null&&e.throwIfDisposed!=null});class ph extends te{constructor(e,t,n,s){super(e.shape,e.dtype,e.dataId,s);this.trainable=t,this.name=n}assign(e){if(e.dtype!==this.dtype)throw new Error(`dtype of the new value (${e.dtype}) and previous value (${this.dtype}) must match`);if(!ie(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);vi().disposeTensor(this),this.dataId=e.dataId,vi().incRef(this,null)}dispose(){vi().disposeVariable(this),this.isDisposedInternal=!0}}Object.defineProperty(ph,Symbol.hasInstance,{value:e=>e instanceof te&&e.assign!=null&&e.assign instanceof Function});(function(e){e.R0="R0",e.R1="R1",e.R2="R2",e.R3="R3",e.R4="R4",e.R5="R5",e.R6="R6"})(r.Rank||(r.Rank={}));var Qy;(function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"})(Qy||(Qy={}));var eb;(function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"})(eb||(eb={}));var tb;(function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"})(tb||(tb={}));var nb;(function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"})(nb||(nb={}));const Yk={float32:tb,int32:Qy,bool:eb,complex64:nb};function Bn(e,t){if(e==="string"||t==="string"){if(e==="string"&&t==="string")return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return Yk[e][t]}function np(e){return Bn(e,"int32")}function Gt(e,t){if(e.dtype===t.dtype)return[e,t];const n=Bn(e.dtype,t.dtype);return[e.cast(n),t.cast(n)]}function FT(e,t){A(e.dtype===t.dtype,()=>`The dtypes of the first(${e.dtype}) and second(${t.dtype}) input must match`)}function sp(e,t){return t.some(n=>n.id===e.id)}function Zi(e){const t=[],n=new Set;return _T(e,t,n),t}function _T(e,t,n){if(e==null)return;if(e instanceof te){t.push(e);return}if(!Hk(e))return;const s=e;for(const i in s){const o=s[i];n.has(o)||(n.add(o),_T(o,t,n))}}function Hk(e){return Array.isArray(e)||typeof e=="object"}var qk=Object.freeze({__proto__:null,makeTypesMatch:Gt,assertTypesMatch:FT,isTensorInList:sp,getTensorsInContainer:Zi});class WT{constructor(){this.registeredVariables={},this.nextTapeNodeId=0,this.numBytes=0,this.numTensors=0,this.numStringTensors=0,this.numDataBuffers=0,this.gradientDepth=0,this.kernelDepth=0,this.scopeStack=[],this.numDataMovesStack=[],this.nextScopeId=0,this.tensorInfo=new WeakMap,this.profiling=!1,this.activeProfile={newBytes:0,newTensors:0,peakBytes:0,kernels:[],result:null}}dispose(){for(const e in this.registeredVariables)this.registeredVariables[e].dispose()}}class mh{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new WT}async ready(){if(this.pendingBackendInit!=null)return this.pendingBackendInit.then(()=>{});if(this.backendInstance!=null)return;const e=this.getSortedBackends();for(let t=0;t<e.length;t++){const n=e[t],s=await this.initializeBackend(n).success;if(s){await this.setBackend(n);return}}throw new Error("Could not initialize any backends, all backend initializations failed.")}get backend(){if(this.pendingBackendInit!=null)throw new Error(`Backend '${this.backendName}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);if(this.backendInstance==null){const{name:e,asyncInit:t}=this.initializeBackendsAndReturnBest();if(t)throw new Error(`The highest priority backend '${e}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);this.setBackend(e)}return this.backendInstance}backendNames(){return Object.keys(this.registryFactory)}findBackend(e){if(!(e in this.registry))if(e in this.registryFactory){const{asyncInit:t}=this.initializeBackend(e);if(t)return null}else return null;return this.registry[e]}findBackendFactory(e){return e in this.registryFactory?this.registryFactory[e].factory:null}registerBackend(e,t,n=1){return e in this.registryFactory?(console.warn(`${e} backend was already registered. Reusing existing backend factory.`),!1):(this.registryFactory[e]={factory:t,priority:n},!0)}async setBackend(e){if(this.registryFactory[e]==null)throw new Error(`Backend name '${e}' not found in registry`);if(this.backendName=e,this.registry[e]==null){this.backendInstance=null;const{success:t,asyncInit:n}=this.initializeBackend(e),s=n?await t:t;if(!s)return!1}return this.backendInstance=this.registry[e],this.setupRegisteredKernels(),this.profiler=new _k(this.backendInstance),!0}setupRegisteredKernels(){const e=Zd(this.backendName);e.forEach(t=>{t.setupFunc!=null&&t.setupFunc(this.backendInstance)})}disposeRegisteredKernels(e){const t=Zd(e);t.forEach(n=>{n.disposeFunc!=null&&n.disposeFunc(this.registry[e])})}initializeBackend(e){const t=this.registryFactory[e];if(t==null)throw new Error(`Cannot initialize backend ${e}, no registration found.`);try{const n=t.factory();if(n&&!(n instanceof f)&&typeof n.then=="function"){const s=++this.pendingBackendInitId,i=n.then(o=>s<this.pendingBackendInitId?!1:(this.registry[e]=o,this.pendingBackendInit=null,!0)).catch(o=>(s<this.pendingBackendInitId||(this.pendingBackendInit=null,console.warn(`Initialization of backend ${e} failed`),console.warn(o.stack||o.message)),!1));return this.pendingBackendInit=i,{success:i,asyncInit:!0}}else return this.registry[e]=n,{success:!0,asyncInit:!1}}catch(n){return console.warn(`Initialization of backend ${e} failed`),console.warn(n.stack||n.message),{success:!1,asyncInit:!1}}}removeBackend(e){if(!(e in this.registryFactory))throw new Error(`${e} backend not found in registry`);this.backendName===e&&this.pendingBackendInit!=null&&this.pendingBackendInitId++,e in this.registry&&(this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e]),delete this.registryFactory[e],this.backendName===e&&(this.pendingBackendInit=null,this.backendName=null,this.backendInstance=null)}getSortedBackends(){if(Object.keys(this.registryFactory).length===0)throw new Error("No backend found in registry.");return Object.keys(this.registryFactory).sort((e,t)=>this.registryFactory[t].priority-this.registryFactory[e].priority)}initializeBackendsAndReturnBest(){const e=this.getSortedBackends();for(let t=0;t<e.length;t++){const n=e[t],{success:s,asyncInit:i}=this.initializeBackend(n);if(i||s)return{name:n,asyncInit:i}}throw new Error("Could not initialize any backends, all backend initializations failed.")}moveData(e,t){const n=this.state.tensorInfo.get(t),s=n.backend,i=this.readSync(t);s.disposeData(t),n.backend=e,e.move(t,i,n.shape,n.dtype),this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack[this.state.numDataMovesStack.length-1]++}tidy(e,t){let n=null;if(t==null){if(typeof e!="function")throw new Error("Please provide a function to tidy()");t=e}else{if(typeof e!="string"&&!(e instanceof String))throw new Error("When calling with two arguments, the first argument to tidy() must be a string");if(typeof t!="function")throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");n=e}let s;return this.scopedRun(()=>this.startScope(n),()=>this.endScope(s),()=>(s=t(),s instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),s))}scopedRun(e,t,n){e();try{const s=n();return t(),s}catch(s){throw t(),s}}nextTensorId(){return mh.nextTensorId++}nextVariableId(){return mh.nextVariableId++}clone(e){const t=this.makeTensorFromDataId(e.dataId,e.shape,e.dtype),n={x:e},s=o=>({x:()=>{const a="float32",c={x:o},h={dtype:a};return G.runKernelFunc(p=>p.cast(o,a),c,null,ka,h)}}),i=[];return this.addTapeNode(this.state.activeScope.name,n,[t],s,i,{}),t}runKernel(e,t,n,s,i){const o=null,a=null;return this.runKernelFunc(o,t,a,e,n,s,i)}shouldCheckForMemLeaks(){return this.ENV.getBool("IS_TEST")}checkKernelForMemLeak(e,t,n){const s=this.backend.numDataIds();let i=0;n.forEach(c=>{i+=c.dtype==="complex64"?3:1});const o=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],a=s-t-i-o;if(a>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${a} data ids) after running '${e}'`)}runKernelFunc(e,t,n,s,i,o,a){let c,h=[];const p=this.isTapeOn();s==null&&(s=this.state.activeScope!=null?this.state.activeScope.name:"");const m=this.state.numBytes,y=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);let b;const w=Ky(s,this.backendName);let L;if(w!=null)b=()=>{const v=this.backend.numDataIds();L=w.kernelFunc({inputs:t,attrs:i,backend:this.backend});const C=Array.isArray(L)?L:[L];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(s,v,C);const O=C.map(({dataId:D,shape:k,dtype:F})=>this.makeTensorFromDataId(D,k,F));if(p){let D=this.getTensorsForGradient(s,t,O);if(D==null){a==null&&(a=[]);const k=O.filter((F,B)=>a[B]);D=(o||[]).slice().concat(k)}h=this.saveTensorsForBackwardMode(D)}return O};else{const v=C=>{if(!p)return;h=C.map(O=>this.keep(this.clone(O)))};b=()=>{const C=this.backend.numDataIds();L=this.tidy(()=>e(this.backend,v));const O=Array.isArray(L)?L:[L];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(s,C,O),O}}let T;return this.scopedRun(()=>this.state.kernelDepth++,()=>this.state.kernelDepth--,()=>{!this.ENV.getBool("DEBUG")&&!this.state.profiling?c=b():(T=this.profiler.profileKernel(s,t,()=>b()),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(T),c=T.outputs)}),p&&this.addTapeNode(s,t,c,n,h,i),this.state.profiling&&this.state.activeProfile.kernels.push({name:s,bytesAdded:this.state.numBytes-m,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-y,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(t).map(v=>t[v]!=null?t[v].shape:null),outputShapes:c.map(v=>v.shape),kernelTimeMs:T.timeMs,extraInfo:T.extraInfo}),Array.isArray(L)?c:c[0]}saveTensorsForBackwardMode(e){const t=e.map(n=>this.keep(this.clone(n)));return t}getTensorsForGradient(e,t,n){const s=Xy(e);if(s!=null){const i=s.inputsToSave||[],o=s.outputsToSave||[];let a;s.saveAllInputs?(A(Array.isArray(t),()=>"saveAllInputs is true, expected inputs to be an array."),a=Object.keys(t).map(h=>t[h])):a=i.map(h=>t[h]);const c=n.filter((h,p)=>o[p]);return a.concat(c)}return null}makeTensor(e,t,n,s){if(e==null)throw new Error("Values passed to engine.makeTensor() are null");n=n||"float32",s=s||this.backend;let i=e;n==="string"&&Ji(e[0])&&(i=e.map(c=>ep(c)));const o=s.write(i,t,n),a=new te(t,n,o,this.nextTensorId());if(this.incRef(a,s),n==="string"){const c=this.state.tensorInfo.get(o),h=Xx(i);this.state.numBytes+=h-c.bytes,c.bytes=h}return a}makeTensorFromDataId(e,t,n,s){n=n||"float32";const i=new te(t,n,e,this.nextTensorId());return this.incRef(i,s),i}makeVariable(e,t=!0,n,s){n=n||this.nextVariableId().toString(),s!=null&&s!==e.dtype&&(e=e.cast(s));const i=new ph(e,t,n,this.nextTensorId());if(this.state.registeredVariables[i.name]!=null)throw new Error(`Variable with name ${i.name} was already registered`);return this.state.registeredVariables[i.name]=i,this.incRef(i,this.backend),i}incRef(e,t){const n=this.state.tensorInfo.has(e.dataId)?this.state.tensorInfo.get(e.dataId).refCount:0;if(this.state.numTensors++,e.dtype==="string"&&this.state.numStringTensors++,n===0){this.state.numDataBuffers++;let s=0;e.dtype!=="complex64"&&e.dtype!=="string"&&(s=e.size*iy(e.dtype)),this.state.tensorInfo.set(e.dataId,{backend:t||this.backend,dtype:e.dtype,shape:e.shape,bytes:s,refCount:0}),this.state.numBytes+=s}this.state.tensorInfo.get(e.dataId).refCount++,e instanceof ph||this.track(e)}disposeTensor(e){if(!this.state.tensorInfo.has(e.dataId))return;this.state.numTensors--,e.dtype==="string"&&this.state.numStringTensors--;const t=this.state.tensorInfo.get(e.dataId),n=t.refCount;n<=1?(e.dtype!=="complex64"&&(this.state.numBytes-=t.bytes),this.state.numDataBuffers--,t.backend.disposeData(e.dataId),this.state.tensorInfo.delete(e.dataId)):this.state.tensorInfo.get(e.dataId).refCount--}disposeVariables(){for(const e in this.state.registeredVariables){const t=this.state.registeredVariables[e];this.disposeVariable(t)}}disposeVariable(e){this.disposeTensor(e),this.state.registeredVariables[e.name]!=null&&delete this.state.registeredVariables[e.name]}memory(){const e=this.backend.memory();return e.numTensors=this.state.numTensors,e.numDataBuffers=this.state.numDataBuffers,e.numBytes=this.state.numBytes,this.state.numStringTensors>0&&(e.unreliable=!0,e.reasons==null&&(e.reasons=[]),e.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),e}async profile(e){this.state.profiling=!0;const t=this.state.numBytes,n=this.state.numTensors;this.state.activeProfile.kernels=[],this.state.activeProfile.result=await e(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max(...this.state.activeProfile.kernels.map(s=>s.totalBytesSnapshot)),this.state.activeProfile.newBytes=this.state.numBytes-t,this.state.activeProfile.newTensors=this.state.numTensors-n;for(const s of this.state.activeProfile.kernels)s.kernelTimeMs=await s.kernelTimeMs,s.extraInfo=await s.extraInfo;return this.state.activeProfile}isTapeOn(){return this.state.gradientDepth>0&&this.state.kernelDepth===0}addTapeNode(e,t,n,s,i,o){const a={id:this.state.nextTapeNodeId++,kernelName:e,inputs:t,outputs:n,saved:i},c=Xy(e);c!=null&&(s=c.gradFunc),s!=null&&(a.gradient=h=>(h=h.map((p,m)=>{if(p==null){const y=n[m],b=Da(y.size,y.dtype);return this.makeTensor(b,y.shape,y.dtype)}return p}),s(h.length>1?h:h[0],i,o))),this.state.activeTape.push(a)}keep(e){return e.kept=!0,e}startTape(){this.state.gradientDepth===0&&(this.state.activeTape=[]),this.state.gradientDepth++}endTape(){this.state.gradientDepth--}startScope(e){const t={track:[],name:"unnamed scope",id:this.state.nextScopeId++};e&&(t.name=e),this.state.scopeStack.push(t),this.state.activeScope=t}endScope(e){const t=Zi(e),n=new Set(t.map(i=>i.id));for(let i=0;i<this.state.activeScope.track.length;i++){const o=this.state.activeScope.track[i];!o.kept&&!n.has(o.id)&&o.dispose()}const s=this.state.scopeStack.pop();this.state.activeScope=this.state.scopeStack.length===0?null:this.state.scopeStack[this.state.scopeStack.length-1],t.forEach(i=>{!i.kept&&i.scopeId===s.id&&this.track(i)})}gradients(e,t,n,s=!1){if(A(t.length>0,()=>"gradients() received an empty list of xs."),n!=null&&n.dtype!=="float32")throw new Error(`dy must have 'float32' dtype, but has '${n.dtype}'`);const i=this.scopedRun(()=>this.startTape(),()=>this.endTape(),()=>this.tidy("forward",e));A(i instanceof te,()=>"The result y returned by f() must be a tensor.");const o=Uk(this.state.activeTape,t,i);if(!s&&o.length===0&&t.length>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.");return this.tidy("backward",()=>{const a={};a[i.id]=n==null?jk(i.shape):n,Bk(a,o,h=>this.tidy(h),Kk);const c=t.map(h=>a[h.id]);return this.state.gradientDepth===0&&(this.state.activeTape.forEach(h=>{for(const p of h.saved)p.dispose()}),this.state.activeTape=null),{value:i,grads:c}})}customGrad(e){return A($r(e),()=>"The f passed in customGrad(f) must be a function."),(...t)=>{A(t.every(i=>i instanceof te),()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors");let n;const s={};return t.forEach((i,o)=>{s[o]=i}),this.runKernelFunc((i,o)=>(n=e(...t,o),A(n.value instanceof te,()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),A($r(n.gradFunc),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."),n.value),s,(i,o)=>{const a=n.gradFunc(i,o),c=Array.isArray(a)?a:[a];A(c.length===t.length,()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns the same number of tensors as inputs passed to f(...)."),A(c.every(p=>p instanceof te),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors.");const h={};return c.forEach((p,m)=>{h[m]=()=>p}),h})}}readSync(e){const t=this.state.tensorInfo.get(e);return t.backend.readSync(e)}read(e){const t=this.state.tensorInfo.get(e);return t.backend.read(e)}async time(e){const t=Jn(),n=await this.backend.time(e);return n.wallMs=Jn()-t,n}track(e){return this.state.activeScope!=null&&(e.scopeId=this.state.activeScope.id,this.state.activeScope.track.push(e)),e}get registeredVariables(){return this.state.registeredVariables}reset(){this.pendingBackendInitId++,this.state.dispose(),this.ENV.reset(),this.state=new WT;for(const e in this.registry)this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e];this.backendName=null,this.backendInstance=null,this.pendingBackendInit=null}}mh.nextTensorId=0,mh.nextVariableId=0;function jk(e){const t=ry(M(e),"float32");return G.makeTensor(t,e,"float32")}function $T(){const e=tT();if(e._tfengine==null){const t=new eT(e);e._tfengine=new mh(t)}return Nk(e._tfengine.ENV),zk(()=>e._tfengine),e._tfengine}const G=$T();function Kk(e,t){const n={a:e,b:t};return G.runKernelFunc((s,i)=>{const o=s.add(e,t);return i([e,t]),o},n,null,Oo)}function Xk(){return typeof navigator!="undefined"&&navigator!=null}function UT(){if(Xk()){const e=navigator.userAgent||navigator.vendor||window.opera;return/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(e)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(e.substr(0,4))}return!1}function sb(){return typeof window!="undefined"&&window.document!=null||typeof WorkerGlobalScope!="undefined"}var Jk=Object.freeze({__proto__:null,isMobile:UT,isBrowser:sb});const Qi=ae();Qi.registerFlag("DEBUG",()=>!1,e=>{e&&console.warn("Debugging mode is ON. The output of every math call will be downloaded to CPU and checked for NaNs. This significantly impacts performance.")}),Qi.registerFlag("IS_BROWSER",()=>sb()),Qi.registerFlag("IS_NODE",()=>typeof process!="undefined"&&typeof process.versions!="undefined"&&typeof process.versions.node!="undefined"),Qi.registerFlag("IS_CHROME",()=>typeof navigator!="undefined"&&navigator!=null&&navigator.userAgent!=null&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor)),Qi.registerFlag("PROD",()=>!1),Qi.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",()=>Qi.getBool("DEBUG")),Qi.registerFlag("DEPRECATION_WARNINGS_ENABLED",()=>!0),Qi.registerFlag("IS_TEST",()=>!1);function Ni(e,t){let n=e;if(un(e))return t==="string"?[]:[e.length];if(!Array.isArray(e))return[];const s=[];for(;Array.isArray(n)||un(n)&&t!=="string";)s.push(n.length),n=n[0];return Array.isArray(e)&&ae().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&BT(e,s,[]),s}function BT(e,t,n){if(n=n||[],!Array.isArray(e)&&!un(e)){A(t.length===0,()=>`Element arr[${n.join("][")}] is a primitive, but should be an array/TypedArray of ${t[0]} elements`);return}A(t.length>0,()=>`Element arr[${n.join("][")}] should be a primitive, but is an array of ${e.length} elements`),A(e.length===t[0],()=>`Element arr[${n.join("][")}] should have ${t[0]} elements, but has ${e.length} elements`);const s=t.slice(1);for(let i=0;i<e.length;++i)BT(e[i],s,n.concat(i))}function MT(e,t,n,s){if(e==null)return;if(e!=="numeric"&&e!==t||e==="numeric"&&t==="string")throw new Error(`Argument '${n}' passed to '${s}' must be ${e} tensor, but got ${t} tensor`)}function W(e,t,n,s="numeric"){if(e instanceof te)return MT(s,e.dtype,t,n),e;let i=Ea(e);if(i!=="string"&&["bool","int32","float32"].indexOf(s)>=0&&(i=s),MT(s,i,t,n),e==null||!un(e)&&!Array.isArray(e)&&typeof e!="number"&&typeof e!="boolean"&&typeof e!="string"){const h=e==null?"null":e.constructor.name;throw new Error(`Argument '${t}' passed to '${n}' must be a Tensor or TensorLike, but got '${h}'`)}const o=Ni(e,i);!un(e)&&!Array.isArray(e)&&(e=[e]);const a=!0,c=i!=="string"?Ur(e,i):Q(e,[],a);return G.makeTensor(c,o,i)}function fh(e,t,n,s="numeric"){if(!Array.isArray(e))throw new Error(`Argument ${t} passed to ${n} must be a \`Tensor[]\` or \`TensorLike[]\``);const i=e;return i.map((o,a)=>W(o,`${t}[${a}]`,n),s)}const PT="__op";function z(e){const t=Object.keys(e);if(t.length!==1)throw new Error(`Please provide an object with a single key (operation name) mapping to a function. Got an object with ${t.length} keys.`);let n=t[0];const s=e[n];n.endsWith("_")&&(n=n.substring(0,n.length-1)),n=n+PT;const i=(...o)=>{G.startScope(n);try{const a=s(...o);return Ro(a)&&console.error("Cannot return a Promise inside of tidy."),G.endScope(a),a}catch(a){throw G.endScope(null),a}};return Object.defineProperty(i,"name",{value:n,configurable:!0}),i}function Zk(e,t){const n=W(e,"real","complex"),s=W(t,"imag","complex");U(n.shape,s.shape,`real and imag shapes, ${n.shape} and ${s.shape}, must match in call to tf.complex().`);const i=a=>a.complex(n,s),o={real:n,imag:s};return G.runKernelFunc(i,o,null,xd)}const er=z({complex_:Zk});function Br(e,t,n,s){if(s==null&&(s=Ea(e)),s==="complex64")throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!un(e)&&!Array.isArray(e)&&typeof e!="number"&&typeof e!="boolean"&&typeof e!="string")throw new Error("values passed to tensor(values) must be a number/boolean/string or an array of numbers/booleans/strings, or a TypedArray");if(t!=null){ay(t);const i=M(t),o=M(n);A(i===o,()=>`Based on the provided shape, [${t}], the tensor should have ${i} values but has ${o}`);for(let a=0;a<n.length;++a){const c=n[a],h=a===n.length-1?c!==M(t.slice(a)):!0;A(n[a]===t[a]||!h,()=>`Error creating a new Tensor. Inferred shape (${n}) does not match the provided shape (${t}). `)}}return!un(e)&&!Array.isArray(e)&&(e=[e]),t=t||n,e=s!=="string"?Ur(e,s):Q(e,[],!0),G.makeTensor(e,t,s)}function sn(e,t,n){const s=Ni(e,n);return Br(e,t,s,n)}const ib={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8};const ip=4;async function rb(e,t){const n=[],s=[],i=Array.isArray(e)?e.map(a=>a.name):Object.keys(e);for(let a=0;a<i.length;++a){const c=i[a],h=Array.isArray(e)?e[a].tensor:e[c];if(h.dtype!=="float32"&&h.dtype!=="int32"&&h.dtype!=="bool"&&h.dtype!=="string"&&h.dtype!=="complex64")throw new Error(`Unsupported dtype in weight '${c}': ${h.dtype}`);const p={name:c,shape:h.shape,dtype:h.dtype};if(h.dtype==="string"){const m=new Promise(async y=>{const b=await h.bytes(),w=b.reduce((v,C)=>v+C.length,0)+ip*b.length,L=new Uint8Array(w);let T=0;for(let v=0;v<b.length;v++){const C=b[v],O=new Uint8Array(new Uint32Array([C.length]).buffer);L.set(O,T),T+=ip,L.set(C,T),T+=C.length}y(L)});s.push(m)}else s.push(h.data());t!=null&&(p.group=t),n.push(p)}const o=await Promise.all(s);return{data:Qk(o),specs:n}}function rp(e,t){const n={};let s,i=0;for(const o of t){const a=o.name,c=o.dtype,h=o.shape,p=M(h);let m;if("quantization"in o){const y=o.quantization;if(y.dtype==="uint8"||y.dtype==="uint16"){if(!("min"in y&&"scale"in y))throw new Error(`Weight ${o.name} with quantization ${y.dtype} doesn't have corresponding metadata min and scale.`)}else if(y.dtype==="float16"){if(c!=="float32")throw new Error(`Weight ${o.name} is quantized with ${y.dtype} which only supports weights of type float32 not ${c}.`)}else throw new Error(`Weight ${o.name} has unknown quantization dtype ${y.dtype}. Supported quantization dtypes are: 'uint8', 'uint16', and 'float16'.`);const b=ib[y.dtype],w=e.slice(i,i+p*b),L=y.dtype==="uint8"?new Uint8Array(w):new Uint16Array(w);if(c==="float32")if(y.dtype==="uint8"||y.dtype==="uint16"){m=new Float32Array(L.length);for(let T=0;T<L.length;T++){const v=L[T];m[T]=v*y.scale+y.min}}else if(y.dtype==="float16")s===void 0&&(s=rF()),m=s(L);else throw new Error(`Unsupported quantization type ${y.dtype} for weight type float32.`);else if(c==="int32"){if(y.dtype!=="uint8"&&y.dtype!=="uint16")throw new Error(`Unsupported quantization type ${y.dtype} for weight type int32.`);m=new Int32Array(L.length);for(let T=0;T<L.length;T++){const v=L[T];m[T]=Math.round(v*y.scale+y.min)}}else throw new Error(`Unsupported dtype in weight '${a}': ${c}`);i+=p*b}else if(c==="string"){const y=M(o.shape);m=[];for(let b=0;b<y;b++){const w=new Uint32Array(e.slice(i,i+ip))[0];i+=ip;const L=new Uint8Array(e.slice(i,i+w));m.push(L),i+=w}}else{const y=ib[c],b=e.slice(i,i+p*y);if(c==="float32")m=new Float32Array(b);else if(c==="int32")m=new Int32Array(b);else if(c==="bool")m=new Uint8Array(b);else if(c==="complex64"){m=new Float32Array(b);const w=new Float32Array(m.length/2),L=new Float32Array(m.length/2);for(let C=0;C<w.length;C++)w[C]=m[C*2],L[C]=m[C*2+1];const T=sn(w,h,"float32"),v=sn(L,h,"float32");n[a]=er(T,v),T.dispose(),v.dispose()}else throw new Error(`Unsupported dtype in weight '${a}': ${c}`);i+=p*y}c!=="complex64"&&(n[a]=sn(m,h,c))}return n}function Qk(e){if(e===null)throw new Error(`Invalid input value: ${JSON.stringify(e)}`);let t=0;const n=[];e.forEach(o=>{if(t+=o.byteLength,n.push(o.byteLength===o.buffer.byteLength?o:new o.constructor(o)),!(o instanceof Float32Array||o instanceof Int32Array||o instanceof Uint8Array))throw new Error(`Unsupported TypedArray subtype: ${o.constructor.name}`)});const s=new Uint8Array(t);let i=0;return n.forEach(o=>{s.set(new Uint8Array(o.buffer),i),i+=o.byteLength}),s.buffer}const ob=typeof Buffer!="undefined"&&(typeof Blob=="undefined"||typeof atob=="undefined"||typeof btoa=="undefined");function zT(e){return ob?Buffer.byteLength(e):new Blob([e]).size}function eF(e){if(ob)return Buffer.from(e).toString("base64");const t=new Uint8Array(e);let n="";for(let s=0,i=t.length;s<i;s++)n+=String.fromCharCode(t[s]);return btoa(n)}function tF(e){if(ob){const s=Buffer.from(e,"base64");return s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength)}const t=atob(e),n=new Uint8Array(t.length);for(let s=0;s<t.length;++s)n.set([t.charCodeAt(s)],s);return n.buffer}function op(e){if(e.length===1)return e[0];let t=0;e.forEach(i=>{t+=i.byteLength});const n=new Uint8Array(t);let s=0;return e.forEach(i=>{n.set(new Uint8Array(i),s),s+=i.byteLength}),n.buffer}function VT(e){const t="/";for(e=e.trim();e.endsWith(t);)e=e.slice(0,e.length-1);const n=e.split(t);return n[n.length-1]}function gh(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("Expected JSON model topology, received ArrayBuffer.");return{dateSaved:new Date,modelTopologyType:"JSON",modelTopologyBytes:e.modelTopology==null?0:zT(JSON.stringify(e.modelTopology)),weightSpecsBytes:e.weightSpecs==null?0:zT(JSON.stringify(e.weightSpecs)),weightDataBytes:e.weightData==null?0:e.weightData.byteLength}}function nF(){const e=n=>{let s=n<<13,i=0;for(;(s&8388608)===0;)i-=8388608,s<<=1;return s&=~8388608,i+=947912704,s|i},t=new Uint32Array(2048);t[0]=0;for(let n=1;n<1024;n++)t[n]=e(n);for(let n=1024;n<2048;n++)t[n]=939524096+(n-1024<<13);return t}function sF(){const e=new Uint32Array(64);e[0]=0,e[31]=1199570944,e[32]=2147483648,e[63]=3347054592;for(let t=1;t<31;t++)e[t]=t<<23;for(let t=33;t<63;t++)e[t]=2147483648+(t-32<<23);return e}function iF(){const e=new Uint32Array(64);for(let t=0;t<64;t++)e[t]=1024;return e[0]=e[32]=0,e}function rF(){const e=nF(),t=sF(),n=iF();return s=>{const i=new ArrayBuffer(4*s.length),o=new Uint32Array(i);for(let a=0;a<s.length;a++){const c=s[a],h=e[n[c>>10]+(c&1023)]+t[c>>10];o[a]=h}return new Float32Array(i)}}class en{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return en.instance==null&&(en.instance=new en),en.instance}static registerSaveRouter(e){en.getInstance().saveRouters.push(e)}static registerLoadRouter(e){en.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return en.getHandlers(e,"save")}static getLoadHandlers(e,t){return en.getHandlers(e,"load",t)}static getHandlers(e,t,n){const s=[],i=t==="load"?en.getInstance().loadRouters:en.getInstance().saveRouters;return i.forEach(o=>{const a=o(e,n);a!==null&&s.push(a)}),s}}const oF=e=>en.registerSaveRouter(e),aF=e=>en.registerLoadRouter(e),ab=e=>en.getSaveHandlers(e),cb=(e,t)=>en.getLoadHandlers(e,t);const ap="tensorflowjs",lb=1,Eo="models_store",Mr="model_info_store";async function dte(){const e=hb();return new Promise((t,n)=>{const s=e.deleteDatabase(ap);s.onsuccess=()=>t(),s.onerror=i=>n(i)})}function hb(){if(!ae().getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");const e=typeof window=="undefined"?self:window,t=e.indexedDB||e.mozIndexedDB||e.webkitIndexedDB||e.msIndexedDB||e.shimIndexedDB;if(t==null)throw new Error("The current browser does not appear to support IndexedDB.");return t}function ub(e){const t=e.result;t.createObjectStore(Eo,{keyPath:"modelPath"}),t.createObjectStore(Mr,{keyPath:"modelPath"})}class Do{constructor(e){if(this.indexedDB=hb(),e==null||!e)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=e}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");return this.databaseAction(this.modelPath,e)}async load(){return this.databaseAction(this.modelPath)}databaseAction(e,t){return new Promise((n,s)=>{const i=this.indexedDB.open(ap,lb);i.onupgradeneeded=()=>ub(i),i.onsuccess=()=>{const o=i.result;if(t==null){const a=o.transaction(Eo,"readonly"),c=a.objectStore(Eo),h=c.get(this.modelPath);h.onsuccess=()=>{if(h.result==null)return o.close(),s(new Error(`Cannot find model with path '${this.modelPath}' in IndexedDB.`));n(h.result.modelArtifacts)},h.onerror=p=>(o.close(),s(h.error)),a.oncomplete=()=>o.close()}else{const a=gh(t),c=o.transaction(Mr,"readwrite");let h=c.objectStore(Mr);const p=h.put({modelPath:this.modelPath,modelArtifactsInfo:a});let m;p.onsuccess=()=>{m=o.transaction(Eo,"readwrite");const y=m.objectStore(Eo),b=y.put({modelPath:this.modelPath,modelArtifacts:t,modelArtifactsInfo:a});b.onsuccess=()=>n({modelArtifactsInfo:a}),b.onerror=w=>{h=c.objectStore(Mr);const L=h.delete(this.modelPath);L.onsuccess=()=>(o.close(),s(b.error)),L.onerror=T=>(o.close(),s(b.error))}},p.onerror=y=>(o.close(),s(p.error)),c.oncomplete=()=>{m==null?o.close():m.oncomplete=()=>o.close()}}},i.onerror=o=>s(i.error)})}}Do.URL_SCHEME="indexeddb://";const GT=e=>ae().getBool("IS_BROWSER")&&(!Array.isArray(e)&&e.startsWith(Do.URL_SCHEME))?cF(e.slice(Do.URL_SCHEME.length)):null;en.registerSaveRouter(GT),en.registerLoadRouter(GT);function cF(e){return new Do(e)}function lF(e){return e.startsWith(Do.URL_SCHEME)?e.slice(Do.URL_SCHEME.length):e}class hF{constructor(){this.indexedDB=hb()}async listModels(){return new Promise((e,t)=>{const n=this.indexedDB.open(ap,lb);n.onupgradeneeded=()=>ub(n),n.onsuccess=()=>{const s=n.result,i=s.transaction(Mr,"readonly"),o=i.objectStore(Mr),a=o.getAll();a.onsuccess=()=>{const c={};for(const h of a.result)c[h.modelPath]=h.modelArtifactsInfo;e(c)},a.onerror=c=>(s.close(),t(a.error)),i.oncomplete=()=>s.close()},n.onerror=s=>t(n.error)})}async removeModel(e){return e=lF(e),new Promise((t,n)=>{const s=this.indexedDB.open(ap,lb);s.onupgradeneeded=()=>ub(s),s.onsuccess=()=>{const i=s.result,o=i.transaction(Mr,"readwrite"),a=o.objectStore(Mr),c=a.get(e);let h;c.onsuccess=()=>{if(c.result==null)return i.close(),n(new Error(`Cannot find model with path '${e}' in IndexedDB.`));{const p=a.delete(e),m=()=>{h=i.transaction(Eo,"readwrite");const y=h.objectStore(Eo),b=y.delete(e);b.onsuccess=()=>t(c.result.modelArtifactsInfo),b.onerror=w=>n(c.error)};p.onsuccess=m,p.onerror=y=>(m(),i.close(),n(c.error))}},c.onerror=p=>(i.close(),n(c.error)),o.oncomplete=()=>{h==null?i.close():h.oncomplete=()=>i.close()}},s.onerror=i=>n(s.error)})}}const Ci="/",ko="tensorflowjs_models",YT="info",uF="model_topology",dF="weight_specs",pF="weight_data",mF="model_metadata";function pte(){if(!ae().getBool("IS_BROWSER")||typeof window=="undefined"||typeof window.localStorage=="undefined")throw new Error("purgeLocalStorageModels() cannot proceed because local storage is unavailable in the current environment.");const e=window.localStorage,t=[];for(let n=0;n<e.length;++n){const s=e.key(n),i=ko+Ci;if(s.startsWith(i)&&s.length>i.length){e.removeItem(s);const o=qT(s);t.indexOf(o)===-1&&t.push(o)}}return t}function HT(e){return{info:[ko,e,YT].join(Ci),topology:[ko,e,uF].join(Ci),weightSpecs:[ko,e,dF].join(Ci),weightData:[ko,e,pF].join(Ci),modelMetadata:[ko,e,mF].join(Ci)}}function qT(e){const t=e.split(Ci);if(t.length<3)throw new Error(`Invalid key format: ${e}`);return t.slice(1,t.length-1).join(Ci)}function fF(e){return e.startsWith(Fo.URL_SCHEME)?e.slice(Fo.URL_SCHEME.length):e}class Fo{constructor(e){if(!ae().getBool("IS_BROWSER")||typeof window=="undefined"||typeof window.localStorage=="undefined")throw new Error("The current environment does not support local storage.");if(this.LS=window.localStorage,e==null||!e)throw new Error("For local storage, modelPath must not be null, undefined or empty.");this.modelPath=e,this.keys=HT(this.modelPath)}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");{const t=JSON.stringify(e.modelTopology),n=JSON.stringify(e.weightSpecs),s=gh(e);try{return this.LS.setItem(this.keys.info,JSON.stringify(s)),this.LS.setItem(this.keys.topology,t),this.LS.setItem(this.keys.weightSpecs,n),this.LS.setItem(this.keys.weightData,eF(e.weightData)),this.LS.setItem(this.keys.modelMetadata,JSON.stringify({format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,userDefinedMetadata:e.userDefinedMetadata})),{modelArtifactsInfo:s}}catch(i){throw this.LS.removeItem(this.keys.info),this.LS.removeItem(this.keys.topology),this.LS.removeItem(this.keys.weightSpecs),this.LS.removeItem(this.keys.weightData),this.LS.removeItem(this.keys.modelMetadata),new Error(`Failed to save model '${this.modelPath}' to local storage: size quota being exceeded is a possible cause of this failure: modelTopologyBytes=${s.modelTopologyBytes}, weightSpecsBytes=${s.weightSpecsBytes}, weightDataBytes=${s.weightDataBytes}.`)}}}async load(){const e=JSON.parse(this.LS.getItem(this.keys.info));if(e==null)throw new Error(`In local storage, there is no model with name '${this.modelPath}'`);if(e.modelTopologyType!=="JSON")throw new Error("BrowserLocalStorage does not support loading non-JSON model topology yet.");const t={},n=JSON.parse(this.LS.getItem(this.keys.topology));if(n==null)throw new Error(`In local storage, the topology of model '${this.modelPath}' is missing.`);t.modelTopology=n;const s=JSON.parse(this.LS.getItem(this.keys.weightSpecs));if(s==null)throw new Error(`In local storage, the weight specs of model '${this.modelPath}' are missing.`);t.weightSpecs=s;const i=this.LS.getItem(this.keys.modelMetadata);if(i!=null){const a=JSON.parse(i);t.format=a.format,t.generatedBy=a.generatedBy,t.convertedBy=a.convertedBy,t.userDefinedMetadata=a.userDefinedMetadata}const o=this.LS.getItem(this.keys.weightData);if(o==null)throw new Error(`In local storage, the binary weight values of model '${this.modelPath}' are missing.`);return t.weightData=tF(o),t}}Fo.URL_SCHEME="localstorage://";const jT=e=>ae().getBool("IS_BROWSER")&&(!Array.isArray(e)&&e.startsWith(Fo.URL_SCHEME))?gF(e.slice(Fo.URL_SCHEME.length)):null;en.registerSaveRouter(jT),en.registerLoadRouter(jT);function gF(e){return new Fo(e)}class yF{constructor(){A(ae().getBool("IS_BROWSER"),()=>"Current environment is not a web browser"),A(typeof window=="undefined"||typeof window.localStorage!="undefined",()=>"Current browser does not appear to support localStorage"),this.LS=window.localStorage}async listModels(){const e={},t=ko+Ci,n=Ci+YT;for(let s=0;s<this.LS.length;++s){const i=this.LS.key(s);if(i.startsWith(t)&&i.endsWith(n)){const o=qT(i);e[o]=JSON.parse(this.LS.getItem(i))}}return e}async removeModel(e){e=fF(e);const t=HT(e);if(this.LS.getItem(t.info)==null)throw new Error(`Cannot find model at path '${e}'`);const n=JSON.parse(this.LS.getItem(t.info));return this.LS.removeItem(t.info),this.LS.removeItem(t.topology),this.LS.removeItem(t.weightSpecs),this.LS.removeItem(t.weightData),n}}const Va="://";class Ts{constructor(){this.managers={}}static getInstance(){return Ts.instance==null&&(Ts.instance=new Ts),Ts.instance}static registerManager(e,t){A(e!=null,()=>"scheme must not be undefined or null."),e.endsWith(Va)&&(e=e.slice(0,e.indexOf(Va))),A(e.length>0,()=>"scheme must not be an empty string.");const n=Ts.getInstance();A(n.managers[e]==null,()=>`A model store manager is already registered for scheme '${e}'.`),n.managers[e]=t}static getManager(e){const t=this.getInstance().managers[e];if(t==null)throw new Error(`Cannot find model manager for scheme '${e}'`);return t}static getSchemes(){return Object.keys(this.getInstance().managers)}}function cp(e){if(e.indexOf(Va)===-1)throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${Ts.getSchemes().join(",")}`);return{scheme:e.split(Va)[0],path:e.split(Va)[1]}}async function KT(e,t,n=!1){A(e!==t,()=>`Old path and new path are the same: '${e}'`);const s=en.getLoadHandlers(e);A(s.length>0,()=>`Copying failed because no load handler is found for source URL ${e}.`),A(s.length<2,()=>`Copying failed because more than one (${s.length}) load handlers for source URL ${e}.`);const i=s[0],o=en.getSaveHandlers(t);A(o.length>0,()=>`Copying failed because no save handler is found for destination URL ${t}.`),A(o.length<2,()=>`Copying failed because more than one (${s.length}) save handlers for destination URL ${t}.`);const a=o[0],c=cp(e).scheme,h=cp(e).path,p=c===cp(e).scheme,m=await i.load();n&&p&&await Ts.getManager(c).removeModel(h);const y=await a.save(m);return n&&!p&&await Ts.getManager(c).removeModel(h),y.modelArtifactsInfo}async function bF(){const e=Ts.getSchemes(),t={};for(const n of e){const s=await Ts.getManager(n).listModels();for(const i in s){const o=n+Va+i;t[o]=s[i]}}return t}async function wF(e){const t=cp(e),n=Ts.getManager(t.scheme);return n.removeModel(t.path)}async function LF(e,t){const n=!1;return KT(e,t,n)}async function SF(e,t){const n=!0;return KT(e,t,n)}class IF{fetch(e,t){return fetch(e,t)}now(){return performance.now()}encode(e,t){if(t!=="utf-8"&&t!=="utf8")throw new Error(`Browser's encoder only supports utf-8, but got ${t}`);return this.textEncoder==null&&(this.textEncoder=new TextEncoder),this.textEncoder.encode(e)}decode(e,t){return new TextDecoder(t).decode(e)}}if(ae().get("IS_BROWSER")){ae().setPlatform("browser",new IF);try{Ts.registerManager(Fo.URL_SCHEME,new yF)}catch(e){}try{Ts.registerManager(Do.URL_SCHEME,new hF)}catch(e){}}const xF={importFetch:()=>F2()};let Ga;function mte(){Ga=null}function fte(e){Ga=e}function gte(){return Ga}class TF{constructor(){this.util=require("util"),this.textEncoder=new this.util.TextEncoder}fetch(e,t){return ae().global.fetch!=null?ae().global.fetch(e,t):(Ga==null&&(Ga=xF.importFetch()),Ga(e,t))}now(){const e=process.hrtime();return e[0]*1e3+e[1]/1e6}encode(e,t){if(t!=="utf-8"&&t!=="utf8")throw new Error(`Node built-in encoder only supports utf-8, but got ${t}`);return this.textEncoder.encode(e)}decode(e,t){return e.length===0?"":new this.util.TextDecoder(t).decode(e)}}ae().get("IS_NODE")&&ae().setPlatform("node",new TF);function wt(e,t="float32",n){return t=t||"float32",ay(e),new an(e,t,n)}function AF(e,t){const n=W(e,"x","cast");if(!Wr(t))throw new Error(`Failed to cast to unknown dtype ${t}`);if(t==="string"&&n.dtype!=="string"||t!=="string"&&n.dtype==="string")throw new Error("Only strings can be casted to strings");const s={x:n},i={dtype:t};return G.runKernelFunc(o=>o.cast(n,t),s,null,ka,i)}const ve=z({cast_:AF});function vF(e){const t=W(e,"x","clone",null),n=()=>G.makeTensorFromDataId(t.dataId,t.shape,t.dtype),s={x:t};return G.runKernelFunc(n,s,null,$l)}const Pr=z({clone_:vF});function XT(e,t=!1){console.log(e.toString(t))}$T();const NF={buffer:wt,cast:ve,clone:Pr,print:XT};Vk(NF);const CF="model",RF=".json",OF=".weights.bin";function JT(e){return new Promise(t=>setTimeout(t)).then(e)}class Ya{constructor(e){if(!ae().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(Ya.URL_SCHEME)&&(e=e.slice(Ya.URL_SCHEME.length)),(e==null||e.length===0)&&(e=CF),this.modelTopologyFileName=e+RF,this.weightDataFileName=e+OF}async save(e){if(typeof document=="undefined")throw new Error("Browser downloads are not supported in this environment since `document` is not present");const t=window.URL.createObjectURL(new Blob([e.weightData],{type:"application/octet-stream"}));if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserDownloads.save() does not support saving model topology in binary formats yet.");{const n=[{paths:["./"+this.weightDataFileName],weights:e.weightSpecs}],s={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,weightsManifest:n},i=window.URL.createObjectURL(new Blob([JSON.stringify(s)],{type:"application/json"})),o=this.jsonAnchor==null?document.createElement("a"):this.jsonAnchor;if(o.download=this.modelTopologyFileName,o.href=i,await JT(()=>o.dispatchEvent(new MouseEvent("click"))),e.weightData!=null){const a=this.weightDataAnchor==null?document.createElement("a"):this.weightDataAnchor;a.download=this.weightDataFileName,a.href=t,await JT(()=>a.dispatchEvent(new MouseEvent("click")))}return{modelArtifactsInfo:gh(e)}}}}Ya.URL_SCHEME="downloads://";class EF{constructor(e){if(e==null||e.length<1)throw new Error(`When calling browserFiles, at least 1 file is required, but received ${e}`);this.files=e}async load(){const e=this.files[0],t=this.files.slice(1);return new Promise((n,s)=>{const i=new FileReader;i.onload=o=>{const a=JSON.parse(o.target.result),c=a.modelTopology;if(c==null){s(new Error(`modelTopology field is missing from file ${e.name}`));return}t.length===0&&n({modelTopology:c});const h=a.weightsManifest;if(h==null){s(new Error(`weightManifest field is missing from file ${e.name}`));return}let p;try{p=this.checkManifestAndWeightFiles(h,t)}catch(w){s(w);return}const m=[],y=[],b=[];h.forEach(w=>{w.paths.forEach(L=>{y.push(L),b.push(null)}),m.push(...w.weights)}),h.forEach(w=>{w.paths.forEach(L=>{const T=new FileReader;T.onload=v=>{const C=v.target.result,O=y.indexOf(L);b[O]=C,b.indexOf(null)===-1&&n({modelTopology:c,weightSpecs:m,weightData:op(b),format:a.format,generatedBy:a.generatedBy,convertedBy:a.convertedBy,userDefinedMetadata:a.userDefinedMetadata})},T.onerror=v=>s(`Failed to weights data from file of path '${L}'.`),T.readAsArrayBuffer(p[L])})})},i.onerror=o=>s(`Failed to read model topology and weights manifest JSON from file '${e.name}'. BrowserFiles supports loading Keras-style tf.Model artifacts only.`),i.readAsText(e)})}checkManifestAndWeightFiles(e,t){const n=[],s=t.map(o=>VT(o.name)),i={};for(const o of e)o.paths.forEach(a=>{const c=VT(a);if(n.indexOf(c)!==-1)throw new Error(`Duplicate file basename found in weights manifest: '${c}'`);if(n.push(c),s.indexOf(c)===-1)throw new Error(`Weight file with basename '${c}' is not provided.`);i[a]=t[s.indexOf(c)]});if(n.length!==t.length)throw new Error(`Mismatch in the number of files in weights manifest (${n.length}) and the number of weight files provided (${t.length}).`);return i}}const DF=e=>ae().getBool("IS_BROWSER")&&(!Array.isArray(e)&&e.startsWith(Ya.URL_SCHEME))?kF(e.slice(Ya.URL_SCHEME.length)):null;en.registerSaveRouter(DF);function kF(e="model"){return new Ya(e)}function FF(e){return new EF(e)}function ZT(e,t,n,s){a(e),n=n==null?0:n,s=s==null?1:s,c(n,s);let i=0;const o=h=>(h.then(p=>{const m=n+ ++i/e.length*(s-n);return t(m),p}),h);function a(h){A(h!=null&&Array.isArray(h)&&h.length>0,()=>"promises must be a none empty array")}function c(h,p){A(h>=0&&h<=1,()=>`Progress fraction must be in range [0, 1], but got startFraction ${h}`),A(p>=0&&p<=1,()=>`Progress fraction must be in range [0, 1], but got endFraction ${p}`),A(p>=h,()=>`startFraction must be no more than endFraction, but got startFraction ${h} and endFraction ${p}`)}return Promise.all(e.map(o))}async function QT(e,t){t==null&&(t={});const n=t.fetchFunc==null?ae().platform.fetch:t.fetchFunc,s=e.map(y=>n(y,t.requestInit,{isBinary:!0})),i=0,o=.5,a=t.onProgress==null?await Promise.all(s):await ZT(s,t.onProgress,i,o),c=a.map(y=>y.arrayBuffer()),h=.5,p=1,m=t.onProgress==null?await Promise.all(c):await ZT(c,t.onProgress,h,p);return m}async function eA(e,t="",n,s){const i=a=>QT(a,{requestInit:s}),o=tA(i);return o(e,t,n)}function tA(e){return async(t,n="",s)=>{const i=t.map(()=>!1),o={},a=s!=null?s.map(()=>!1):[],c=[];if(t.forEach((w,L)=>{let T=0;w.weights.forEach(v=>{const C="quantization"in v?v.quantization.dtype:v.dtype,O=ib[C]*M(v.shape),D=()=>{i[L]=!0,o[L]==null&&(o[L]=[]),o[L].push({manifestEntry:v,groupOffset:T,sizeBytes:O})};s!=null?s.forEach((k,F)=>{k===v.name&&(D(),a[F]=!0)}):D(),c.push(v.name),T+=O})}),!a.every(w=>w)){const w=s.filter((L,T)=>!a[T]);throw new Error(`Could not find weights in manifest with names: ${w.join(", ")}.
Manifest JSON has weights with names: ${c.join(", ")}.`)}const h=i.reduce((w,L,T)=>(L&&w.push(T),w),[]),p=[];h.forEach(w=>{t[w].paths.forEach(L=>{const T=n+(n.endsWith("/")?"":"/")+L;p.push(T)})});const m=await e(p),y={};let b=0;return h.forEach(w=>{const L=t[w].paths.length;let T=0;for(let k=0;k<L;k++)T+=m[b+k].byteLength;const v=new ArrayBuffer(T),C=new Uint8Array(v);let O=0;for(let k=0;k<L;k++){const F=new Uint8Array(m[b+k]);C.set(F,O),O+=F.byteLength}const D=o[w];D.forEach(k=>{const F=v.slice(k.groupOffset,k.groupOffset+k.sizeBytes),B=rp(F,[k.manifestEntry]);for(const $ in B)y[$]=B[$]}),b+=L}),y}}const _F="application/octet-stream",WF="application/json";class db{constructor(e,t){if(this.DEFAULT_METHOD="POST",t==null&&(t={}),this.weightPathPrefix=t.weightPathPrefix,this.onProgress=t.onProgress,this.weightUrlConverter=t.weightUrlConverter,t.fetchFunc!=null?(A(typeof t.fetchFunc=="function",()=>"Must pass a function that matches the signature of `fetch` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)"),this.fetch=t.fetchFunc):this.fetch=ae().platform.fetch,A(e!=null&&e.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(e)&&A(e.length===2,()=>`URL paths for http must have a length of 2, (actual length is ${e.length}).`),this.path=e,t.requestInit!=null&&t.requestInit.body!=null)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=t.requestInit||{}}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");const t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit);t.body=new FormData;const n=[{paths:["./model.weights.bin"],weights:e.weightSpecs}],s={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,userDefinedMetadata:e.userDefinedMetadata,weightsManifest:n};t.body.append("model.json",new Blob([JSON.stringify(s)],{type:WF}),"model.json"),e.weightData!=null&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:_F}),"model.weights.bin");const i=await this.fetch(this.path,t);if(i.ok)return{modelArtifactsInfo:gh(e),responses:[i]};throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${i.status}.`)}async load(){const e=await this.fetch(this.path,this.requestInit);if(!e.ok)throw new Error(`Request to ${this.path} failed with status code ${e.status}. Please verify this URL points to the model JSON of the model to load.`);let t;try{t=await e.json()}catch(b){let w=`Failed to parse model JSON of response from ${this.path}.`;throw this.path.endsWith(".pb")?w+=" Your path contains a .pb file extension. Support for .pb models have been removed in TensorFlow.js 1.0 in favor of .json models. You can re-convert your Python TensorFlow model using the TensorFlow.js 1.0 conversion scripts or you can convert your.pb models with the 'pb2json'NPM script in the tensorflow/tfjs-converter repository.":w+=" Please make sure the server is serving valid JSON for this request.",new Error(w)}const n=t.modelTopology,s=t.weightsManifest,i=t.generatedBy,o=t.convertedBy,a=t.format,c=t.userDefinedMetadata;if(n==null&&s==null)throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`);let h,p;if(s!=null){const b=await this.loadWeights(s);[h,p]=b}const m={modelTopology:n,weightSpecs:h,weightData:p,userDefinedMetadata:c,generatedBy:i,convertedBy:o,format:a},y=t.modelInitializer;return y&&(m.modelInitializer=y),m}async loadWeights(e){const t=Array.isArray(this.path)?this.path[1]:this.path,[n,s]=$F(t),i=this.weightPathPrefix||n,o=[];for(const p of e)o.push(...p.weights);const a=[],c=[];for(const p of e)for(const m of p.paths)this.weightUrlConverter!=null?c.push(this.weightUrlConverter(m)):a.push(i+m+s);this.weightUrlConverter&&a.push(...await Promise.all(c));const h=await QT(a,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress});return[o,op(h)]}}db.URL_SCHEME_REGEX=/^https?:\/\//;function $F(e){const t=e.lastIndexOf("/"),n=e.lastIndexOf("?"),s=e.substring(0,t),i=n>t?e.substring(n):"";return[s+"/",i]}function pb(e){return e.match(db.URL_SCHEME_REGEX)!=null}const nA=(e,t)=>{if(typeof fetch=="undefined"&&(t==null||t.fetchFunc==null))return null;{let n=!0;if(Array.isArray(e)?n=e.every(s=>pb(s)):n=pb(e),n)return mb(e,t)}return null};en.registerSaveRouter(nA),en.registerLoadRouter(nA);function mb(e,t){return new db(e,t)}function lp(e,t){return mb(e,t)}class fb{constructor(e){this.modelArtifacts=e}async load(){return this.modelArtifacts}}class UF{constructor(e){this.saveHandler=e}async save(e){return this.saveHandler(e)}}function BF(e,t,n,s){if(arguments.length===1){const i=e.modelTopology!=null||e.weightSpecs!=null;return i?new fb(e):(console.warn("Please call tf.io.fromMemory() with only one argument. The argument should be of type ModelArtifacts. The multi-argument signature of tf.io.fromMemory() has been deprecated and will be removed in a future release."),new fb({modelTopology:e}))}else return console.warn("Please call tf.io.fromMemory() with only one argument. The argument should be of type ModelArtifacts. The multi-argument signature of tf.io.fromMemory() has been deprecated and will be removed in a future release."),new fb({modelTopology:e,weightSpecs:t,weightData:n,trainingConfig:s})}function MF(e){return new UF(e)}var PF=Object.freeze({__proto__:null,browserFiles:FF,browserHTTPRequest:lp,concatenateArrayBuffers:op,decodeWeights:rp,encodeWeights:rb,fromMemory:BF,getLoadHandlers:cb,getModelArtifactsInfoForJSON:gh,getSaveHandlers:ab,http:mb,isHTTPScheme:pb,loadWeights:eA,registerLoadRouter:aF,registerSaveRouter:oF,weightsLoaderFactory:tA,withSaveHandler:MF,copyModel:LF,listModels:bF,moveModel:SF,removeModel:wF});function zF(e,t){const n=W(e,"x","reshape",null),s={x:n},i={shape:t},o=(a,c)=>(t=Vt(t,n.size),A(n.size===M(t),()=>"new shape and old shape must have the same number of elements."),c([n]),a.reshape(n,t));return G.runKernelFunc(o,s,null,Kl,i)}const K=z({reshape_:zF});function VF(e,t,n=!1,s=!1){let i=W(e,"a","matMul"),o=W(t,"b","matMul");[i,o]=Gt(i,o);const a=(p,m)=>{m([i,o]);const y=n?i.shape[i.rank-2]:i.shape[i.rank-1],b=s?o.shape[o.rank-1]:o.shape[o.rank-2],w=n?i.shape[i.rank-1]:i.shape[i.rank-2],L=s?o.shape[o.rank-2]:o.shape[o.rank-1],T=i.shape.slice(0,-2),v=o.shape.slice(0,-2),C=M(T),O=M(v),D=C===O||C===1||O===1;A(i.rank>=2&&o.rank>=2&&D,()=>`Error in matMul: the input batch dimensions must either be the same or at least one input batch dimension must be 1. Got input batch dimensions of (${T}) and (${v}).`),A(y===b,()=>`Error in matMul: inner shapes (${y}) and (${b}) of Tensors with shapes ${i.shape} and ${o.shape} and transposeA=${n} and transposeB=${s} must match.`);const k=C>O?T:v,F=k.concat([w,L]),B=n?K(i,[C,y,w]):K(i,[C,w,y]),$=s?K(o,[O,L,b]):K(o,[O,b,L]),Y=p.batchMatMul(B,$,n,s);return K(Y,F)},c={a:i,b:o},h={transposeA:n,transposeB:s};return G.runKernelFunc(a,c,null,Id,h)}const lt=z({matMul_:VF});function GF(e,t,n=1,s=0){if(t<2)throw new Error(`Error in oneHot: depth must be >=2, but it is ${t}`);const i=W(e,"indices","oneHot","int32"),o=[...i.shape,t],a=(p,m)=>(m([i]),K(p.oneHot(K(i,[i.size]),t,n,s),o)),c={indices:i},h={depth:t,onValue:n,offValue:s};return G.runKernelFunc(a,c,null,Wy,h)}const _o=z({oneHot_:GF});function YF(e,t){const n=W(e,"x","transpose");if(t==null&&(t=n.shape.map((o,a)=>a).reverse()),A(n.rank===t.length,()=>`Error in transpose: rank of input ${n.rank} must match length of perm ${t}.`),t.forEach(o=>{A(o>=0&&o<n.rank,()=>`All entries in 'perm' must be between 0 and ${n.rank-1} but got ${t}`)}),n.rank<=1)return n.clone();const s={x:n},i={perm:t};return G.runKernelFunc(o=>o.transpose(n,t),s,null,oh,i)}const Ye=z({transpose_:YF});function HF(e,t,n){const s=W(e,"labels","confusionMatrix"),i=W(t,"predictions","confusionMatrix");A(n==null||n>0&&Number.isInteger(n),()=>`If provided, numClasses must be a positive integer, but got ${n}`),A(s.rank===1,()=>`Expected the rank of labels to be 1, but got ${s.rank}`),A(i.rank===1,()=>`Expected the rank of predictions to be 1, but got ${i.rank}`),A(s.shape[0]===i.shape[0],()=>`Mismatch in the number of examples: ${s.shape[0]} vs. ${i.shape[0]}. Labels and predictions should have the same number of elements.`),A(n>0&&Number.isInteger(n),()=>`numClasses is required to be a positive integer, but got ${n}`);const o=_o(ve(s,"int32"),n),a=_o(ve(i,"int32"),n),c=Ye(o),h=lt(c,a);return ve(h,"int32")}const qF=z({confusionMatrix_:HF});var jF=Object.freeze({__proto__:null,confusionMatrix:qF});function sA(e,t,n){if(ne(e),t!=null&&t.length!==3)throw new Error("tensor3d() requires shape to have three numbers");const s=Ni(e,n);if(s.length!==3&&s.length!==1)throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");if(s.length===1&&t==null)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return Br(e,t,s,n)}let Ha;function KF(e,t=3){if(t>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");if(e==null)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");let n=!1,s=!1,i=!1,o=!1,a=!1;if(e.data instanceof Uint8Array)n=!0;else if(typeof ImageData!="undefined"&&e instanceof ImageData)s=!0;else if(typeof HTMLVideoElement!="undefined"&&e instanceof HTMLVideoElement)i=!0;else if(typeof HTMLImageElement!="undefined"&&e instanceof HTMLImageElement)o=!0;else if(e.getContext!=null)a=!0;else throw new Error(`pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData in browser, or OffscreenCanvas, ImageData in webworker or {data: Uint32Array, width: number, height: number}, but was ${e.constructor.name}`);if(i){const w=2;if(i&&e.readyState<w)throw new Error("The video element has not loaded data yet. Please wait for `loadeddata` event on the <video> element.")}const c=Ky(qd,G.backendName);if(c!=null){const w={pixels:e},L={numChannels:t};return G.runKernel(qd,w,L)}const[h,p]=i?[e.videoWidth,e.videoHeight]:[e.width,e.height];let m;a?m=e.getContext("2d").getImageData(0,0,h,p).data:s||n?m=e.data:(o||i)&&(Ha==null&&(Ha=document.createElement("canvas").getContext("2d")),Ha.canvas.width=h,Ha.canvas.height=p,Ha.drawImage(e,0,0,h,p),m=Ha.getImageData(0,0,h,p).data);let y;if(t===4)y=new Int32Array(m);else{const w=h*p;y=new Int32Array(w*t);for(let L=0;L<w;L++)for(let T=0;T<t;++T)y[L*t+T]=m[L*4+T]}const b=[p,h,t];return sA(y,b,"int32")}async function XF(e,t){let n=W(e,"img","toPixels");if(!(e instanceof te)){const p=n;n=ve(p,"int32"),p.dispose()}if(n.rank!==2&&n.rank!==3)throw new Error(`toPixels only supports rank 2 or 3 tensors, got rank ${n.rank}.`);const[s,i]=n.shape.slice(0,2),o=n.rank===2?1:n.shape[2];if(o>4||o===2)throw new Error(`toPixels only supports depth of size 1, 3 or 4 but got ${o}`);if(n.dtype!=="float32"&&n.dtype!=="int32")throw new Error(`Unsupported type for toPixels: ${n.dtype}. Please use float32 or int32 tensors.`);const a=await n.data(),c=n.dtype==="float32"?255:1,h=new Uint8ClampedArray(i*s*4);for(let p=0;p<s*i;++p){const m=[0,0,0,255];for(let b=0;b<o;b++){const w=a[p*o+b];if(n.dtype==="float32"){if(w<0||w>1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${w}.`)}else if(n.dtype==="int32"&&(w<0||w>255))throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${w}.`);o===1?(m[0]=w*c,m[1]=w*c,m[2]=w*c):m[b]=w*c}const y=p*4;h[y+0]=Math.round(m[0]),h[y+1]=Math.round(m[1]),h[y+2]=Math.round(m[2]),h[y+3]=Math.round(m[3])}if(t!=null){t.width=i,t.height=s;const p=t.getContext("2d"),m=new ImageData(h,i,s);p.putImageData(m,0,0)}return n!==e&&n.dispose(),h}const iA=z({fromPixels_:KF});var JF=Object.freeze({__proto__:null,toPixels:XF,fromPixels:iA});function hp(e,t){if(e.rank<1)throw new Error(`tf.gatherND() expects the input to be rank 1 or higher, but the rank was ${e.rank}.`);if(t.rank<1)throw new Error(`tf.gatherND() expects the indices to be rank 1 or higher, but the rank was ${t.rank}.`);if(t.dtype!=="int32")throw new Error(`tf.gatherND() expects the indices to be int32 type, but the dtype was ${t.dtype}.`);if(t.shape[t.rank-1]>e.rank)throw new Error(`index innermost dimension length must be <= tensor rank; saw: ${t.shape[t.rank-1]} vs. ${e.rank}`);if(e.size===0)throw new Error(`Requested more than 0 entries, but input is empty. Input shape: ${e.shape}.`);const n=t.shape,s=n[n.length-1];let i=1;for(let p=0;p<n.length-1;++p)i*=n[p];const o=e.shape,a=n.slice();a.pop();let c=1;for(let p=s;p<e.rank;++p)c*=o[p],a.push(o[p]);const h=[...Ke(e.shape).map(p=>p/c),1].slice(0,s);return[a,i,c,h]}var ZF=Object.freeze({__proto__:null,prepareAndValidate:hp});function gb(e,t,n){const s=t.rank>1?t.shape[t.rank-1]:1,i=t.rank>1?t.rank-1:1,o=`Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: ${n.shape}, indices.shape: ${t.shape}, shape: ${e}, sliceDim: ${s}, and batchDim: ${i}.`;if(n.rank<i)throw new Error(o+` update.rank < ${i}. `);if(e.length<s+(n.rank-i))throw new Error(o+` Output shape length < ${s+(n.rank-i)}`);if(n.rank!==i+e.length-s)throw new Error(o+` update.rank != ${i+e.length-s}`);for(let a=0;a<i;++a)if(n.shape[a]!==t.shape[a])throw new Error(o+` updates.shape[${a}] (${n.shape[a]}) != indices.shape[${a}] (${t.shape[a]}).`);for(let a=0;a<n.rank-i;++a)if(n.shape[a+i]!==e[a+s])throw new Error(o+` updates.shape[${a+i}] (${n.shape[a+i]}) != shape[${a+i}] (${e[a+i]})`)}function yb(e,t,n){if(t.rank<1)throw new Error(`tf.scatterND() expects the indices to be rank 1 or higher, but the rank was ${t.rank}.`);if(e.rank<1)throw new Error(`tf.scatterND() expects the updates to be rank 1 or higher, but the rank was ${e.rank}.`);if(t.dtype!=="int32")throw new Error(`The dtype of 'indices' should be int32, but got dtype: ${t.dtype}`);if(n.length<1)throw new Error(`Output rank must be greater or equal to 1, but got shape: ${n}`);if(n.length===0){if(t.size===0)throw new Error(`Indices specified for empty output. indices shape: ${t.shape}`);if(e.size===0)throw new Error(`Updates specified for empty output. updates shape: ${e.shape}`)}gb(n,t,e)}function qa(e,t,n){const s=t.shape.length,i=s>1?t.shape[s-1]:1,o=n.length;let a=1;for(let y=i;y<o;++y)a*=n[y];const c=i<1?1:i,h=M(t.shape)/c,p=[...Ke(n.slice(0,i)),1],m=M(n);return{sliceRank:i,numUpdates:h,sliceSize:a,strides:p,outputSize:m}}var QF=Object.freeze({__proto__:null,validateUpdateShape:gb,validateInput:yb,calculateShapes:qa});function bb(e,t,n){const s=e.shape.length;A(s===t.length,()=>`Error in slice${s}D: Length of begin ${t} must match the rank of the array (${s}).`),A(s===n.length,()=>`Error in slice${s}D: Length of size ${n} must match the rank of the array (${s}).`);for(let i=0;i<s;++i)A(t[i]+n[i]<=e.shape[i],()=>`Error in slice${s}D: begin[${i}] + size[${i}] (${t[i]+n[i]}) would overflow input.shape[${i}] (${e.shape[i]})`)}function up(e){const t=[];let n=0;for(;e>0;)e&1&&t.push(n),e/=2,n++;return t}function dp(e,t,n){const s=[];for(let i=0;i<e.length;i++)s[i]=Math.ceil((t[i]-e[i])/n[i]);return s}function rA(e,t,n,s){const i=[...e];for(let o=i.length;o<s.length;o++)i.push(1);for(let o=0;o<n;o++)o===0?i[t]=1:(i.splice(t,0,1),i.pop());return i}function oA(e,t,n){return n<=e?n:n-(t-1)}function aA(e,t){const n=[];for(let s=0;s<e;s++)n.push(t+s);return n}function cA(e,t,n,s,i,o,a,c,h){const p=e.length;let m=new Array(p),y=new Array(p),b=new Array(p);if(t.length&&n>0){const w=t[0],L=n+1;m=lA(a,w,L,s,e),y=hA(c,w,L,i,e),b=rA(o,w,L,e)}else for(let w=0;w<p;w++)m[w]=dA(a,s,o,e,w,h),y[w]=pA(c,i,o,e,w,h),b[w]=uA(o,w,h);return{begin:m,end:y,strides:b}}function lA(e,t,n,s,i){const o=[...i],a=aA(n,t);for(let c=0;c<o.length;c++)if(a.indexOf(c)>-1)o[c]=0;else{const h=oA(t,n,c);let p=s[h];e&1<<h&&(p=0),o[c]=p}return o}function hA(e,t,n,s,i){const o=[...i],a=aA(n,t);for(let c=0;c<o.length;c++)if(a.indexOf(c)>-1)o[c]=Number.MAX_SAFE_INTEGER;else{const h=oA(t,n,c);let p=s[h];e&1<<h&&(p=Number.MAX_SAFE_INTEGER),o[c]=p}for(let c=0;c<o.length;c++){const h=i[c];o[c]<0&&(o[c]+=h),o[c]=S(0,o[c],i[c])}return o}function uA(e,t,n){let s=e[t];return(n&1<<t||s==null)&&(s=1),s}function dA(e,t,n,s,i,o){let a=t[i];const c=n[i]||1;(e&1<<i||o&1<<i||a==null)&&(c>0?a=Number.MIN_SAFE_INTEGER:a=Number.MAX_SAFE_INTEGER);const h=s[i];return a<0&&(a+=h),a=S(0,a,h-1),a}function pA(e,t,n,s,i,o){let a=t[i];const c=n[i]||1;(e&1<<i||o&1<<i||a==null)&&(c>0?a=Number.MAX_SAFE_INTEGER:a=Number.MIN_SAFE_INTEGER);const h=s[i];return a<0&&(a+=h),c>0?a=S(0,a,h):a=S(-1,a,h-1),a}function wb(e,t,n){let s=n.length;for(let i=0;i<n.length;i++)if(n[i]>1){s=i;break}for(let i=s+1;i<n.length;i++)if(t[i]>0||n[i]!==e[i])return!1;return!0}function Lb(e,t){let n=e.length>0?e[e.length-1]:1;for(let s=0;s<e.length-1;s++)n+=e[s]*t[s];return n}function pp(e,t,n){let s;const i=e.shape.length;typeof t=="number"?s=[t,...new Array(i-1).fill(0)]:t.length<i?s=t.concat(new Array(i-t.length).fill(0)):s=t.slice(),s.forEach(a=>{A(a!==-1,()=>"slice() does not support negative begin indexing.")});let o;return n==null?o=new Array(i).fill(-1):typeof n=="number"?o=[n,...new Array(i-1).fill(-1)]:n.length<i?o=n.concat(new Array(i-n.length).fill(-1)):o=n,o=o.map((a,c)=>a>=0?a:(A(a===-1,()=>`Negative size values should be exactly -1 but got ${a} for the slice() size at index ${c}.`),e.shape[c]-s[c])),[s,o]}var mA=Object.freeze({__proto__:null,assertParamsValid:bb,maskToAxes:up,computeOutShape:dp,stridesWithElidedDims:rA,getNormalizedAxes:cA,startIndicesWithElidedDims:lA,stopIndicesWithElidedDims:hA,stridesForAxis:uA,startForAxis:dA,stopForAxis:pA,isSliceContinous:wb,computeFlatOffset:Lb,parseSliceParams:pp});class Wo{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}}class Bs{constructor(){this.classNameMap={}}static getMap(){return Bs.instance==null&&(Bs.instance=new Bs),Bs.instance}static register(e){Bs.getMap().classNameMap[e.className]=[e,e.fromConfig]}}function ge(e){A(e.className!=null,()=>"Class being registered does not have the static className property defined."),A(typeof e.className=="string",()=>"className is required to be a string, but got type "+typeof e.className),A(e.className.length>0,()=>"Class being registered has an empty-string as its className, which is disallowed."),Bs.register(e)}var e_=Object.freeze({__proto__:null,Serializable:Wo,SerializationMap:Bs,registerClass:ge});const t_=.001,fA=.1;function n_(e,t,n){return n==null&&(n=mp()),Sb(e,t,(s,i)=>xb(s,i,n))}function mp(){return G.backend.floatPrecision()===32?t_:fA}function Sb(e,t,n){let s=!0;if((un(e)||un(t))&&(s=!1),un(e)&&un(t)&&(s=!0),s){const a=e.constructor.name,c=t.constructor.name;if(a!==c)throw new Error(`Arrays are of different type. Actual: ${a}. Expected: ${c}`)}if(Array.isArray(e)&&Array.isArray(t)){const a=Ni(e),c=Ni(t);if(!ie(a,c))throw new Error(`Arrays have different shapes. Actual: [${a}]. Expected: [${c}]`)}const i=un(e)?e:Q(e),o=un(t)?t:Q(t);if(i.length!==o.length)throw new Error(`Arrays have different lengths actual: ${i.length} vs expected: ${o.length}.
Actual: ${i}.
Expected: ${o}.`);for(let a=0;a<o.length;++a){const c=i[a],h=o[a];if(!n(c,h))throw new Error(`Arrays differ: actual[${a}] = ${c}, expected[${a}] = ${h}.
Actual: ${i}.
Expected: ${o}.`)}}function s_(e,t){e().then(()=>t.fail(),()=>t())}function i_(e,t){const n=typeof t=="string"||typeof t=="number"||typeof t=="boolean"?[t]:t;return Ji(e)||Ji(e[0])||Ji(t)||Ji(t[0])?Sb(e,n,(s,i)=>s==i):Sb(e,t,(s,i)=>xb(s,i,0))}function Ib(e,t,n){if(n==null&&(n=mp()),!xb(e,t,n))throw new Error(`Numbers differ: actual === ${e}, expected === ${t}`)}function xb(e,t,n){return!isFinite(e)&&!isFinite(t)?!0:!(isNaN(e)||isNaN(t)||Math.abs(e-t)>n)}function r_(e,t,n){for(let s=0;s<e.length;s++)if(e[s]<t||e[s]>n)throw new Error(`Value out of range:${e[s]} low: ${t}, high: ${n}`)}function o_(e,t){expect(new Float32Array(e)).toEqual(new Float32Array(t))}var a_=Object.freeze({__proto__:null,TEST_EPSILON_FLOAT16:fA,expectArraysClose:n_,testEpsilon:mp,expectPromiseToFail:s_,expectArraysEqual:i_,expectNumbersClose:Ib,expectValuesInRange:r_,expectArrayBuffersEqual:o_});const gA="2.7.0";function c_(){ae().set("PROD",!0)}function l_(){ae().set("DEBUG",!0)}function h_(){ae().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function dn(e){ae().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(e+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}Gk(dn);function u_(){G.disposeVariables()}function tr(){return G}function fp(){return G.memory()}function d_(e){return G.profile(e)}function ee(e,t){return G.tidy(e,t)}function qe(e){const t=Zi(e);t.forEach(n=>n.dispose())}function wn(e){return G.keep(e)}function p_(e){return G.time(e)}function yA(e){return G.setBackend(e)}function m_(){return G.ready()}function f_(){return G.backendName}function g_(e){G.removeBackend(e)}function y_(e){return G.findBackend(e)}function b_(e){return G.findBackendFactory(e)}function Tb(e,t,n=1){return G.registerBackend(e,t,n)}function bA(){return G.backend}function w_(e,t){ae().setPlatform(e,t)}function L_(e,t){let n=W(e,"a","add"),s=W(t,"b","add");[n,s]=Gt(n,s);const i=(a,c)=>{const h=a.add(n,s);return c([n,s]),h},o={a:n,b:s};return G.runKernelFunc(i,o,null,Oo)}const be=z({add_:L_});function S_(e,t){let n=W(e,"a","floorDiv"),s=W(t,"b","floorDiv");[n,s]=Gt(n,s);const i=(a,c)=>{const h=a.floorDiv(n,s);return c([n,s]),h},o={a:n,b:s};return G.runKernelFunc(i,o,null,Iy)}const gp=z({floorDiv_:S_});function I_(e,t){let n=W(e,"a","div"),s=W(t,"b","div");if([n,s]=Gt(n,s),n.dtype==="int32"&&s.dtype==="int32")return gp(n,s);const i=(c,h)=>{const p=c.realDivide(n,s);return h([n,s]),p},o={a:n,b:s},a={};return G.runKernelFunc(i,o,null,_a,a)}const We=z({div_:I_});function x_(e,t){let n=W(e,"a","mul"),s=W(t,"b","mul");[n,s]=Gt(n,s);const i=(a,c)=>{const h=a.multiply(n,s);return c([n,s]),h},o={a:n,b:s};return G.runKernelFunc(i,o,null,Wa)}const X=z({mul_:x_});function T_(e){const t=W(e,"x","abs"),n={x:t};return G.runKernelFunc((s,i)=>(i([t]),t.dtype==="complex64"?s.complexAbs(t):s.abs(t)),n,null,wd)}const pn=z({abs_:T_});function A_(e){const t=W(e,"x","acos"),n={x:t};return G.runKernelFunc((s,i)=>{const o=s.acos(t);return i([t]),o},n,null,Ll)}const Ab=z({acos_:A_});function v_(e){const t=W(e,"x","acosh"),n={x:t};return G.runKernelFunc((s,i)=>{const o=s.acosh(t);return i([t]),o},n,null,Sl)}const vb=z({acosh_:v_});function N_(e){A(Array.isArray(e),()=>"The argument passed to tf.addN() must be a list of tensors"),A(e.length>=1,()=>`Must pass at least one tensor to tf.addN(), but got ${e.length}`);const t=e.map((o,a)=>W(o,`tensors${a}`,"addN")),n=t[0];t.forEach(o=>{if(o.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),t.forEach(o=>{if(!ie(o.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});const s=(o,a)=>{const c=o.addN(t);return a(t),c},i=t;return G.runKernelFunc(s,i,null,ly)}const wA=z({addN_:N_});function Nb(e,t){for(let n=0;n<e.length;++n)if(e[e.length-n-1]!==t-1-n)return!1;return!0}function LA(e,t,n){const s=e.length+t.length,i=[];let o=0,a=0;for(let c=0;c<s;c++)n.indexOf(c)===-1?i.push(e[o++]):i.push(t[a++]);return i}function vn(e,t){const n=[],s=e.length;for(let o=0;o<s;o++)t.indexOf(o)===-1&&n.push(e[o]);const i=t.map(o=>e[o]);return[n,i]}function Nn(e,t){const n=t.map(s=>1);return LA(e,n,t)}function Zn(e,t,n){A(Nb(t,n),()=>`${e} supports only inner-most axes for now. Got axes ${t} and rank-${n} input.`)}function Qn(e,t){if(Nb(e,t))return null;const n=[];for(let s=0;s<t;++s)e.indexOf(s)===-1&&n.push(s);return e.forEach(s=>n.push(s)),n}function yh(e){return e.map((t,n)=>[n,t]).sort((t,n)=>t[1]-n[1]).map(t=>t[0])}function hs(e,t){const n=[];for(let s=t-e;s<t;++s)n.push(s);return n}function C_(e,t=null,n=!1){let s=W(e,"x","all","bool");const i=c=>{const h=je(t,s.shape);let p=h;const m=Qn(p,s.rank);m!=null&&(s=Ye(s,m),p=hs(p.length,s.rank));const y=c.all(s,p);if(n){const b=Nn(y.shape,h);return K(y,b)}return y},o={x:s},a={axis:t,keepDims:n};return G.runKernelFunc(i,o,null,sT,a)}const yp=z({all_:C_});function R_(e,t=null,n=!1){let s=W(e,"x","any","bool");const i=c=>{const h=je(t,s.shape);let p=h;const m=Qn(p,s.rank);m!=null&&(s=Ye(s,m),p=hs(p.length,s.rank));const y=c.any(s,p);if(n){const b=Nn(y.shape,h);return K(y,b)}return y},o={x:s},a={axis:t,keepDims:n};return G.runKernelFunc(i,o,null,iT,a)}const bh=z({any_:R_});function O_(e,t=0){let n=W(e,"x","argMax");const s=(a,c)=>{c([n]);let h=je(t,n.shape);const p=Qn(h,n.rank);return p!=null&&(n=Ye(n,p),h=hs(h.length,n.rank)),a.argMax(n,h[0])},i={x:n},o={axis:t};return G.runKernelFunc(s,i,null,hy,o)}const wh=z({argMax_:O_});function E_(e,t=0){let n=W(e,"x","argMin");const s=(a,c)=>{c([n]),t==null&&(t=0);let h=je(t,n.shape);const p=Qn(h,n.rank);return p!=null&&(n=Ye(n,p),h=hs(h.length,n.rank)),a.argMin(n,h[0])},i={x:n},o={axis:t};return G.runKernelFunc(s,i,null,uy,o)}const Cb=z({argMin_:E_});function D_(e){const t=W(e,"x","asin"),n={x:t};return G.runKernelFunc((s,i)=>{const o=s.asin(t);return i([t]),o},n,null,Il)}const Rb=z({asin_:D_});function k_(e){const t=W(e,"x","asinh"),n={x:t};return G.runKernelFunc((s,i)=>{const o=s.asinh(t);return i([t]),o},n,null,xl)}const Ob=z({asinh_:k_});function F_(e){const t=W(e,"x","atan"),n={x:t};return G.runKernelFunc((s,i)=>{const o=s.atan(t);return i([t]),o},n,null,Tl)}const Eb=z({atan_:F_});function __(e,t){let n=W(e,"a","atan2"),s=W(t,"b","atan2");[n,s]=Gt(n,s);const i=(a,c)=>{const h=a.atan2(n,s);return c([n,s]),h},o={a:n,b:s};return G.runKernelFunc(i,o,null,Ld)}const Db=z({atan2_:__});function W_(e){const t=W(e,"x","atanh"),n={x:t};return G.runKernelFunc((s,i)=>{const o=s.atanh(t);return i([t]),o},n,null,Al)}const kb=z({atanh_:W_});function bp(e,t,n,s,i="NHWC",o){const a=e[3],c=[...t,a],h=Gr(i);return _n(e,c,n,o,s,null,null,h)}function Mn(e,t,n,s,i,o,a="channelsLast"){const[c,h]=wp(t);let p;if(a==="channelsLast")p=[c,h,e[3],e[3]];else if(a==="channelsFirst")p=[c,h,e[1],e[1]];else throw new Error(`Unknown dataFormat ${a}`);return _n(e,p,n,s,i,o,!1,a)}function Lh(e,t,n,s,i,o,a="NDHWC"){const[c,h,p]=_b(t);let m,y;if(a==="NDHWC")y="channelsLast",m=[c,h,p,e[4],e[4]];else if(a==="NCDHW")y="channelsFirst",m=[c,h,p,e[1],e[1]];else throw new Error(`Unknown dataFormat ${a}`);return zr(e,m,n,s,i,!1,y,o)}function _n(e,t,n,s,i,o,a=!1,c="channelsLast"){let[h,p,m,y]=[-1,-1,-1,-1];if(c==="channelsLast")[h,p,m,y]=e;else if(c==="channelsFirst")[h,y,p,m]=e;else throw new Error(`Unknown dataFormat ${c}`);const[b,w,,L]=t,[T,v]=wp(n),[C,O]=wp(s),D=ja(b,C),k=ja(w,O),{padInfo:F,outHeight:B,outWidth:$}=B_(i,p,m,T,v,D,k,o,c),Y=a?L*y:L;let j;return c==="channelsFirst"?j=[h,Y,B,$]:c==="channelsLast"&&(j=[h,B,$,Y]),{batchSize:h,dataFormat:c,inHeight:p,inWidth:m,inChannels:y,outHeight:B,outWidth:$,outChannels:Y,padInfo:F,strideHeight:T,strideWidth:v,filterHeight:b,filterWidth:w,effectiveFilterHeight:D,effectiveFilterWidth:k,dilationHeight:C,dilationWidth:O,inShape:e,outShape:j,filterShape:t}}function zr(e,t,n,s,i,o=!1,a="channelsLast",c){let[h,p,m,y,b]=[-1,-1,-1,-1,-1];if(a==="channelsLast")[h,p,m,y,b]=e;else if(a==="channelsFirst")[h,b,p,m,y]=e;else throw new Error(`Unknown dataFormat ${a}`);const[w,L,T,,v]=t,[C,O,D]=_b(n),[k,F,B]=_b(s),$=ja(w,k),Y=ja(L,F),j=ja(T,B),{padInfo:Z,outDepth:re,outHeight:de,outWidth:he}=M_(i,p,m,y,C,O,D,$,Y,j,c),ue=o?v*b:v;let me;return a==="channelsFirst"?me=[h,ue,re,de,he]:a==="channelsLast"&&(me=[h,re,de,he,ue]),{batchSize:h,dataFormat:a,inDepth:p,inHeight:m,inWidth:y,inChannels:b,outDepth:re,outHeight:de,outWidth:he,outChannels:ue,padInfo:Z,strideDepth:C,strideHeight:O,strideWidth:D,filterDepth:w,filterHeight:L,filterWidth:T,effectiveFilterDepth:$,effectiveFilterHeight:Y,effectiveFilterWidth:j,dilationDepth:k,dilationHeight:F,dilationWidth:B,inShape:e,outShape:me,filterShape:t}}function $_(e,t,n,s,i){s==null&&(s=Fb(e,t,n));const o=e[0],a=e[1],c=$o((o-t+2*s)/n+1,i);A(we(c),()=>`The output # of rows (${c}) must be an integer. Change the stride and/or zero pad parameters`);const h=$o((a-t+2*s)/n+1,i);return A(we(h),()=>`The output # of columns (${h}) must be an integer. Change the stride and/or zero pad parameters`),[c,h]}function U_(e,t,n,s,i,o){i==null&&(i=Fb(e,t,s));const a=e[0],c=e[1],h=e[2],p=$o((a-t+2*i)/s+1,o);A(we(p),()=>`The output # of depths (${p}) must be an integer. Change the stride and/or zero pad parameters`);const m=$o((c-t+2*i)/s+1,o);A(we(m),()=>`The output # of rows (${m}) must be an integer. Change the stride and/or zero pad parameters`);const y=$o((h-t+2*i)/s+1,o);return A(we(y),()=>`The output # of columns (${y}) must be an integer. Change the stride and/or zero pad parameters`),[p,m,y,n]}function Fb(e,t,n,s=1){const i=ja(t,s);return Math.floor((e[0]*(n-1)-n+i)/2)}function wp(e){return typeof e=="number"?[e,e,e]:e.length===2?[e[0],e[1],1]:e}function _b(e){return typeof e=="number"?[e,e,e]:e}function ja(e,t){return t<=1?e:e+(e-1)*(t-1)}function B_(e,t,n,s,i,o,a,c,h){let p,m,y;if(typeof e=="number"){const b=e===0?"VALID":"NUMBER";p={top:e,bottom:e,left:e,right:e,type:b};const w=$_([t,n],o,s,e,c);m=w[0],y=w[1]}else if(e==="same"){m=Math.ceil(t/s),y=Math.ceil(n/i);const b=Math.max(0,(m-1)*s+o-t),w=Math.max(0,(y-1)*i+a-n),L=Math.floor(b/2),T=b-L,v=Math.floor(w/2),C=w-v;p={top:L,bottom:T,left:v,right:C,type:"SAME"}}else if(e==="valid")p={top:0,bottom:0,left:0,right:0,type:"VALID"},m=Math.ceil((t-o+1)/s),y=Math.ceil((n-a+1)/i);else if(typeof e=="object"){const b=h==="channelsLast"?e[1][0]:e[2][0],w=h==="channelsLast"?e[1][1]:e[2][1],L=h==="channelsLast"?e[2][0]:e[3][0],T=h==="channelsLast"?e[2][1]:e[3][1],v=b===0&&w===0&&L===0&&T===0?"VALID":"EXPLICIT";p={top:b,bottom:w,left:L,right:T,type:v},m=$o((t-o+b+w)/s+1,c),y=$o((n-a+L+T)/i+1,c)}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:p,outHeight:m,outWidth:y}}function M_(e,t,n,s,i,o,a,c,h,p,m){let y,b,w,L;if(typeof e=="number"){const T=e===0?"VALID":"NUMBER";y={top:e,bottom:e,left:e,right:e,front:e,back:e,type:T};const v=U_([t,n,s,1],c,1,i,e,m);b=v[0],w=v[1],L=v[2]}else if(e==="same"){b=Math.ceil(t/i),w=Math.ceil(n/o),L=Math.ceil(s/a);const T=(b-1)*i+c-t,v=(w-1)*o+h-n,C=(L-1)*a+p-s,O=Math.floor(T/2),D=T-O,k=Math.floor(v/2),F=v-k,B=Math.floor(C/2),$=C-B;y={top:k,bottom:F,left:B,right:$,front:O,back:D,type:"SAME"}}else if(e==="valid")y={top:0,bottom:0,left:0,right:0,front:0,back:0,type:"VALID"},b=Math.ceil((t-c+1)/i),w=Math.ceil((n-h+1)/o),L=Math.ceil((s-p+1)/a);else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:y,outDepth:b,outHeight:w,outWidth:L}}function $o(e,t){if(!t)return e;switch(t){case"round":return Math.round(e);case"ceil":return Math.ceil(e);case"floor":return Math.floor(e);default:throw new Error(`Unknown roundingMode ${t}`)}}function Vr(e){const[t,n,s]=wp(e);return t===1&&n===1&&s===1}function cn(e,t){return Vr(e)||Vr(t)}function Gr(e){if(e==="NHWC")return"channelsLast";if(e==="NCHW")return"channelsFirst";throw new Error(`Unknown dataFormat ${e}`)}function P_(e,t,n,s,i){const o=W(e,"x","avgPool","float32"),a=1;A(cn(n,a),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`);let c=o,h=!1;o.rank===3&&(h=!0,c=K(o,[1,o.shape[0],o.shape[1],o.shape[2]])),A(c.rank===4,()=>`Error in avgPool: x must be rank 4 but got rank ${c.rank}.`),i!=null&&A(we(s),()=>`Error in avgPool: pad must be an integer when using, dimRoundingMode ${i} but got pad ${s}.`);const p=(w,L)=>{const T=Mn(c.shape,t,n,1,s,i);return L([c]),T.filterWidth===1&&T.filterHeight===1&&ie(T.inShape,T.outShape)?c.clone():w.avgPool(c,T)},m={x:c},y={filterSize:t,strides:n,pad:s,dimRoundingMode:i};let b=G.runKernelFunc(p,m,null,vl,y);return b=ve(b,o.dtype),h?K(b,[b.shape[1],b.shape[2],b.shape[3]]):b}const Sh=z({avgPool_:P_});function z_(e,t,n,s,i,o="NDHWC",a){a==null?a=[1,1,1]:dn("dilations is deprecated, this field will be gone in v3.0.0.");const c=W(e,"x","avgPool3d","float32");let h=c,p=!1;c.rank===4&&(p=!0,h=K(c,[1,c.shape[0],c.shape[1],c.shape[2],c.shape[3]])),A(h.rank===5,()=>`Error in avgPool3d: x must be rank 5 but got rank ${h.rank}.`),A(o==="NDHWC",()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${o}`),A(cn(n,a),()=>`Error in avgPool3d: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`),i!=null&&A(we(s),()=>`Error in avgPool3d: pad must be an integer when using, dimRoundingMode ${i} but got pad ${s}.`);const m=(L,T)=>{a==null&&(a=[1,1,1]);const v=Lh(h.shape,t,n,a,s,i,o);return T([h]),L.avgPool3d(h,v)},y={x:h},b={filterSize:t,strides:n,pad:s,dimRoundingMode:i,dataFormat:o,dilations:a};let w=G.runKernelFunc(m,y,null,dy,b);return w=ve(w,h.dtype),p?K(w,[w.shape[1],w.shape[2],w.shape[3],w.shape[4]]):w}const Wb=z({avgPool3d_:z_});function Lp(e,t){const n=e[0].length;e.forEach((i,o)=>{A(i.length===n,()=>`Error in concat${n}D: rank of tensors[${o}] must be the same as the rank of the rest (${n})`)}),A(t>=0&&t<n,()=>`Error in concat${n}D: axis must be between 0 and ${n-1}.`);const s=e[0];e.forEach((i,o)=>{for(let a=0;a<n;a++)A(a===t||i[a]===s[a],()=>`Error in concat${n}D: Shape of tensors[${o}] (${i}) does not match the shape of the rest (${s}) along the non-concatenated axis ${o}.`)})}function nr(e,t){const n=e[0].slice();for(let s=1;s<e.length;s++)n[t]+=e[s][t];return n}function V_(e,t=0){A(e.length>=1,()=>"Pass at least one tensor to concat");let n=fh(e,"tensors","concat");n[0].dtype==="complex64"&&n.forEach(a=>{if(a.dtype!=="complex64")throw new Error(`Cannot concatenate complex64 tensors with a tensor
with dtype ${a.dtype}. `)});const s=(a,c)=>{const h=je(t,n[0].shape)[0],p=nr(n.map(b=>b.shape),h);if(M(p)===0)return sn([],p);if(n=n.filter(b=>b.size>0),n.length===1)return n[0];const m=n.map(b=>b.shape);Lp(m,h);const y=a.concat(n,h);return c(n),y},i=n,o={axis:t};return G.runKernelFunc(s,i,null,Rl,o)}const Yt=z({concat_:V_});function G_(e){const t=W(e,"x","sigmoid"),n={x:t};return G.runKernelFunc((s,i)=>{const o=s.sigmoid(t);return i([o]),o},n,null,nh)}const Ri=z({sigmoid_:G_});function Y_(e,t,n){const s=W(e,"x","slice");if(s.rank===0)throw new Error("Slicing scalar is not possible");const i=(c,h)=>{const[p,m]=pp(s,t,n);return bb(s,p,m),h([s]),c.slice(s,p,m)},o={x:s},a={begin:t,size:n};return G.runKernelFunc(i,o,null,Vd,a)}const nt=z({slice_:Y_});function H_(e){const t=W(e,"x","tanh"),n={x:t};return G.runKernelFunc((s,i)=>{const o=s.tanh(t);return i([o]),o},n,null,rh)}const Ka=z({tanh_:H_});function q_(e,t,n,s,i,o){const a=W(e,"forgetBias","basicLSTMCell"),c=W(t,"lstmKernel","basicLSTMCell"),h=W(n,"lstmBias","basicLSTMCell"),p=W(s,"data","basicLSTMCell"),m=W(i,"c","basicLSTMCell"),y=W(o,"h","basicLSTMCell"),b=Yt([p,y],1),w=lt(b,c),L=be(w,h),T=L.shape[0],v=L.shape[1]/4,C=[T,v],O=nt(L,[0,0],C),D=nt(L,[0,v],C),k=nt(L,[0,v*2],C),F=nt(L,[0,v*3],C),B=be(X(Ri(O),Ka(D)),X(m,Ri(be(a,k)))),$=X(Ka(B),Ri(F));return[B,$]}const j_=z({basicLSTMCell_:q_});function K_(e,t,n){const s=W(e,"x","batchToSpaceND"),i=t.reduce((h,p)=>h*p);A(s.rank>=1+t.length,()=>`input rank is ${s.rank} but should be > than blockShape.length ${t.length}`),A(n.length===t.length,()=>`crops.length is ${n.length} but should be equal to blockShape.length ${t.length}`),A(s.shape[0]%i===0,()=>`input tensor batch is ${s.shape[0]} but is not divisible by the product of the elements of blockShape ${t.join(" * ")} === ${i}`);const o=h=>h.batchToSpaceND(s,t,n),a={x:s},c={blockShape:t,crops:n};return G.runKernelFunc(o,a,null,py,c)}const Ih=z({batchToSpaceND_:K_});function X_(e){let t;return e.rank===0||e.rank===1?t=K(e,[1,1,1,e.size]):e.rank===2?t=K(e,[1,1,e.shape[0],e.shape[1]]):e.rank===3?t=K(e,[1,e.shape[0],e.shape[1],e.shape[2]]):t=e,t}function J_(e,t,n,s,i,o){o==null&&(o=.001);const a=W(e,"x","batchNorm"),c=W(t,"mean","batchNorm"),h=W(n,"variance","batchNorm");let p;i!=null&&(p=W(i,"scale","batchNorm"));let m;s!=null&&(m=W(s,"offset","batchNorm")),A(c.rank===h.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),A(m==null||c.rank===m.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),A(p==null||c.rank===p.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");const y=X_(a),b=(v,C)=>(C([y,c,h,p]),v.batchNorm(y,Sp(c),Sp(h),Sp(m),Sp(p),o)),w={x:y,scale:p,offset:m,mean:c,variance:h},L={varianceEpsilon:o},T=G.runKernelFunc(b,w,null,Wl,L);return K(T,a.shape)}function Sp(e){return e==null?null:e.rank===0?K(e,[e.size]):e.rank===1?e:e.rank===2?K(e,[1,1,e.shape[0],e.shape[1]]):e.rank===3?K(e,[1,e.shape[0],e.shape[1],e.shape[2]]):e}const Uo=z({batchNorm_:J_});function Z_(e,t,n,s,i,o){const a=W(e,"x","batchNorm"),c=W(t,"mean","batchNorm"),h=W(n,"variance","batchNorm");let p;i!=null&&(p=W(i,"scale","batchNorm"));let m;return s!=null&&(m=W(s,"offset","batchNorm")),A(a.rank===2,()=>`Error in batchNorm2D: x must be rank 2 but got rank ${a.rank}.`),A(c.rank===2||c.rank===1,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${c.rank}.`),A(h.rank===2||h.rank===1,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${h.rank}.`),p!=null&&A(p.rank===2||p.rank===1,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${p.rank}.`),m!=null&&A(m.rank===2||m.rank===1,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${m.rank}.`),Uo(a,c,h,m,p,o)}const SA=z({batchNorm2d_:Z_});function Q_(e,t,n,s,i,o){const a=W(e,"x","batchNorm"),c=W(t,"mean","batchNorm"),h=W(n,"variance","batchNorm");let p;i!=null&&(p=W(i,"scale","batchNorm"));let m;return s!=null&&(m=W(s,"offset","batchNorm")),A(a.rank===3,()=>`Error in batchNorm3D: x must be rank 3 but got rank ${a.rank}.`),A(c.rank===3||c.rank===1,()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${c.rank}.`),A(h.rank===3||h.rank===1,()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${h.rank}.`),p!=null&&A(p.rank===3||p.rank===1,()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${p.rank}.`),m!=null&&A(m.rank===3||m.rank===1,()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${m.rank}.`),Uo(a,c,h,m,p,o)}const IA=z({batchNorm3d_:Q_});function eW(e,t,n,s,i,o){const a=W(e,"x","batchNorm"),c=W(t,"mean","batchNorm"),h=W(n,"variance","batchNorm");let p;i!=null&&(p=W(i,"scale","batchNorm"));let m;return s!=null&&(m=W(s,"offset","batchNorm")),A(a.rank===4,()=>`Error in batchNorm4D: x must be rank 4 but got rank ${a.rank}.`),A(c.rank===4||c.rank===1,()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${c.rank}.`),A(h.rank===4||h.rank===1,()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${h.rank}.`),p!=null&&A(p.rank===4||p.rank===1,()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${p.rank}.`),m!=null&&A(m.rank===4||m.rank===1,()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${m.rank}.`),Uo(a,c,h,m,p,o)}const xA=z({batchNorm4d_:eW});function tW(e,t){let n=W(e,"broadcastTo","x");const s=n.shape;if(t.some(m=>!(m>0)||m%1!==0))throw new Error(`broadcastTo(): Invalid broadcast shape [${t}].`);if(t.length<n.rank)throw new Error(`broadcastTo(): shape.length=${t.length} < input.rank=${n.rank}.`);if(t.length>n.rank){const m=n.shape.slice();for(;m.length<t.length;)m.unshift(1);n=K(n,m)}const i=n.shape,o=Array.from(t);for(let m=t.length-1;m>=0;m--)if(i[m]===t[m])o[m]=1;else if(n.shape[m]!==1)throw new Error(`broadcastTo(): [${s}] cannot be broadcast to [${t}].`);const a=o.map((m,y)=>m>1?y:-1).filter(m=>m>=0);if(a.length===0)return Pr(n);const c=m=>m.tile(n,o),h={x:n},p={shape:t,inputShape:i};return G.runKernelFunc(c,h,null,my,p)}const xh=z({broadcastTo_:tW});function nW(e){const t=W(e,"x","ceil"),n={x:t};return G.runKernelFunc(s=>s.ceil(t),n,null,Nl)}const $b=z({ceil_:nW});function sW(e,t,n){const s=W(e,"x","clipByValue");A(t<=n,()=>`Error in clip: min (${t}) must be less than or equal to max (${n}).`);const i={x:s},o={clipValueMin:t,clipValueMax:n};return G.runKernelFunc((a,c)=>{const h=a.clip(s,t,n);return c([s]),h},i,null,Cl,o)}const es=z({clipByValue_:sW});function iW(e){return Yt(e,0)}const TA=z({concat1d_:iW});function rW(e,t){return Yt(e,t)}const AA=z({concat2d_:rW});function oW(e,t){return Yt(e,t)}const vA=z({concat3d_:oW});function aW(e,t){return Yt(e,t)}const NA=z({concat4d_:aW});function cW(e,t,n,s,i="NHWC",o=[1,1],a){const c=W(e,"x","conv2d"),h=W(t,"filter","conv2d");let p=c,m=!1;c.rank===3&&(m=!0,p=K(c,[1,c.shape[0],c.shape[1],c.shape[2]])),A(p.rank===4,()=>`Error in conv2d: input must be rank 4, but got rank ${p.rank}.`),A(h.rank===4,()=>`Error in conv2d: filter must be rank 4, but got rank ${h.rank}.`),a!=null&&A(we(s),()=>`Error in conv2d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${s}.`);const y=i==="NHWC"?p.shape[3]:p.shape[1];A(y===h.shape[2],()=>`Error in conv2d: depth of input (${y}) must match input depth for filter ${h.shape[2]}.`),A(cn(n,o),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${o}'`);const b=(v,C)=>{const O=Gr(i),D=_n(p.shape,h.shape,n,o,s,a,!1,O),k=v.conv2d(p,h,D);return C([p,h]),k},w={x:p,filter:h},L={strides:n,pad:s,dataFormat:i,dilations:o,dimRoundingMode:a},T=G.runKernelFunc(b,w,null,Td,L);return m?K(T,[T.shape[1],T.shape[2],T.shape[3]]):T}const sr=z({conv2d_:cW});function lW(e,t,n,s,i="NWC",o=1,a){const c=W(e,"x","conv1d"),h=W(t,"filter","conv1d");let p=c,m=!1;c.rank===2&&(m=!0,p=K(c,[1,c.shape[0],c.shape[1]])),A(p.rank===3,()=>`Error in conv1d: input must be rank 3, but got rank ${p.rank}.`),A(h.rank===3,()=>`Error in conv1d: filter must be rank 3, but got rank ${h.rank}.`),a!=null&&A(we(s),()=>`Error in conv1d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${s}.`),A(p.shape[2]===h.shape[1],()=>`Error in conv1d: depth of input (${p.shape[2]}) must match input depth for filter ${h.shape[1]}.`),A(cn(n,o),()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${n} and dilation '${o}'`),A(i==="NWC",()=>`Error in conv1d: got dataFormat of ${i} but only NWC is currently supported.`);const y=K(h,[1,h.shape[0],h.shape[1],h.shape[2]]),b=K(p,[p.shape[0],1,p.shape[1],p.shape[2]]),w=[1,n],L=[1,o],T="NHWC",v=sr(b,y,w,s,T,L,a);return m?K(v,[v.shape[2],v.shape[3]]):K(v,[v.shape[0],v.shape[2],v.shape[3]])}const Ip=z({conv1d_:lW});function hW(e,t,n,s,i,o="NHWC",a){A(e.length===t.rank,()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);let c=e,h=t,p=!1;t.rank===3&&(p=!0,h=K(t,[1,t.shape[0],t.shape[1],t.shape[2]]),c=[1,e[0],e[1],e[2]]),A(c.length===4,()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${c.length}.`),A(h.rank===4,()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${h.rank}`),A(n.rank===4,()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${n.rank}`);const m=o==="NHWC"?c[3]:c[1],y=o==="NHWC"?h.shape[3]:h.shape[1];A(m===n.shape[2],()=>`Error in conv2dDerInput: depth of input (${m}) must match input depth for filter ${n.shape[2]}.`),A(y===n.shape[3],()=>`Error in conv2dDerInput: depth of output (${y}) must match output depth for filter ${n.shape[3]}.`),a!=null&&A(we(i),()=>`Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode ${a} but got pad ${i}.`);const b=(v,C)=>{const O=1,D=Gr(o),k=_n(c,n.shape,s,O,i,a,!1,D),F=v.conv2dDerInput(h,n,k);return C([h,n]),F},w={dy:h,filter:n},L={strides:s,pad:i,dataFormat:o,dimRoundingMode:a,inputShape:c},T=G.runKernelFunc(b,w,null,Ad,L);return p?K(T,[T.shape[1],T.shape[2],T.shape[3]]):T}const Ub=z({conv2DBackpropInput_:hW});function uW(e,t,n,s,i,o){const a=W(e,"x","conv2dTranspose"),c=W(t,"filter","conv2dTranspose");return Ub(n,a,c,s,i,"NHWC",o)}const xp=z({conv2dTranspose_:uW});function dW(e,t,n,s,i="NDHWC",o=[1,1,1]){const a=W(e,"x","conv3d"),c=W(t,"filter","conv3d");let h=a,p=!1;a.rank===4&&(p=!0,h=K(a,[1,a.shape[0],a.shape[1],a.shape[2],a.shape[3]])),A(h.rank===5,()=>`Error in conv3d: input must be rank 5, but got rank ${h.rank}.`),A(c.rank===5,()=>`Error in conv3d: filter must be rank 5, but got rank ${c.rank}.`),A(h.shape[4]===c.shape[3],()=>`Error in conv3d: depth of input (${h.shape[4]}) must match input depth for filter ${c.shape[3]}.`),A(cn(n,o),()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${n} and dilations '${o}'`),A(i==="NDHWC",()=>`Error in conv3d: got dataFormat of ${i} but only NDHWC is currently supported.`);const m=(L,T)=>{const v=zr(h.shape,c.shape,n,o,s),C=L.conv3d(h,c,v);return T([h,c]),C},y={x:h,filter:c},b={strides:n,pad:s,dataFormat:i,dilations:o},w=G.runKernelFunc(m,y,null,vd,b);return p?K(w,[w.shape[1],w.shape[2],w.shape[3],w.shape[4]]):w}const Bb=z({conv3d_:dW});function pW(e,t,n,s,i){A(e.length===t.rank,()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);let o=e,a=t,c=!1;t.rank===4&&(c=!0,a=K(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]]),o=[1,e[0],e[1],e[2],e[3]]);const h=o[4],p=a.shape[4];A(o.length===5,()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${o.length}.`),A(a.rank===5,()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${a.rank}`),A(n.rank===5,()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${n.rank}`),A(h===n.shape[3],()=>`Error in conv3dDerInput: depth of input (${h}) must match input depth for filter ${n.shape[3]}.`),A(p===n.shape[4],()=>`Error in conv3dDerInput: depth of output (${p}) must match output depth for filter ${n.shape[4]}.`);const m=L=>{const T=1,v=zr(o,n.shape,s,T,i);return L.conv3dDerInput(a,n,v)},y={dy:a,filter:n},b={pad:i,strides:s,inputShape:o},w=G.runKernelFunc(m,y,null,yy,b);return c?K(w,[w.shape[1],w.shape[2],w.shape[3],w.shape[4]]):w}const CA=z({conv3DBackpropInput_:pW});function mW(e,t,n,s,i){const o=W(e,"x","conv3dTranspose"),a=W(t,"filter","conv3dTranspose");return CA(n,o,a,s,i)}const fW=z({conv3dTranspose_:mW});function gW(e){const t=W(e,"x","cos"),n={x:t};return G.runKernelFunc((s,i)=>{const o=s.cos(t);return i([t]),o},n,null,Fa)}const Th=z({cos_:gW});function yW(e){const t=W(e,"x","cosh"),n={x:t};return G.runKernelFunc((s,i)=>{const o=s.cosh(t);return i([t]),o},n,null,Ol)}const Tp=z({cosh_:yW});function bW(e,t=0,n=!1,s=!1){const i=W(e,"x","cumsum"),o=(h,p)=>{const m=Qn([t],i.rank);let y=i;m!=null&&(y=Ye(i,m));const b=hs(1,i.rank)[0];let w=h.cumsum(y,b,n,s);if(p([i]),m!=null){const L=yh(m);w=Ye(w,L)}return w},a={x:i},c={axis:t,exclusive:n,reverse:s};return G.runKernelFunc(o,a,null,by,c)}const Ap=z({cumsum_:bW});function wW(e,t,n="NHWC"){const s=W(e,"x","depthToSpace"),i=n==="NHWC"?s.shape[1]:s.shape[2],o=n==="NHWC"?s.shape[2]:s.shape[3],a=n==="NHWC"?s.shape[3]:s.shape[1];A(i*t>=0,()=>`Negative dimension size caused by overflow when multiplying
${i} and ${t} for depthToSpace with input shape
${s.shape}`),A(o*t>=0,()=>`Negative dimension size caused by overflow when multiplying
${o} and ${t} for depthToSpace with input shape
${s.shape}`),A(a%(t*t)===0,()=>`Dimension size must be evenly divisible by ${t*t} but is ${a} for depthToSpace with input shape ${s.shape}`);const c=m=>m.depthToSpace(s,t,n),h={x:s},p={blockSize:t,dataFormat:n};return G.runKernelFunc(c,h,null,aT,p)}const Mb=z({depthToSpace_:wW});function LW(e,t,n,s,i="NHWC",o=[1,1],a){const c=W(e,"x","depthwiseConv2d"),h=W(t,"filter","depthwiseConv2d");let p=c,m=!1;c.rank===3&&(m=!0,p=K(c,[1,c.shape[0],c.shape[1],c.shape[2]])),A(p.rank===4,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${p.rank}.`),A(h.rank===4,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${h.rank}.`),A(p.shape[3]===h.shape[2],()=>`Error in depthwiseConv2d: number of input channels (${p.shape[3]}) must match the inChannels dimension in filter ${h.shape[2]}.`),a!=null&&A(we(s),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${s}.`);const y=(T,v)=>{o==null&&(o=[1,1]),A(cn(n,o),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${o}'`);const C=_n(p.shape,h.shape,n,o,s,a,!0),O=T.depthwiseConv2D(p,h,C);return v([p,h]),O},b={x:p,filter:h},w={strides:n,pad:s,dataFormat:i,dilations:o,dimRoundingMode:a},L=G.runKernelFunc(y,b,null,Nd,w);return m?K(L,[L.shape[1],L.shape[2],L.shape[3]]):L}const Bo=z({depthwiseConv2d_:LW});function SW(e){const t=W(e,"x","diag"),n=i=>{const o=K(t,[t.size]),a=i.diag(o),c=[...e.shape,...e.shape];return K(a,c)},s={x:t};return G.runKernelFunc(n,s,null,cT)}const IW=z({diag_:SW});function xW(e,t,n,s,i=[1,1],o="NHWC"){const a=W(e,"x","dilation2d"),c=W(t,"filter","dilation2d");A(a.rank===3||a.rank===4,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${a.rank}.`),A(c.rank===3,()=>`Error in dilation2d: filter must be rank 3, but got rank ${c.rank}.`),A(o==="NHWC",()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${o}`);let h=a,p=!1;a.rank===3&&(h=K(a,[1,a.shape[0],a.shape[1],a.shape[2]]),p=!0);const m={x:h,filter:c},y={strides:n,pad:s,dilations:i},b=G.runKernel(Cd,m,y);return p?K(b,[b.shape[1],b.shape[2],b.shape[3]]):b}const Pb=z({dilation2d_:xW});function Mo(e,t){const n=e.length,s=[];for(let i=0;i<n;i++){const o=n-1-i,a=e[o]||1,c=t[t.length-1-i]||1;c>1&&a===1&&s.unshift(o)}return s}function mn(e,t){const n=[];for(let s=0;s<t.length;s++){const i=e[e.length-s-1],o=t.length-s-1,a=t[o];(i==null||i===1&&a>1)&&n.unshift(o)}return n}function st(e,t){const n=[],s=Math.max(e.length,t.length);for(let i=0;i<s;i++){let o=e[e.length-i-1];o==null&&(o=1);let a=t[t.length-i-1];if(a==null&&(a=1),o===1)n.unshift(a);else if(a===1)n.unshift(o);else if(o!==a){const c=`Operands could not be broadcast together with shapes ${e} and ${t}.`;throw Error(c)}else n.unshift(o)}return n}function TW(e,t){let n=W(e,"a","equal"),s=W(t,"b","equal");[n,s]=Gt(n,s),st(n.shape,s.shape);const i=a=>a.equal(n,s),o={a:n,b:s};return G.runKernelFunc(i,o,null,hT)}const ei=z({equal_:TW});function AW(e,t,n){const s=W(t,"a","where"),i=W(n,"b","where"),o=W(e,"condition","where","bool"),a=st(s.shape,i.shape),c=xh(s,a),h=xh(i,a);o.rank===1&&A(o.shape[0]===s.shape[0],()=>"The first dimension of `a` must match the size of `condition`."),o.rank!==1&&U(o.shape,h.shape,"Error in where: ");const p=(y,b)=>{const w=y.select(o,c,h);return b([o]),w},m={condition:o,t:c,e:h};return G.runKernelFunc(p,m,null,Py)}const Pn=z({where_:AW});function vW(e){const t=W(e,"x","zerosLike"),n={x:t};return G.runKernelFunc(s=>s.zerosLike(t),n,null,jy)}const tt=z({zerosLike_:vW});function NW(e,t){let n=W(e,"a","div"),s=W(t,"b","div");[n,s]=Gt(n,s);const i=We(n,s),o=tt(i),a=ei(s,o);return Pn(a,o,i)}const zb=z({divNoNan_:NW});function CW(e,t){const n=W(e,"t1","dot"),s=W(t,"t2","dot");A((n.rank===1||n.rank===2)&&(s.rank===1||s.rank===2),()=>`Error in dot: inputs must all be rank 1 or 2, but got ranks ${n.rank} and ${s.rank}.`);const i=n.rank===1?n.size:n.shape[1],o=s.rank===1?s.size:s.shape[0];if(A(i===o,()=>`Error in dot: inner dimensions of inputs must match, but got ${i} and ${o}.`),n.rank===1&&s.rank===1){const a=K(n,[1,-1]),c=K(s,[-1,1]),h=lt(a,c);return K(h,[])}else if(n.rank===1&&s.rank===2){const a=K(n,[1,-1]),c=K(s,[s.shape[0],s.shape[1]]),h=lt(a,c);return K(h,[h.size])}else if(n.rank===2&&s.rank===1){const a=K(s,[-1,1]),c=lt(n,a);return K(c,[c.size])}else{const a=K(s,[s.shape[0],s.shape[1]]),c=lt(n,a);return c}}const RA=z({dot_:CW});function RW(e){const t=W(e,"x","elu"),n=(i,o)=>{const a=i.elu(t);return o([a]),a},s={x:t};return G.runKernelFunc(n,s,null,El)}const Xa=z({elu_:RW});function OW(e){let t=W(e,"x","erf");A(t.dtype==="int32"||t.dtype==="float32",()=>"Input dtype must be `int32` or `float32`."),t.dtype==="int32"&&(t=ve(t,"float32"));const n={x:t};return G.runKernelFunc((s,i)=>{const o=s.erf(t);return i([t]),o},n,null,Dl)}const Vb=z({erf_:OW});function EW(e){const t=W(e,"x","exp"),n={x:t};return G.runKernelFunc((s,i)=>{const o=s.exp(t);return i([o]),o},n,null,kl)}const As=z({exp_:EW});function DW(e,t=0){const n=null,s=W(e,"x","expandDims",n);A(t<=s.rank,()=>"Axis must be <= rank of the tensor");const i=s.shape.slice();return t<0&&(A(-(s.rank+1)<=t,()=>`Axis must be in the interval [${-(s.rank+1)}, ${s.rank}]`),t=s.rank+t+1),i.splice(t,0,1),K(s,i)}const ts=z({expandDims_:DW});function kW(e){const t=W(e,"x","expm1"),n={x:t};return G.runKernelFunc((s,i)=>{const o=s.expm1(t);return i([t]),o},n,null,Fl)}const Gb=z({expm1_:kW});function FW(e,t){const n=null,s=W(e,"x","tile",n);A(s.rank===t.length,()=>`Error in transpose: rank of input ${s.rank} must match length of reps ${t}.`);const i=(h,p)=>{const m=h.tile(s,t);return p([s]),m},o=[s],a={x:s},c={reps:t};return G.runKernelFunc(i,a,null,Yy,c,o)}const Yr=z({tile_:FW});function _W(e,t,n,s="float32"){t==null&&(t=e);const i=wt([e,t],s),o=e<=t?e:t;for(let c=0;c<o;++c)i.set(1,c,c);const a=K(i.toTensor(),[e,t]);if(n==null)return a;if(n.length===1)return Yr(ts(a,0),[n[0],1,1]);if(n.length===2)return Yr(ts(ts(a,0),0),[n[0],n[1],1,1]);if(n.length===3)return Yr(ts(ts(ts(a,0),0),0),[n[0],n[1],n[2],1,1]);throw new Error(`eye() currently supports only 1D and 2D batchShapes, but received ${n.length}D.`)}const vp=z({eye_:_W});function Ja(e,t,n){const s={shape:e,value:t,dtype:n};return G.runKernelFunc(i=>i.fill(e,t,n),{},null,Sy,s)}function WW(e){const t=W(e,"x","floor"),n={x:t};return G.runKernelFunc(s=>s.floor(t),n,null,_l)}const Za=z({floor_:WW});const Yb=30;function Ah(e){return e<=Yb?e:bd(e,Math.floor(Math.sqrt(e)))}function $W(e,t){let n=!1,s;for(e<=Yb?(s=e,n=!0):s=bd(e,Math.floor(Math.sqrt(e)));!n;)s>t||s===e?n=!0:s=bd(e,s+1);return s}function UW(e,t,n){const s=[],i=e.length;for(let o=0;o<i;o++)o!==t?s.push(e[o]):s.push(n);return s}function OA(e,t,n){const s=e.shape[n],i=[];let o=1,a=1;for(let c=0;c<n;c++)i.push(e.shape[c]),o*=e.shape[c];for(let c=0;c<t.rank;c++)i.push(t.shape[c]);for(let c=n+1;c<e.rank;c++)i.push(e.shape[c]),a*=e.shape[c];return{batchSize:o,sliceSize:a,dimSize:s,outputShape:i}}var BW=Object.freeze({__proto__:null,segOpComputeOptimalWindowSize:$W,computeOutShape:UW,collectGatherOpShapeInfo:OA});function MW(e,t,n=0){const s=W(e,"x","gather"),i=W(t,"indices","gather","int32"),o={x:s,indices:i},a={axis:n},c=(h,p)=>{const m=je(n,s.shape)[0],y=OA(s,i,m),b=h.gather(s,K(i,[i.size]),m);return p([s,i]),K(b,y.outputShape)};return G.runKernelFunc(c,o,null,xy,a)}const Qa=z({gather_:MW});function PW(e,t){let n=W(e,"a","greater"),s=W(t,"b","greater");[n,s]=Gt(n,s),st(n.shape,s.shape);const i=a=>a.greater(n,s),o={a:n,b:s};return G.runKernelFunc(i,o,null,dT)}const vs=z({greater_:PW});function zW(e,t){let n=W(e,"a","greaterEqual"),s=W(t,"b","greaterEqual");[n,s]=Gt(n,s),st(n.shape,s.shape);const i=(a,c)=>{const h=a.greaterEqual(n,s);return c([n,s]),h},o={a:n,b:s};return G.runKernelFunc(i,o,null,Ty)}const ir=z({greaterEqual_:zW});function VW(e){const t=W(e,"input","imag"),n=i=>i.imag(t),s={input:t};return G.runKernelFunc(n,s,null,Fd)}const vh=z({imag_:VW});function GW(e){const t=W(e,"x","isFinite"),n={x:t};return G.runKernelFunc(s=>s.isFinite(t),n,null,Ul)}const EA=z({isFinite_:GW});function YW(e){const t=W(e,"x","isInf"),n={x:t};return G.runKernelFunc(s=>s.isInf(t),n,null,Bl)}const DA=z({isInf_:YW});function HW(e){const t=W(e,"x","isNaN"),n={x:t};return G.runKernelFunc(s=>s.isNaN(t),n,null,Ml)}const kA=z({isNaN_:HW});function qW(e,t){let n=W(e,"a","maximum"),s=W(t,"b","maximum");[n,s]=Gt(n,s),n.dtype==="bool"&&(n=ve(n,"int32"),s=ve(s,"int32")),st(n.shape,s.shape);const i=(a,c)=>{const h=a.maximum(n,s);return c([n,s]),h},o={a:n,b:s};return G.runKernelFunc(i,o,null,Ny)}const Ms=z({maximum_:qW});function Ce(e,t){if((un(e)&&t!=="string"||Array.isArray(e))&&t!=="complex64")throw new Error("Error creating a new Scalar: value must be a primitive (number|boolean|string)");if(t==="string"&&un(e)&&!(e instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");const n=[],s=[];return Br(e,n,s,t)}function jW(e,t=.2){const n=W(e,"x","leakyRelu");return Ms(X(Ce(t),n),n)}const Np=z({leakyRelu_:jW});function KW(e,t){let n=W(e,"a","less"),s=W(t,"b","less");[n,s]=Gt(n,s),st(n.shape,s.shape);const i=a=>a.less(n,s),o={a:n,b:s};return G.runKernelFunc(i,o,null,pT)}const Nh=z({less_:KW});function XW(e,t){let n=W(e,"a","lessEqual"),s=W(t,"b","lessEqual");[n,s]=Gt(n,s),st(n.shape,s.shape);const i=(a,c)=>{const h=a.lessEqual(n,s);return c([n,s]),h},o={a:n,b:s};return G.runKernelFunc(i,o,null,mT)}const Hr=z({lessEqual_:XW});function FA(e,t,n){if(n<=0)throw new Error("The number of values should be positive.");const s={start:e,stop:t,num:n};return G.runKernelFunc(i=>i.linspace(e,t,n),{},null,fT,s)}function JW(e,t=5,n=1,s=1,i=.5){const o=W(e,"x","localResponseNormalization");A(o.rank===4||o.rank===3,()=>`Error in localResponseNormalization: x must be rank 3 or 4 but got
rank ${o.rank}.`),A(we(t),()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`);let a=o,c=!1;o.rank===3&&(c=!0,a=K(o,[1,o.shape[0],o.shape[1],o.shape[2]]));const h=(b,w)=>{const L=b.localResponseNormalization4D(a,t,n,s,i);return w([a,L]),L},p={x:a},m={depthRadius:t,bias:n,alpha:s,beta:i},y=G.runKernelFunc(h,p,null,vy,m);return c?K(y,[y.shape[1],y.shape[2],y.shape[3]]):y}const Hb=z({localResponseNormalization_:JW});function ZW(e){const t=W(e,"x","log"),n={x:t};return G.runKernelFunc((s,i)=>{const o=s.log(t);return i([t]),o},n,null,Pl)}const us=z({log_:ZW});function QW(e){const t=W(e,"x","log1p"),n={x:t};return G.runKernelFunc((s,i)=>{const o=s.log1p(t);return i([t]),o},n,null,zl)}const Cp=z({log1p_:QW});function e$(e){return A($r(e),()=>"The f passed in grad(f) must be a function"),(t,n)=>{const s=W(t,"x","tf.grad",null),i=n!=null?W(n,"dy","tf.grad"):null;return G.tidy(()=>{const{value:o,grads:a}=G.gradients(()=>e(s),[s],i);return i!=null&&U(o.shape,i.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),Rp(a),a[0]})}}function t$(e){return A($r(e),()=>"The f passed in grads(f) must be a function"),(t,n)=>{A(Array.isArray(t),()=>"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s");const s=fh(t,"args","tf.grads",null),i=n!=null?W(n,"dy","tf.grads"):null;return G.tidy(()=>{const{value:o,grads:a}=G.gradients(()=>e(...s),s,i);return i!=null&&U(o.shape,i.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Rp(a),a})}}function n$(e){return A($r(e),()=>"The f passed in valueAndGrad(f) must be a function"),(t,n)=>{A(t instanceof te,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),A(n==null||n instanceof te,()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");const{grads:s,value:i}=G.gradients(()=>e(t),[t],n);return Rp(s),{grad:s[0],value:i}}}function s$(e){return A($r(e),()=>"The f passed in valueAndGrads(f) must be a function"),(t,n)=>{A(Array.isArray(t)&&t.every(i=>i instanceof te),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),A(n==null||n instanceof te,()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");const s=G.gradients(()=>e(...t),t,n);return n!=null&&U(s.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Rp(s.grads),s}}function qb(e,t){A($r(e),()=>"The f passed in variableGrads(f) must be a function"),A(t==null||Array.isArray(t)&&t.every(p=>p instanceof ph),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");const n=t!=null;if(!n){t=[];for(const p in G.registeredVariables)t.push(G.registeredVariables[p])}const s=n?t.filter(p=>!p.trainable):null,i=t.length;t=t.filter(p=>p.trainable),A(t.length>0,()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${i} variables is trainable.`);const o=!0,{value:a,grads:c}=G.gradients(e,t,null,o);A(c.some(p=>p!=null),()=>"Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize()."),A(a.rank===0,()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${a.rank} tensor`);const h={};return t.forEach((p,m)=>{c[m]!=null&&(h[p.name]=c[m])}),s!=null&&s.forEach(p=>h[p.name]=null),{value:a,grads:h}}function Oi(e){return G.customGrad(e)}function Rp(e){const t=e.filter(n=>n==null).length;if(t>0)throw new Error(`Cannot compute gradient of y=f(x) with respect to x. Make sure that
the f you passed encloses all operations that lead from x to y.`)}function i$(e){const t=W(e,"x","neg"),n={x:t};return G.runKernelFunc(s=>s.neg(t),n,null,ky)}const Ht=z({neg_:i$});function r$(e){const t=W(e,"x","softplus"),n={x:t};return G.runKernelFunc((s,i)=>{const o=s.softplus(t);return i([t]),o},n,null,sh)}const ec=z({softplus_:r$});function o$(e){const t=W(e,"x","logSigmoid"),n=Oi(s=>{const i=Ht(ec(Ht(s))),o=a=>{const c=X(a,Ri(Ht(s)));return c};return{value:i,gradFunc:o}});return n(t)}const _A=z({logSigmoid_:o$});function a$(e,t=null,n=!1){const s=W(e,"x","max"),i=(c,h)=>{const p=je(t,s.shape);let m=p;const y=Qn(m,s.rank);let b=s;y!=null&&(b=Ye(s,y),m=hs(m.length,b.rank));const w=c.max(b,m);y!=null&&b.dispose();let L=w;if(n){const T=Nn(L.shape,je(t,s.shape));L=K(L,T),w.dispose()}return h([s,L]),L},o={x:s},a={reductionIndices:t,keepDims:n};return G.runKernelFunc(i,o,null,Vl,a)}const ns=z({max_:a$});function c$(e,t){let n=W(e,"a","sub"),s=W(t,"b","sub");[n,s]=Gt(n,s);const i=(a,c)=>{const h=a.subtract(n,s);return c([n,s]),h},o={a:n,b:s};return G.runKernelFunc(i,o,null,Ba)}const Re=z({sub_:c$});function l$(e,t=null,n=!1){let s=W(e,"x","sum");s.dtype==="bool"&&(s=ve(s,"int32"));const i=(c,h)=>{h([s]);const p=je(t,s.shape),m=Qn(p,s.rank);let y=p,b=s;m!=null&&(b=Ye(s,m),y=hs(y.length,s.rank));let w=c.sum(b,y);if(n){const L=Nn(w.shape,p);w=K(w,L)}return w},o={x:s},a={axis:t,keepDims:n};return G.runKernelFunc(i,o,null,zy,a)}const $e=z({sum_:l$});function h$(e,t=-1){const n=W(e,"logits","logSoftmax");if(t===-1&&(t=n.rank-1),t!==n.rank-1)throw Error(`Log Softmax along a non-last dimension is not yet supported. Logits was rank ${n.rank} and axis was ${t}`);const s=(a,c)=>{const h=!0,p=ns(e,t,!0),m=Re(e,p),y=Re(ve(m,"float32"),us($e(As(m),t,h)));return c([y]),y},i={logits:n},o={axis:t};return G.runKernelFunc(s,i,null,Ay,o)}const Op=z({logSoftmax_:h$});function u$(e,t=null,n=!1){const s=W(e,"x","logSumExp"),i=je(t,s.shape),o=ns(s,i,!0),a=Re(s,o),c=As(a),h=$e(c,i),p=us(h),m=be(K(o,p.shape),p);if(n){const y=Nn(m.shape,i);return K(m,y)}return m}const jb=z({logSumExp_:u$});function d$(e,t){const n=W(e,"a","logicalAnd","bool"),s=W(t,"b","logicalAnd","bool");st(n.shape,s.shape);const i={a:n,b:s};return G.runKernelFunc(o=>o.logicalAnd(n,s),i,null,gT)}const Ps=z({logicalAnd_:d$});function p$(e){const t=W(e,"x","logicalNot","bool"),n={x:t};return G.runKernelFunc(s=>s.logicalNot(t),n,null,_d)}const Ch=z({logicalNot_:p$});function m$(e,t){const n=W(e,"a","logicalOr","bool"),s=W(t,"b","logicalOr","bool");st(n.shape,s.shape);const i={a:n,b:s};return G.runKernelFunc(o=>o.logicalOr(n,s),i,null,yT)}const Ep=z({logicalOr_:m$});function f$(e,t){const n=W(e,"a","logicalXor","bool"),s=W(t,"b","logicalXor","bool");return st(n.shape,s.shape),Ps(Ep(e,t),Ch(Ps(e,t)))}const WA=z({logicalXor_:f$});function g$(e,t,n,s,i){const o=W(e,"x","maxPool"),a=1;let c=o,h=!1;o.rank===3&&(h=!0,c=K(o,[1,o.shape[0],o.shape[1],o.shape[2]])),A(c.rank===4,()=>`Error in maxPool: input must be rank 4 but got rank ${c.rank}.`),A(cn(n,a),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`),i!=null&&A(we(s),()=>`Error in maxPool: pad must be an integer when using, dimRoundingMode ${i} but got pad ${s}.`);const p=(w,L)=>{const T=Mn(c.shape,t,n,1,s,i);let v;return T.filterWidth===1&&T.filterHeight===1&&ie(T.inShape,T.outShape)?v=c.clone():v=w.maxPool(c,T),L([c,v]),v},m={x:c},y={filterSize:t,strides:n,pad:s,dimRoundingMode:i},b=G.runKernelFunc(p,m,null,Gl,y);return h?K(b,[b.shape[1],b.shape[2],b.shape[3]]):b}const Rh=z({maxPool_:g$});function y$(e,t=[1,1,1],n,s,i,o="NDHWC",a){a==null?a=[1,1,1]:dn("dilations is deprecated, this field will be gone in v3.0.0.");const c=W(e,"x","maxPool3d");let h=c,p=!1;c.rank===4&&(p=!0,h=K(c,[1,c.shape[0],c.shape[1],c.shape[2],c.shape[3]])),A(h.rank===5,()=>`Error in maxPool3d: x must be rank 5 but got rank ${h.rank}.`),A(o==="NDHWC",()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${o}`),A(cn(n,a),()=>`Error in maxPool3d: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`),i!=null&&A(we(s),()=>`Error in maxPool3d: pad must be an integer when using, dimRoundingMode ${i} but got pad ${s}.`);const m=(L,T)=>{a==null&&(a=[1,1,1]);const v=Lh(h.shape,t,n,a,s,i,o),C=L.maxPool3d(h,v);return T([h,C]),C},y={x:h},b={filterSize:t,strides:n,pad:s,dimRoundingMode:i,dataFormat:o,dilations:a},w=G.runKernelFunc(m,y,null,Cy,b);return p?K(w,[w.shape[1],w.shape[2],w.shape[3],w.shape[4]]):w}const Kb=z({maxPool3d_:y$});function b$(e,t,n,s,i=!1){const o=W(e,"x","maxPoolWithArgmax"),a={x:o},c={filterSize:t,strides:n,pad:s,includeBatchInIndex:i},h=G.runKernel($d,a,c);return{result:h[0],indexes:h[1]}}const $A=z({maxPoolWithArgmax_:b$});function pt(e,t="float32"){if(t==="complex64"){const s=pt(e,"float32"),i=pt(e,"float32");return er(s,i)}const n=Da(M(e),t);return G.makeTensor(n,e,t)}function ti(e,t="float32"){if(t==="complex64"){const s=ti(e,"float32"),i=pt(e,"float32");return er(s,i)}const n=ry(M(e),t);return G.makeTensor(n,e,t)}function w$(e,t=null,n=!1){const s=W(e,"x","mean"),i=je(t,s.shape),o=vn(s.shape,i),a=o[1],c=M(a),h={x:s},p={axis:t,keepDims:n},m=()=>{const b=Ce(c),w=b.dtype===s.dtype?s:ve(s,b.dtype),L=We(w,b);return $e(L,t,n)},y=Oi(b=>{const w=G.runKernelFunc(m,h,null,Ry,p),L=T=>{const v=b.shape.slice();i.forEach(D=>{v[D]=1});const C=K(T,v),O=We(X(C,ti(b.shape,"float32")),c);return O};return{value:w,gradFunc:L}});return y(s)}const qt=z({mean_:w$});function L$(e,t=null,n=!1){const s=W(e,"x","min"),i=(c,h)=>{const p=je(t,s.shape);let m=p;const y=Qn(m,s.rank);let b=s;y!=null&&(b=Ye(s,y),m=hs(m.length,s.rank));const w=c.min(b,m);y!=null&&b.dispose();let L=w;if(n){const T=Nn(L.shape,p);L=K(w,T),w.dispose()}return h([s,L]),L},o={x:s},a={axis:t,keepDims:n};return G.runKernelFunc(i,o,null,Oy,a)}const tc=z({min_:L$});function S$(e,t){let n=W(e,"a","minimum"),s=W(t,"b","minimum");[n,s]=Gt(n,s),n.dtype==="bool"&&(n=ve(n,"int32"),s=ve(s,"int32")),st(n.shape,s.shape);const i=(a,c)=>{const h=a.minimum(n,s);return c([n,s]),h},o={a:n,b:s};return G.runKernelFunc(i,o,null,Ey)}const Po=z({minimum_:S$});function I$(e,t,n){A(n==="reflect"||n==="symmetric",()=>`Invalid mode. Mode must be either reflect or symmetric. Got ${n}.`);const s=W(e,"x","mirrorPad");if(s.rank===0)throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");A(t.length===s.rank,()=>`Padding doesn't match input. Must be ${s.rank}. Got ${t.length}.`);const i=n==="reflect"?1:0;for(let c=0;c<s.rank;c++)A(t[c].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),A(t[c][0]>=0&&t[c][0]<=s.shape[c]-i&&t[c][1]>=0&&t[c][1]<=s.shape[c]-i,()=>`Padding in dimension ${c} cannot be greater than or equal to ${s.shape[c]-i} or less than 0 for input of shape ${s.shape}`);const o={paddings:t,mode:n},a={x:s};return G.runKernel(Yl,a,o)}const Xb=z({mirrorPad_:I$});function x$(e,t){let n=W(e,"a","mod"),s=W(t,"b","mod");[n,s]=Gt(n,s);const i=(a,c)=>{const h=a.mod(n,s);return c([n,s]),h},o={a:n,b:s};return G.runKernelFunc(i,o,null,Dy)}const Dp=z({mod_:x$});function T$(e){const t=W(e,"x","square"),n={},s=[t],i=[];return G.runKernelFunc((o,a)=>(a([t]),o.square(t)),{x:t},null,"Square",n,s,i)}const At=z({square_:T$});function A$(e,t=null,n=!1){e=W(e,"x","moments");const s=je(t,e.shape),i=qt(e,s,n);let o=i.shape;n||(o=Nn(i.shape,s));const a=At(Re(ve(e,"float32"),K(i,o))),c=qt(a,s,n);return{mean:i,variance:c}}const kp=z({moments_:A$});function v$(e,t,n,s){const i=W(t,"data","multiRNNCell"),o=fh(n,"c","multiRNNCell"),a=fh(s,"h","multiRNNCell");let c=i;const h=[];for(let y=0;y<e.length;y++){const b=e[y](c,o[y],a[y]);h.push(b[0]),h.push(b[1]),c=b[1]}const p=[],m=[];for(let y=0;y<h.length;y+=2)p.push(h[y]),m.push(h[y+1]);return[p,m]}const N$=z({multiRNNCell_:v$});function C$(e,t,n,s=!1){const i=W(e,"logits","multinomial"),o=i.size,a=i.rank;if(o<2)throw new Error(`Error in multinomial: you need at least 2 outcomes, but got ${o}.`);if(a>2)throw new Error(`Rank of probabilities must be 1 or 2, but is ${a}`);n=n||Math.random();const c=a===1?K(i,[1,-1]):i,h=G.runKernelFunc(p=>p.multinomial(c,s,t,n),{logits2D:c});return a===1?K(h,[h.size]):h}const UA=z({multinomial_:C$});function R$(e,t){let n=W(e,"a","notEqual"),s=W(t,"b","notEqual");[n,s]=Gt(n,s),st(n.shape,s.shape);const i=a=>a.notEqual(n,s),o={a:n,b:s};return G.runKernelFunc(i,o,null,Hl)}const qr=z({notEqual_:R$});function O$(e){const t=W(e,"input","real"),n=i=>i.real(t),s={input:t};return G.runKernelFunc(n,s,null,zd)}const nc=z({real_:O$});function E$(e){const t=W(e,"x","onesLike"),n=(i,o)=>{if(t.dtype==="complex64"){const a=Wn(nc(t)),c=tt(vh(t));return er(a,c)}return i.onesLike(t)},s={x:t};return G.runKernelFunc(n,s,null,_y)}const Wn=z({onesLike_:E$});function D$(e,t){const n=W(e,"v1","outerProduct"),s=W(t,"v2","outerProduct");A(n.rank===1&&s.rank===1,()=>`Error in outerProduct: inputs must be rank 1, but got ranks ${n.rank} and ${s.rank}.`);const i=K(n,[-1,1]),o=K(s,[1,-1]);return lt(i,o)}const k$=z({outerProduct_:D$});function F$(e,t,n=0){const s=W(e,"x","pad");if(s.rank===0)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");const i=(c,h)=>(h([s]),c.pad(s,t,n)),o={paddings:t,constantValue:n},a={x:s};return G.runKernelFunc(i,a,null,Md,o)}const Ei=z({pad_:F$});function _$(e,t,n=0){return A(t.length===2,()=>"Invalid number of paddings. Must be length of 2."),Ei(e,[t],n)}const W$=z({pad1d_:_$});function $$(e,t,n=0){return A(t.length===2&&t[0].length===2&&t[1].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),Ei(e,t,n)}const U$=z({pad2d_:$$});function B$(e,t,n=0){return A(t.length===3&&t[0].length===2&&t[1].length===2&&t[2].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),Ei(e,t,n)}const M$=z({pad3d_:B$});function P$(e,t,n=0){return A(t.length===4&&t[0].length===2&&t[1].length===2&&t[2].length===2&&t[3].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),Ei(e,t,n)}const z$=z({pad4d_:P$});function V$(e,t,n){const s=W(e,"x","spaceToBatchND");A(s.rank>=1+t.length,()=>`input rank ${s.rank} should be > than [blockShape] ${t.length}`),A(n.length===t.length,()=>`paddings.shape[0] ${n.length} must be equal to [blockShape] ${t.length}`),A(s.shape.reduce((c,h,p)=>p>0&&p<=t.length?c&&(h+n[p-1][0]+n[p-1][1])%t[p-1]===0:c,!0),()=>`input spatial dimensions ${s.shape.slice(1)} with paddings ${n.toString()} must be divisible by blockShapes ${t.toString()}`);const i=c=>c.spaceToBatchND(s,t,n),o={x:s},a={blockShape:t,paddings:n};return G.runKernelFunc(i,o,null,Gd,a)}const Oh=z({spaceToBatchND_:V$});function G$(e,t,n,s,i,o){i==null&&(i=[1,1]),o==null&&(o=1),s===0&&(s="valid");const a=W(e,"x","maxPool");let c=a,h=!1;a.rank===3&&(h=!0,c=K(a,[1,a.shape[0],a.shape[1],a.shape[2]])),A(cn(o,i),()=>`Error in pool: Either strides or dilations must be 1. Got strides ${o} and dilations '${i}'`);const p=Mn(c.shape,t,o,i,s),m=[p.dilationHeight,p.dilationWidth];let y;s==="same"?y=H$([p.filterHeight,p.filterWidth],m):y=[[0,0],[0,0]];const b=m[0]===1&&m[1]===1,[w,L]=Y$([p.inHeight,p.inWidth],m,y),T=b?s:"valid",v=b?c:Oh(c,m,w),C=n==="avg"?()=>Sh(v,t,o,T):()=>Rh(v,t,o,T),O=C(),D=b?O:Ih(O,m,L);return h?K(D,[D.shape[1],D.shape[2],D.shape[3]]):D}function Y$(e,t,n){const s=n.map(m=>m[0]),i=n.map(m=>m[1]),o=e.concat(s,i),a=t.map((m,y)=>(m-o[y]%m)%m),c=i.map((m,y)=>m+a[y]),h=t.map((m,y)=>[s[y],c[y]]),p=t.map((m,y)=>[0,a[y]]);return[h,p]}function H$(e,t){const n=e.map((a,c)=>a+(a-1)*(t[c]-1)),s=n.map(a=>a-1),i=s.map(a=>Math.floor(a/2)),o=s.map((a,c)=>a-i[c]);return s.map((a,c)=>[i[c],o[c]])}const BA=z({pool_:G$});function q$(e,t){let n=W(e,"base","pow"),s=W(t,"exp","pow");[n,s]=Gt(n,s);const i={a:n,b:s},o=(a,c)=>{const h=a.pow(n,s);return c([n,s,h]),h};return G.runKernelFunc(o,i,null,$y)}const ni=z({pow_:q$});function j$(e,t){const n=W(e,"x","prelu"),s=W(t,"alpha","prelu"),i=(a,c)=>{const h=a.prelu(n,s);return c([n,s]),h},o={x:n,alpha:s};return G.runKernelFunc(i,o,null,Pd)}const Eh=z({prelu_:j$});function K$(e,t=null,n=!1){let s=W(e,"x","prod");s.dtype==="bool"&&(s=ve(s,"int32"));const i=c=>{const h=je(t,s.shape),p=Qn(h,s.rank);let m=h,y=s;p!=null&&(y=Ye(s,p),m=hs(m.length,s.rank));let b=c.prod(y,m);if(n){const w=Nn(b.shape,h);b=K(b,w)}return b},o={x:s},a={axis:t,keepDims:n};return G.runKernelFunc(i,o,null,LT,a)}const Fp=z({prod_:K$});function X$(e,t,n){const s=M(e);let i=null;if(n==null||n==="float32")i=new Float32Array(s);else if(n==="int32")i=new Int32Array(s);else if(n==="bool")i=new Uint8Array(s);else throw new Error(`Unknown data type ${n}`);for(let o=0;o<s;o++)i[o]=t();return G.makeTensor(i,e,n)}const J$=z({rand_:X$});var sc=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function yte(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function zo(e,t){return t={exports:{}},e(t,t.exports),t.exports}function bte(e){return e&&e.default||e}function wte(){throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs")}var Z$=zo(function(e){(function(t,n,s){function i(h){var p=this,m=c();p.next=function(){var y=2091639*p.s0+p.c*23283064365386963e-26;return p.s0=p.s1,p.s1=p.s2,p.s2=y-(p.c=y|0)},p.c=1,p.s0=m(" "),p.s1=m(" "),p.s2=m(" "),p.s0-=m(h),p.s0<0&&(p.s0+=1),p.s1-=m(h),p.s1<0&&(p.s1+=1),p.s2-=m(h),p.s2<0&&(p.s2+=1),m=null}function o(h,p){return p.c=h.c,p.s0=h.s0,p.s1=h.s1,p.s2=h.s2,p}function a(h,p){var m=new i(h),y=p&&p.state,b=m.next;return b.int32=function(){return m.next()*4294967296|0},b.double=function(){return b()+(b()*2097152|0)*11102230246251565e-32},b.quick=b,y&&(typeof y=="object"&&o(y,m),b.state=function(){return o(m,{})}),b}function c(){var h=4022871197,p=function(m){m=m.toString();for(var y=0;y<m.length;y++){h+=m.charCodeAt(y);var b=.02519603282416938*h;h=b>>>0,b-=h,b*=h,h=b>>>0,b-=h,h+=b*4294967296}return(h>>>0)*23283064365386963e-26};return p}n&&n.exports?n.exports=a:s&&s.amd?s(function(){return a}):this.alea=a})(sc,e,!1)}),Q$=zo(function(e){(function(t,n,s){function i(c){var h=this,p="";h.x=0,h.y=0,h.z=0,h.w=0,h.next=function(){var y=h.x^h.x<<11;return h.x=h.y,h.y=h.z,h.z=h.w,h.w^=h.w>>>19^y^y>>>8},c===(c|0)?h.x=c:p+=c;for(var m=0;m<p.length+64;m++)h.x^=p.charCodeAt(m)|0,h.next()}function o(c,h){return h.x=c.x,h.y=c.y,h.z=c.z,h.w=c.w,h}function a(c,h){var p=new i(c),m=h&&h.state,y=function(){return(p.next()>>>0)/4294967296};return y.double=function(){do var b=p.next()>>>11,w=(p.next()>>>0)/4294967296,L=(b+w)/(1<<21);while(L===0);return L},y.int32=p.next,y.quick=y,m&&(typeof m=="object"&&o(m,p),y.state=function(){return o(p,{})}),y}n&&n.exports?n.exports=a:s&&s.amd?s(function(){return a}):this.xor128=a})(sc,e,!1)}),eU=zo(function(e){(function(t,n,s){function i(c){var h=this,p="";h.next=function(){var y=h.x^h.x>>>2;return h.x=h.y,h.y=h.z,h.z=h.w,h.w=h.v,(h.d=h.d+362437|0)+(h.v=h.v^h.v<<4^(y^y<<1))|0},h.x=0,h.y=0,h.z=0,h.w=0,h.v=0,c===(c|0)?h.x=c:p+=c;for(var m=0;m<p.length+64;m++)h.x^=p.charCodeAt(m)|0,m==p.length&&(h.d=h.x<<10^h.x>>>4),h.next()}function o(c,h){return h.x=c.x,h.y=c.y,h.z=c.z,h.w=c.w,h.v=c.v,h.d=c.d,h}function a(c,h){var p=new i(c),m=h&&h.state,y=function(){return(p.next()>>>0)/4294967296};return y.double=function(){do var b=p.next()>>>11,w=(p.next()>>>0)/4294967296,L=(b+w)/(1<<21);while(L===0);return L},y.int32=p.next,y.quick=y,m&&(typeof m=="object"&&o(m,p),y.state=function(){return o(p,{})}),y}n&&n.exports?n.exports=a:s&&s.amd?s(function(){return a}):this.xorwow=a})(sc,e,!1)}),tU=zo(function(e){(function(t,n,s){function i(c){var h=this;h.next=function(){var m=h.x,y=h.i,b,w,L;return b=m[y],b^=b>>>7,w=b^b<<24,b=m[y+1&7],w^=b^b>>>10,b=m[y+3&7],w^=b^b>>>3,b=m[y+4&7],w^=b^b<<7,b=m[y+7&7],b=b^b<<13,w^=b^b<<9,m[y]=w,h.i=y+1&7,w};function p(m,y){var b,w,L=[];if(y===(y|0))w=L[0]=y;else for(y=""+y,b=0;b<y.length;++b)L[b&7]=L[b&7]<<15^y.charCodeAt(b)+L[b+1&7]<<13;for(;L.length<8;)L.push(0);for(b=0;b<8&&L[b]===0;++b);for(b==8?w=L[7]=-1:w=L[b],m.x=L,m.i=0,b=256;b>0;--b)m.next()}p(h,c)}function o(c,h){return h.x=c.x.slice(),h.i=c.i,h}function a(c,h){c==null&&(c=+new Date);var p=new i(c),m=h&&h.state,y=function(){return(p.next()>>>0)/4294967296};return y.double=function(){do var b=p.next()>>>11,w=(p.next()>>>0)/4294967296,L=(b+w)/(1<<21);while(L===0);return L},y.int32=p.next,y.quick=y,m&&(m.x&&o(m,p),y.state=function(){return o(p,{})}),y}n&&n.exports?n.exports=a:s&&s.amd?s(function(){return a}):this.xorshift7=a})(sc,e,!1)}),nU=zo(function(e){(function(t,n,s){function i(c){var h=this;h.next=function(){var m=h.w,y=h.X,b=h.i,w,L;return h.w=m=m+1640531527|0,L=y[b+34&127],w=y[b=b+1&127],L^=L<<13,w^=w<<17,L^=L>>>15,w^=w>>>12,L=y[b]=L^w,h.i=b,L+(m^m>>>16)|0};function p(m,y){var b,w,L,T,v,C=[],O=128;for(y===(y|0)?(w=y,y=null):(y=y+"\0",w=0,O=Math.max(O,y.length)),L=0,T=-32;T<O;++T)y&&(w^=y.charCodeAt((T+32)%y.length)),T===0&&(v=w),w^=w<<10,w^=w>>>15,w^=w<<4,w^=w>>>13,T>=0&&(v=v+1640531527|0,b=C[T&127]^=w+v,L=b==0?L+1:0);for(L>=128&&(C[(y&&y.length||0)&127]=-1),L=127,T=4*128;T>0;--T)w=C[L+34&127],b=C[L=L+1&127],w^=w<<13,b^=b<<17,w^=w>>>15,b^=b>>>12,C[L]=w^b;m.w=v,m.X=C,m.i=L}p(h,c)}function o(c,h){return h.i=c.i,h.w=c.w,h.X=c.X.slice(),h}function a(c,h){c==null&&(c=+new Date);var p=new i(c),m=h&&h.state,y=function(){return(p.next()>>>0)/4294967296};return y.double=function(){do var b=p.next()>>>11,w=(p.next()>>>0)/4294967296,L=(b+w)/(1<<21);while(L===0);return L},y.int32=p.next,y.quick=y,m&&(m.X&&o(m,p),y.state=function(){return o(p,{})}),y}n&&n.exports?n.exports=a:s&&s.amd?s(function(){return a}):this.xor4096=a})(sc,e,!1)}),sU=zo(function(e){(function(t,n,s){function i(c){var h=this,p="";h.next=function(){var y=h.b,b=h.c,w=h.d,L=h.a;return y=y<<25^y>>>7^b,b=b-w|0,w=w<<24^w>>>8^L,L=L-y|0,h.b=y=y<<20^y>>>12^b,h.c=b=b-w|0,h.d=w<<16^b>>>16^L,h.a=L-y|0},h.a=0,h.b=0,h.c=2654435769|0,h.d=1367130551,c===Math.floor(c)?(h.a=c/4294967296|0,h.b=c|0):p+=c;for(var m=0;m<p.length+20;m++)h.b^=p.charCodeAt(m)|0,h.next()}function o(c,h){return h.a=c.a,h.b=c.b,h.c=c.c,h.d=c.d,h}function a(c,h){var p=new i(c),m=h&&h.state,y=function(){return(p.next()>>>0)/4294967296};return y.double=function(){do var b=p.next()>>>11,w=(p.next()>>>0)/4294967296,L=(b+w)/(1<<21);while(L===0);return L},y.int32=p.next,y.quick=y,m&&(typeof m=="object"&&o(m,p),y.state=function(){return o(p,{})}),y}n&&n.exports?n.exports=a:s&&s.amd?s(function(){return a}):this.tychei=a})(sc,e,!1)}),Vo=zo(function(e){(function(t,n){var s=this,i=256,o=6,a=52,c="random",h=n.pow(i,o),p=n.pow(2,a),m=p*2,y=i-1,b;function w(k,F,B){var $=[];F=F==!0?{entropy:!0}:F||{};var Y=C(v(F.entropy?[k,D(t)]:k==null?O():k,3),$),j=new L($),Z=function(){for(var re=j.g(o),de=h,he=0;re<p;)re=(re+he)*i,de*=i,he=j.g(1);for(;re>=m;)re/=2,de/=2,he>>>=1;return(re+he)/de};return Z.int32=function(){return j.g(4)|0},Z.quick=function(){return j.g(4)/4294967296},Z.double=Z,C(D(j.S),t),(F.pass||B||function(re,de,he,ue){return ue&&(ue.S&&T(ue,j),re.state=function(){return T(j,{})}),he?(n[c]=re,de):re})(Z,Y,"global"in F?F.global:this==n,F.state)}n["seed"+c]=w;function L(k){var F,B=k.length,$=this,Y=0,j=$.i=$.j=0,Z=$.S=[];for(B||(k=[B++]);Y<i;)Z[Y]=Y++;for(Y=0;Y<i;Y++)Z[Y]=Z[j=y&j+k[Y%B]+(F=Z[Y])],Z[j]=F;($.g=function(re){for(var de,he=0,ue=$.i,me=$.j,ce=$.S;re--;)de=ce[ue=y&ue+1],he=he*i+ce[y&(ce[ue]=ce[me=y&me+de])+(ce[me]=de)];return $.i=ue,$.j=me,he})(i)}function T(k,F){return F.i=k.i,F.j=k.j,F.S=k.S.slice(),F}function v(k,F){var B=[],$=typeof k,Y;if(F&&$=="object")for(Y in k)try{B.push(v(k[Y],F-1))}catch(j){}return B.length?B:$=="string"?k:k+"\0"}function C(k,F){for(var B=k+"",$,Y=0;Y<B.length;)F[y&Y]=y&($^=F[y&Y]*19)+B.charCodeAt(Y++);return D(F)}function O(){try{var k;return b&&(k=b.randomBytes)?k=k(i):(k=new Uint8Array(i),(s.crypto||s.msCrypto).getRandomValues(k)),D(k)}catch($){var F=s.navigator,B=F&&F.plugins;return[+new Date,s,B,s.screen,D(t)]}}function D(k){return String.fromCharCode.apply(0,k)}if(C(n.random(),t),e.exports){e.exports=w;try{b=require("crypto")}catch(k){}}})([],Math)});Vo.alea=Z$,Vo.xor128=Q$,Vo.xorwow=eU,Vo.xorshift7=tU,Vo.xor4096=nU,Vo.tychei=sU;var iU=Vo,ic=iU.alea;class Jb{constructor(e,t,n,s,i){this.mean=e,this.stdDev=t,this.dtype=n,this.nextVal=NaN,this.truncated=s,this.truncated&&(this.upper=this.mean+this.stdDev*2,this.lower=this.mean-this.stdDev*2);const o=i||Math.random();this.random=ic(o.toString())}nextValue(){if(!isNaN(this.nextVal)){const s=this.nextVal;return this.nextVal=NaN,s}let e,t,n=!1;for(;!n;){let s,i,o;do s=2*this.random()-1,i=2*this.random()-1,o=s*s+i*i;while(o>=1||o===0);const a=Math.sqrt(-2*Math.log(o)/o);e=this.mean+this.stdDev*s*a,t=this.mean+this.stdDev*i*a,(!this.truncated||this.isValidTruncated(e))&&(n=!0)}return(!this.truncated||this.isValidTruncated(t))&&(this.nextVal=this.convertValue(t)),this.convertValue(e)}convertValue(e){return this.dtype==null||this.dtype==="float32"?e:Math.round(e)}isValidTruncated(e){return e<=this.upper&&e>=this.lower}}class rU{constructor(e,t,n,s){this.alpha=e,this.beta=1/t,this.dtype=n;const i=s||Math.random();this.randu=ic(i.toString()),this.randn=new Jb(0,1,n,!1,this.randu()),e<1?this.d=e+2/3:this.d=e-1/3,this.c=1/Math.sqrt(9*this.d)}nextValue(){let e,t,n,s,i,o;for(;;){do s=this.randn.nextValue(),o=1+this.c*s;while(o<=0);if(o*=o*o,e=s*s,t=1-.331*e*e,n=.5*e+this.d*(1-o+Math.log(o)),i=this.randu(),i<t||Math.log(i)<n)break}return o=1/this.beta*this.d*o,this.alpha<1&&(o*=Math.pow(this.randu(),1/this.alpha)),this.convertValue(o)}convertValue(e){return this.dtype==="float32"?e:Math.round(e)}}class oU{constructor(e=0,t=1,n,s){if(this.canReturnFloat=()=>this.dtype==null||this.dtype==="float32",this.min=e,this.range=t-e,this.dtype=n,s==null&&(s=Math.random()),typeof s=="number"&&(s=s.toString()),!this.canReturnFloat()&&this.range<=1)throw new Error(`The difference between ${e} - ${t} <= 1 and dtype is not float`);this.random=ic(s)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}}function Lte(e){const t=e.length,n=lU(e),s=cU(e),i=t/6*(Math.pow(n,2)+.25*Math.pow(s-3,2)),o=5.991;if(i>o)throw new Error(`Invalid p-value for JB: ${i}`)}function Ste(e,t,n,s){s==null&&(s=mp());const i=Zb(e);Ib(i,t,s),Ib(aU(e,i),n,s)}function Zb(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n];return t/e.length}function aU(e,t){let n=0;for(let s=0;s<e.length;s++){const i=e[s]-t;n+=i*i}return Math.sqrt(n/e.length)}function cU(e){const t=Zb(e),n=e.length;let s=0,i=0;for(let o=0;o<n;o++){const a=e[o]-t;s+=Math.pow(a,2),i+=Math.pow(a,4)}return 1/n*i/Math.pow(1/n*s,2)}function lU(e){const t=Zb(e),n=e.length;let s=0,i=0;for(let o=0;o<n;o++){const a=e[o]-t;s+=Math.pow(a,2),i+=Math.pow(a,3)}return 1/n*i/Math.pow(1/(n-1)*s,3/2)}function hU(e,t,n=1,s="float32",i){if(n==null&&(n=1),s==null&&(s="float32"),s!=="float32"&&s!=="int32")throw new Error(`Unsupported data type ${s}`);const o=new rU(t,n,s,i),a=wt(e,s);for(let c=0;c<a.values.length;c++)a.values[c]=o.nextValue();return a.toTensor()}const uU=z({randomGamma_:hU});function dU(e,t=0,n=1,s,i){if(s!=null&&s==="bool")throw new Error(`Unsupported data type ${s}`);const o=new Jb(t,n,s,!1,i),a=wt(e,s);for(let c=0;c<a.values.length;c++)a.values[c]=o.nextValue();return a.toTensor()}const Qb=z({randomNormal_:dU});function pU(e,t=0,n=1,s="float32",i){const o=wt(e,s),a=new oU(t,n,null,i);for(let c=0;c<o.values.length;c++)o.values[c]=a.nextValue();return o.toTensor()}const Go=z({randomUniform_:pU});function ds(e,t){ne(e);const n=Ni(e,t);if(n.length!==1)throw new Error("tensor1d() requires values to be a flat/TypedArray");const s=null;return Br(e,s,n,t)}function Dh(e,t,n=1,s="float32"){if(n===0)throw new Error("Cannot have a step of zero");const i=()=>{const a=e===t,c=e<t&&n<0,h=t<e&&n>1;if(a||c||h)return pt([0],s);const p=Math.abs(Math.ceil((t-e)/n)),m=Da(p,s);t<e&&n===1&&(n=-1),m[0]=e;for(let y=1;y<m.length;y++)m[y]=m[y-1]+n;return ds(m,s)},o={start:e,stop:t,step:n,dtype:s};return G.runKernelFunc(i,{},null,ST,o)}function mU(e){const t=W(e,"x","reciprocal"),n={x:t};return G.runKernelFunc((s,i)=>{const o=s.reciprocal(t);return i([t]),o},n,null,ql)}const ew=z({reciprocal_:mU});function fU(e){const t=W(e,"x","relu"),n=(i,o)=>(o([t]),t.dtype==="bool"?ve(t,"int32"):i.relu(t)),s={x:t};return G.runKernelFunc(n,s,null,jl)}const Di=z({relu_:fU});function gU(e){const t=W(e,"x","relu6"),n=(i,o)=>(o([t]),t.dtype==="bool"?ve(t,"int32"):i.relu6(t)),s={x:t};return G.runKernelFunc(n,s,null,Xl)}const tw=z({relu6_:gU});function yU(e,t){const n=W(e,"x","reverse"),s=a=>{const c=je(t,n.shape);if(n.rank===0)return Pr(n);const h=a.reverse(n,c);return K(h,n.shape)},i={x:n},o={dims:t};return G.runKernelFunc(s,i,null,My,o)}const Ns=z({reverse_:yU});function bU(e){const t=W(e,"x","reverse");return A(t.rank===1,()=>`Error in reverse1D: x must be rank 1 but got rank ${t.rank}.`),Ns(t,0)}const wU=z({reverse1d_:bU});function LU(e,t){const n=W(e,"x","reverse");return A(n.rank===2,()=>`Error in reverse2D: x must be rank 2 but got rank ${n.rank}.`),Ns(n,t)}const SU=z({reverse2d_:LU});function IU(e,t){const n=W(e,"x","reverse");return A(n.rank===3,()=>`Error in reverse3D: x must be rank 3 but got rank ${n.rank}.`),Ns(n,t)}const xU=z({reverse3d_:IU});function TU(e,t){const n=W(e,"x","reverse");return A(n.rank===4,()=>`Error in reverse4D: x must be rank 4 but got rank ${n.rank}.`),Ns(n,t)}const AU=z({reverse4d_:TU});function vU(e){const t=W(e,"x","round"),n={x:t};return G.runKernelFunc(s=>s.round(t),n,null,Jl)}const nw=z({round_:vU});function NU(e){const t=W(e,"x","rsqrt"),n={x:t};return G.runKernelFunc((s,i)=>{const o=s.rsqrt(t);return i([t]),o},n,null,Zl)}const _p=z({rsqrt_:NU});function CU(e){const t=W(e,"x","selu"),n=(i,o)=>{const a=i.selu(t);return o([t]),a},s={x:t};return G.runKernelFunc(n,s,null,Ql)}const Wp=z({selu_:CU});function RU(e,t,n,s,i,o=[1,1],a="NHWC"){const c=W(e,"x","separableConv2d"),h=W(t,"depthwiseFilter","separableConv2d"),p=W(n,"pointwiseFilter","separableConv2d");let m=c,y=!1;if(c.rank===3&&(y=!0,m=K(c,[1,c.shape[0],c.shape[1],c.shape[2]])),a==="NCHW")throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");A(m.rank===4,()=>`Error in separableConv2d: input must be rank 4, but got rank ${m.rank}.`),A(h.rank===4,()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${h.rank}.`),A(p.rank===4,()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${h.rank}.`),A(p.shape[0]===1,()=>`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${p.shape[0]}.`),A(p.shape[1]===1,()=>`Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${p.shape[1]}.`);const b=h.shape[2],w=h.shape[3];A(p.shape[2]===b*w,()=>`Error in separableConv2d: the third dimension of pointwise filter must be ${b*w}, but got ${p.shape[2]}.`);const L=Bo(m,h,s,i,a,o),T=1,v=sr(L,p,T,"valid",a);return y?K(v,[v.shape[1],v.shape[2],v.shape[3]]):v}const sw=z({separableConv2d_:RU});async function OU(e,t){const n=W(e,"x","setdiff1d"),s=W(t,"y","setdiff1d");A(n.dtype===s.dtype,()=>`x and y should have the same dtype, but got x (${n.dtype}) and y (${s.dtype}).`),A(n.rank===1,()=>`x should be 1D tensor, but got x (${n.shape}).`),A(s.rank===1,()=>`y should be 1D tensor, but got y (${s.shape}).`);const i=await n.data(),o=await s.data(),a=new Set(o);let c=0;for(let m=0;m<i.length;m++)a.has(i[m])||c++;const h=new an([c],n.dtype),p=new an([c],"int32");for(let m=0,y=0;m<i.length;m++)a.has(i[m])||(h.values[y]=i[m],p.values[y]=m,y++);return[h.toTensor(),p.toTensor()]}const MA=OU;function EU(e){const t=W(e,"x","sign"),n={x:t};return G.runKernelFunc(s=>s.sign(t),n,null,th)}const iw=z({sign_:EU});function DU(e){const t=W(e,"x","sin"),n={x:t};return G.runKernelFunc((s,i)=>{const o=s.sin(t);return i([t]),o},n,null,$a)}const $p=z({sin_:DU});function kU(e){const t=W(e,"x","sinh"),n={x:t};return G.runKernelFunc((s,i)=>{const o=s.sinh(t);return i([t]),o},n,null,eh)}const Up=z({sinh_:kU});function FU(e,t,n){const s=W(e,"x","slice1d");return A(s.rank===1,()=>`slice1d expects a rank-1 tensor, but got a rank-${s.rank} tensor`),nt(s,[t],[n])}const Bp=z({slice1d_:FU});function _U(e,t,n){const s=W(e,"x","slice2d");return A(s.rank===2,()=>`slice2d expects a rank-2 tensor, but got a rank-${s.rank} tensor`),nt(s,t,n)}const rw=z({slice2d_:_U});function WU(e,t,n){const s=W(e,"x","slice3d");return A(s.rank===3,()=>`slice3d expects a rank-3 tensor, but got a rank-${s.rank} tensor`),nt(s,t,n)}const Mp=z({slice3d_:WU});function $U(e,t,n){const s=W(e,"x","slice4d");return A(s.rank===4,()=>`slice4d expects a rank-4 tensor, but got a rank-${s.rank} tensor`),nt(s,t,n)}const kh=z({slice4d_:$U});function UU(e,t=-1){const n=W(e,"logits","softmax","float32");if(t===-1&&(t=n.rank-1),t!==n.rank-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${n.rank} and dim was ${t}`);const s={logits:n},i={dim:t};return G.runKernelFunc((o,a)=>{const c=o.softmax(n,t);return a([c]),c},s,null,Gy,i)}const Yo=z({softmax_:UU});function BU(e){A(e.dtype==="complex64",()=>`The dtype for tf.spectral.fft() must be complex64 but got ${e.dtype}.`);const t={input:e};return G.runKernelFunc(n=>{const s=e.shape[e.shape.length-1],i=e.size/s,o=e.as2D(i,s),a=n.fft(o);return a.reshape(e.shape)},t,null,Ed)}const Fh=z({fft_:BU});function MU(e){A(e.dtype==="complex64",()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${e.dtype}.`);const t={input:e};return G.runKernelFunc(n=>{const s=e.shape[e.shape.length-1],i=e.size/s,o=K(e,[i,s]),a=n.ifft(o);return K(a,e.shape)},t,null,kd)}const rc=z({ifft_:MU});function PU(e){const t=e.shape[e.shape.length-1],n=e.size/t;let s;if(t<=2){const i=K(e,[n,t]);s=rc(i)}else{const i=[n,2*(t-1)],o=K(nc(e),[n,t]),a=K(vh(e),[n,t]),c=Ns(nt(o,[0,1],[n,t-2]),1),h=X(Ns(nt(a,[0,1],[n,t-2]),1),Ce(-1)),p=Yt([o,c],1),m=Yt([a,h],1),y=K(er(p,m),[i[0],i[1]]);s=rc(y)}if(s=nc(s),e.rank===3&&e.shape[0]!==0){const i=s,o=e.shape[0];s=K(s,[o,s.shape[0]/o,s.shape[1]]),i.dispose()}return s}const Pp=z({irfft_:PU});function PA(e,t,n=0){let s=[];if(typeof t=="number")A(e.shape[n]%t===0,()=>"Number of splits must evenly divide the axis."),s=new Array(t).fill(e.shape[n]/t);else{const i=t.reduce((a,c)=>(c===-1&&(a+=1),a),0);A(i<=1,()=>"There should be only one negative value in split array.");const o=t.indexOf(-1);if(o!==-1){const a=t.reduce((c,h)=>h>0?c+h:c);t[o]=e.shape[n]-a}A(e.shape[n]===t.reduce((a,c)=>a+c),()=>"The sum of sizes must match the size of the axis dimension."),s=t}return s}function zU(e,t,n=0){const s=W(e,"x","split"),i=(c,h)=>{const p=je(n,s.shape)[0],m=PA(s,t,p);return c.split(s,m,p)},o={x:s},a={numOrSizeSplits:t,axis:n};return G.runKernelFunc(i,o,null,Vy,a)}const ps=z({split_:zU});function VU(e,t){A(e.dtype==="float32",()=>`The dtype for rfft() must be real value but got ${e.dtype}`);let n=e.shape[e.shape.length-1];const s=e.size/n;let i;if(t!=null&&t<n){const L=e.shape.map(v=>0),T=e.shape.map(v=>v);T[e.shape.length-1]=t,i=nt(e,L,T),n=t}else if(t!=null&&t>n){const L=e.shape.map(T=>T);L[e.shape.length-1]=t-n,i=Yt([e,pt(L)],e.shape.length-1),n=t}else i=e;const o=tt(i),a=K(er(i,o),[s,n]),c=Fh(a),h=Math.floor(n/2)+1,p=nc(c),m=vh(c),y=ps(p,[h,n-h],p.shape.length-1),b=ps(m,[h,n-h],m.shape.length-1),w=i.shape.slice();return w[i.shape.length-1]=h,K(er(y[0],b[0]),w)}const _h=z({rfft_:VU});function GU(e){const t=W(e,"x","sqrt"),n={x:t};return G.runKernelFunc((s,i)=>{const o=s.sqrt(t);return i([t]),o},n,null,ih)}const Cn=z({sqrt_:GU});function YU(e,t){let n=W(e,"a","squaredDifference"),s=W(t,"b","squaredDifference");[n,s]=Gt(n,s),st(n.shape,s.shape);const i=(c,h)=>{const p=c.squaredDifference(n,s);return h([n,s]),p},o={a:n,b:s},a={};return G.runKernelFunc(i,o,null,Ua,a)}const Wh=z({squaredDifference_:YU});function HU(e,t){const n=W(e,"x","squeeze");return K(n,hn(n.shape,t).newShape)}const jr=z({squeeze_:HU});function qU(e,t=0){const n=fh(e,"tensors","stack");if(A(n.length>=1,()=>"Pass at least one tensor to tf.stack"),n.length===1)return ts(n[0],t);const s=n[0].rank,i=n[0].shape,o=n[0].dtype;A(t<=s,()=>"Axis must be <= rank of the tensor"),n.forEach(c=>{U(i,c.shape,"All tensors passed to stack must have matching shapes"),A(o===c.dtype,()=>"All tensors passed to stack must have matching dtypes")});const a=n.map(c=>ts(c,t));return Yt(a,t)}const ss=z({stack_:qU});function jU(e,t=0){const n=W(e,"x","step"),s={x:n},i={alpha:t};return G.runKernelFunc(o=>o.step(n,t),s,null,ah,i)}const oc=z({step_:jU});function KU(e,t,n,s,i=0,o=0,a=0,c=0,h=0){let p=W(e,"x","stridedSlice");const m=w=>{s==null&&(s=new Array(t.length));const L=up(a);if(L.length>1)throw new Error("Multiple ellipses in slice is not allowed.");if(a!==0&&c!==0)throw new Error("Using both ellipsisMask and newAxisMask is not yet supported.");if(a!==0&&h!==0)throw new Error("Using both ellipsisMask and shrinkAxisMask is not yet supported.");const T=p.rank-t.length,v=up(c),C=p.shape.slice();v.forEach(Z=>{t[Z]=0,n[Z]=1,C.splice(Z,0,1)}),p=K(p,C);const{begin:O,end:D,strides:k}=cA(p.shape,L,T,t,n,s,i,o,a);t=O,n=D,s=k;const F=up(h);F.forEach(Z=>{n[Z]=t[Z]+1,s[Z]=1});const B=dp(t,n,s),$=B.filter((Z,re)=>F.indexOf(re)===-1),Y=s.every(Z=>Z===1);if(Y)return K(nt(p,t,B),$);const j=w.stridedSlice(p,t,n,s);return K(j,$)},y={x:p},b={begin:t,end:n,strides:s,beginMask:i,endMask:o,ellipsisMask:a,newAxisMask:c,shrinkAxisMask:h};return G.runKernelFunc(m,y,null,vT,b)}const ow=z({stridedSlice_:KU});function XU(e){const t=W(e,"x","tan"),n={x:t};return G.runKernelFunc((s,i)=>{const o=s.tan(t);return i([t]),o},n,null,Ma)}const aw=z({tan_:XU});function Kr(e,t,n){if(ne(e),t!=null&&t.length!==2)throw new Error("tensor2d() requires shape to have two numbers");const s=Ni(e,n);if(s.length!==2&&s.length!==1)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(s.length===1&&t==null)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return Br(e,t,s,n)}function ac(e,t,n){if(ne(e),t!=null&&t.length!==4)throw new Error("tensor4d() requires shape to have four numbers");const s=Ni(e,n);if(s.length!==4&&s.length!==1)throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");if(s.length===1&&t==null)throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");return Br(e,t,s,n)}function JU(e,t,n){if(ne(e),t!=null&&t.length!==5)throw new Error("tensor5d() requires shape to have five numbers");const s=Ni(e,n);if(s.length!==5&&s.length!==1)throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray");if(s.length===1&&t==null)throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");return Br(e,t,s,n)}function ZU(e,t,n){if(ne(e),t!=null&&t.length!==6)throw new Error("tensor6d() requires shape to have six numbers");const s=Ni(e,n);if(s.length!==6&&s.length!==1)throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray");if(s.length===1&&t==null)throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");return t=t||s,Br(e,t,s,n)}function QU(e,t=1,n=!0){const s=W(e,"x","topk");if(s.rank===0)throw new Error("topk() expects the input to be of rank 1 or higher");const i=s.shape[s.shape.length-1];if(t>i)throw new Error(`'k' passed to topk() must be <= the last dimension (${i}) but got ${t}`);const o={x:s},a={k:t,sorted:n},[c,h]=G.runKernelFunc(p=>p.topk(s,t,n),o,null,NT,a);return{values:c,indices:h}}const cw=z({topk_:QU});function eB(e,t=0,n=1,s,i){if(s!=null&&s==="bool")throw new Error("Unsupported data type $ { dtype }");const o=new Jb(t,n,s,!0,i),a=wt(e,s);for(let c=0;c<a.values.length;c++)a.values[c]=o.nextValue();return a.toTensor()}const $h=z({truncatedNormal_:eB});function tB(e,t=0){const n=W(e,"x","unique",null);A(n.rank>0,()=>"The input tensor must be at least 1D");const s={x:n},i={axis:t},[o,a]=G.runKernel(Hd,s,i);return{values:o,indices:a}}const zp=z({unique_:tB});function nB(e,t,n){const s=W(e,"x","unsortedSegmentSum"),i=W(t,"segmentIds","unsortedSegmentSum","int32");A(we(n),()=>"numSegments must be of dtype int");const o={x:s,segmentIds:i},a={numSegments:n},c=(h,p)=>{const m=h.unsortedSegmentSum(s,i,n);return p([i]),m};return G.runKernelFunc(c,o,null,qy,a)}const lw=z({unsortedSegmentSum_:nB});function sB(e,t=0){const n=W(e,"x","unstack");A(t>=-n.shape.length&&t<n.shape.length,()=>`Axis = ${t} is not in [-${n.shape.length}, ${n.shape.length})`),t<0&&(t+=n.shape.length);const s={value:n},i={axis:t},o=a=>a.unstack(n,t);return G.runKernelFunc(o,s,null,Hy,i)}const si=z({unstack_:sB});function zA(e,t=!0,n,s){return G.makeVariable(e,t,n,s)}function Vp(e,t){const n=[];for(let o=0;o<t.length;o++)t[o]&&n.push(o);const s=wt(e,"int32"),i=wt([n.length,e.length],"int32");for(let o=0;o<n.length;o++){const a=s.indexToLoc(n[o]),c=o*e.length;i.values.set(a,c)}return i.toTensor()}async function iB(e){const t=W(e,"condition","whereAsync","bool"),n=await t.data(),s=Vp(t.shape,n);return e!==t&&t.dispose(),s}const hw=iB;async function rB(e,t,n){const s=W(e,"tensor","boolMask"),i=W(t,"mask","boolMask","bool"),o=n==null?0:n,a=i.rank,c=s.shape;A(a>0,()=>"mask cannot be scalar"),U(c.slice(o,o+a),i.shape,"mask's shape must match the first K dimensions of tensor's shape,");let h=1;for(let T=o;T<o+a;T++)h*=c[T];const p=c.slice(0,o).concat([h],c.slice(o+a)),m=K(s,p),y=K(i,[-1]),b=await hw(y),w=jr(b,[1]),L=Qa(m,w,o);return e!==s&&s.dispose(),t!==i&&i.dispose(),w.dispose(),m.dispose(),y.dispose(),b.dispose(),L}const oB=rB;function aB(e,t){dn("strict variants of ops have been deprecated and will be removed in future");const n=W(e,"a","notEqualStrict"),s=W(t,"b","notEqualStrict");return U(n.shape,s.shape,"Error in notEqualStrict: "),qr(n,s)}function cB(e,t){dn("strict variants of ops have been deprecated and will be removed in future");const n=W(e,"a","lessStrict"),s=W(t,"b","lessStrict");return U(n.shape,s.shape,"Error in lessStrict: "),Nh(n,s)}function lB(e,t){dn("strict variants of ops have been deprecated and will be removed in future");const n=W(e,"a","equalStrict"),s=W(t,"b","equalStrict");return U(n.shape,s.shape,"Error in equalStrict: "),ei(n,s)}function hB(e,t){dn("strict variants of ops have been deprecated and will be removed in future");const n=W(e,"a","lessEqualStrict"),s=W(t,"b","lessEqualStrict");return U(n.shape,s.shape,"Error in lessEqualStrict: "),Hr(n,s)}function uB(e,t){dn("strict variants of ops have been deprecated and will be removed in future");const n=W(e,"a","greaterStrict"),s=W(t,"b","greaterStrict");return U(n.shape,s.shape,"Error in greaterStrict: "),vs(n,s)}function dB(e,t){dn("strict variants of ops have been deprecated and will be removed in future");const n=W(e,"a","greaterEqualStrict"),s=W(t,"b","greaterEqualStrict");return U(n.shape,s.shape,"Error in greaterEqualStrict: "),ir(n,s)}const VA=z({equalStrict_:lB}),GA=z({greaterEqualStrict_:dB}),YA=z({greaterStrict_:uB}),HA=z({lessEqualStrict_:hB}),qA=z({lessStrict_:cB}),jA=z({notEqualStrict_:aB});function pB(e,t){dn("strict variants of ops have been deprecated and will be removed in future");const n=W(e,"a","addStrict"),s=W(t,"b","addStrict");return U(n.shape,s.shape,"Error in addStrict: "),be(n,s)}function mB(e,t){dn("strict variants of ops have been deprecated and will be removed in future");const n=W(e,"a","subStrict"),s=W(t,"b","subStrict");return U(n.shape,s.shape,"Error in subStrict: "),Re(n,s)}function fB(e,t){return dn("strict variants of ops have been deprecated and will be removed in future"),U(e.shape,t.shape,"Error in powStrict: "),ni(e,t)}function gB(e,t){dn("strict variants of ops have been deprecated and will be removed in future");const n=W(e,"a","mul"),s=W(t,"b","mul");return U(n.shape,s.shape,"Error in multiplyStrict: "),X(n,s)}function yB(e,t){dn("strict variants of ops have been deprecated and will be removed in future");const n=W(e,"a","div"),s=W(t,"b","div");return U(n.shape,s.shape,"Error in divideStrict: "),We(n,s)}function bB(e,t){dn("strict variants of ops have been deprecated and will be removed in future");const n=W(e,"a","modStrict"),s=W(t,"b","modStrict");return U(n.shape,s.shape,"Error in modStrict: "),Dp(n,s)}function wB(e,t){dn("strict variants of ops have been deprecated and will be removed in future");const n=W(e,"a","minimumStrict"),s=W(t,"b","minimumStrict");return U(n.shape,s.shape,"Error in minimumStrict: "),Po(n,s)}function LB(e,t){dn("strict variants of ops have been deprecated and will be removed in future");const n=W(e,"a","maximumStrict"),s=W(t,"b","maximumStrict");return U(n.shape,s.shape,"Error in maximumStrict: "),Ms(n,s)}function SB(e,t){dn("strict variants of ops have been deprecated and will be removed in future");const n=W(e,"a","squaredDifferenceStrict"),s=W(t,"b","squaredDifferenceStrict");return U(n.shape,s.shape,"Error in squaredDifferenceStrict: "),Wh(n,s)}const KA=z({addStrict_:pB}),XA=z({divStrict_:yB}),JA=z({maximumStrict_:LB}),ZA=z({minimumStrict_:wB}),QA=z({modStrict_:bB}),ev=z({mulStrict_:gB}),tv=z({powStrict_:fB}),nv=z({squaredDifferenceStrict_:SB}),sv=z({subStrict_:mB});function IB(e,t="euclidean",n=null,s=!1){e=W(e,"x","norm");const i=iv(e,t,n);let o=i.shape;if(s){const a=je(n,e.shape);o=Nn(i.shape,a)}return K(i,o)}function iv(e,t,n=null){if(e.rank===0)return pn(e);if(e.rank!==1&&n===null)return iv(K(e,[-1]),t,n);if(e.rank===1||typeof n=="number"||Array.isArray(n)&&n.length===1){if(t===1)return $e(pn(e),n);if(t===Infinity)return ns(pn(e),n);if(t===-Infinity)return tc(pn(e),n);if(t==="euclidean"||t===2)return Cn($e(ni(pn(e),Ce(2,"int32")),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}if(Array.isArray(n)&&n.length===2){if(t===1)return ns($e(pn(e),n[0]),n[1]-1);if(t===Infinity)return ns($e(pn(e),n[1]),n[0]);if(t===-Infinity)return tc($e(pn(e),n[1]),n[0]);if(t==="fro"||t==="euclidean")return Cn($e(At(e),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}throw new Error(`Error in norm: invalid axis: ${n}`)}const Gp=z({norm_:IB});function xB(e,t,n,s,i=!0){const o=W(e,"v","movingAverage"),a=W(t,"x","movingAverage"),c=W(n,"decay","movingAverage");FT(o,a),A(ie(o.shape,a.shape),()=>"Shape mismatch in v and x");const h=Ce(1),p=Re(h,c);let m=X(Re(a,o),p);if(i){A(s!=null,()=>"When using zeroDebias: true, step is required.");const y=W(s,"step","movingAverage");m=We(m,Re(h,ni(c,y)))}return be(o,m)}const TB=z({movingAverage_:xB});function AB(e,t,n){const s=W(e,"indices","scatterND","int32"),i=W(t,"updates","scatterND");yb(i,s,n);const o=h=>h.scatterND(s,i,n),a={indices:s,updates:i},c={shape:n};return G.runKernelFunc(o,a,null,TT,c)}const rv=z({scatterND_:AB});function vB(e,t,n,s){if(e.dtype!=="int32")throw new Error(`tf.sparseToDense() expects the indices to be int32 type, but the dtype was ${e.dtype}.`);if(e.rank>2)throw new Error(`sparseIndices should be a scalar, vector, or matrix, but got shape ${e.shape}.`);const i=e.rank>0?e.shape[0]:1,o=e.rank>1?e.shape[1]:1;if(n.length!==o)throw new Error(`outputShape has incorrect number of elements:, ${n.length}, should be: ${o}.`);const a=t.size;if(!(t.rank===0||t.rank===1&&a===i))throw new Error(`sparseValues has incorrect shape ${t.shape}, should be [] or [${i}]`);if(t.dtype!==s.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}function NB(e,t,n,s=0){const i=W(e,"sparseIndices","sparseToDense","int32"),o=W(t,"sparseValues","sparseToDense"),a=W(s,"defaultValue","sparseToDense",o.dtype);vB(i,o,n,a);const c={sparseIndices:i,sparseValues:o,defaultValue:a},h={outputShape:n};return G.runKernelFunc(p=>p.sparseToDense(i,o,n,a),c,null,AT,h)}const uw=z({sparseToDense_:NB});function CB(e,t){const n=W(t,"indices","gatherND","int32"),s=W(e,"x","gatherND"),i=a=>a.gatherND(s,n),o={params:s,indices:n};return G.runKernelFunc(i,o,null,uT)}const ov=z({gatherND_:CB});function RB(e,t){if(t==null)return e.shape.slice();if(ie(e.shape,t))return t;if(e.shape.length===t.length){const n=[];for(let s=0;s<e.shape.length;s++)t[s]==null&&e.shape[s]!=null?n.push(e.shape[s]):n.push(t[s]);return n}return t}function OB(e,t,n,s){const i=W(e,"x","dropout");if(A(i.dtype==="float32",()=>`x has to be a floating point tensor since it's going to be scaled, but got a ${i.dtype} tensor instead.`),A(t>=0&&t<1,()=>`rate must be a float in the range [0, 1), but got ${t}.`),t===0)return e instanceof te?i.clone():i;const o=RB(i,n),a=1-t,c=We(Za(be(Go(o,0,1,"float32",s),a)),a);return X(i,c)}const av=z({dropout_:OB});function cv(e){return Math.floor(Math.pow(2,Math.ceil(Math.log(e)/Math.log(2))))}function dw(e,t,n){const s=1-e%2,i=new Float32Array(e);for(let o=0;o<e;++o){const a=2*Math.PI*o/(e+s-1);i[o]=t-n*Math.cos(a)}return ds(i,"float32")}async function EB(e,t,n=1){const s=W(e,"predictions","inTopK"),i=W(t,"targets","inTopK");A(s.rank>1,()=>`inTopK() expects the predictions to be of rank 2 or higher, but got ${s.rank}`),A(s.rank-1===i.rank,()=>`predictions rank should be 1 larger than targets rank, but got predictions rank ${s.rank} and targets rank ${i.rank}`),U(s.shape.slice(0,s.shape.length-1),i.shape,"predictions's shape should be align with the targets' shape, except the last dimension.");const o=s.shape[s.shape.length-1];A(n>0&&n<=o,()=>`'k' passed to inTopK() must be > 0 && <= the predictions last dimension (${o}), but got ${n}`);const a=await s.data(),c=await i.data(),[h,p]=[a.length/o,o],m=bt("bool",h);for(let y=0;y<h;y++){const b=y*p,w=a.subarray(b,b+p),L=[];for(let T=0;T<w.length;T++)L.push({value:w[T],index:T});L.sort((T,v)=>v.value-T.value),m[y]=0;for(let T=0;T<n;T++)if(L[T].index===c[y]){m[y]=1;break}}return e!==s&&s.dispose(),t!==i&&i.dispose(),sn(m,i.shape,"bool")}const DB=EB;function kB(e,t,n,s,i,o="NHWC",a){let c=e;e.rank===3&&(c=K(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let h=t;h.rank===3&&(h=K(t,[1,t.shape[0],t.shape[1],t.shape[2]])),A(c.rank===4,()=>`Error in conv2dDerFilter: input must be rank 4, but got shape ${c.shape}.`),A(h.rank===4,()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${h.shape}.`),A(n.length===4,()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${n}.`);const p=o==="NHWC"?c.shape[3]:c.shape[1],m=o==="NHWC"?h.shape[3]:h.shape[1];A(p===n[2],()=>`Error in conv2dDerFilter: depth of input ${p}) must match input depth in filter (${n[2]}.`),A(m===n[3],()=>`Error in conv2dDerFilter: depth of dy (${m}) must match output depth for filter (${n[3]}).`),a!=null&&A(we(i),()=>`Error in conv2dDerFilter: pad must be an integer when using, dimRoundingMode ${a} but got pad ${i}.`);const y=L=>{const T=1,v=Gr(o),C=_n(c.shape,n,s,T,i,a,!1,v);return L.conv2dDerFilter(c,h,C)},b={x:c,dy:h},w={strides:s,pad:i,dataFormat:o,dimRoundingMode:a,filterShape:n};return G.runKernelFunc(y,b,null,fy,w)}const pw=z({conv2DBackpropFilter_:kB});function Yp(e,t,n){if(n==null||n==="linear")return e;if(n==="relu")return X(e,oc(t));throw new Error(`Cannot compute gradient for fused activation ${n}.`)}function Hp(e,t){let n=t;const s=mn(e.shape,t.shape);return s.length>0&&(n=$e(n,s)),K(n,e.shape)}function qp(e,t,n){if(t==="linear")return e;if(t==="relu")return Di(e);if(t==="elu")return Xa(e);if(t==="relu6")return tw(e);if(t==="prelu")return Eh(e,n);throw new Error(`Unknown fused activation ${t}.`)}const jp=(e,t)=>{const n=e>0;return!n||t==="linear"};function FB({x:e,filter:t,strides:n,pad:s,dataFormat:i="NHWC",dilations:o=[1,1],dimRoundingMode:a,bias:c,activation:h="linear",preluActivationWeights:p}){if(h=h||"linear",jp(G.state.gradientDepth,h)===!1){let F=sr(e,t,n,s,i,o,a);return c!=null&&(F=be(F,c)),qp(F,h,p)}const m=W(e,"x","conv2d"),y=W(t,"filter","conv2d");let b=m,w=!1;m.rank===3&&(w=!0,b=K(m,[1,m.shape[0],m.shape[1],m.shape[2]])),A(b.rank===4,()=>`Error in fused conv2d: input must be rank 4, but got rank ${b.rank}.`),A(y.rank===4,()=>`Error in fused conv2d: filter must be rank 4, but got rank ${y.rank}.`),a!=null&&A(we(s),()=>`Error in fused conv2d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${s}.`),A(b.shape[3]===y.shape[2],()=>`Error in conv2d: depth of input (${b.shape[3]}) must match input depth for filter ${y.shape[2]}.`),A(cn(n,o),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${o}'`),A(i==="NHWC",()=>`Error in conv2d: got dataFormat of ${i} but only NHWC is currently supported.`);const L=_n(b.shape,y.shape,n,o,s,a);let T;c!=null&&(T=W(c,"bias","fused conv2d"),[T]=Gt(T,m),st(L.outShape,T.shape));let v;p!=null&&(v=W(p,"prelu weights","fused conv2d"));const C=(F,B)=>{const[$,Y,j,Z]=B,re=Yp(F,j,h);A(Vr(o),()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${o}'`);const de=Ub(Y.shape,re,$,n,s),he=pw(Y,re,$.shape,n,s),ue=[de,he];if(Z!=null){const me=Hp(Z,re);ue.push(me)}return ue},O=F=>{const B=F.fusedConv2d({input:b,filter:y,convInfo:L,bias:T,activation:h,preluActivationWeights:v});return B},D={x:b,filter:y,bias:T,preluActivationWeights:v},k={strides:n,pad:s,dataFormat:i,dilations:o,dimRoundingMode:a,activation:h};if(c==null){const F=Oi((B,$,Y)=>{let j=G.runKernelFunc(O,D,null,Xd,k);return Y([$,B,j]),w&&(j=K(j,[j.shape[1],j.shape[2],j.shape[3]])),{value:j,gradFunc:C}});return F(b,y)}else{const F=Oi((B,$,Y,j)=>{let Z=G.runKernelFunc(O,D,null,Xd,k);return j([$,B,Z,Y]),w&&(Z=K(Z,[Z.shape[1],Z.shape[2],Z.shape[3]])),{value:Z,gradFunc:C}});return F(b,y,T)}}const mw=z({fusedConv2d_:FB});function _B(e,t,n,s,i,o=[1,1],a){let c=e;e.rank===3&&(c=K(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let h=t;h.rank===3&&(h=K(t,[1,t.shape[0],t.shape[1],t.shape[2]]));const p=b=>{const w=_n(e.shape,n,s,o,i,a,!0);return b.depthwiseConv2DDerFilter(c,h,w)},m={x:c,dy:h},y={strides:s,pad:i,dimRoundingMode:a,dilations:o,filterShape:n};return G.runKernelFunc(p,m,null,wy,y)}const lv=z({depthwiseConv2dNativeBackpropFilter_:_B});function WB(e,t,n,s,i,o=[1,1],a){let c=t,h=!1;t.rank===3&&(h=!0,c=K(t,[1,t.shape[0],t.shape[1],t.shape[2]]));const p=w=>{const L=_n(e,n.shape,s,o,i,a,!0);return w.depthwiseConv2DDerInput(c,n,L)},m={dy:c,filter:n},y={strides:s,pad:i,dimRoundingMode:a,dilations:o,inputShape:e},b=G.runKernelFunc(p,m,null,Ly,y);return h?K(b,[b.shape[1],b.shape[2],b.shape[3]]):b}const hv=z({depthwiseConv2dNativeBackpropInput_:WB});function $B({x:e,filter:t,strides:n,pad:s,dataFormat:i="NHWC",dilations:o=[1,1],dimRoundingMode:a,bias:c,activation:h="linear",preluActivationWeights:p}){if(jp(G.state.gradientDepth,h)===!1){let F=Bo(e,t,n,s,i,o,a);return c!=null&&(F=be(F,c)),qp(F,h,p)}const m=W(e,"x","depthwiseConv2d"),y=W(t,"filter","depthwiseConv2d");let b=m,w=!1;m.rank===3&&(w=!0,b=K(m,[1,m.shape[0],m.shape[1],m.shape[2]])),A(b.rank===4,()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${b.rank}.`),A(y.rank===4,()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${y.rank}.`),A(b.shape[3]===y.shape[2],()=>`Error in fused depthwiseConv2d: number of input channels (${b.shape[3]}) must match the inChannels dimension in filter ${y.shape[2]}.`),o==null&&(o=[1,1]),A(cn(n,o),()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${o}'`),a!=null&&A(we(s),()=>`Error in fused depthwiseConv2d: pad must be an integer when using dimRoundingMode ${a} but got pad ${s}.`);const L=_n(b.shape,y.shape,n,o,s,a,!0);let T;c!=null&&(T=W(c,"bias","fused conv2d"),[T]=Gt(T,m),st(L.outShape,T.shape));let v;p!=null&&(v=W(p,"prelu weights","fused depthwiseConv2d"));const C=(F,B)=>{A(Vr(o),()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${o}'`);const[$,Y,j,Z]=B,re=Yp(F,j,h),de=hv(Y.shape,re,$,n,s,o,a),he=lv(Y,re,$.shape,n,s,o,a);if(Z!=null){const ue=Hp(T,re);return[de,he,ue]}return[de,he]},O=F=>{const B=F.fusedDepthwiseConv2D({input:b,filter:y,convInfo:L,bias:T,activation:h,preluActivationWeights:v});return B},D={x:b,filter:y,bias:T,preluActivationWeights:v},k={strides:n,pad:s,dataFormat:i,dilations:o,dimRoundingMode:a,activation:h};if(c==null){const F=Oi((B,$,Y)=>{let j=G.runKernelFunc(O,D,null,Jd,k);return Y([$,B,j]),w&&(j=K(j,[j.shape[1],j.shape[2],j.shape[3]])),{value:j,gradFunc:C}});return F(b,y)}else{const F=Oi((B,$,Y,j)=>{let Z=G.runKernelFunc(O,D,null,Jd,k);return j([$,B,Z,Y]),w&&(Z=K(Z,[Z.shape[1],Z.shape[2],Z.shape[3]])),{value:Z,gradFunc:C}});return F(b,y,T)}}const uv=z({fusedDepthwiseConv2d_:$B});function UB({a:e,b:t,transposeA:n=!1,transposeB:s=!1,bias:i,activation:o="linear",preluActivationWeights:a}){if(jp(G.state.gradientDepth,o)===!1){let Z=lt(e,t,n,s);return i!=null&&(Z=be(Z,i)),qp(Z,o,a)}let c=W(e,"a","fused matMul"),h=W(t,"b","fused matMul");[c,h]=Gt(c,h);const p=n?c.shape[c.rank-2]:c.shape[c.rank-1],m=s?h.shape[h.rank-1]:h.shape[h.rank-2],y=n?c.shape[c.rank-1]:c.shape[c.rank-2],b=s?h.shape[h.rank-2]:h.shape[h.rank-1],w=c.shape.slice(0,-2),L=h.shape.slice(0,-2),T=M(w),v=M(L);A(c.rank>=2&&h.rank>=2&&c.rank===h.rank,()=>`Error in fused matMul: inputs must have the same rank of at least 2, got ranks ${c.rank} and ${h.rank}.`),A(ie(w,L),()=>`Error in fused matMul: outer dimensions (${w}) and (${L}) of Tensors with shapes ${c.shape} and ${h.shape} must match.`),A(p===m,()=>`Error in fused matMul: inner shapes (${p}) and (${m}) of Tensors with shapes ${c.shape} and ${h.shape} and transposeA=${n} and transposeB=${s} must match.`);const C=c.shape.slice(0,-2).concat([y,b]),O=n?K(c,[T,p,y]):K(c,[T,y,p]),D=s?K(h,[v,b,m]):K(h,[v,m,b]);let k;i!=null&&(k=W(i,"bias","fused matMul"),[k]=Gt(k,c),st(C,k.shape));let F;a!=null&&(F=W(a,"prelu weights","fused matMul"));const B=(Z,re)=>{const[de,he,ue,me]=re,ce=Yp(K(Z,ue.shape),ue,o);let ye,pe;if(!n&&!s?(ye=lt(ce,he,!1,!0),pe=lt(de,ce,!0,!1)):!n&&s?(ye=lt(ce,he,!1,!1),pe=lt(ce,de,!0,!1)):n&&!s?(ye=lt(he,ce,!1,!0),pe=lt(de,ce,!1,!1)):(ye=lt(he,ce,!0,!0),pe=lt(ce,de,!0,!0)),i!=null){const Le=Hp(me,ce);return[ye,pe,Le]}else return[ye,pe]},$=Z=>{const re=Z.fusedBatchMatMul({a:O,b:D,transposeA:n,transposeB:s,bias:k,activation:o,preluActivationWeights:F});return re},Y={a:O,b:D,bias:k,preluActivationWeights:F},j={transposeA:n,transposeB:s,activation:o};if(i==null){const Z=Oi((re,de,he)=>{const ue=G.runKernelFunc($,Y,null,Kd,j);return he([re,de,ue]),{value:K(ue,C),gradFunc:B}});return Z(O,D)}else{const Z=Oi((re,de,he,ue)=>{const me=G.runKernelFunc($,Y,null,Kd,j);return ue([re,de,me,he]),{value:K(me,C),gradFunc:B}});return Z(O,D,k)}}const Kp=z({fusedMatMul_:UB});var BB=Object.freeze({__proto__:null,conv2d:mw,depthwiseConv2d:uv,matMul:Kp});function MB(e){return dw(e,.54,.46)}const PB=z({hammingWindow_:MB});function zB(e){return dw(e,.5,.5)}const dv=z({hannWindow_:zB});function VB(e,t,n,s=!1,i=0){let o=0;const a=[];for(;o+t<=e.size;)a.push(nt(e,o,t)),o+=n;if(s)for(;o<e.size;){const c=o+t-e.size,h=Yt([nt(e,o,t-c),Ja([c],i)]);a.push(h),o+=n}return a.length===0?Kr([],[0,t]):K(Yt(a),[a.length,t])}const pv=z({frame_:VB});function GB(e,t,n,s,i=dv){s==null&&(s=cv(t));const o=pv(e,t,n),a=X(o,i(t)),c=[];for(let h=0;h<o.shape[0];h++)c.push(_h(nt(a,[h,0],[1,t]),s));return Yt(c)}const YB=z({stft_:GB});function HB(e,t,n,s,i,o){const a=W(e,"image","cropAndResize"),c=W(t,"boxes","cropAndResize","float32"),h=W(n,"boxInd","cropAndResize","int32");i=i||"bilinear",o=o||0;const p=c.shape[0];A(a.rank===4,()=>`Error in cropAndResize: image must be rank 4,but got rank ${a.rank}.`),A(c.rank===2&&c.shape[1]===4,()=>`Error in cropAndResize: boxes must be have size [${p},4] but had shape ${c.shape}.`),A(h.rank===1&&h.shape[0]===p,()=>`Error in cropAndResize: boxInd must be have size [${p}] but had shape ${c.shape}.`),A(s.length===2,()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${s.length}.`),A(s[0]>=1&&s[1]>=1,()=>`cropSize must be atleast [1,1], but was ${s}`),A(i==="bilinear"||i==="nearest",()=>`method must be bilinear or nearest, but was ${i}`);const m=L=>L.cropAndResize(a,c,h,s,i,o),y={image:a,boxes:c,boxInd:h},b={method:i,extrapolationValue:o,cropSize:s},w=G.runKernelFunc(m,y,null,oT,b);return w}const qB=z({cropAndResize_:HB});function jB(e){const t=W(e,"image","flipLeftRight","float32");A(t.rank===4,()=>`Error in flipLeftRight: image must be rank 4,but got rank ${t.rank}.`);const n={image:t},s=G.runKernel(Dd,n,{});return s}const KB=z({flipLeftRight_:jB});function XB(e,t,n=0,s=.5){const i=W(e,"image","rotateWithOffset","float32");A(i.rank===4,()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${i.rank}.`);const o={image:i},a={radians:t,fillValue:n,center:s},c=G.runKernel(jd,o,a);return c}const JB=z({rotateWithOffset_:XB});function cc(e,t,n,s,i,o){s==null&&(s=.5),i==null&&(i=Number.NEGATIVE_INFINITY),o==null&&(o=0);const a=e.shape[0];return n=Math.min(n,a),A(0<=s&&s<=1,()=>`iouThreshold must be in [0, 1], but was '${s}'`),A(e.rank===2,()=>`boxes must be a 2D tensor, but was of rank '${e.rank}'`),A(e.shape[1]===4,()=>`boxes must have 4 columns, but 2nd dimension was ${e.shape[1]}`),A(t.rank===1,()=>"scores must be a 1D tensor"),A(t.shape[0]===a,()=>`scores has incompatible shape with boxes. Expected ${a}, but was ${t.shape[0]}`),A(0<=o&&o<=1,()=>`softNmsSigma must be in [0, 1], but was '${o}'`),{maxOutputSize:n,iouThreshold:s,scoreThreshold:i,softNmsSigma:o}}function ZB(e,t,n,s=.5,i=Number.NEGATIVE_INFINITY){const o=W(e,"boxes","nonMaxSuppression"),a=W(t,"scores","nonMaxSuppression"),c=cc(o,a,n,s,i);n=c.maxOutputSize,s=c.iouThreshold,i=c.scoreThreshold;const h={maxOutputSize:n,iouThreshold:s,scoreThreshold:i};return G.runKernelFunc(p=>p.nonMaxSuppression(o,a,n,s,i),{boxes:o,scores:a},null,Fy,h)}const QB=z({nonMaxSuppression_:ZB});function eM(e,t,n){const s=tM(e,t,n),i=s<0?-(s+1):s;e.splice(i,0,t)}function tM(e,t,n){return sM(e,t,n||nM)}function nM(e,t){return e>t?1:e<t?-1:0}function sM(e,t,n){let s=0,i=e.length,o=0,a=!1;for(;s<i;){o=s+(i-s>>>1);const c=n(t,e[o]);c>0?s=o+1:(i=o,a=!c)}return a?s:-s-1}function Xp(e,t,n,s,i){return fw(e,t,n,s,i,0).selectedIndices}function Jp(e,t,n,s,i,o){return fw(e,t,n,s,i,0,!1,o,!0)}function Zp(e,t,n,s,i,o){return fw(e,t,n,s,i,o,!0)}function fw(e,t,n,s,i,o,a=!1,c=!1,h=!1){const p=[];for(let v=0;v<t.length;v++)t[v]>i&&p.push({score:t[v],boxIndex:v,suppressBeginIndex:0});p.sort(mv);const m=o>0?-.5/o:0,y=[],b=[];for(;y.length<n&&p.length>0;){const v=p.pop(),{score:C,boxIndex:O,suppressBeginIndex:D}=v;if(C<i)break;let k=!1;for(let F=y.length-1;F>=D;--F){const B=iM(e,O,y[F]);if(B>=s){k=!0;break}if(v.score=v.score*rM(s,m,B),v.score<=i)break}v.suppressBeginIndex=y.length,k||(v.score===C?(y.push(O),b.push(v.score)):v.score>i&&eM(p,v,mv))}const w=y.length,L=n-w;c&&L>0&&(y.push(...new Array(L).fill(0)),b.push(...new Array(L).fill(0)));const T={selectedIndices:ds(y,"int32")};return a&&(T.selectedScores=ds(b,"float32")),h&&(T.validOutputs=Ce(w,"int32")),T}function iM(e,t,n){const s=e.subarray(t*4,t*4+4),i=e.subarray(n*4,n*4+4),o=Math.min(s[0],s[2]),a=Math.min(s[1],s[3]),c=Math.max(s[0],s[2]),h=Math.max(s[1],s[3]),p=Math.min(i[0],i[2]),m=Math.min(i[1],i[3]),y=Math.max(i[0],i[2]),b=Math.max(i[1],i[3]),w=(c-o)*(h-a),L=(y-p)*(b-m);if(w<=0||L<=0)return 0;const T=Math.max(o,p),v=Math.max(a,m),C=Math.min(c,y),O=Math.min(h,b),D=Math.max(C-T,0)*Math.max(O-v,0);return D/(w+L-D)}function rM(e,t,n){const s=Math.exp(t*n*n);return n<=e?s:0}function mv(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex}async function oM(e,t,n,s=.5,i=Number.NEGATIVE_INFINITY){const o=W(e,"boxes","nonMaxSuppressionAsync"),a=W(t,"scores","nonMaxSuppressionAsync"),c=cc(o,a,n,s,i);n=c.maxOutputSize,s=c.iouThreshold,i=c.scoreThreshold;const h=await Promise.all([o.data(),a.data()]),p=h[0],m=h[1],y=Xp(p,m,n,s,i);return o!==e&&o.dispose(),a!==t&&a.dispose(),y}const aM=oM;function cM(e,t,n,s=.5,i=Number.NEGATIVE_INFINITY,o=0){const a=W(e,"boxes","nonMaxSuppression"),c=W(t,"scores","nonMaxSuppression"),h=cc(a,c,n,s,i,o);n=h.maxOutputSize,s=h.iouThreshold,i=h.scoreThreshold,o=h.softNmsSigma;const p={boxes:a,scores:c},m={maxOutputSize:n,iouThreshold:s,scoreThreshold:i,softNmsSigma:o},y=G.runKernel(Bd,p,m);return{selectedIndices:y[0],selectedScores:y[1]}}const lM=z({nonMaxSuppressionWithScore_:cM});async function hM(e,t,n,s=.5,i=Number.NEGATIVE_INFINITY,o=0){const a=W(e,"boxes","nonMaxSuppressionAsync"),c=W(t,"scores","nonMaxSuppressionAsync"),h=cc(a,c,n,s,i,o);n=h.maxOutputSize,s=h.iouThreshold,i=h.scoreThreshold,o=h.softNmsSigma;const p=await Promise.all([a.data(),c.data()]),m=p[0],y=p[1],b=Zp(m,y,n,s,i,o);return a!==e&&a.dispose(),c!==t&&c.dispose(),b}const uM=hM;function dM(e,t,n,s=.5,i=Number.NEGATIVE_INFINITY,o=!1){const a=W(e,"boxes","nonMaxSuppression"),c=W(t,"scores","nonMaxSuppression"),h=cc(a,c,n,s,i,null),p=h.maxOutputSize,m=h.iouThreshold,y=h.scoreThreshold,b={boxes:a,scores:c},w={maxOutputSize:p,iouThreshold:m,scoreThreshold:y,padToMaxOutputSize:o},L=G.runKernel(Ud,b,w);return{selectedIndices:L[0],validOutputs:L[1]}}const pM=z({nonMaxSuppressionPadded_:dM});async function mM(e,t,n,s=.5,i=Number.NEGATIVE_INFINITY,o=!1){const a=W(e,"boxes","nonMaxSuppressionAsync"),c=W(t,"scores","nonMaxSuppressionAsync"),h=cc(a,c,n,s,i,null),p=h.maxOutputSize,m=h.iouThreshold,y=h.scoreThreshold,[b,w]=await Promise.all([a.data(),c.data()]),L=Jp(b,w,p,m,y,o);return a!==e&&a.dispose(),c!==t&&c.dispose(),L}const fM=mM;function gM(e,t,n=!1){const s=W(e,"images","resizeBilinear");A(s.rank===3||s.rank===4,()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${s.rank}.`),A(t.length===2,()=>`Error in resizeBilinear: new shape must 2D, but got shape ${t}.`);let i=s,o=!1;s.rank===3&&(o=!0,i=K(s,[1,s.shape[0],s.shape[1],s.shape[2]]));const[a,c]=t,h=(b,w)=>(w([i]),b.resizeBilinear(i,a,c,n)),p={images:i},m={alignCorners:n,size:t},y=G.runKernelFunc(h,p,null,By,m);return o?K(y,[y.shape[1],y.shape[2],y.shape[3]]):y}const fv=z({resizeBilinear_:gM});function yM(e,t,n=!1){const s=W(e,"images","resizeNearestNeighbor");A(s.rank===3||s.rank===4,()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${s.rank}.`),A(t.length===2,()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${t}.`),A(s.dtype==="float32"||s.dtype==="int32",()=>"`images` must have `int32` or `float32` as dtype");let i=s,o=!1;s.rank===3&&(o=!0,i=K(s,[1,s.shape[0],s.shape[1],s.shape[2]]));const[a,c]=t,h={images:i},p={alignCorners:n,size:t},m=(b,w)=>(w([i]),b.resizeNearestNeighbor(i,a,c,n)),y=G.runKernelFunc(m,h,null,Uy,p);return o?K(y,[y.shape[1],y.shape[2],y.shape[3]]):y}const gv=z({resizeNearestNeighbor_:yM});function bM(e,t,n){A(t%1===0,()=>`bandPart(): numLower must be an integer, got ${t}.`),A(n%1===0,()=>`bandPart(): numUpper must be an integer, got ${n}.`);const s=W(e,"a","bandPart");A(s.rank>=2,()=>`bandPart(): Rank must be at least 2, got ${s.rank}.`);const i=s.shape,[o,a]=s.shape.slice(-2);if(!(t<=o))throw new Error(`bandPart(): numLower (${t}) must not be greater than the number of rows (${o}).`);if(!(n<=a))throw new Error(`bandPart(): numUpper (${n}) must not be greater than the number of columns (${a}).`);t<0&&(t=o),n<0&&(n=a);const c=K(Dh(0,o,1,"int32"),[-1,1]),h=Dh(0,a,1,"int32"),p=Re(c,h),m=Ps(Hr(p,Ce(+t,"int32")),ir(p,Ce(-n,"int32"))),y=pt([o,a],s.dtype);return K(ss(si(K(s,[-1,o,a])).map(b=>Pn(m,b,y))),i)}const wM=z({bandPart_:bM});function LM(e){let t;if(Array.isArray(e)){t=!1,A(e!=null&&e.length>0,()=>"Gram-Schmidt process: input must not be null, undefined, or empty");const i=e[0].shape[0];for(let o=1;o<e.length;++o)A(e[o].shape[0]===i,()=>`Gram-Schmidt: Non-unique lengths found in the input vectors: (${e[o].shape[0]} vs. ${i})`)}else t=!0,e=ps(e,e.shape[0],0).map(i=>jr(i,[0]));A(e.length<=e[0].shape[0],()=>`Gram-Schmidt: Number of vectors (${e.length}) exceeds number of dimensions (${e[0].shape[0]}).`);const n=[],s=e;for(let i=0;i<e.length;++i)n.push(G.tidy(()=>{let o=s[i];if(i>0)for(let a=0;a<i;++a){const c=X($e(X(n[a],o)),n[a]);o=Re(o,c)}return We(o,Gp(o,"euclidean"))}));return t?ss(n,0):n}const SM=z({gramSchmidt_:LM});function IM(e,t=!1){if(A(e.rank>=2,()=>`qr() requires input tensor to have a rank >= 2, but got rank ${e.rank}`),e.rank===2)return yv(e,t);{const n=e.shape.slice(0,e.shape.length-2).reduce((h,p)=>h*p),s=si(K(e,[n,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),i=[],o=[];s.forEach(h=>{const[p,m]=yv(h,t);i.push(p),o.push(m)});const a=K(ss(i,0),e.shape),c=K(ss(o,0),e.shape);return[a,c]}}function yv(e,t=!1){return G.tidy(()=>{A(e.shape.length===2,()=>`qr2d() requires a 2D Tensor, but got a ${e.shape.length}D Tensor.`);const n=e.shape[0],s=e.shape[1];let i=vp(n),o=Pr(e);const a=Kr([[1]],[1,1]);let c=Pr(a);const h=n>=s?s:n;for(let p=0;p<h;++p){const m=o,y=c,b=i;[c,o,i]=G.tidy(()=>{const w=nt(o,[p,p],[n-p,1]),L=Gp(w),T=nt(o,[p,p],[1,1]),v=Pn(vs(T,0),Kr([[-1]]),Kr([[1]])),C=Re(T,X(v,L)),O=We(w,C);O.shape[0]===1?c=Pr(a):c=Yt([a,nt(O,[1,0],[O.shape[0]-1,O.shape[1]])],0);const D=Ht(We(lt(v,C),L)),k=nt(o,[p,0],[n-p,s]),F=X(D,c),B=Ye(c);if(p===0)o=Re(k,lt(F,lt(B,k)));else{const j=Re(k,lt(F,lt(B,k)));o=Yt([nt(o,[0,0],[p,s]),j],0)}const $=Ye(F),Y=nt(i,[0,p],[n,i.shape[1]-p]);if(p===0)i=Re(Y,lt(lt(Y,c),$));else{const j=Re(Y,lt(lt(Y,c),$));i=Yt([nt(i,[0,0],[n,p]),j],1)}return[c,o,i]}),qe([m,y,b])}return!t&&n>s&&(i=nt(i,[0,0],[n,s]),o=nt(o,[0,0],[s,s])),[i,o]})}const xM=z({qr_:IM});(function(e){e[e.NONE=0]="NONE",e[e.MEAN=1]="MEAN",e[e.SUM=2]="SUM",e[e.SUM_BY_NONZERO_WEIGHTS=3]="SUM_BY_NONZERO_WEIGHTS"})(r.Reduction||(r.Reduction={}));function TM(e,t,n=r.Reduction.SUM_BY_NONZERO_WEIGHTS){const s=W(e,"losses","computeWeightedLoss");let i=null;t!=null&&(i=W(t,"weights","computeWeightedLoss"));const o=i==null?s:X(s,i);if(n===r.Reduction.NONE)return o;if(n===r.Reduction.SUM)return $e(o);if(n===r.Reduction.MEAN){if(i==null)return qt(o);{const a=s.size/i.size,c=We($e(o),$e(i));return a>1?We(c,Ce(a)):c}}if(n===r.Reduction.SUM_BY_NONZERO_WEIGHTS){if(i==null)return We($e(o),Ce(s.size));{const a=X(i,ti(s.shape)),c=ve($e(qr(a,Ce(0))),"float32");return We($e(o),c)}}throw Error(`Unknown reduction: ${n}`)}const rr=z({computeWeightedLoss_:TM});function AM(e,t,n,s=r.Reduction.SUM_BY_NONZERO_WEIGHTS){const i=W(e,"labels","absoluteDifference"),o=W(t,"predictions","absoluteDifference");let a=null;n!=null&&(a=W(n,"weights","absoluteDifference")),U(i.shape,o.shape,"Error in absoluteDifference: ");const c=pn(Re(i,o));return rr(c,a,s)}const vM=z({absoluteDifference_:AM});function NM(e,t,n,s,i=r.Reduction.SUM_BY_NONZERO_WEIGHTS){const o=W(e,"labels","cosineDistance"),a=W(t,"predictions","cosineDistance");let c=null;s!=null&&(c=W(s,"weights","cosineDistance")),U(o.shape,a.shape,"Error in cosineDistance: ");const h=Ce(1),p=Re(h,$e(X(o,a),n,!0));return rr(p,c,i)}const CM=z({cosineDistance_:NM});function RM(e,t,n,s=r.Reduction.SUM_BY_NONZERO_WEIGHTS){let i=W(e,"labels","hingeLoss");const o=W(t,"predictions","hingeLoss");let a=null;n!=null&&(a=W(n,"weights","hingeLoss")),U(i.shape,o.shape,"Error in hingeLoss: ");const c=Ce(1);i=Re(X(Ce(2),i),c);const h=Di(Re(c,X(i,o)));return rr(h,a,s)}const OM=z({hingeLoss_:RM});function EM(e,t,n,s=1,i=r.Reduction.SUM_BY_NONZERO_WEIGHTS){const o=W(e,"labels","huberLoss"),a=W(t,"predictions","huberLoss");let c=null;n!=null&&(c=W(n,"weights","huberLoss")),U(o.shape,a.shape,"Error in huberLoss: ");const h=Ce(s),p=pn(Re(a,o)),m=Po(p,h),y=Re(p,m),b=be(X(Ce(.5),At(m)),X(h,y));return rr(b,c,i)}const DM=z({huberLoss_:EM});function kM(e,t,n,s=1e-7,i=r.Reduction.SUM_BY_NONZERO_WEIGHTS){const o=W(e,"labels","logLoss"),a=W(t,"predictions","logLoss");let c=null;n!=null&&(c=W(n,"weights","logLoss")),U(o.shape,a.shape,"Error in logLoss: ");const h=Ce(1),p=Ce(s),m=Ht(X(o,us(be(a,p)))),y=X(Re(h,o),us(be(Re(h,a),p))),b=Re(m,y);return rr(b,c,i)}const FM=z({logLoss_:kM});function _M(e,t,n,s=r.Reduction.SUM_BY_NONZERO_WEIGHTS){const i=W(e,"labels","meanSquaredError"),o=W(t,"predictions","meanSquaredError");let a=null;n!=null&&(a=W(n,"weights","meanSquaredError")),U(i.shape,o.shape,"Error in meanSquaredError: ");const c=Wh(i,o);return rr(c,a,s)}const WM=z({meanSquaredError_:_M});function $M(e,t){const n=W(e,"labels","sigmoidCrossEntropyWithLogits"),s=W(t,"logits","sigmoidCrossEntropyWithLogits");U(n.shape,s.shape,"Error in sigmoidCrossEntropyWithLogits: ");const i=Di(s),o=X(s,n),a=Cp(As(Ht(pn(s))));return be(Re(i,o),a)}function UM(e,t,n,s=0,i=r.Reduction.SUM_BY_NONZERO_WEIGHTS){let o=W(e,"multiClassLabels","sigmoidCrossEntropy");const a=W(t,"logits","sigmoidCrossEntropy");let c=null;if(n!=null&&(c=W(n,"weights","sigmoidCrossEntropy")),U(o.shape,a.shape,"Error in sigmoidCrossEntropy: "),s>0){const p=Ce(s),m=Ce(1),y=Ce(.5);o=be(X(o,Re(m,p)),X(y,p))}const h=$M(o,a);return rr(h,c,i)}const BM=z({sigmoidCrossEntropy_:UM});function MM(e,t,n=-1){if(n===-1&&(n=t.rank-1),n!==t.rank-1)throw Error(`Softmax cross entropy along a non-last dimension is not yet supported. Labels / logits was rank ${t.rank} and dim was ${n}`);const s=Oi((i,o,a)=>{const c=!0,h=jb(o,[n],c),p=Re(ve(o,"float32"),h);a([i,p]);const m=Ht(X(p,i)),y=$e(m,[n]),b=(w,L)=>{const[T,v]=L,C=Nn(w.shape,[n]);return[X(K(w,C),Re(ve(T,"float32"),As(v))),X(K(w,C),Re(As(v),ve(T,"float32")))]};return{value:y,gradFunc:b}});return s(e,t)}function PM(e,t,n,s=0,i=r.Reduction.SUM_BY_NONZERO_WEIGHTS){let o=W(e,"onehotLabels","softmaxCrossEntropy");const a=W(t,"logits","softmaxCrossEntropy");let c=null;if(n!=null&&(c=W(n,"weights","softmaxCrossEntropy")),U(o.shape,a.shape,"Error in softmaxCrossEntropy: "),s>0){const p=Ce(s),m=Ce(1),y=Ce(o.shape[1]);o=be(X(o,Re(m,p)),We(p,y))}const h=MM(o,a);return rr(h,c,i)}const zM=z({softmaxCrossEntropy_:PM});const VM={fft:Fh,ifft:rc,rfft:_h,irfft:Pp},GM={hammingWindow:PB,hannWindow:dv,frame:pv,stft:YB},Xr={flipLeftRight:KB,resizeNearestNeighbor:gv,resizeBilinear:fv,rotateWithOffset:JB,cropAndResize:qB,nonMaxSuppression:QB,nonMaxSuppressionAsync:aM,nonMaxSuppressionWithScore:lM,nonMaxSuppressionWithScoreAsync:uM,nonMaxSuppressionPadded:pM,nonMaxSuppressionPaddedAsync:fM},bv={bandPart:wM,gramSchmidt:SM,qr:xM},YM={absoluteDifference:vM,computeWeightedLoss:rr,cosineDistance:CM,hingeLoss:OM,huberLoss:DM,logLoss:FM,meanSquaredError:WM,sigmoidCrossEntropy:BM,softmaxCrossEntropy:zM};class or extends Wo{minimize(e,t=!1,n){const{value:s,grads:i}=this.computeGradients(e,n);if(n!=null){const o=n.map(a=>({name:a.name,tensor:i[a.name]}));this.applyGradients(o)}else this.applyGradients(i);return qe(i),t?s:(s.dispose(),null)}get iterations(){return this.iterations_==null&&(this.iterations_=0),this.iterations_}incrementIterations(){this.iterations_=this.iterations+1}computeGradients(e,t){return qb(e,t)}dispose(){this.iterations_!=null&&qe(this.iterations_)}async saveIterations(){return this.iterations_==null&&(this.iterations_=0),{name:"iter",tensor:Ce(this.iterations_,"int32")}}async getWeights(){throw new Error("getWeights() is not implemented for this optimizer yet.")}async setWeights(e){throw new Error(`setWeights() is not implemented for this optimizer class ${this.getClassName()}`)}async extractIterations(e){return this.iterations_=(await e[0].tensor.data())[0],e.slice(1)}}Object.defineProperty(or,Symbol.hasInstance,{value:e=>e.minimize!=null&&e.computeGradients!=null&&e.applyGradients!=null});class Uh extends or{constructor(e,t,n=null){super();this.learningRate=e,this.rho=t,this.epsilon=n,this.accumulatedGrads=[],this.accumulatedUpdates=[],n==null&&(this.epsilon=G.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);t.forEach((n,s)=>{const i=G.registeredVariables[n],o=!1;this.accumulatedGrads[s]==null&&(this.accumulatedGrads[s]={originalName:`${n}/accum_grad`,variable:ee(()=>tt(i).variable(o))}),this.accumulatedUpdates[s]==null&&(this.accumulatedUpdates[s]={originalName:`${n}/accum_var`,variable:ee(()=>tt(i).variable(o))});const a=Array.isArray(e)?e[s].tensor:e[n];if(a==null)return;const c=this.accumulatedGrads[s].variable,h=this.accumulatedUpdates[s].variable;ee(()=>{const p=be(X(c,this.rho),X(At(a),1-this.rho)),m=X(We(Cn(be(h,this.epsilon)),Cn(be(c,this.epsilon))),a),y=be(X(h,this.rho),X(At(m),1-this.rho));c.assign(p),h.assign(y);const b=be(X(m,-this.learningRate),i);i.assign(b)})}),this.incrementIterations()}dispose(){this.accumulatedUpdates!=null&&(qe(this.accumulatedGrads.map(e=>e.variable)),qe(this.accumulatedUpdates.map(e=>e.variable)))}async getWeights(){const e=[...this.accumulatedGrads,...this.accumulatedUpdates];return[await this.saveIterations()].concat(e.map(t=>({name:t.originalName,tensor:t.variable})))}async setWeights(e){e=await this.extractIterations(e);const t=e.length/2,n=!1;this.accumulatedGrads=e.slice(0,t).map(s=>({originalName:s.name,variable:s.tensor.variable(n)})),this.accumulatedUpdates=e.slice(t,t*2).map(s=>({originalName:s.name,variable:s.tensor.variable(n)}))}getConfig(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.rho,t.epsilon)}}Uh.className="Adadelta",ge(Uh);class Bh extends or{constructor(e,t=.1){super();this.learningRate=e,this.initialAccumulatorValue=t,this.accumulatedGrads=[]}applyGradients(e){const t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);t.forEach((n,s)=>{const i=G.registeredVariables[n];if(this.accumulatedGrads[s]==null){const c=!1;this.accumulatedGrads[s]={originalName:`${n}/accumulator`,variable:ee(()=>Ja(i.shape,this.initialAccumulatorValue).variable(c))}}const o=Array.isArray(e)?e[s].tensor:e[n];if(o==null)return;const a=this.accumulatedGrads[s].variable;ee(()=>{const c=be(a,At(o));a.assign(c);const h=be(X(We(o,Cn(be(c,G.backend.epsilon()))),-this.learningRate),i);i.assign(h)})}),this.incrementIterations()}dispose(){this.accumulatedGrads!=null&&qe(this.accumulatedGrads.map(e=>e.variable))}async getWeights(){return[await this.saveIterations()].concat(this.accumulatedGrads.map(e=>({name:e.originalName,tensor:e.variable})))}async setWeights(e){e=await this.extractIterations(e);const t=!1;this.accumulatedGrads=e.map(n=>({originalName:n.name,variable:n.tensor.variable(t)}))}getConfig(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}}static fromConfig(e,t){return new e(t.learningRate,t.initialAccumulatorValue)}}Bh.className="Adagrad",ge(Bh);class Mh extends or{constructor(e,t,n,s=null){super();this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=s,this.accumulatedFirstMoment=[],this.accumulatedSecondMoment=[],ee(()=>{this.accBeta1=Ce(t).variable(),this.accBeta2=Ce(n).variable()}),s==null&&(this.epsilon=G.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);ee(()=>{const n=Re(1,this.accBeta1),s=Re(1,this.accBeta2);t.forEach((i,o)=>{const a=G.registeredVariables[i],c=!1;this.accumulatedFirstMoment[o]==null&&(this.accumulatedFirstMoment[o]={originalName:`${i}/m`,variable:ee(()=>tt(a).variable(c))}),this.accumulatedSecondMoment[o]==null&&(this.accumulatedSecondMoment[o]={originalName:`${i}/v`,variable:ee(()=>tt(a).variable(c))});const h=Array.isArray(e)?e[o].tensor:e[i];if(h==null)return;const p=this.accumulatedFirstMoment[o].variable,m=this.accumulatedSecondMoment[o].variable,y=be(X(p,this.beta1),X(h,1-this.beta1)),b=be(X(m,this.beta2),X(At(h),1-this.beta2)),w=We(y,n),L=We(b,s);p.assign(y),m.assign(b);const T=be(X(We(w,be(Cn(L),this.epsilon)),-this.learningRate),a);a.assign(T)}),this.accBeta1.assign(X(this.accBeta1,this.beta1)),this.accBeta2.assign(X(this.accBeta2,this.beta2))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.accBeta2.dispose(),this.accumulatedFirstMoment!=null&&qe(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedSecondMoment!=null&&qe(this.accumulatedSecondMoment.map(e=>e.variable))}async getWeights(){const e=[...this.accumulatedFirstMoment,...this.accumulatedSecondMoment];return[await this.saveIterations()].concat(e.map(t=>({name:t.originalName,tensor:t.variable})))}async setWeights(e){e=await this.extractIterations(e),ee(()=>{this.accBeta1.assign(ni(this.beta1,this.iterations_+1)),this.accBeta2.assign(ni(this.beta2,this.iterations_+1))});const t=e.length/2,n=!1;this.accumulatedFirstMoment=e.slice(0,t).map(s=>({originalName:s.name,variable:s.tensor.variable(n)})),this.accumulatedSecondMoment=e.slice(t,t*2).map(s=>({originalName:s.name,variable:s.tensor.variable(n)}))}getConfig(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon)}}Mh.className="Adam",ge(Mh);class Ph extends or{constructor(e,t,n,s=null,i=0){super();this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=s,this.decay=i,this.accumulatedFirstMoment=[],this.accumulatedWeightedInfNorm=[],ee(()=>{this.iteration=Ce(0).variable(),this.accBeta1=Ce(t).variable()}),s==null&&(this.epsilon=G.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);ee(()=>{const n=Re(1,this.accBeta1),s=We(-this.learningRate,be(X(this.iteration,this.decay),1));t.forEach((i,o)=>{const a=G.registeredVariables[i],c=!1;this.accumulatedFirstMoment[o]==null&&(this.accumulatedFirstMoment[o]={originalName:`${i}/m`,variable:tt(a).variable(c)}),this.accumulatedWeightedInfNorm[o]==null&&(this.accumulatedWeightedInfNorm[o]={originalName:`${i}/v`,variable:tt(a).variable(c)});const h=Array.isArray(e)?e[o].tensor:e[i];if(h==null)return;const p=this.accumulatedFirstMoment[o].variable,m=this.accumulatedWeightedInfNorm[o].variable,y=be(X(p,this.beta1),X(h,1-this.beta1)),b=X(m,this.beta2),w=pn(h),L=Ms(b,w);p.assign(y),m.assign(L);const T=be(X(We(s,n),We(y,be(L,this.epsilon))),a);a.assign(T)}),this.iteration.assign(be(this.iteration,1)),this.accBeta1.assign(X(this.accBeta1,this.beta1))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.iteration.dispose(),this.accumulatedFirstMoment!=null&&qe(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedWeightedInfNorm!=null&&qe(this.accumulatedWeightedInfNorm.map(e=>e.variable))}async getWeights(){throw new Error("getWeights() is not implemented for Adamax yet.")}async setWeights(e){throw new Error("setWeights() is not implemented for Adamax yet.")}getConfig(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon,decay:this.decay}}static fromConfig(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon,t.decay)}}Ph.className="Adamax",ge(Ph);class lc extends or{constructor(e){super();this.learningRate=e,this.setLearningRate(e)}applyGradients(e){const t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);t.forEach((n,s)=>{const i=Array.isArray(e)?e[s].tensor:e[n];if(i==null)return;const o=G.registeredVariables[n];ee(()=>{const a=be(X(this.c,i),o);o.assign(a)})}),this.incrementIterations()}setLearningRate(e){this.learningRate=e,this.c!=null&&this.c.dispose(),this.c=wn(Ce(-e))}dispose(){this.c.dispose()}async getWeights(){return[await this.saveIterations()]}async setWeights(e){if(e=await this.extractIterations(e),e.length!==0)throw new Error("SGD optimizer does not have settable weights.")}getConfig(){return{learningRate:this.learningRate}}static fromConfig(e,t){return new e(t.learningRate)}}lc.className="SGD",ge(lc);class zh extends lc{constructor(e,t,n=!1){super(e);this.learningRate=e,this.momentum=t,this.useNesterov=n,this.accumulations=[],this.m=Ce(this.momentum)}applyGradients(e){const t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);t.forEach((n,s)=>{const i=G.registeredVariables[n];if(this.accumulations[s]==null){const c=!1;this.accumulations[s]={originalName:`${n}/momentum`,variable:ee(()=>tt(i).variable(c))}}const o=this.accumulations[s].variable,a=Array.isArray(e)?e[s].tensor:e[n];if(a==null)return;ee(()=>{let c;const h=be(X(this.m,o),a);this.useNesterov?c=be(X(this.c,be(a,X(h,this.m))),i):c=be(X(this.c,h),i),o.assign(h),i.assign(c)})}),this.incrementIterations()}dispose(){this.m.dispose(),this.accumulations!=null&&qe(this.accumulations.map(e=>e.variable))}setMomentum(e){this.momentum=e}async getWeights(){return[await this.saveIterations()].concat(this.accumulations.map(e=>({name:e.originalName,tensor:e.variable})))}async setWeights(e){e=await this.extractIterations(e);const t=!1;this.accumulations=e.map(n=>({originalName:n.name,variable:n.tensor.variable(t)}))}getConfig(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}}static fromConfig(e,t){return new e(t.learningRate,t.momentum,t.useNesterov)}}zh.className="Momentum",ge(zh);class Vh extends or{constructor(e,t=.9,n=0,s=null,i=!1){super();if(this.learningRate=e,this.decay=t,this.momentum=n,this.epsilon=s,this.accumulatedMeanSquares=[],this.accumulatedMoments=[],this.accumulatedMeanGrads=[],this.centered=i,s==null&&(this.epsilon=G.backend.epsilon()),e==null)throw new Error("learningRate for RMSPropOptimizer must be defined.")}applyGradients(e){const t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);t.forEach((n,s)=>{const i=G.registeredVariables[n],o=!1;this.accumulatedMeanSquares[s]==null&&(this.accumulatedMeanSquares[s]={originalName:`${n}/rms`,variable:ee(()=>tt(i).variable(o))}),this.accumulatedMoments[s]==null&&(this.accumulatedMoments[s]={originalName:`${n}/momentum`,variable:ee(()=>tt(i).variable(o))}),this.accumulatedMeanGrads[s]==null&&this.centered&&(this.accumulatedMeanGrads[s]={originalName:`${n}/mg`,variable:ee(()=>tt(i).variable(o))});const a=Array.isArray(e)?e[s].tensor:e[n];if(a==null)return;const c=this.accumulatedMeanSquares[s].variable,h=this.accumulatedMoments[s].variable;ee(()=>{const p=be(X(c,this.decay),X(At(a),1-this.decay));if(this.centered){const m=this.accumulatedMeanGrads[s].variable,y=be(X(m,this.decay),X(a,1-this.decay)),b=We(X(a,this.learningRate),Cn(Re(p,be(At(y),this.epsilon)))),w=be(X(h,this.momentum),b);c.assign(p),m.assign(y),h.assign(w);const L=Re(i,w);i.assign(L)}else{const m=be(X(c,this.decay),X(At(a),1-this.decay)),y=be(X(h,this.momentum),We(X(a,this.learningRate),Cn(be(m,this.epsilon))));c.assign(m),h.assign(y);const b=Re(i,y);i.assign(b)}})}),this.incrementIterations()}dispose(){this.accumulatedMeanSquares!=null&&qe(this.accumulatedMeanSquares.map(e=>e.variable)),this.accumulatedMeanGrads!=null&&this.centered&&qe(this.accumulatedMeanGrads.map(e=>e.variable)),this.accumulatedMoments!=null&&qe(this.accumulatedMoments.map(e=>e.variable))}async getWeights(){const e=[...this.accumulatedMeanSquares,...this.accumulatedMoments];return this.centered&&e.push(...this.accumulatedMeanGrads),[await this.saveIterations()].concat(e.map(t=>({name:t.originalName,tensor:t.variable})))}async setWeights(e){e=await this.extractIterations(e);const t=this.centered?e.length/3:e.length/2,n=!1;this.accumulatedMeanSquares=e.slice(0,t).map(s=>({originalName:s.name,variable:s.tensor.variable(n)})),this.accumulatedMoments=e.slice(t,t*2).map(s=>({originalName:s.name,variable:s.tensor.variable(n)})),this.centered&&(this.accumulatedMeanGrads=e.slice(t*2,t*3).map(s=>({originalName:s.name,variable:s.tensor.variable(n)})))}getConfig(){return{learningRate:this.learningRate,decay:this.decay,momentum:this.momentum,epsilon:this.epsilon,centered:this.centered}}static fromConfig(e,t){return new e(t.learningRate,t.decay,t.momentum,t.epsilon,t.centered)}}Vh.className="RMSProp",ge(Vh);class Ho{static sgd(e){return new lc(e)}static momentum(e,t,n=!1){return new zh(e,t,n)}static rmsprop(e,t=.9,n=0,s=null,i=!1){return new Vh(e,t,n,s,i)}static adam(e=.001,t=.9,n=.999,s=null){return new Mh(e,t,n,s)}static adadelta(e=.001,t=.95,n=null){return new Uh(e,t,n)}static adamax(e=.002,t=.9,n=.999,s=null,i=0){return new Ph(e,t,n,s,i)}static adagrad(e,t=.1){return new Bh(e,t)}}const qo={sgd:Ho.sgd,momentum:Ho.momentum,adadelta:Ho.adadelta,adagrad:Ho.adagrad,rmsprop:Ho.rmsprop,adamax:Ho.adamax,adam:Ho.adam};const HM=(()=>typeof requestAnimationFrame!="undefined"?requestAnimationFrame:typeof setImmediate!="undefined"?setImmediate:e=>e())();function Qp(){return new Promise(e=>HM(()=>e()))}function gw(e,t,n){const s=n*(typeof e=="number"?e:e[0]),i=t*(typeof e=="number"?e:e[1]);return[s,i]}function Gh(e,t,n,s=!0){let i=[];if(s)i=i.concat(t.slice(0)),i.push(e[0]/n),i=i.concat(e.slice(1));else{i=i.concat(e[0]);const o=t.length;for(let a=0;a<o;++a)i=i.concat([e[a+1]/t[a],t[a]]);i=i.concat(e.slice(o+1))}return i}function Yh(e,t,n=!0){const s=[];if(n){s.push(t);for(let i=t+1;i<e;++i)i<=2*t?(s.push(i),s.push(i-(t+1))):s.push(i)}else{const i=[],o=[];for(let a=1;a<e;++a)a>=t*2+1||a%2===1?o.push(a):i.push(a);s.push(...i),s.push(0),s.push(...o)}return s}function Hh(e,t,n,s=!0){const i=[];s?i.push(e[0]/n):i.push(e[0]*n);for(let o=1;o<e.length;++o)o<=t.length?s?i.push(t[o-1]*e[o]):i.push(e[o]/t[o-1]):i.push(e[o]);return i}function yw(e,t){const n=[0];for(let s=0;s<t;++s)n.push(e[s][0]);return n}function bw(e,t,n){const s=e.slice(0,1);for(let i=0;i<n;++i)s.push(e[i+1]-t[i][0]-t[i][1]);return s}const em=1.7580993408473768,tm=1.0507009873554805;const ww=.3275911,Lw=.254829592,Sw=-.284496736,Iw=1.421413741,xw=-1.453152027,Tw=1.061405429;function hc(...e){ae().getBool("IS_TEST")||console.warn(...e)}function qM(...e){ae().getBool("IS_TEST")||console.log(...e)}function ar(e,t){if(e.length!==t.length)throw new Error(`Cannot merge real and imag arrays of different lengths. real:${e.length}, imag: ${t.length}.`);const n=new Float32Array(e.length*2);for(let s=0;s<n.length;s+=2)n[s]=e[s/2],n[s+1]=t[s/2];return n}function wv(e){const t=new Float32Array(e.length/2),n=new Float32Array(e.length/2);for(let s=0;s<e.length;s+=2)t[s/2]=e[s],n[s/2]=e[s+1];return{real:t,imag:n}}function Lv(e){const t=Math.ceil(e.length/4),n=new Float32Array(t),s=new Float32Array(t);for(let i=0;i<e.length;i+=4)n[Math.floor(i/4)]=e[i],s[Math.floor(i/4)]=e[i+1];return{real:n,imag:s}}function Sv(e){const t=Math.floor(e.length/4),n=new Float32Array(t),s=new Float32Array(t);for(let i=2;i<e.length;i+=4)n[Math.floor(i/4)]=e[i],s[Math.floor(i/4)]=e[i+1];return{real:n,imag:s}}function Aw(e,t){const n=e[t*2],s=e[t*2+1];return{real:n,imag:s}}function Iv(e,t,n,s){e[s*2]=t,e[s*2+1]=n}function xv(e,t){const n=new Float32Array(e/2),s=new Float32Array(e/2);for(let i=0;i<Math.ceil(e/2);i++){const o=(t?2:-2)*Math.PI*(i/e);n[i]=Math.cos(o),s[i]=Math.sin(o)}return{real:n,imag:s}}function Tv(e,t,n){const s=(n?2:-2)*Math.PI*(e/t),i=Math.cos(s),o=Math.sin(s);return{real:i,imag:o}}function jM(e,t,n){if(t==="complex64"){if(e.dtype==="complex64")return e.clone();const s=pt(e.shape),i=ve(e,"float32"),o=n.complex(i,s);return s.dispose(),i.dispose(),o}if(!Oa(e.dtype,t))return G.makeTensorFromDataId(e.dataId,e.shape,t);if(e.dtype==="complex64"){const s=n.real(e),i=ve(s,t);return s.dispose(),i}if(t==="int32")return n.int(e);if(t==="bool"){const s=Ce(0,e.dtype),i=n.notEqual(e,s);return s.dispose(),i}else throw new Error(`Error in Cast: failed to cast ${e.dtype} to ${t}`)}function Av(e,t){return G.makeTensorFromDataId(e.dataId,t,e.dtype)}function vw(e,t,n){const s=(t-e)/(n-1),i=Da(n,"float32");i[0]=e;for(let o=1;o<i.length;o++)i[o]=i[o-1]+s;return ds(i,"float32")}var Nw=Object.freeze({__proto__:null,slice_util:mA,segment_util:BW,castTensor:jM,reshapeTensor:Av,linspaceImpl:vw,upcastType:Bn,axesAreInnerMostDims:Nb,combineLocations:LA,computeOutAndReduceShapes:vn,expandShapeToKeepDim:Nn,assertAxesAreInnerMostDims:Zn,getAxesPermutation:Qn,getUndoAxesPermutation:yh,getInnerMostAxes:hs,getBroadcastDims:Mo,getReductionAxes:mn,assertAndGetBroadcastShape:st,assertParamsConsistent:Lp,computeOutShape:nr,computeDilation2DInfo:bp,computePool2DInfo:Mn,computePool3DInfo:Lh,computeConv2DInfo:_n,computeConv3DInfo:zr,computeDefaultPad:Fb,tupleValuesAreOne:Vr,eitherStridesOrDilationsAreOne:cn,convertConv2DDataFormat:Gr,getFusedDyActivation:Yp,getFusedBiasGradient:Hp,applyActivation:qp,shouldFuse:jp,PARALLELIZE_THRESHOLD:Yb,computeOptimalWindowSize:Ah,getImageCenter:gw,getReshaped:Gh,getPermuted:Yh,getReshapedPermuted:Hh,getSliceBeginCoords:yw,getSliceSize:bw,prepareAndValidate:hp,validateUpdateShape:gb,validateInput:yb,calculateShapes:qa,SELU_SCALEALPHA:em,SELU_SCALE:tm,ERF_P:ww,ERF_A1:Lw,ERF_A2:Sw,ERF_A3:Iw,ERF_A4:xw,ERF_A5:Tw,warn:hc,log:qM,mergeRealAndImagArrays:ar,splitRealAndImagArrays:wv,complexWithEvenIndex:Lv,complexWithOddIndex:Sv,getComplexWithIndex:Aw,assignToTypedArray:Iv,exponents:xv,exponent:Tv,prepareSplitSize:PA});function Cw(e,t,n){const s=new Array(e.rank).fill(0),i=e.shape.slice();return t.map(o=>{const a=[...i];a[n]=o;const c=nt(e,s,a);return s[n]+=o,c})}function Rw(e,t){const n=new Array(e.rank);for(let i=0;i<n.length;i++)n[i]=e.shape[i]*t[i];const s=wt(n,e.dtype);for(let i=0;i<s.values.length;++i){const o=s.indexToLoc(i),a=new Array(e.rank);for(let h=0;h<a.length;h++)a[h]=o[h]%e.shape[h];const c=e.locToIndex(a);s.values[i]=e.values[c]}return s.toTensor()}function Ow(e,t,n,s,i){const o=t[t.length-1],[a,c]=[e.length/o,o],h=bt(n,a*s),p=bt("int32",a*s);for(let y=0;y<a;y++){const b=y*c,w=e.subarray(b,b+c),L=[];for(let O=0;O<w.length;O++)L.push({value:w[O],index:O});L.sort((O,D)=>D.value-O.value);const T=y*s,v=h.subarray(T,T+s),C=p.subarray(T,T+s);for(let O=0;O<s;O++)v[O]=L[O].value,C[O]=L[O].index}const m=t.slice();return m[m.length-1]=s,[sn(h,m,n),sn(p,m,"int32")]}var KM=Object.freeze({__proto__:null,nonMaxSuppressionV3Impl:Xp,nonMaxSuppressionV4Impl:Jp,nonMaxSuppressionV5Impl:Zp,split:Cw,tile:Rw,topkImpl:Ow,whereImpl:Vp});const XM={kernelName:wd,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>X(e,oc(ve(n,"float32"),-1))}}};const JM={kernelName:Ll,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const s=At(ve(n,"float32")),i=Cn(Re(Ce(1),s));return Ht(We(e,i))}}}};const ZM={kernelName:Sl,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const s=Cn(Re(At(ve(n,"float32")),1));return We(e,s)}}}};const QM={kernelName:Oo,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,i=st(n.shape,s.shape),o=()=>{let c=e;const h=mn(n.shape,i);return h.length>0&&(c=$e(c,h)),K(c,n.shape)},a=()=>{let c=e;const h=mn(s.shape,i);return h.length>0&&(c=$e(c,h)),K(c,s.shape)};return{a:o,b:a}}};const eP={kernelName:ly,saveAllInputs:!0,gradFunc:(e,t)=>{const n={};return t.forEach((s,i)=>{n[i]=()=>e.clone()}),n}};const tP={kernelName:hy,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>tt(n)}}};const nP={kernelName:uy,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>tt(n)}}};const sP={kernelName:Il,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>We(e,Cn(Re(Ce(1),At(ve(n,"float32")))))}}};const iP={kernelName:xl,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const s=Cn(be(Ce(1),At(ve(n,"float32"))));return We(e,s)}}}};const rP={kernelName:Ld,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,i=st(n.shape,s.shape),o=()=>{const c=be(At(n),At(s));let h=X(e,We(s,c));const p=mn(n.shape,i);return p.length>0&&(h=$e(h,p)),K(h,n.shape)},a=()=>{const c=be(At(n),At(s));let h=Ht(X(e,We(n,c)));const p=mn(s.shape,i);return p.length>0&&(h=$e(h,p)),K(h,s.shape)};return{a:o,b:a}}};const oP={kernelName:Tl,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>We(e,be(At(ve(n,"float32")),1))}}};const aP={kernelName:Al,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>We(e,Re(Ce(1),At(ve(n,"float32"))))}}};function cP(e,t,n,s,i=[1,1,1],o,a){const c=W(e,"dy","avgPool3dBackprop"),h=W(t,"input","avgPool3dBackprop");let p=c,m=h,y=!1;h.rank===4&&(y=!0,p=K(c,[1,c.shape[0],c.shape[1],c.shape[2],c.shape[3]]),m=K(h,[1,h.shape[0],h.shape[1],h.shape[2],h.shape[3]])),A(p.rank===5,()=>`Error in avgPool3dBackprop: dy must be rank 5 but got rank ${p.rank}.`),A(m.rank===5,()=>`Error in avgPool3dBackprop: input must be rank 5 but got rank ${m.rank}.`),A(cn(s,i),()=>`Error in avgPool3dBackprop: Either strides or dilations must be 1. Got strides ${s} and dilations '${i}'`),a!=null&&A(we(o),()=>`Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode ${a} but got pad ${o}.`);const b=v=>{const C=Lh(m.shape,n,s,i,o,a);return v.avgPool3dBackprop(p,m,C)},w={dy:p,input:m},L={filterSize:n,strides:s,dilations:i,pad:o,dimRoundingMode:a},T=G.runKernelFunc(b,w,null,rT,L);return y?K(T,[T.shape[1],T.shape[2],T.shape[3],T.shape[4]]):T}const lP=z({avgPool3dBackprop_:cP});const hP={kernelName:dy,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{filterSize:i,strides:o,dilations:a,pad:c,dimRoundingMode:h}=n,p=a==null?[1,1,1]:a;return{x:()=>lP(e,s,i,o,p,c,h)}}};function uP(e,t,n,s,i){const o=W(e,"dy","avgPoolBackprop"),a=W(t,"input","avgPoolBackprop");A(a.rank===o.rank,()=>`Rank of input (${a.rank}) does not match rank of dy (${o.rank})`);let c=a,h=o,p=!1;a.rank===3&&(p=!0,c=K(a,[1,a.shape[0],a.shape[1],a.shape[2]]),h=K(o,[1,o.shape[0],o.shape[1],o.shape[2]])),A(h.rank===4,()=>`Error in avgPoolBackprop: dy must be rank 4 but got rank ${h.rank}.`),A(c.rank===4,()=>`Error in avgPoolBackprop: input must be rank 4 but got rank ${c.rank}.`);const m=L=>{const T=Mn(c.shape,n,s,1,i);return L.avgPoolBackprop(h,c,T)},y={dy:h,input:c},b={filterSize:n,strides:s,pad:i},w=G.runKernelFunc(m,y,null,Sd,b);return p?K(w,[w.shape[1],w.shape[2],w.shape[3]]):w}const dP=z({avgPoolBackprop_:uP});const pP={kernelName:vl,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{filterSize:i,strides:o,pad:a}=n;return{x:()=>dP(e,s,i,o,a)}}};const mP={kernelName:Id,inputsToSave:["a","b"],gradFunc:(e,t,n)=>{const[s,i]=t,{transposeA:o,transposeB:a}=n;return!o&&!a?{a:()=>lt(e,i,!1,!0),b:()=>lt(s,e,!0,!1)}:!o&&a?{a:()=>lt(e,i,!1,!1),b:()=>lt(e,s,!0,!1)}:o&&!a?{a:()=>lt(i,e,!1,!0),b:()=>lt(s,e,!1,!1)}:{a:()=>lt(i,e,!0,!0),b:()=>lt(e,s,!0,!0)}}};const fP={kernelName:py,gradFunc:(e,t,n)=>{const{blockShape:s,crops:i}=n;return{x:()=>Oh(e,s,i)}}};const gP={kernelName:my,gradFunc:(e,t,n)=>{const s=n,i=s.inputShape,o=s.shape,a=Array.from(o);for(let h=i.length-1;h>=0;h--)if(i[h]===o[h])a[h]=1;else if(i[h]!==1)throw new Error(`broadcastTo(): [${i}] cannot be broadcast to [${o}].`);const c=[];for(let h=0;h<a.length;h++)a[h]>1&&c.push(h);return{x:()=>$e(e,c,!0)}}};const yP={kernelName:ka,gradFunc:e=>({x:()=>e.clone()})};const bP={kernelName:Nl,gradFunc:e=>({x:()=>tt(e)})};const wP={kernelName:Cl,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{clipValueMin:i,clipValueMax:o}=n;return{x:()=>Pn(Ps(ir(s,i),Hr(s,o)),e,tt(e))}}};const LP={kernelName:Rl,saveAllInputs:!0,gradFunc:(e,t,n)=>{const s=t.map(h=>h.shape),{axis:i}=n,o=je(i,t[0].shape)[0],a=s.map(h=>h[o]),c=ps(e,a,o);return c.map(h=>()=>h)}};const SP={kernelName:Td,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const[s,i]=t,{dilations:o,strides:a,pad:c,dataFormat:h}=n;return A(Vr(o),()=>`Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${o}'`),{x:()=>Ub(s.shape,e,i,a,c,h),filter:()=>pw(s,e,i.shape,a,c,h)}}};const IP={kernelName:Ad,inputsToSave:["dy","filter"],gradFunc:(e,t,n)=>{const[s,i]=t,{strides:o,pad:a,dataFormat:c,dimRoundingMode:h}=n;return{dy:()=>sr(e,i,o,a,c,1,h),filter:()=>pw(e,s,i.shape,o,a,c,h)}}};function xP(e,t,n,s,i){let o=e;e.rank===4&&(o=K(e,[1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]]));let a=t;a.rank===4&&(a=K(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]])),A(o.rank===5,()=>`Error in conv3dDerFilter: input must be rank 5, but got shape ${o.shape}.`),A(a.rank===5,()=>`Error in conv3dDerFilter: dy must be rank 5, but got shape ${a.shape}.`),A(n.length===5,()=>`Error in conv3dDerFilter: filterShape must be length 5, but got ${n}.`),A(o.shape[4]===n[3],()=>`Error in conv3dDerFilter: depth of input ${o.shape[4]}) must match input depth in filter (${n[3]}.`),A(a.shape[4]===n[4],()=>`Error in conv3dDerFilter: depth of dy (${a.shape[4]}) must match output depth for filter (${n[4]}).`);const c=m=>{const y=1,b=zr(o.shape,n,s,y,i);return m.conv3dDerFilter(o,a,b)},h={x:o,dy:a},p={strides:s,pad:i,filterShape:n};return G.runKernelFunc(c,h,null,gy,p)}const TP=z({conv3DBackpropFilter_:xP});const AP={kernelName:vd,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const{dilations:s,strides:i,pad:o}=n;A(Vr(s),()=>`Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`);const[a,c]=t;return{x:()=>CA(a.shape,e,c,i,o),filter:()=>TP(a,e,c.shape,i,o)}}};const vP={kernelName:Fa,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>X(Ht($p(ve(n,"float32"))),e)}}};const NP={kernelName:Ol,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>X(Up(ve(n,"float32")),e)}}};const CP={kernelName:by,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{axis:i,exclusive:o,reverse:a}=n;return{x:()=>{const c=Qn([i],s.rank);let h=Ap(e,i,o,!a);return c!=null&&(h=Ye(h,c)),h}}}};const RP={kernelName:Nd,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const{dilations:s,strides:i,pad:o,dimRoundingMode:a}=n,c=s==null?[1,1]:s;A(Vr(c),()=>`Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations '${c}'`);const[h,p]=t;return A(h.rank===4,()=>`Error in gradient of depthwiseConv2dNative: input must be rank 4, but got rank ${h.rank}.`),A(p.rank===4,()=>`Error in gradient of depthwiseConv2dNative: filter must be rank 4, but got rank ${p.rank}.`),A(h.shape[3]===p.shape[2],()=>`Error in gradient of depthwiseConv2d: number of input channels (${h.shape[3]}) must match the inChannels dimension in filter ${p.shape[2]}.`),A(cn(i,c),()=>`Error in gradient of depthwiseConv2d: Either strides or dilations must be 1. Got strides ${i} and dilations '${c}'.`),a!=null&&A(we(o),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${o}.`),{x:()=>hv(h.shape,e,p,i,o,s,a),filter:()=>lv(h,e,p.shape,i,o,s,a)}}};const OP={kernelName:Cd,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const[s,i]=t,o={x:s,filter:i,dy:e},a={x:s,filter:i,dy:e};return{x:()=>G.runKernel(Rd,o,n),filter:()=>G.runKernel(Od,a,n)}}};const EP={kernelName:_a,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,i=st(n.shape,s.shape),o=()=>{const c=We(e,ve(s,"float32")),h=mn(n.shape,i);return h.length>0?K($e(c,h),n.shape):c},a=()=>{let c=X(e,ve(n,"float32"));const h=mn(s.shape,i);h.length>0&&(c=K($e(c,h),s.shape));const p=At(s);return Ht(We(c,ve(p,"float32")))};return{a:o,b:a}}};const DP={kernelName:El,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t,s=o=>o.eluDer(e,n),i={dy:e,y:n};return{x:()=>G.runKernelFunc(s,i,null,lT)}}};const kP={kernelName:Dl,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t,s=X(As(Ht(At(n))),2/Math.sqrt(Math.PI));return{x:()=>X(e,s)}}};const FP={kernelName:kl,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>X(e,n)}}};const _P={kernelName:Fl,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>X(e,As(n))}}};const WP={kernelName:_l,gradFunc:e=>({x:()=>tt(e)})};const $P={kernelName:Iy,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,i=st(n.shape,s.shape),o=()=>{const c=We(e,ve(s,"float32")),h=mn(n.shape,i);return h.length>0?K($e(c,h),n.shape):c},a=()=>{let c=X(e,ve(n,"float32"));const h=mn(s.shape,i);h.length>0&&(c=K($e(c,h),s.shape));const p=At(s);return Ht(We(c,ve(p,"float32")))};return{a:o,b:a}}};const UP={kernelName:Wl,inputsToSave:["x","mean","variance","scale"],gradFunc:(e,t,n)=>{const{varianceEpsilon:s}=n,[i,o,a,c]=t,h=c==null?Ce(1):c,p=mn(o.shape,i.shape),m=[];if(o.rank===1){for(let k=0;k<i.shape.length-1;++k)m.push(i.shape[k]);m.push(1)}const y=Re(i,o),b=X(e,h),w=_p(be(a,Ce(s))),L=X(X(X(w,w),w),Ce(-.5)),T=()=>o.rank===1?K(X(X(e,Yr(K(w,[1,1,1,o.shape[0]]),m)),h),i.shape):K(X(X(e,w),h),i.shape),v=()=>{let k=X(X(w,Ce(-1)),b);return o.rank===1&&(k=$e(k,p)),K(k,o.shape)},C=()=>{let k=X(X(L,y),b);return o.rank===1&&(k=$e(k,p)),K(k,o.shape)},O=()=>{const k=X(y,w);let F=X(e,k);return o.rank===1&&(F=$e(F,p)),K(F,o.shape)},D=()=>{let k=e;return o.rank===1&&(k=$e(k,p)),K(k,o.shape)};return{x:T,mean:v,variance:C,scale:O,offset:D}}};const BP={kernelName:xy,inputsToSave:["x","indices"],gradFunc:(e,t,n)=>{const[s,i]=t,{axis:o}=n,a=je(o,s.shape)[0],c=()=>{const h=s.shape,p=i.size,m=h.slice(0,a),y=m.length,b=h.slice(o,h.length).slice(1),w=b.length,L=vv(0,y),T=vv(y+1,y+1+w),v=Nv([m,[p],b]),C=K(e,v),O=K(i,[p]),D=Nv([[y],L,T]),k=Ye(C,D);let F=lw(k,O,s.shape[a]);const B=yh(D);return F=Ye(F,B),F};return{x:c,indices:()=>i}}};function vv(e,t){const n=[];for(let s=e;s<t;++s)n.push(s);return n}function Nv(e){const t=[];for(let n=0;n<e.length;++n)for(let s=0;s<e[n].length;++s)t.push(e[n][s]);return t}const MP={kernelName:Ty,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t;return{a:()=>tt(n),b:()=>tt(s)}}};const PP={kernelName:$l,gradFunc:e=>({x:()=>ve(e,"float32")})};const zP={kernelName:Ul,gradFunc:e=>({x:()=>tt(e)})};const VP={kernelName:Bl,gradFunc:e=>({x:()=>tt(e)})};const GP={kernelName:Ml,gradFunc:e=>({x:()=>tt(e)})};const YP={kernelName:zl,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>We(e,be(n,1))}}};const HP={kernelName:Pl,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>We(e,ve(n,"float32"))}}};const qP={kernelName:Ay,inputsToSave:[],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[s]=t,{axis:i}=n;return{logits:()=>{const o=!0,a=As(s);return Re(e,X($e(e,i,o),a))}}}};function jP(e,t,n,s=5,i=1,o=1,a=.5){const c=m=>m.LRNGrad(n,e,t,s,i,o,a),h={x:e,y:t,dy:n},p={depthRadius:s,bias:i,alpha:o,beta:a};return G.runKernelFunc(c,h,null,bT,p)}const KP=z({localResponseNormalizationBackprop_:jP});const XP={kernelName:vy,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[s,i]=t,{depthRadius:o,bias:a,alpha:c,beta:h}=n;return{x:()=>KP(s,i,e,o,a,c,h)}}};function Cv(e,t,n,s){return t.rank<n.rank&&(t=K(t,Nn(t.shape,s))),e.rank<n.rank&&(e=K(e,Nn(e.shape,s))),{x:()=>{const i=X(e,ve(ei(n,t),e.dtype));return i}}}const Rv={kernelName:Vl,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const s=n,{reductionIndices:i}=s,o=t[0],a=t[1],c=je(i,o.shape),h=Cv(e,a,o,c);return{x:()=>h.x()}}};const JP={kernelName:Ny,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,i=()=>X(e,ve(ir(n,s),"float32")),o=()=>X(e,ve(Nh(n,s),"float32"));return{a:i,b:o}}};function ZP(e,t,n,s,i,o=[1,1,1],a,c){const h=W(e,"dy","maxPool3dBackprop"),p=W(t,"input","maxPool3dBackprop"),m=W(n,"output","maxPool3dBackprop");let y=h,b=p,w=m,L=!1;p.rank===4&&(L=!0,y=K(h,[1,h.shape[0],h.shape[1],h.shape[2],h.shape[3]]),b=K(p,[1,p.shape[0],p.shape[1],p.shape[2],p.shape[3]]),w=K(m,[1,m.shape[0],m.shape[1],m.shape[2],m.shape[3]])),A(y.rank===5,()=>`Error in maxPool3dBackprop: dy must be rank 5 but got rank ${y.rank}.`),A(b.rank===5,()=>`Error in maxPool3dBackprop: input must be rank 5 but got rank ${b.rank}.`),A(w.rank===5,()=>`Error in maxPool3dBackprop: output must be rank 5 but got rank ${w.rank}.`),A(cn(i,o),()=>`Error in maxPool3dBackprop: Either strides or dilations must be 1. Got strides ${i} and dilations '${o}'`),c!=null&&A(we(a),()=>`Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode ${c} but got pad ${a}.`);const T=D=>{const k=Lh(b.shape,s,i,o,a,c);return D.maxPool3dBackprop(y,b,w,k)},v={dy:y,input:b,output:w},C={filterSize:s,strides:i,dilations:o,pad:a,dimRoundingMode:c},O=G.runKernelFunc(T,v,null,wT,C);return L?K(O,[O.shape[1],O.shape[2],O.shape[3],O.shape[4]]):O}const QP=z({maxPool3dBackprop_:ZP});const ez={kernelName:Cy,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[s,i]=t,{filterSize:o,strides:a,dilations:c,pad:h,dimRoundingMode:p}=n,m=c==null?[1,1,1]:c;return{x:()=>QP(e,s,i,o,a,m,h,p)}}};function tz(e,t,n,s,i,o,a){const c=W(e,"dy","maxPoolBackprop"),h=W(t,"input","maxPoolBackprop"),p=W(n,"output","maxPoolBackprop");A(h.rank===c.rank,()=>`Rank of input (${h.rank}) does not match rank of dy (${c.rank})`),A(c.rank===4,()=>`Error in maxPoolBackprop: dy must be rank 4 but got rank ${c.rank}.`),A(h.rank===4,()=>`Error in maxPoolBackprop: input must be rank 4 but got rank ${h.rank}.`),a!=null&&A(we(o),()=>`Error in maxPoolBackprop: pad must be an integer when using, dimRoundingMode ${a} but got pad ${o}.`);const m=w=>{const L=Mn(h.shape,s,i,1,o,a);return w.maxPoolBackprop(c,h,p,L)},y={dy:c,input:h,output:p},b={filterSize:s,strides:i,pad:o,dimRoundingMode:a};return G.runKernelFunc(m,y,null,Wd,b)}const nz=z({maxPoolBackprop_:tz});const sz={kernelName:Gl,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[s,i]=t,{filterSize:o,strides:a,pad:c}=n;return{x:()=>nz(e,s,i,o,a,c)}}};const iz={kernelName:Oy,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const s=n,{axis:i}=s,[o,a]=t,c=je(i,o.shape),h=Cv(e,a,o,c);return{x:()=>h.x()}}};const rz={kernelName:Ey,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,i=()=>X(e,ve(Hr(n,s),"float32")),o=()=>X(e,ve(vs(n,s),"float32"));return{a:i,b:o}}};const oz={kernelName:Yl,inputsToSave:["x"],gradFunc:(e,t,n)=>{const s=t[0],{paddings:i}=n,o=i.map(a=>a[0]);return{x:()=>nt(e,o,s.shape)}}};const az={kernelName:Dy,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,i=st(n.shape,s.shape),o=()=>{const c=mn(n.shape,i);return c.length>0?K($e(e,c),n.shape):e},a=()=>{const c=X(e,Ht(Za(We(n,s)))),h=mn(s.shape,i);return h.length>0?K($e(c,h),s.shape):c};return{a:o,b:a}}};const cz={kernelName:Wa,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,i=st(n.shape,s.shape),o=()=>{const c=X(e,ve(s,"float32")),h=mn(n.shape,i);return h.length>0?K($e(c,h),n.shape):c},a=()=>{const c=X(e,ve(n,"float32")),h=mn(s.shape,i);return h.length>0?K($e(c,h),s.shape):c};return{a:o,b:a}}};const lz={kernelName:ky,gradFunc:e=>({x:()=>Ht(e)})};const hz={kernelName:Wy,inputsToSave:["indices"],gradFunc:(e,t)=>{const n=t[0];return{indices:()=>pt(n.shape,"float32")}}};const uz={kernelName:_y,gradFunc:e=>({x:()=>tt(e)})};const Ov={kernelName:Md,inputsToSave:["x"],gradFunc:(e,t,n)=>{const s=t[0],{paddings:i}=n,o=i.map(a=>a[0]);return{x:()=>nt(e,o,s.shape)}}};const dz={kernelName:$y,inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:(e,t)=>{const[n,s,i]=t,o=n,a=s,c=st(o.shape,a.shape),h=()=>{const m=ve(a,"float32");let y=X(e,X(m,ni(o,Re(m,Ce(1)))));const b=mn(o.shape,c);return b.length>0&&(y=$e(y,b)),K(y,o.shape)},p=()=>{const m=vs(o,0),y=Pn(m,us(o),tt(o));let b=X(e,X(i,y));const w=mn(a.shape,c);return w.length>0&&(b=$e(b,w)),K(b,a.shape)};return{a:h,b:p}}};const pz={kernelName:Pd,inputsToSave:["x","alpha"],gradFunc:(e,t)=>{const[n,s]=t,i=vs(n,0);return{x:()=>Pn(i,e,X(e,s)),alpha:()=>{let o=Pn(i,tt(e),X(e,n));const a=mn(s.shape,e.shape);return a.length>0&&(o=$e(o,a)),K(o,s.shape)}}}};const mz={kernelName:ql,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>We(e,Ht(At(n)))}}};const fz={kernelName:Xl,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t,s=X(Hr(n,6),oc(n));return{x:()=>X(e,ve(s,"float32"))}}};const gz={kernelName:jl,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>X(e,ve(oc(n),"float32"))}}};const yz={kernelName:Kl,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>K(e,n.shape)}}};const bz={kernelName:By,inputsToSave:["images"],gradFunc:(e,t,n)=>{const[s]=t,i=c=>{const{alignCorners:h}=n;return c.resizeBilinearBackprop(e,s,h)},o={images:s},a=()=>G.runKernelFunc(i,o,null,xT,n);return{images:a}}};const wz={kernelName:Uy,inputsToSave:["images"],gradFunc:(e,t,n)=>{const[s]=t,i=c=>{const{alignCorners:h}=n;return c.resizeNearestNeighborBackprop(e,s,h)},o={images:s},a=()=>G.runKernelFunc(i,o,null,IT,n);return{images:a}}};const Lz={kernelName:My,gradFunc:(e,t,n)=>{const{dims:s}=n,i=je(s,e.shape);return{x:()=>Ns(e,i)}}};const Sz={kernelName:Jl,gradFunc:e=>({x:()=>tt(e)})};const Iz={kernelName:Zl,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Ht(We(e,X(ni(n,1.5),2)))}}};const xz={kernelName:Py,inputsToSave:["condition"],gradFunc:(e,t)=>{const[n]=t;return{condition:()=>ve(tt(n),"float32"),t:()=>X(e,ve(n,e.dtype)),e:()=>X(e,ve(Ch(n),e.dtype))}}};const Tz={kernelName:Ql,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const s=vs(n,Ce(0)),i=Ce(em),o=Ce(tm),a=X(e,o),c=X(X(e,i),As(ve(n,"float32")));return Pn(s,a,c)}}}};const Az={kernelName:nh,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>X(e,X(n,Re(Ce(1),n)))}}};const vz={kernelName:th,gradFunc:e=>({x:()=>tt(e)})};const Nz={kernelName:$a,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>X(Th(ve(n,"float32")),e)}}};const Cz={kernelName:eh,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>X(Tp(ve(n,"float32")),e)}}};const Rz={kernelName:Vd,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{begin:i,size:o}=n,a=s.shape,[c,h]=pp(s,i,o),p=[];for(let m=0;m<e.rank;m++)p.push([c[m],a[m]-c[m]-h[m]]);return{x:()=>Ei(e,p)}}};const Oz={kernelName:Gy,outputsToSave:[!0],gradFunc:(e,t,n)=>{const[s]=t,{dim:i}=n,o=!0,a=X(e,s);return{logits:()=>Re(a,X($e(a,[i],o),s))}}};const Ez={kernelName:sh,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>X(e,Ri(n))}}};const Ev={kernelName:Gd,gradFunc:(e,t,n)=>{const{blockShape:s,paddings:i}=n;return{x:()=>Ih(e,s,i)}}};const Dv={kernelName:Vy,gradFunc:(e,t,n)=>{const{axis:s}=n;return{x:()=>Yt(e,s)}}};const Dz={kernelName:ih,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>We(e,X(Cn(ve(n,"float32")),2))}}};const kz={kernelName:Yd,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>X(e,X(ve(n,"float32"),2))}}};const Fz={kernelName:Ua,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,i=Ce(2),o=()=>X(e,X(i,Re(n,s))),a=()=>X(e,X(i,Re(s,n)));return{a:o,b:a}}};const _z={kernelName:ah,gradFunc:e=>({x:()=>tt(e)})};const Wz={kernelName:Ba,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,i=st(n.shape,s.shape),o=()=>{let c=e;const h=mn(n.shape,i);return h.length>0&&(c=$e(c,h)),K(c,n.shape)},a=()=>{let c=e;const h=mn(s.shape,i);return h.length>0&&(c=$e(c,h)),K(Ht(c),s.shape)};return{a:o,b:a}}};const $z={kernelName:zy,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,i=s.shape.slice(),{axis:o}=n,a=je(o,s.shape);a.forEach(p=>{i[p]=1});const c=K(e,i),h=X(c,ti(s.shape,"float32"));return{x:()=>h}}};const Uz={kernelName:Ma,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>We(e,At(Th(n)))}}};const Bz={kernelName:rh,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>X(Re(Ce(1),At(n)),e)}}};const Mz={kernelName:Yy,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{reps:i}=n,o=()=>{let a=tt(s);if(s.rank===1)for(let c=0;c<i[0];++c)a=be(a,nt(e,[c*s.shape[0]],[s.shape[0]]));else if(s.rank===2)for(let c=0;c<i[0];++c)for(let h=0;h<i[1];++h)a=be(a,nt(e,[c*s.shape[0],h*s.shape[1]],[s.shape[0],s.shape[1]]));else if(s.rank===3)for(let c=0;c<i[0];++c)for(let h=0;h<i[1];++h)for(let p=0;p<i[2];++p)a=be(a,nt(e,[c*s.shape[0],h*s.shape[1],p*s.shape[2]],[s.shape[0],s.shape[1],s.shape[2]]));else if(s.rank===4)for(let c=0;c<i[0];++c)for(let h=0;h<i[1];++h)for(let p=0;p<i[2];++p)for(let m=0;m<i[3];++m)a=be(a,nt(e,[c*s.shape[0],h*s.shape[1],p*s.shape[2],m*s.shape[3]],[s.shape[0],s.shape[1],s.shape[2],s.shape[3]]));else throw new Error(`Gradient for tile operation is not implemented for rank-${s.rank} tensors yet.`);return a};return{x:o}}};const Pz={kernelName:oh,gradFunc:(e,t,n)=>{const s=n,{perm:i}=s,o=yh(i);return{x:()=>Ye(e,o)}}};const zz={kernelName:Hy,gradFunc:(e,t,n)=>{const s=n,{axis:i}=s;return{value:()=>ss(e,i)}}};const Vz={kernelName:qy,inputsToSave:["segmentIds"],gradFunc:(e,t)=>{const[n]=t,s=()=>Gz(e,n);return{x:s}}};function Gz(e,t){const n=Ms(t,tt(t)),s=Qa(e,n);let i=ir(t,Ce(0,"int32"));const o=s.rank-i.rank;for(let c=0;c<o;++c)i=ts(i,c+1);i=Ps(i,ti(s.shape,"bool"));const a=tt(s);return Pn(i,s,a)}const Yz={kernelName:jy,gradFunc:e=>({x:()=>tt(e)})};const Hz=[XM,JM,ZM,QM,eP,tP,nP,sP,iP,rP,oP,aP,hP,pP,mP,fP,gP,yP,bP,wP,LP,IP,SP,AP,vP,NP,CP,RP,OP,EP,DP,kP,FP,_P,$P,WP,UP,BP,MP,PP,zP,VP,GP,YP,HP,qP,XP,Rv,Rv,JP,ez,sz,iz,rz,oz,az,cz,lz,hz,uz,Ov,Ov,dz,pz,mz,fz,gz,yz,bz,wz,Lz,Sz,Iz,xz,Tz,Az,vz,Nz,Cz,Rz,Oz,Ez,Ev,Ev,Dv,Dv,Dz,Fz,kz,_z,Wz,$z,Uz,Bz,Mz,Pz,zz,Vz,Yz];for(const e of Hz)CT(e);te.prototype.abs=function(){return this.throwIfDisposed(),pn(this)};te.prototype.acos=function(){return this.throwIfDisposed(),Ab(this)};te.prototype.acosh=function(){return this.throwIfDisposed(),vb(this)};te.prototype.addStrict=function(e){return this.throwIfDisposed(),KA(this,e)};te.prototype.add=function(e){return this.throwIfDisposed(),be(this,e)};te.prototype.all=function(e,t){return this.throwIfDisposed(),yp(this,e,t)};te.prototype.any=function(e,t){return this.throwIfDisposed(),bh(this,e,t)};te.prototype.argMax=function(e){return this.throwIfDisposed(),wh(this,e)};te.prototype.argMin=function(e){return this.throwIfDisposed(),Cb(this,e)};te.prototype.asScalar=function(){return this.throwIfDisposed(),A(this.size===1,()=>"The array must have only 1 element."),K(this,[])};te.prototype.asType=function(e){return this.throwIfDisposed(),ve(this,e)};te.prototype.as1D=function(){return this.throwIfDisposed(),K(this,[this.size])};te.prototype.as2D=function(e,t){return this.throwIfDisposed(),K(this,[e,t])};te.prototype.as3D=function(e,t,n){return this.throwIfDisposed(),K(this,[e,t,n])};te.prototype.as4D=function(e,t,n,s){return this.throwIfDisposed(),K(this,[e,t,n,s])};te.prototype.as5D=function(e,t,n,s,i){return this.throwIfDisposed(),K(this,[e,t,n,s,i])};te.prototype.asin=function(){return this.throwIfDisposed(),Rb(this)};te.prototype.asinh=function(){return this.throwIfDisposed(),Ob(this)};te.prototype.atan=function(){return this.throwIfDisposed(),Eb(this)};te.prototype.atan2=function(e){return this.throwIfDisposed(),Db(this,e)};te.prototype.atanh=function(){return this.throwIfDisposed(),kb(this)};te.prototype.avgPool=function(e,t,n,s){return this.throwIfDisposed(),Sh(this,e,t,n,s)};te.prototype.batchToSpaceND=function(e,t){return this.throwIfDisposed(),Ih(this,e,t)};te.prototype.batchNorm=function(e,t,n,s,i){return this.throwIfDisposed(),Uo(this,e,t,n,s,i)};te.prototype.broadcastTo=function(e){return this.throwIfDisposed(),xh(this,e)};te.prototype.cast=function(e){return this.throwIfDisposed(),ve(this,e)};te.prototype.ceil=function(){return this.throwIfDisposed(),$b(this)};te.prototype.clipByValue=function(e,t){return this.throwIfDisposed(),es(this,e,t)};te.prototype.concat=function(e,t){return this.throwIfDisposed(),e instanceof te&&(e=[e]),Yt([this,...e],t)};te.prototype.conv1d=function(e,t,n,s,i,o){return this.throwIfDisposed(),Ip(this,e,t,n,s,i,o)};te.prototype.conv2dTranspose=function(e,t,n,s,i){return this.throwIfDisposed(),xp(this,e,t,n,s,i)};te.prototype.conv2d=function(e,t,n,s,i,o){return this.throwIfDisposed(),sr(this,e,t,n,s,i,o)};te.prototype.cos=function(){return this.throwIfDisposed(),Th(this)};te.prototype.cosh=function(){return this.throwIfDisposed(),Tp(this)};te.prototype.cumsum=function(e,t,n){return this.throwIfDisposed(),Ap(this,e,t,n)};te.prototype.depthToSpace=function(e,t){return this.throwIfDisposed(),Mb(this,e,t)};te.prototype.depthwiseConv2D=function(e,t,n,s,i,o){return dn("depthwiseConv2D is deprecated, use depthwiseConv2d instead"),this.throwIfDisposed(),Bo(this,e,t,n,s,i,o)};te.prototype.depthwiseConv2d=function(e,t,n,s,i,o){return this.throwIfDisposed(),Bo(this,e,t,n,s,i,o)};te.prototype.dilation2d=function(e,t,n,s,i){return this.throwIfDisposed(),Pb(this,e,t,n,s,i)};te.prototype.divNoNan=function(e){return this.throwIfDisposed(),zb(this,e)};te.prototype.divStrict=function(e){return this.throwIfDisposed(),XA(this,e)};te.prototype.div=function(e){return this.throwIfDisposed(),We(this,e)};te.prototype.dot=function(e){return this.throwIfDisposed(),RA(this,e)};te.prototype.elu=function(){return this.throwIfDisposed(),Xa(this)};te.prototype.equalStrict=function(e){return this.throwIfDisposed(),VA(this,e)};te.prototype.equal=function(e){return this.throwIfDisposed(),ei(this,e)};te.prototype.erf=function(){return this.throwIfDisposed(),Vb(this)};te.prototype.exp=function(){return this.throwIfDisposed(),As(this)};te.prototype.expandDims=function(e){return this.throwIfDisposed(),ts(this,e)};te.prototype.expm1=function(){return this.throwIfDisposed(),Gb(this)};te.prototype.fft=function(){return this.throwIfDisposed(),Fh(this)};te.prototype.flatten=function(){return this.throwIfDisposed(),K(this,[this.size])};te.prototype.floor=function(){return this.throwIfDisposed(),Za(this)};te.prototype.floorDiv=function(e){return this.throwIfDisposed(),gp(this,e)};te.prototype.gather=function(e,t){return this.throwIfDisposed(),Qa(this,e,t)};te.prototype.greaterEqualStrict=function(e){return this.throwIfDisposed(),GA(this,e)};te.prototype.greaterEqual=function(e){return this.throwIfDisposed(),ir(this,e)};te.prototype.greaterStrict=function(e){return this.throwIfDisposed(),YA(this,e)};te.prototype.greater=function(e){return this.throwIfDisposed(),vs(this,e)};te.prototype.ifft=function(){return this.throwIfDisposed(),rc(this)};te.prototype.irfft=function(){return this.throwIfDisposed(),Pp(this)};te.prototype.isFinite=function(){return this.throwIfDisposed(),EA(this)};te.prototype.isInf=function(){return this.throwIfDisposed(),DA(this)};te.prototype.isNaN=function(){return this.throwIfDisposed(),kA(this)};te.prototype.leakyRelu=function(e){return this.throwIfDisposed(),Np(this,e)};te.prototype.lessEqualStrict=function(e){return this.throwIfDisposed(),HA(this,e)};te.prototype.lessEqual=function(e){return this.throwIfDisposed(),Hr(this,e)};te.prototype.lessStrict=function(e){return this.throwIfDisposed(),qA(this,e)};te.prototype.less=function(e){return this.throwIfDisposed(),Nh(this,e)};te.prototype.localResponseNormalization=function(e,t,n,s){return this.throwIfDisposed(),Hb(this,e,t,n,s)};te.prototype.logSigmoid=function(){return this.throwIfDisposed(),_A(this)};te.prototype.logSoftmax=function(e){return this.throwIfDisposed(),Op(this,e)};te.prototype.logSumExp=function(e,t){return this.throwIfDisposed(),jb(this,e,t)};te.prototype.log=function(){return this.throwIfDisposed(),us(this)};te.prototype.log1p=function(){return this.throwIfDisposed(),Cp(this)};te.prototype.logicalAnd=function(e){return this.throwIfDisposed(),Ps(this,e)};te.prototype.logicalNot=function(){return this.throwIfDisposed(),Ch(this)};te.prototype.logicalOr=function(e){return this.throwIfDisposed(),Ep(this,e)};te.prototype.logicalXor=function(e){return this.throwIfDisposed(),WA(this,e)};te.prototype.matMul=function(e,t,n){return this.throwIfDisposed(),lt(this,e,t,n)};te.prototype.maxPool=function(e,t,n,s){return this.throwIfDisposed(),Rh(this,e,t,n,s)};te.prototype.max=function(e,t){return this.throwIfDisposed(),ns(this,e,t)};te.prototype.maximumStrict=function(e){return this.throwIfDisposed(),JA(this,e)};te.prototype.maximum=function(e){return this.throwIfDisposed(),Ms(this,e)};te.prototype.mean=function(e,t){return this.throwIfDisposed(),qt(this,e,t)};te.prototype.min=function(e,t){return this.throwIfDisposed(),tc(this,e,t)};te.prototype.minimumStrict=function(e){return this.throwIfDisposed(),ZA(this,e)};te.prototype.minimum=function(e){return this.throwIfDisposed(),Po(this,e)};te.prototype.mirrorPad=function(e,t){return this.throwIfDisposed(),Xb(this,e,t)};te.prototype.modStrict=function(e){return this.throwIfDisposed(),QA(this,e)};te.prototype.mod=function(e){return this.throwIfDisposed(),Dp(this,e)};te.prototype.mulStrict=function(e){return this.throwIfDisposed(),ev(this,e)};te.prototype.mul=function(e){return this.throwIfDisposed(),X(this,e)};te.prototype.neg=function(){return this.throwIfDisposed(),Ht(this)};te.prototype.norm=function(e,t,n){return this.throwIfDisposed(),Gp(this,e,t,n)};te.prototype.notEqualStrict=function(e){return this.throwIfDisposed(),jA(this,e)};te.prototype.notEqual=function(e){return this.throwIfDisposed(),qr(this,e)};te.prototype.oneHot=function(e,t=1,n=0){return this.throwIfDisposed(),_o(this,e,t,n)};te.prototype.onesLike=function(){return this.throwIfDisposed(),Wn(this)};te.prototype.pad=function(e,t){return this.throwIfDisposed(),Ei(this,e,t)};te.prototype.pool=function(e,t,n,s,i){return this.throwIfDisposed(),BA(this,e,t,n,s,i)};te.prototype.powStrict=function(e){return this.throwIfDisposed(),tv(this,e)};te.prototype.pow=function(e){return this.throwIfDisposed(),ni(this,e)};te.prototype.prelu=function(e){return this.throwIfDisposed(),Eh(this,e)};te.prototype.prod=function(e,t){return this.throwIfDisposed(),Fp(this,e,t)};te.prototype.reciprocal=function(){return this.throwIfDisposed(),ew(this)};te.prototype.relu=function(){return this.throwIfDisposed(),Di(this)};te.prototype.relu6=function(){return this.throwIfDisposed(),tw(this)};te.prototype.reshapeAs=function(e){return this.throwIfDisposed(),K(this,e.shape)};te.prototype.reshape=function(e){return this.throwIfDisposed(),K(this,e)};te.prototype.resizeBilinear=function(e,t){return this.throwIfDisposed(),fv(this,e,t)};te.prototype.resizeNearestNeighbor=function(e,t){return this.throwIfDisposed(),gv(this,e,t)};te.prototype.reverse=function(e){return this.throwIfDisposed(),Ns(this,e)};te.prototype.rfft=function(){return this.throwIfDisposed(),_h(this)};te.prototype.round=function(){return this.throwIfDisposed(),nw(this)};te.prototype.rsqrt=function(){return this.throwIfDisposed(),_p(this)};te.prototype.selu=function(){return this.throwIfDisposed(),Wp(this)};te.prototype.separableConv2d=function(e,t,n,s,i,o){return this.throwIfDisposed(),sw(this,e,t,n,s,i,o)};te.prototype.sigmoid=function(){return this.throwIfDisposed(),Ri(this)};te.prototype.sign=function(){return this.throwIfDisposed(),iw(this)};te.prototype.sin=function(){return this.throwIfDisposed(),$p(this)};te.prototype.sinh=function(){return this.throwIfDisposed(),Up(this)};te.prototype.slice=function(e,t){return this.throwIfDisposed(),nt(this,e,t)};te.prototype.softmax=function(e){return this.throwIfDisposed(),Yo(this,e)};te.prototype.softplus=function(){return this.throwIfDisposed(),ec(this)};te.prototype.spaceToBatchND=function(e,t){return this.throwIfDisposed(),Oh(this,e,t)};te.prototype.split=function(e,t){return this.throwIfDisposed(),ps(this,e,t)};te.prototype.sqrt=function(){return this.throwIfDisposed(),Cn(this)};te.prototype.square=function(){return this.throwIfDisposed(),At(this)};te.prototype.squaredDifference=function(e){return this.throwIfDisposed(),Wh(this,e)};te.prototype.squaredDifferenceStrict=function(e){return this.throwIfDisposed(),nv(this,e)};te.prototype.squeeze=function(e){return this.throwIfDisposed(),jr(this,e)};te.prototype.stack=function(e,t){this.throwIfDisposed();const n=e instanceof te?[this,e]:[this,...e];return ss(n,t)};te.prototype.step=function(e){return this.throwIfDisposed(),oc(this,e)};te.prototype.stridedSlice=function(e,t,n,s,i,o,a,c){return this.throwIfDisposed(),ow(this,e,t,n,s,i,o,a,c)};te.prototype.subStrict=function(e){return this.throwIfDisposed(),sv(this,e)};te.prototype.sub=function(e){return this.throwIfDisposed(),Re(this,e)};te.prototype.sum=function(e,t){return this.throwIfDisposed(),$e(this,e,t)};te.prototype.tan=function(){return this.throwIfDisposed(),aw(this)};te.prototype.tanh=function(){return this.throwIfDisposed(),Ka(this)};te.prototype.tile=function(e){return this.throwIfDisposed(),Yr(this,e)};te.prototype.toBool=function(){return this.throwIfDisposed(),ve(this,"bool")};te.prototype.toFloat=function(){return this.throwIfDisposed(),ve(this,"float32")};te.prototype.toInt=function(){return this.throwIfDisposed(),ve(this,"int32")};te.prototype.topk=function(e,t){return this.throwIfDisposed(),cw(this,e,t)};te.prototype.transpose=function(e){return this.throwIfDisposed(),Ye(this,e)};te.prototype.unique=function(e){return this.throwIfDisposed(),zp(this,e)};te.prototype.unsortedSegmentSum=function(e,t){return this.throwIfDisposed(),lw(this,e,t)};te.prototype.unstack=function(e){return this.throwIfDisposed(),si(this,e)};te.prototype.where=function(e,t){return this.throwIfDisposed(),Pn(e,this,t)};te.prototype.zerosLike=function(){return this.throwIfDisposed(),tt(this)};let nm;function fn(){return nm==null&&(nm=bA().epsilon()),nm}function Ite(e){nm=e}function ii(){return"channelsLast"}class cr extends Error{constructor(e){super(e);Object.setPrototypeOf(this,cr.prototype)}}class ri extends Error{constructor(e){super(e);Object.setPrototypeOf(this,ri.prototype)}}class q extends Error{constructor(e){super(e);Object.setPrototypeOf(this,q.prototype)}}class ze extends Error{constructor(e){super(e);Object.setPrototypeOf(this,ze.prototype)}}class kv extends Error{constructor(e){super(e);Object.setPrototypeOf(this,kv.prototype)}}class qz extends Error{constructor(e){super(e);Object.setPrototypeOf(this,qz.prototype)}}function jo(e,t){if(Array.isArray(e)){let n=[];for(let s=0;s<t;s++)n=n.concat(e);return n}else{const n=new Array(t);return n.fill(e),n}}function Cs(e,t){if(!e)throw new kv(t)}function Fv(e,t){let n=0;for(const s of e)s===t&&n++;return n}function is(e){return e.length===1?e[0]:e}function Et(e){return Array.isArray(e)?e:[e]}function xte(e){const t=Et(e);let n="";for(const s of t){if(s.id==null)throw new q(`Object ${s} passed to objectListUid without an id`);n!==""&&(n=n+", "),n=`${n}${Math.abs(s.id)}`}return n}function lr(e){const t=e.replace(/(.)([A-Z][a-z0-9]+)/g,"$1_$2"),n=t.replace(/([a-z])([A-Z])/g,"$1_$2").toLowerCase();return n[0]!=="_"?n:"private"+n}function Ko(e){return e.length<=1||e.indexOf("_")===-1?e:e.replace(/[_]+(\w|$)/g,(t,n)=>n.toUpperCase())}let zs={};function Ew(e){if(e==null)return null;const t={};return t.className=e.getClassName(),t.config=e.getConfig(),t}function Dw(e){if(e==null||typeof e!="object")return;if(Array.isArray(e))e.forEach(t=>Dw(t));else{const t=Object.keys(e);for(const n of t){const s=e[n];s!=null&&typeof s=="object"&&(!Array.isArray(s)&&s.type==="ndarray"&&typeof s.value=="number"?e[n]=s.value:Dw(s))}}}function qh(e,t={},n={},s="object",i=!1){if(typeof e=="string"){const o=e;let a;if(o in n)a=n[o];else if(o in zs)a=zs[o];else if(a=t[o],a==null)throw new q(`Unknown ${s}: ${e}. This may be due to one of the following reasons:
1. The ${s} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
2. The custom ${s} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);return a}else{const o=e;if(o.className==null||o.config==null)throw new q(`${s}: Improper config format: ${JSON.stringify(o)}.
'className' and 'config' must set.`);const a=o.className;let c,h;if(a in n?[c,h]=n[a]:a in zs?[c,h]=zs.className:a in t&&([c,h]=t[a]),c==null)throw new q(`Unknown ${s}: ${a}. This may be due to one of the following reasons:
1. The ${s} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
2. The custom ${s} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);if(h!=null){const p={};for(const w of Object.keys(zs))p[w]=zs[w];for(const w of Object.keys(n))p[w]=n[w];const m=o.config;m.customObjects=p;const y=Object.assign({},zs);for(const w of Object.keys(n))zs[w]=n[w];Dw(o.config);const b=h(c,o.config,n,i);return zs=Object.assign({},y),b}else{const p=Object.assign({},zs);for(const y of Object.keys(n))zs[y]=n[y];const m=new c(o.config);return zs=Object.assign({},p),m}}}function jz(e,t){return e<t?-1:e>t?1:0}function sm(e,t){return-1*jz(e,t)}function Tte(e){switch(e){case"float32":return"float32";default:throw new q(`Invalid dtype: ${e}`)}}function Ate(e,t){if(e==null||t==null)return e===t;if(e.length!==t.length)return!1;for(let n=0;n<e.length;++n)if(e[n]!==t[n])return!1;return!0}function Jr(e){if(e==null)return e;const t=[];for(const n of e)t.indexOf(n)===-1&&t.push(n);return t}function Kz(e){if(e==null)throw new q(`Invalid value in obj: ${JSON.stringify(e)}`);for(const t in e)if(e.hasOwnProperty(t))return!1;return!0}function uc(e,t,n){if(n==null)return;if(e.indexOf(n)<0)throw new q(`${n} is not a valid ${t}. Valid values are ${e} or null/undefined.`)}function kw(e,t,n=0,s=Infinity){return Cs(n>=0),Cs(s>=n),Array.isArray(e)&&e.length>=n&&e.length<=s&&e.every(i=>typeof i===t)}function Ln(e,t){Array.isArray(e)?(A(e.length>0,()=>`${t} is unexpectedly an empty array.`),e.forEach((n,s)=>Ln(n,`element ${s+1} of ${t}`))):A(Number.isInteger(e)&&e>0,()=>`Expected ${t} to be a positive integer, but got ${_v(e)}.`)}function _v(e){return e===null?"null":Array.isArray(e)?"["+e.map(t=>_v(t)).join(",")+"]":typeof e=="string"?`"${e}"`:`${e}`}function Xz(e,t){let n=Jn(),s;const i=(...o)=>{const a=Jn();return a-n<t||(n=a,s=e(...o)),s};return i}function Wv(e){return e==="relu"?"relu":e==="linear"?"linear":e==="elu"?"elu":null}function vte(...e){Cs(e.length>0,"arrayOfValues is empty");for(const t of e)Cs(Array.isArray(t),"one of the values is not an array"),Cs(t.length>0,"one of the values is empty");return e.reduce((t,n)=>t.length===0?n.map(s=>[s]):n.map(s=>t.map(i=>[...i,s])).reduce((s,i)=>s.concat(i),[]),[])}function Fw(e,t){return ee(()=>Cn($e(X(e,e),t,!0)))}class jh extends Wo{getConfig(){return{}}}class _w extends jh{constructor(e){super();this.defaultMaxValue=2,this.defaultAxis=0,this.maxValue=e.maxValue!=null?e.maxValue:this.defaultMaxValue,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return ee(()=>{const t=Fw(e,this.axis),n=es(t,0,this.maxValue);return X(e,We(n,be(fn(),t)))})}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}}_w.className="MaxNorm",ge(_w);class Ww extends jh{constructor(e){super();this.defaultAxis=0,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return ee(()=>We(e,be(fn(),Fw(e,this.axis))))}getConfig(){return{axis:this.axis}}}Ww.className="UnitNorm",ge(Ww);class $w extends jh{apply(e){return Di(e)}}$w.className="NonNeg",ge($w);class Uw extends jh{constructor(e){super();this.defaultMinValue=0,this.defaultMaxValue=1,this.defaultRate=1,this.defaultAxis=0,this.minValue=e.minValue!=null?e.minValue:this.defaultMinValue,this.maxValue=e.maxValue!=null?e.maxValue:this.defaultMaxValue,this.rate=e.rate!=null?e.rate:this.defaultRate,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return ee(()=>{const t=Fw(e,this.axis),n=be(X(this.rate,es(t,this.minValue,this.maxValue)),X(1-this.rate,t));return X(e,We(n,be(fn(),t)))})}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}}Uw.className="MinMaxNorm",ge(Uw);const $v={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function gn(e){return Ew(e)}function Uv(e,t={}){return qh(e,Bs.getMap().classNameMap,t,"constraint")}function yn(e){if(e==null)return null;if(typeof e=="string"){const t=e in $v?$v[e]:e,n={className:t,config:{}};return Uv(n)}else return e instanceof jh?e:Uv(e)}function Jz(e){return new _w(e)}function Zz(e){return new Ww(e)}function Qz(){return new $w}function e3(e){return new Uw(e)}var t3=Object.freeze({__proto__:null,maxNorm:Jz,unitNorm:Zz,nonNeg:Qz,minMaxNorm:e3});const n3=["channelsFirst","channelsLast"],s3=["valid","same","causal"],i3=["max","avg"],r3=["sum","mul","concat","ave"],Nte=["temporal"];const dc=new Map;function jt(e){uc(n3,"DataFormat",e)}function Rs(e){uc(s3,"PaddingMode",e)}function Bv(e){uc(i3,"PoolMode",e)}const Kh=[],Mv="/";function Xo(e,t){Kh.push(e);try{const n=t();return Kh.pop(),n}catch(n){throw Kh.pop(),n}}function o3(){return Kh.length===0?"":Kh.join(Mv)+Mv}function Pv(e){if(!Vv(e))throw new Error("Not a valid tensor name: '"+e+"'");return o3()+e}function zv(e){if(!Vv(e))throw new Error("Not a valid tensor name: '"+e+"'");dc.has(e)||dc.set(e,0);const t=dc.get(e);if(dc.set(e,dc.get(e)+1),t>0){const n=`${e}_${t}`;return dc.set(n,1),n}else return e}const a3=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function Vv(e){return!!e.match(a3)}function c3(e){return e===parseInt(e.toString(),10)}function Zr(e,t,n){t==null&&(t=0),n==null&&(n=e.length);let s=1;for(let i=t;i<n;++i)s*=e[i];return s}function im(e){return e=Array.isArray(e)?new Float32Array(e):e,ds(e)}function pc(e){return tc(im(e)).dataSync()[0]}function Qr(e){return ns(im(e)).dataSync()[0]}function l3(e){return $e(im(e)).dataSync()[0]}function h3(e){return l3(e)/e.length}function Cte(e){const t=Re(im(e),Ce(h3(e))),n=$e(X(t,t)).dataSync()[0];return n/e.length}function Rte(e){const t=e.slice().sort((i,o)=>i-o),n=Math.floor((t.length-1)/2),s=Math.ceil((t.length-1)/2);return n===s?t[n]:(t[n]+t[s])/2}function oi(e,t){if(t<e)throw new q(`end (${t}) < begin (${e}) is forbidden.`);const n=[];for(let s=e;s<t;++s)n.push(s);return n}let Gv="webgl";function Ote(e){yA(e),Gv=e}function Ete(){return Gv}function Dte(){return!1}function kte(e){const t=e.shape;return t.length>0?t.reduce((n,s)=>n*s):1}function Xh(e,t){return e.asType(t)}function Jh(e,t=-1){const n=e.shape.slice();return t<0&&(t=n.length+t+1),n.splice(t,0,1),e.reshape(n)}function u3(e,t){return ee(()=>{if(e.shape.length!==2)throw new q(`repeat() expects a rank-2 tensor, but received a rank-${e.shape.length} tensor.`);const n=Jh(e,1);return Pw(n,[1,t,1])})}function d3(e){const t=[Zr(e.shape)];return e.reshape(t)}function p3(e){if(e.rank<=1)throw new q(`batchFlatten requires a minimum rank of 2. Got rank: ${e.rank}.`);const t=[e.shape[0],Zr(e.shape,1)];return e.reshape(t)}function Jo(e,t,n){return ee(()=>{switch(e.rank){case 1:return Bp(e,t,n);case 2:return rw(e,[t,0],[n,e.shape[1]]);case 3:return Mp(e,[t,0,0],[n,e.shape[1],e.shape[2]]);case 4:return kh(e,[t,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3]]);case 5:return nt(e,[t,0,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3],e.shape[4]]);case 6:return nt(e,[t,0,0,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3],e.shape[4],e.shape[5]]);default:throw new q(`sliceAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}})}function Bw(e,t,n){return ee(()=>{switch(e.rank){case 1:return Bp(e,t,n);case 2:return rw(e,[0,t],[e.shape[0],n]);case 3:return Mp(e,[0,0,t],[e.shape[0],e.shape[1],n]);case 4:return kh(e,[0,0,0,t],[e.shape[0],e.shape[1],e.shape[2],n]);default:throw new q(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}})}function rm(e,t,n,s){return ee(()=>{switch(e.rank){case 1:return Bp(e,t,n);case 2:switch(s){case 1:return Jo(e,t,n);case 2:return Bw(e,t,n);default:throw new q(`The axis is not within the rank of the tensor ${s}`)}case 3:switch(s){case 1:return Jo(e,t,n);case 2:return Mp(e,[0,t,0],[e.shape[0],n,e.shape[2]]);case 3:return Bw(e,t,n);default:throw new q(`The axis is not within the rank of the tensor ${s}`)}case 4:switch(s){case 1:return Jo(e,t,n);case 2:return kh(e,[0,t,0,0],[e.shape[0],n,e.shape[2],e.shape[3]]);case 3:return kh(e,[0,0,t,0],[e.shape[0],e.shape[1],n,e.shape[3]]);case 4:return Bw(e,t,n);default:throw new q(`The axis is not within the rank of the tensor ${s}`)}default:throw new q(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}})}function Mw(e,t=-1){let n;return t<0&&(n=e[0].rank,n!==0?t=n:t=0),t===e[0].rank&&(t=-1),Yt(e,t)}function Yv(e,t){switch(e.rank){case 1:return TA([e,t]);case 2:return AA([e,t],0);case 3:return vA([e,t],0);case 4:return NA([e,t],0);default:throw new q(`concatAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}}function Pw(e,t){if(Array.isArray(t)||(t=[t]),e.rank!==t.length)throw new q(`The length of input n (${t.length}) does not match the number of dimensions in input x (${e.rank})`);return Yr(e,t)}function om(e,t=0,n=1,s,i){return Qb(e,t,n,s,i)}function ki(e,t,n,s){if(e.rank<2||t.rank<2)throw new ze(`dot requires both inputs to be rank >= 2 but got x shape = ${e.shape} and y shape = ${t.shape}`);if(t.rank>=3){const i=e.shape.slice(-1)[0],o=t.shape.slice(-2)[0];if(i!==o)throw new ze(`If rank y >= 3, then the second last dim of y must equal the last dim of x but got x shape = ${e.shape} and y shape = ${t.shape}`)}if(e.rank===2&&t.rank===2){const i=!1,o=!1;return Kp({a:e,b:t,transposeA:i,transposeB:o,bias:s?zw(e.rank,s,ii()):null,activation:n})}else{const i=e.shape.slice(),o=i.pop();e=e.reshape([-1,o]);const a=t.shape.slice(),c=a.pop(),h=a.pop(),p=[...a,c],m=Array.from({length:t.rank},(L,T)=>T===0?t.rank-2:T<=t.rank-2?T-1:T);t=t.transpose(m).reshape([h,-1]);const y=[...i,...p],b=!1,w=!1;return Kp({a:e,b:t,transposeA:b,transposeB:w,bias:s?zw(e.rank,s,ii()):null,activation:n}).reshape(y)}}function Fte(e){return ee(()=>{const t=tt(e),n=Wn(e);return Pn(ei(e,t),t,Pn(vs(e,tt(e)),n,X(-1,n)))})}function _te(e,t){return ee(()=>{if(e.rank!==1)throw new Error("Only 1D one-hot tensors are supported in the deeplearn backend, at present.");return e=e.toInt(),_o(e,t).toFloat()})}function Hv(e,t,n){return ee(()=>(Array.isArray(t)?t=ds(t,"int32"):t=t.toInt(),Qa(e,t,n)))}function Zh(e){return X(e,e)}function Wte(e,t){return ee(()=>{if(typeof t=="number"&&(t=Ce(Math.round(t),"int32")),t.dtype!=="int32")throw new ze(`Non-int32 dtype (${t.dtype}) is not supported by pow() yet`);return ni(e,t)})}function zw(e,t,n){const s=t.shape;if(t.rank!==1&&t.rank!==e)throw new q(`Unexpected bias dimensions: ${t.rank}; expected it to be 1 or ${e}`);if(e===5){if(n==="channelsFirst")return s.length===1?t.reshape([1,s[0],1,1,1]):t.reshape([1,s[3],s[0],s[1],s[2]]);if(n==="channelsLast")return s.length===1?t.reshape([1,1,1,1,s[0]]):t.reshape([1].concat(s))}else if(e===4){if(n==="channelsFirst")return s.length===1?t.reshape([1,s[0],1,1]):t.reshape([1,s[2],s[0],s[1]]);if(n==="channelsLast")return s.length===1?t.reshape([1,1,1,s[0]]):t.reshape([1].concat(s))}else if(e===3){if(n==="channelsFirst")return s.length===1?t.reshape([1,s[0],1]):t.reshape([1,s[1],s[0]]);if(n==="channelsLast")return s.length===1?t.reshape([1,1,s[0]]):t.reshape([1].concat(s))}else if(e<3)return t;throw new q(`Unsupported input rank by biasAdd: ${t.rank}`)}function Fi(e,t,n){return ee(()=>(n==null&&(n=ii()),jt(n),e.add(zw(e.rank,t,n))))}function m3(e,t=1){if(t!==1)throw new ze(`Support for alpha values other than 1 (${t}) is not implemented yet.`);return Xa(e)}function f3(e){return ee(()=>We(e,pn(e).add(1)))}function qv(e,t,n,s){return ee(()=>av(e,t,n,s))}function g3(e){return ee(()=>{const t=be(.5,X(.2,e));return es(t,0,1)})}function Qh(e,t,n=!1){return n?e():t()}const y3=["fanIn","fanOut","fanAvg"],b3=["normal","uniform","truncatedNormal"],$te=["Zeros","Ones","Constant","RandomNormal","RandomUniform","TruncatedNormal","VarianceScaling","Orthogonal","Identity"];function w3(e){uc(y3,"FanMode",e)}function L3(e){uc(b3,"Distribution",e)}class Vs extends Wo{fromConfigUsesCustomObjects(){return!1}getConfig(){return{}}}class Vw extends Vs{apply(e,t){return pt(e,t)}}Vw.className="Zeros",ge(Vw);class am extends Vs{apply(e,t){return ti(e,t)}}am.className="Ones",ge(am);class Gw extends Vs{constructor(e){super();if(typeof e!="object")throw new q(`Expected argument of type ConstantConfig but got ${e}`);if(e.value===void 0)throw new q(`config must have value set but got ${e}`);this.value=e.value}apply(e,t){return ee(()=>X(Ce(this.value),ti(e,t)))}getConfig(){return{value:this.value}}}Gw.className="Constant",ge(Gw);class Yw extends Vs{constructor(e){super();this.DEFAULT_MINVAL=-.05,this.DEFAULT_MAXVAL=.05,this.minval=e.minval||this.DEFAULT_MINVAL,this.maxval=e.maxval||this.DEFAULT_MAXVAL,this.seed=e.seed}apply(e,t){return Go(e,this.minval,this.maxval,t)}getConfig(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}}}Yw.className="RandomUniform",ge(Yw);class Hw extends Vs{constructor(e){super();this.DEFAULT_MEAN=0,this.DEFAULT_STDDEV=.05,this.mean=e.mean||this.DEFAULT_MEAN,this.stddev=e.stddev||this.DEFAULT_STDDEV,this.seed=e.seed}apply(e,t){if(t=t||"float32",t!=="float32"&&t!=="int32")throw new ze(`randomNormal does not support dType ${t}.`);return om(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}}Hw.className="RandomNormal",ge(Hw);class qw extends Vs{constructor(e){super();this.DEFAULT_MEAN=0,this.DEFAULT_STDDEV=.05,this.mean=e.mean||this.DEFAULT_MEAN,this.stddev=e.stddev||this.DEFAULT_STDDEV,this.seed=e.seed}apply(e,t){if(t=t||"float32",t!=="float32"&&t!=="int32")throw new ze(`truncatedNormal does not support dType ${t}.`);return $h(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}}qw.className="TruncatedNormal",ge(qw);class jw extends Vs{constructor(e){super();this.gain=e.gain!=null?e.gain:1}apply(e,t){return ee(()=>{if(e.length!==2||e[0]!==e[1])throw new q("Identity matrix initializer can only be used for 2D square matrices.");return X(this.gain,vp(e[0]))})}getConfig(){return{gain:this.gain}}}jw.className="Identity",ge(jw);function S3(e,t="channelsLast"){let n,s;if(jt(t),e.length===2)n=e[0],s=e[1];else if([3,4,5].indexOf(e.length)!==-1){if(t==="channelsFirst"){const i=Zr(e,2);n=e[1]*i,s=e[0]*i}else if(t==="channelsLast"){const i=Zr(e,0,e.length-2);n=e[e.length-2]*i,s=e[e.length-1]*i}}else{const i=Zr(e);n=Math.sqrt(i),s=Math.sqrt(i)}return[n,s]}class rs extends Vs{constructor(e){super();if(e.scale<0)throw new q(`scale must be a positive float. Got: ${e.scale}`);this.scale=e.scale==null?1:e.scale,this.mode=e.mode==null?"fanIn":e.mode,w3(this.mode),this.distribution=e.distribution==null?"normal":e.distribution,L3(this.distribution),this.seed=e.seed}apply(e,t){const n=S3(e),s=n[0],i=n[1];let o=this.scale;if(this.mode==="fanIn"?o/=Math.max(1,s):this.mode==="fanOut"?o/=Math.max(1,i):o/=Math.max(1,(s+i)/2),this.distribution==="normal"){const a=Math.sqrt(o);if(t=t||"float32",t!=="float32"&&t!=="int32")throw new ze(`${this.getClassName()} does not support dType ${t}.`);return $h(e,0,a,t,this.seed)}else{const a=Math.sqrt(3*o);return Go(e,-a,a,t)}}getConfig(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}}}rs.className="VarianceScaling",ge(rs);class cm extends rs{constructor(e){super({scale:1,mode:"fanAvg",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return rs.className}}cm.className="GlorotUniform",ge(cm);class lm extends rs{constructor(e){super({scale:1,mode:"fanAvg",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return rs.className}}lm.className="GlorotNormal",ge(lm);class hm extends rs{constructor(e){super({scale:2,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return rs.className}}hm.className="HeNormal",ge(hm);class um extends rs{constructor(e){super({scale:2,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return rs.className}}um.className="HeUniform",ge(um);class dm extends rs{constructor(e){super({scale:1,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return rs.className}}dm.className="LeCunNormal",ge(dm);class pm extends rs{constructor(e){super({scale:1,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return rs.className}}pm.className="LeCunNormal",ge(pm);class Kw extends Vs{constructor(e){super();if(this.DEFAULT_GAIN=1,this.gain=e.gain==null?this.DEFAULT_GAIN:e.gain,this.seed=e.seed,this.seed!=null)throw new ze("Random seed is not implemented for Orthogonal Initializer yet.")}apply(e,t){return ee(()=>{if(e.length<2)throw new ze("Shape must be at least 2D.");e[0]*e[1]>2e3&&console.warn(`Orthogonal initializer is being called on a matrix with more than 2000 (${e[0]*e[1]}) elements: Slowness may result.`);const n=e[0]>e[1]?[e[1],e[0]]:e,s=om(n,0,1,"float32");let i=bv.gramSchmidt(s);return e[0]>e[1]&&(i=i.transpose()),X(this.gain,i)})}getConfig(){return{gain:this.gain,seed:this.seed}}}Kw.className="Orthogonal",ge(Kw);const jv={constant:"Constant",glorotNormal:"GlorotNormal",glorotUniform:"GlorotUniform",heNormal:"HeNormal",heUniform:"HeUniform",identity:"Identity",leCunNormal:"LeCunNormal",leCunUniform:"LeCunUniform",ones:"Ones",orthogonal:"Orthogonal",randomNormal:"RandomNormal",randomUniform:"RandomUniform",truncatedNormal:"TruncatedNormal",varianceScaling:"VarianceScaling",zeros:"Zeros"};function Kv(e,t={}){return qh(e,Bs.getMap().classNameMap,t,"initializer")}function Kt(e){return Ew(e)}function Pt(e){if(typeof e=="string"){const t=e in jv?jv[e]:e;if(t==="GlorotNormal")return new lm;if(t==="GlorotUniform")return new cm;if(t==="HeNormal")return new hm;if(t==="HeUniform")return new um;if(t==="LeCunNormal")return new dm;if(t==="LeCunUniform")return new pm;{const n={};return n.className=t,n.config={},Kv(n)}}else return e instanceof Vs?e:Kv(e)}function I3(){return new Vw}function x3(){return new am}function T3(e){return new Gw(e)}function A3(e){return new Yw(e)}function v3(e){return new Hw(e)}function N3(e){return new qw(e)}function C3(e){return new jw(e)}function R3(e){return new rs(e)}function O3(e){return new cm(e)}function E3(e){return new lm(e)}function D3(e){return new hm(e)}function k3(e){return new um(e)}function F3(e){return new dm(e)}function _3(e){return new pm(e)}function W3(e){return new Kw(e)}var $3=Object.freeze({__proto__:null,zeros:I3,ones:x3,constant:T3,randomUniform:A3,randomNormal:v3,truncatedNormal:N3,identity:C3,varianceScaling:R3,glorotUniform:O3,glorotNormal:E3,heNormal:D3,heUniform:k3,leCunNormal:F3,leCunUniform:_3,orthogonal:W3});let U3=0;function Xv(){return U3++}const mm={};function fm(e=""){return e in mm||(mm[e]=0),mm[e]+=1,e+mm[e].toString()}function Xw(e){return Array.isArray(e)&&Array.isArray(e[0])}function gm(e){return e.length===0?[]:Array.isArray(e[0])?e:[e]}function Je(e){let t;if(Array.isArray(e)){if(e.length!==1)throw new q(`Expected Tensor length to be 1; got ${e.length}`);t=e[0]}else t=e;return t}function Nt(e){if(Array.isArray(e)&&Array.isArray(e[0])){if(e.length===1)return e=e,e[0];throw new q(`Expected exactly 1 Shape; got ${e.length}`)}else return e}function ym(e){let t=0;for(const n of e)n.shape.length===0?t+=1:t+=n.shape.reduce((s,i)=>s*i);return t}const Jv="Variable";class ai{constructor(e,t="float32",n=Jv,s=!0,i=null){this.dtype=t==null?"float32":t,this.shape=e.shape,this.id=Xv(),n=n==null?Jv:n,this.originalName=Pv(n),this.name=zv(this.originalName),this.trainable_=s,this.constraint=i,this.val=zA(e,this.trainable_,this.name,this.dtype)}read(){return this.assertNotDisposed(),this.val}write(e){return this.assertNotDisposed(),B3(this.val,e),this.val.id!==e.id&&(this.val.assign(e),this.constraint!=null&&this.val.assign(this.constraint.apply(this.val))),this}dispose(){this.assertNotDisposed(),this.val.dispose()}assertNotDisposed(){if(this.val.isDisposed)throw new Error(`LayersVariable ${this.name} is already disposed.`)}get trainable(){return this.trainable_}set trainable(e){this.trainable_=e,this.val.trainable=e}}function B3(e,t){if(e.shape.toString()!==t.shape.toString())throw new Error("Shape mismatch: "+JSON.stringify(e.shape)+" vs. "+JSON.stringify(t.shape))}function Ute(e,t,n,s){return new ai(e,t,n,!0,s)}function Bte(e,t,n){return new ai(pt(e),t,n)}function Mte(e,t,n){return new ai(tt(e),t,n)}function Pte(e,t,n){const s=ti(e);return new ai(s,t,n)}function zte(e,t,n){const s=Wn(e);return new ai(s,t,n)}function Vte(e,t,n){return new ai(vp(e),t,n)}function Gte(e,t,n,s,i,o="randomUniform"){return new ai(Go(e,t,n,s),s,o)}function Yte(e,t=0,n=1,s,i,o="truncatedNormal"){if(s=s||"float32",s!=="float32"&&s!=="int32")throw new ze(`randomNormal does not support dType ${s}.`);return new ai($h(e,t,n,s,i),s,o)}function Hte(e,t=0,n=1,s,i,o="randomNormal"){if(s=s||"float32",s!=="float32"&&s!=="int32")throw new ze(`randomNormalVariable does not support dType ${s}.`);return new ai(Qb(e,t,n,s,i),s,o)}function qte(e,t){return e.write(t)}function jte(e,t){return e.write(be(e.read(),t))}function Kte(e,t){return e.write(Re(e.read(),t))}function Jw(e){return e.map(t=>t.read())}function Zw(e){e.forEach(t=>{const n=t[0];n.write(t[1])})}function Xte(e,t){const n=t.map(i=>i.read()),s=qb(e,n);return t.map(i=>s.grads[i.name])}class Sn{constructor(e){this.dtype=e.dtype,this.shape=e.shape,e.shape!=null?this.ndim=e.shape.length:this.ndim=e.ndim,this.maxNDim=e.maxNDim,this.minNDim=e.minNDim,this.axes=e.axes||{}}}class ci{constructor(e,t,n,s,i,o,a){this.dtype=e,this.shape=t,this.sourceLayer=n,this.inputs=s,this.callArgs=i,this.outputTensorIndex=a,this.id=Xv(),o!=null&&(this.originalName=Pv(o),this.name=zv(this.originalName)),this.rank=t.length}}let M3=0;class bm{constructor(e,t){this.callArgs=t,this.id=M3++,this.outboundLayer=e.outboundLayer,this.inboundLayers=e.inboundLayers,this.nodeIndices=e.nodeIndices,this.tensorIndices=e.tensorIndices,this.inputTensors=e.inputTensors,this.outputTensors=e.outputTensors,this.inputMasks=e.inputMasks,this.outputMasks=e.outputMasks,this.inputShapes=e.inputShapes,this.outputShapes=e.outputShapes;for(const n of e.inboundLayers)n!=null&&n.outboundNodes.push(this);e.outboundLayer.inboundNodes.push(this)}getConfig(){const e=[];for(const t of this.inboundLayers)t!=null?e.push(t.name):e.push(null);return{outboundLayer:this.outboundLayer?this.outboundLayer.name:null,inboundLayers:e,nodeIndices:this.nodeIndices,tensorIndices:this.tensorIndices}}}let P3=0;class ht extends Wo{constructor(e={}){super();this._callHook=null,this._addedWeightNames=[],this._stateful=!1,this.id=P3++,this.activityRegularizer=null,this.inputSpec=null,this.supportsMasking=!1,this._trainableWeights=[],this._nonTrainableWeights=[],this._losses=[],this._updates=[],this._built=!1,this.inboundNodes=[],this.outboundNodes=[];let t=e.name;if(!t){const n=this.getClassName();t=lr(n)+"_"+fm(n)}if(this.name=t,this.trainable_=e.trainable==null?!0:e.trainable,e.inputShape!=null||e.batchInputShape!=null){let n;if(e.batchInputShape!=null)n=e.batchInputShape;else if(e.inputShape!=null){let i=null;e.batchSize!=null&&(i=e.batchSize),n=[i].concat(e.inputShape)}this.batchInputShape=n;let s=e.dtype;s==null&&(s=e.inputDType),s==null&&(s="float32"),this.dtype=s}e.weights!=null?this.initialWeights=e.weights:this.initialWeights=null,this._refCount=null,this.fastWeightInitDuringBuild=!1}static nodeKey(e,t){return e.name+"_ib-"+t.toString()}getNodeAtIndex(e,t){if(this.inboundNodes.length===0)throw new ri(`The layer has never been called and thus has no defined ${t}.`);if(this.inboundNodes.length<=e)throw new q(`Asked to get ${t} at node ${e}, but the layer has only ${this.inboundNodes.length} inbound nodes.`);return this.inboundNodes[e]}getInputAt(e){return is(this.getNodeAtIndex(e,"input").inputTensors)}getOutputAt(e){return is(this.getNodeAtIndex(e,"output").outputTensors)}get input(){if(this.inboundNodes.length>1)throw new cr(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer input" is ill-defined. Use \`getInputAt(nodeIndex)\` instead.`);if(this.inboundNodes.length===0)throw new cr(`Layer ${this.name} is not connected, no input to return.`);return is(this.getNodeAtIndex(0,"input").inputTensors)}get output(){if(this.inboundNodes.length===0)throw new cr(`Layer ${this.name} has no inbound nodes.`);if(this.inboundNodes.length>1)throw new cr(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use \`getOutputAt(nodeIndex)\` instead.`);return is(this.getNodeAtIndex(0,"output").outputTensors)}get losses(){return this._losses}calculateLosses(){return this.losses.map(e=>e())}get updates(){return this._updates}get built(){return this._built}set built(e){this._built=e}get trainable(){return this.trainable_}set trainable(e){this._trainableWeights.forEach(t=>t.trainable=e),this.trainable_=e}get trainableWeights(){return this.trainable_?this._trainableWeights.filter(e=>e.trainable):[]}set trainableWeights(e){this._trainableWeights=e}get nonTrainableWeights(){return this.trainable?this._trainableWeights.filter(e=>!e.trainable).concat(this._nonTrainableWeights):this._trainableWeights.concat(this._nonTrainableWeights)}set nonTrainableWeights(e){this._nonTrainableWeights=e}get weights(){return this.trainableWeights.concat(this.nonTrainableWeights)}get stateful(){return this._stateful}resetStates(){if(!this.stateful)throw new Error("Cannot call the resetStates() method of a non-stateful Layer object.")}assertInputCompatibility(e){if(e=Et(e),this.inputSpec==null||this.inputSpec.length===0)return;const t=Et(this.inputSpec);if(e.length!==t.length)throw new q(`Layer ${this.name} expects ${t.length} inputs, but it received ${e.length} input tensors. Input received: ${e}`);for(let n=0;n<e.length;n++){const s=e[n],i=t[n];if(i==null)continue;const o=s.rank;if(i.ndim!=null&&o!==i.ndim)throw new q(`Input ${n} is incompatible with layer ${this.name}: expected ndim=${i.ndim}, found ndim=${o}`);if(i.maxNDim!=null&&o>i.maxNDim)throw new q(`Input ${n} is incompatible with layer ${this.name}: expected max_ndim=${i.maxNDim}, found ndim=${o}`);if(i.minNDim!=null&&o<i.minNDim)throw new q(`Input ${n} is incompatible with layer ${this.name}: expected min_ndim=${i.minNDim}, found ndim=${o}.`);if(i.dtype!=null&&s.dtype!==i.dtype)throw new q(`Input ${n} is incompatible with layer ${this.name} : expected dtype=${i.dtype}, found dtype=${s.dtype}.`);if(i.axes){const a=s.shape;for(const c in i.axes){const h=Number(c),p=i.axes[c],m=h>=0?a[h]:a[a.length+h];if(p!=null&&[p,null].indexOf(m)===-1)throw new q(`Input ${n} is incompatible with layer ${this.name}: expected axis ${h} of input shape to have value ${p} but got shape ${a}.`)}}if(i.shape!=null)for(let a=0;a<i.shape.length;++a){const c=i.shape[a],h=s.shape[a];if(c!=null&&h!=null&&c!==h)throw new q(`Input ${n} is incompatible with layer ${this.name}: expected shape=${i.shape}, found shape=${s.shape}.`)}}}call(e,t){return e}invokeCallHook(e,t){this._callHook!=null&&this._callHook(e,t)}setCallHook(e){this._callHook=e}clearCallHook(){this._callHook=null}apply(e,t){t=t||{},this.assertNotDisposed();const n=Et(e);let s=!0;for(const o of n)if(!(o instanceof ci)){s=!1;break}let i=!0;for(const o of n)if(o instanceof ci){i=!1;break}if(s===i)throw new q("Arguments to apply() must be all SymbolicTensors or all Tensors");return Xo(this.name,()=>{if(!this.built){this.assertInputCompatibility(e);const o=[];for(const a of Et(e))o.push(a.shape);this.build(is(o)),this.built=!0,this.initialWeights&&this.setWeights(this.initialWeights),this._refCount===null&&i&&(this._refCount=1)}if(this.assertInputCompatibility(e),i){let o=this.call(e,t);const a=Et(o),c=[];for(let h of a)n.indexOf(h)!==-1&&(h=h.clone()),c.push(h);if(o=is(c),this.activityRegularizer!=null)throw new ze("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return o}else{const o=z3(e),a=this.computeOutputShape(o);let c;const h=V3(e);if(this.warnOnIncompatibleInputShape(Array.isArray(e)?o[0]:o),a!=null&&a.length>0&&Array.isArray(a[0])?c=a.map((p,m)=>new ci(h,p,this,Et(e),t,this.name,m)):c=new ci(h,a,this,Et(e),t,this.name),this.addInboundNode(e,c,null,null,o,a,t),this._refCount++,this.activityRegularizer!=null)throw new ze("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return c}})}warnOnIncompatibleInputShape(e){if(this.batchInputShape==null)return;if(e.length!==this.batchInputShape.length)console.warn(`The rank of the input tensor provided (shape: ${JSON.stringify(e)}) does not match that of the batchInputShape (${JSON.stringify(this.batchInputShape)}) of the layer ${this.name}`);else{let t=!1;this.batchInputShape.forEach((n,s)=>{n!=null&&e[s]!=null&&e[s]!==n&&(t=!0)}),t&&console.warn(`The shape of the input tensor (${JSON.stringify(e)}) does not match the expectation of layer ${this.name}: ${JSON.stringify(this.batchInputShape)}`)}}get outputShape(){if(this.inboundNodes==null||this.inboundNodes.length===0)throw new cr(`The layer ${this.name} has never been called and thus has no defined output shape.`);const e=[];for(const t of this.inboundNodes){const n=JSON.stringify(t.outputShapes);e.indexOf(n)===-1&&e.push(n)}if(e.length===1){const t=this.inboundNodes[0].outputShapes;return Array.isArray(t)&&Array.isArray(t[0])&&t.length===1?t[0]:t}else throw new cr(`The layer ${this.name} has multiple inbound nodes with different output shapes. Hence the notion of "output shape" is ill-defined for the layer.`)}countParams(){if(!this.built)throw new ri(`You tried to call countParams() on ${this.name}, but the layer is not built yet. Build it first by calling build(batchInputShape).`);return ym(this.weights)}build(e){this.built=!0}getWeights(e=!1){return Jw(e?this.trainableWeights:this.weights)}setWeights(e){ee(()=>{const t=this.weights;if(t.length!==e.length)throw new q(`You called setWeights(weights) on layer "${this.name}" with a weight list of length ${e.length}, but the layer was expecting ${t.length} weights. Provided weights: ${e}...`);if(t.length===0)return;const n=[],s=Jw(t);for(let i=0;i<s.length;++i){const o=s[i],a=t[i],c=e[i];if(!ie(o.shape,c.shape))throw new q(`Layer weight shape ${o.shape} not compatible with provided weight shape ${c.shape}`);n.push([a,c])}Zw(n)})}addWeight(e,t,n,s,i,o,a){if(this._addedWeightNames.indexOf(e)!==-1)throw new q(`Duplicate weight name ${e} for layer ${this.name}`);this._addedWeightNames.push(e),n==null&&(n="float32"),this.fastWeightInitDuringBuild&&(s=Pt("zeros"));const c=s.apply(t,n),h=new ai(c,n,e,o,a);return c.dispose(),i!=null&&this.addLoss(()=>i.apply(h.read())),o==null&&(o=!0),o?this._trainableWeights.push(h):this._nonTrainableWeights.push(h),h}setFastWeightInitDuringBuild(e){this.fastWeightInitDuringBuild=e}addLoss(e){if(e==null||Array.isArray(e)&&e.length===0)return;e=Et(e),this._losses!==void 0&&this._losses!==null&&this.losses.push(...e)}computeOutputShape(e){return e}computeMask(e,t){if(!this.supportsMasking){if(t!=null)if(Array.isArray(t))t.forEach(n=>{if(n!=null)throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`)});else throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`);return null}return t}addInboundNode(e,t,n,s,i,o,a=null){const c=Et(e);t=Et(t),n=Et(n),s=Et(s),i=gm(i),o=gm(o);const h=[],p=[],m=[];for(const y of c)h.push(y.sourceLayer),p.push(y.nodeIndex),m.push(y.tensorIndex);new bm({outboundLayer:this,inboundLayers:h,nodeIndices:p,tensorIndices:m,inputTensors:c,outputTensors:t,inputMasks:n,outputMasks:s,inputShapes:i,outputShapes:o},a);for(let y=0;y<t.length;y++)t[y].sourceLayer=this,t[y].nodeIndex=this.inboundNodes.length-1,t[y].tensorIndex=y}getConfig(){const e={name:this.name,trainable:this.trainable};return this.batchInputShape!=null&&(e.batchInputShape=this.batchInputShape),this.dtype!=null&&(e.dtype=this.dtype),e}disposeWeights(){return this.weights.forEach(e=>e.dispose()),this.weights.length}assertNotDisposed(){if(this._refCount===0)throw new Error(`Layer '${this.name}' is already disposed.`)}dispose(){if(!this.built)throw new Error(`Cannot dispose Layer ${this.name} because it has not been built yet.`);if(this._refCount===null)throw new Error(`Cannot dispose Layer ${this.name} because it has not been used yet.`);this.assertNotDisposed();let e=0;return--this._refCount===0&&(e=this.disposeWeights()),{refCountAfterDispose:this._refCount,numDisposedVariables:e}}}function z3(e){e=Et(e);const t=[];for(const n of e)t.push(n.shape);return is(t)}function V3(e){return"float32"}function Zv(e,t,n){if((t==null||n!=null&&n>0)&&(t=e.sourceLayer,n=e.nodeIndex),t.inboundNodes.length===0)return[e];{const s=t.inboundNodes[n];if(s.inboundLayers.length===0)return s.inputTensors;{const i=[];for(let o=0;o<s.inboundLayers.length;o++){const a=s.inputTensors[o],c=s.inboundLayers[o],h=s.nodeIndices[o],p=Zv(a,c,h);for(const m of p)i.indexOf(m)===-1&&i.push(m)}return i}}}class mc extends ht{constructor(e){super({dtype:e.dtype,name:e.name!=null?e.name:fm("input").toString()});if(e.batchSize==null&&(e.batchSize=null),e.sparse==null&&(e.sparse=!1),this.trainable=!1,this.built=!0,this.sparse=e.sparse,e.inputShape!=null&&e.batchInputShape!=null)throw new q("Only provide the inputShape OR batchInputShape argument to inputLayer, not both at the same time.");let t=e.batchInputShape;if(t==null){if(e.inputShape==null)throw new q("An InputLayer should be passed either a `batchInputShape` or an `inputShape`.");t=[e.batchSize].concat(e.inputShape)}else if(e.batchSize!=null)throw new q("Cannot specify batchSize if batchInputShape is specified when creating an InputLayer.");const n=e.dtype||"float32";this.batchInputShape=t,this.dtype=n,this.inputSpec=[{shape:t}];const s=new ci(this.dtype,this.batchInputShape,this,[],{},this.name);s.nodeIndex=0,s.tensorIndex=0,new bm({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:[s],outputTensors:[s],inputMasks:[null],outputMasks:[null],inputShapes:[t],outputShapes:[t]})}apply(e,t){throw new q(`Cannot pass any input to an InputLayer's apply() method. InputLayer name: ${this.name}`)}dispose(){return{refCountAfterDispose:this._refCount,numDisposedVariables:0}}getConfig(){return{batchInputShape:this.batchInputShape,dtype:this.dtype,sparse:this.sparse,name:this.name}}}mc.className="InputLayer",ge(mc);function Qv(e){if(e.batchShape==null&&e.shape==null)throw new Error("Please provide to Input either a `shape` or a `batchShape` argument. Note that `shape` does not include the batch dimension.");if(e.batchShape!=null&&e.shape!=null)throw new q("Please provide either a `shape` or `batchShape` argument to Input, but not both.");let t=e.batchShape;e.shape!=null&&t==null&&(t=[null].concat(e.shape));let n=e.dtype;n==null&&(n="float32");const s=new mc({batchInputShape:t,name:e.name,dtype:n,sparse:e.sparse}),i=s.inboundNodes[0].outputTensors;return i[0]}async function eo(e){if(e==null)return;const t=[],n=[],s=[];for(const i in e){const o=e[i];if(typeof o!="number"){const a=o;t.push(a.data()),n.push(i),s.push(a)}}if(t.length>0){const i=await Promise.all(t);for(let o=0;o<i.length;++o)e[n[o]]=i[o][0];qe(s)}}function eN(e){if(e==null)return;for(const t in e){const n=e[t];typeof n!="number"&&n.dispose()}}var tN;(function(e){e[e.SILENT=0]="SILENT",e[e.VERBOSE=1]="VERBOSE"})(tN||(tN={}));const G3=125;class fc{constructor(){this.validationData=null}setParams(e){this.params=e}async onEpochBegin(e,t){}async onEpochEnd(e,t){}async onBatchBegin(e,t){}async onBatchEnd(e,t){}async onTrainBegin(e){}async onTrainEnd(e){}setModel(e){}}class nN{constructor(e,t=10){e==null&&(e=[]),this.callbacks=e,this.queueLength=t}append(e){this.callbacks.push(e)}setParams(e){for(const t of this.callbacks)t.setParams(e)}setModel(e){for(const t of this.callbacks)t.setModel(e)}async onEpochBegin(e,t){t==null&&(t={});for(const n of this.callbacks)await n.onEpochBegin(e,t)}async onEpochEnd(e,t){t==null&&(t={});for(const n of this.callbacks)await n.onEpochEnd(e,t)}async onBatchBegin(e,t){t==null&&(t={});for(const n of this.callbacks)await n.onBatchBegin(e,t)}async onBatchEnd(e,t){t==null&&(t={});for(const n of this.callbacks)await n.onBatchEnd(e,t)}async onTrainBegin(e){e==null&&(e={});for(const t of this.callbacks)await t.onTrainBegin(e)}async onTrainEnd(e){e==null&&(e={});for(const t of this.callbacks)await t.onTrainEnd(e)}}class Y3 extends fc{constructor(){super()}async onEpochBegin(e){this.seen=0,this.totals={}}async onBatchEnd(e,t){t==null&&(t={});const n=t.size==null?0:t.size;this.seen+=n;for(const s in t){const i=t[s];if(typeof i=="number")this.totals.hasOwnProperty(s)||(this.totals[s]=0),this.totals[s]=this.totals[s]+i*n;else{let o;s in this.totals?o=this.totals[s]:this.totals[s]=0;const a=ee(()=>be(this.totals[s],X(i,n)));this.totals[s]=a,o!=null&&o.dispose()}}}async onEpochEnd(e,t){if(t!=null)for(const n of this.params.metrics){if(this.totals[n]==null)continue;typeof this.totals[n]=="number"?t[n]=this.totals[n]/this.seen:ee(()=>{const s=X(We(1,this.seen),this.totals[n]);t[n]=s,this.totals[n].dispose(),wn(t[n])})}}}class sN extends fc{async onTrainBegin(e){this.epoch=[],this.history={}}async onEpochEnd(e,t){t==null&&(t={}),this.epoch.push(e);for(const n in t)this.history[n]==null&&(this.history[n]=[]),this.history[n].push(t[n])}async syncData(){const e=[],t=[],n=[];for(const i in this.history){const o=this.history[i];for(let a=0;a<o.length;++a)if(typeof o[a]!="number"){const c=o[a];e.push(c.data()),t.push(i),n.push(a)}}const s=await Promise.all(e);for(let i=0;i<s.length;++i){const o=this.history[t[i]][n[i]];o.dispose(),this.history[t[i]][n[i]]=s[i][0]}}}class iN extends fc{constructor(e,t){super();if(this.currentEpoch=0,this.yieldEvery=t||"auto",this.yieldEvery==="auto"&&(this.yieldEvery=G3),this.yieldEvery==="never"&&e.onYield!=null)throw new Error("yieldEvery is `never` but you provided an `onYield` callback. Either change `yieldEvery` or remove the callback");yd(this.yieldEvery)&&(this.maybeWait=Xz(this.maybeWait.bind(this),this.yieldEvery)),this.trainBegin=e.onTrainBegin,this.trainEnd=e.onTrainEnd,this.epochBegin=e.onEpochBegin,this.epochEnd=e.onEpochEnd,this.batchBegin=e.onBatchBegin,this.batchEnd=e.onBatchEnd,this.yield=e.onYield}async maybeWait(e,t,n){const s=[];this.yield!=null&&(await eo(n),s.push(this.yield(e,t,n))),s.push(Qp()),await Promise.all(s)}async onEpochBegin(e,t){this.currentEpoch=e,this.epochBegin!=null&&(await eo(t),await this.epochBegin(e,t))}async onEpochEnd(e,t){const n=[];this.epochEnd!=null&&(await eo(t),n.push(this.epochEnd(e,t))),this.yieldEvery==="epoch"&&n.push(Qp()),await Promise.all(n)}async onBatchBegin(e,t){this.batchBegin!=null&&(await eo(t),await this.batchBegin(e,t))}async onBatchEnd(e,t){const n=[];this.batchEnd!=null&&(await eo(t),n.push(this.batchEnd(e,t))),this.yieldEvery==="batch"?n.push(Qp()):yd(this.yieldEvery)&&n.push(this.maybeWait(this.currentEpoch,e,t)),await Promise.all(n)}async onTrainBegin(e){this.trainBegin!=null&&(await eo(e),await this.trainBegin(e))}async onTrainEnd(e){this.trainEnd!=null&&(await eo(e),await this.trainEnd(e))}}function rN(e,t){if(e==null&&(e={}),e instanceof fc)return[e];if(Array.isArray(e)&&e[0]instanceof fc)return e;const n=Et(e);return n.map(s=>new iN(s,t))}class Gs{constructor(){}static registerCallbackConstructor(e,t){A(e>=0&&Number.isInteger(e),()=>`Verbosity level is expected to be an integer >= 0, but got ${e}`),Gs.checkForDuplicate(t),Gs.constructors[e]==null&&(Gs.constructors[e]=[]),Gs.constructors[e].push(t)}static checkForDuplicate(e){for(const t in Gs.constructors){const n=Gs.constructors[+t];n.forEach(s=>{if(s===e)throw new q("Duplicate callback constructor.")})}}static clear(){Gs.constructors={}}static createCallbacks(e){const t=[];for(const n in Gs.constructors){const s=+n;e>=s&&t.push(...Gs.constructors[s])}return t.map(n=>new n)}}Gs.constructors={};function oN(e,t,n,s,i,o,a,c,h){const p=new sN,m=[new Y3,...Gs.createCallbacks(t)];e!=null&&m.push(...e),m.push(p);const y=new nN(m);return y.setParams({epochs:n,initialEpoch:s,samples:i,steps:o,batchSize:a,verbose:t,doValidation:c,metrics:h}),{callbackList:y,history:p}}function li(e,t={},n=!1){return qh(e,Bs.getMap().classNameMap,t,"layer",n)}function wm(e,t){return ee(()=>{e.dtype!=="float32"&&(e=e.asType("float32"));const n=$e(Zh(e),t,!0),s=Ja(n.shape,fn()),i=Cn(Ms(n,s));return We(e,i)})}function hr(e,t){return ee(()=>qt(Zh(Re(t,e)),-1))}function gc(e,t){return ee(()=>qt(pn(Re(t,e)),-1))}function to(e,t){return ee(()=>{const n=Re(e,t),s=es(pn(e),fn(),Number.MAX_VALUE),i=pn(We(n,s));return X(100,qt(i,-1))})}function Qw(e,t){return ee(()=>{const n=es(t,fn(),Number.MAX_VALUE),s=us(be(1,n)),i=es(e,fn(),Number.MAX_VALUE),o=us(be(1,i));return qt(Zh(Re(s,o)),-1)})}function H3(e,t){return ee(()=>{const n=Ms(0,Re(1,X(e,t)));return qt(Zh(n),-1)})}function q3(e,t){return ee(()=>{const n=Ms(0,Re(1,X(e,t)));return qt(n,-1)})}function j3(e,t){return ee(()=>{const n=$e(X(e,t),-1),s=ns(X(Re(1,e),t),-1);return Ms(0,be(1,Re(s,n)))})}function K3(e,t){return ee(()=>{const n=Math.log(2),s=Re(t,e),i=Re(be(s,ec(X(-2,s))),n);return qt(i,-1)})}function eu(e,t,n=!1){return ee(()=>{if(n)t=Yo(t);else{const s=$e(t,t.shape.length-1,!0);t=We(t,s)}return t=es(t,fn(),1-fn()),Ht($e(X(e.toFloat(),us(t)),t.shape.length-1))})}function Lm(e,t,n=!1){return ee(()=>{const s=Za(d3(e)).toInt();t=es(t,fn(),1-fn());const i=t.shape,o=_o(s,i[i.length-1]).reshape(i);return eu(o,t,n)})}function X3(e,t){if(!ie(e.shape,t.shape))throw new q(`logits and labels must have the same shape, but got shapes ${JSON.stringify(e.shape)} and ${JSON.stringify(t.shape)}`);return ee(()=>{const n=t.relu(),s=t.abs().neg();return n.sub(t.mul(e)).add(s.exp().log1p())})}function Sm(e,t){return ee(()=>{let n;return n=es(t,fn(),1-fn()),n=us(We(n,Re(1,n))),qt(X3(e,n),-1)})}function eL(e,t){return ee(()=>{const n=es(e,fn(),1),s=es(t,fn(),1);return $e(X(e,us(We(n,s))),-1)})}function J3(e,t){return ee(()=>{const n=us(be(fn(),t));return qt(Re(t,X(e,n)),-1)})}function Im(e,t){return ee(()=>{const n=wm(e,-1),s=wm(t,-1),i=X(n,s);return Ht($e(i,-1))})}const Jte=hr,Zte=hr,Qte=gc,ene=gc,tne=to,nne=to,sne=Qw,ine=Qw,rne=eL,one=eL,ane=Im,xm={meanSquaredError:hr,meanAbsoluteError:gc,meanAbsolutePercentageError:to,meanSquaredLogarithmicError:Qw,squaredHinge:H3,hinge:q3,categoricalHinge:j3,logcosh:K3,categoricalCrossentropy:eu,sparseCategoricalCrossentropy:Lm,binaryCrossentropy:Sm,kullbackLeiblerDivergence:eL,poisson:J3,cosineProximity:Im};function tL(e){if(typeof e=="string"){if(e in xm)return xm[e];let t=`Unknown loss ${e}`;throw e.toLowerCase().includes("softmaxcrossentropy")&&(t=`Unknown loss ${e}. Use "categoricalCrossentropy" as the string name for tf.losses.softmaxCrossEntropy`),new q(t)}else return e}function nL(e,t){return ee(()=>{const n=X(.5,Wn(t)),s=Xh(vs(t,n),e.dtype);return qt(ei(e,s),-1)})}function sL(e,t){return ee(()=>Xh(ei(wh(e,-1),wh(t,-1)),"float32"))}function aN(e,t){return ee(()=>Ps(e.equal(1),t.equal(1)).sum().cast("float32"))}function Z3(e,t){return ee(()=>Ps(e.equal(1),t.equal(0)).sum().cast("float32"))}function Q3(e,t){return ee(()=>Ps(e.equal(0),t.equal(1)).sum().cast("float32"))}function cN(e,t){return ee(()=>{const n=aN(e,t),s=Q3(e,t),i=n.add(s);return Pn(vs(i,0),n.div(i),0).cast("float32")})}function eV(e,t){return ee(()=>{const n=aN(e,t),s=Z3(e,t),i=n.add(s);return Pn(vs(i,0),n.div(i),0).cast("float32")})}function lN(e,t){return Sm(e,t)}function hN(e,t){return e.rank===t.rank&&(e=e.squeeze([e.rank-1])),t=t.argMax(-1),t.dtype!==e.dtype&&(t=t.asType(e.dtype)),ei(e,t).asType("float32")}function cne(e,t){throw new ze}function lne(e,t){throw new ze}const tV=hr,nV=hr,sV=gc,iV=gc,rV=to,oV=to,iL=eu,aV=Im,uN=Lm,Tm={binaryAccuracy:nL,categoricalAccuracy:sL,precision:cN,categoricalCrossentropy:iL,sparseCategoricalCrossentropy:uN,mse:tV,MSE:nV,mae:sV,MAE:iV,mape:rV,MAPE:oV,cosine:aV};function cV(e){if(typeof e=="string"&&e in Tm)return Tm[e];if(typeof e!="string"&&e!=null)return e;throw new q(`Unknown metric ${e}`)}function Am(e){if(Cs(e!==null,`Unknown LossOrMetricFn ${e}`),typeof e=="string")return e;{let t;for(const n of Object.keys(xm))if(xm[n]===e){t=n;break}if(t!==void 0)return t;for(const n of Object.keys(Tm))if(Tm[n]===e){t=n;break}return t!==void 0?t:e.name}}function lV(e){const t={Adagrad:()=>qo.adagrad(.01),Adadelta:()=>qo.adadelta(1,.95,fn()),Adam:()=>qo.adam(.001,.9,.999,fn()),Adamax:()=>qo.adamax(.002,.9,.999,fn(),0),RMSProp:()=>qo.rmsprop(.001,.9,0,fn()),SGD:()=>qo.sgd(.01)};if(t.adagrad=t.Adagrad,t.adadelta=t.Adadelta,t.adam=t.Adam,t.adamax=t.Adamax,t.rmsprop=t.RMSProp,t.sgd=t.SGD,e in t)return t[e]();throw new q(`Unknown Optimizer ${e}`)}const dN=1*1024*1024;function pN(e,t,n=!1){if(e==null||typeof e!="object"||Object.getPrototypeOf(e)!==Object.prototype||!rL(e))throw new Error("User-defined metadata is expected to be a JSON object, but is not.");if(n){const s=JSON.stringify(e);s.length>dN&&console.warn(`User-defined metadata of model "${t}" is too large in size (length=${s.length} when serialized). It is not recommended to store such large objects in user-defined metadata. Please make sure its serialized length is <= ${dN}.`)}}function rL(e){if(e===null)return!0;if(typeof e=="object")if(Object.getPrototypeOf(e)===Object.prototype){const t=Object.keys(e);for(const n of t){if(typeof n!="string")return!1;if(!rL(e[n]))return!1}return!0}else if(Array.isArray(e)){for(const t of e)if(!rL(t))return!1;return!0}else return!1;else{const t=typeof e;return t==="string"||t==="number"||t==="boolean"}}function hV(e,t,n,s=console.log){const i=dV(e),o=["Layer (type)","Output shape","Param #"];i?(t=t||65,n=n||[.45,.85,1]):(t=t||98,n=n||[.33,.55,.67,1]),n[n.length-1]<=1&&(n=n.map(m=>Math.floor(t*m)));let a;if(!i){o.push("Receives inputs"),a=[];for(const m in e.nodesByDepth)a.push(...e.nodesByDepth[m])}s("_".repeat(t)),vm(o,n,s),s("=".repeat(t));const c=e.layers;for(let m=0;m<c.length;++m)i?pV(c[m],n,s):mV(c[m],n,a,s),s((m===c.length-1?"=":"_").repeat(t));e.checkTrainableWeightsConsistency();const h=uV(e),p=ym(e.nonTrainableWeights);s(`Total params: ${h+p}`),s(`Trainable params: ${h}`),s(`Non-trainable params: ${p}`),s("_".repeat(t))}function uV(e){let t;return e.collectedTrainableWeights!=null?t=ym(e.collectedTrainableWeights):t=ym(e.trainableWeights),t}function dV(e){let t=!0;const n=[],s=[];for(const i in e.nodesByDepth)n.push(e.nodesByDepth[i]);for(const i of n){if(i.length>1||i.length===1&&i[0].inboundLayers.length>1){t=!1;break}s.push(...i)}if(t)for(const i of e.layers){let o=!1;for(const a of i.inboundNodes)if(s.indexOf(a)!==-1)if(o){t=!1;break}else o=!0;if(!t)break}return t}function vm(e,t,n=console.log){let s="";for(let i=0;i<e.length;++i)i>0&&(s=s.slice(0,s.length-1)+" "),s+=e[i],s=s.slice(0,t[i]),s+=" ".repeat(t[i]-s.length);n(s)}function pV(e,t,n){let s;try{s=JSON.stringify(e.outputShape)}catch(c){s="multiple"}const i=e.name,o=e.getClassName(),a=[`${i} (${o})`,s,e.countParams().toString()];vm(a,t,n)}function mV(e,t,n,s){let i;try{i=JSON.stringify(e.outputShape)}catch(m){i="multiple"}const o=[];for(const m of e.inboundNodes){if(n!=null&&n.length>0&&n.indexOf(m)===-1)continue;for(let y=0;y<m.inboundLayers.length;++y){const b=m.inboundLayers[y].name,w=m.nodeIndices[y],L=m.tensorIndices[y];o.push(`${b}[${w}][${L}]`)}}const a=e.name,c=e.getClassName(),h=o.length===0?"":o[0],p=[`${a} (${c})`,i,e.countParams().toString(),h];vm(p,t,s);for(let m=1;m<o.length;++m)vm(["","","",o[m]],t,s)}function mN(e,t,n){return(e==="inboundNodes"||e==="outputLayers"||e==="inputLayers")&&t===0&&typeof n=="string"}function tu(e,t){if(e===null)return null;if(typeof e=="string")return Ko(e);if(typeof e=="number"||typeof e=="boolean")return e;if(e instanceof Array){const n=[],s=e.length;for(let i=0;i<s;++i){const o=e[i];mN(t,i,o)?n.push(o):n.push(tu(o,t))}return n}else{const n={};for(const s of Object.keys(e)){const i=e[s];if(s==="name"&&typeof i=="string")n[s]=i;else{const o=Ko(s);n[o]=tu(i,o)}}return n}}function oL(e,t){if(e==null)return null;if(typeof e=="string")return lr(e);if(typeof e=="number"||typeof e=="boolean")return e;if(e instanceof Array){const n=[],s=e.length;for(let i=0;i<s;++i){const o=e[i];mN(t,i,o)?n.push(o):n.push(oL(o,t))}return n}else{const n={};for(const s of Object.keys(e)){const i=e[s],o=lr(s);(s==="name"||s==="className")&&typeof i=="string"?n[o]=i:n[o]=oL(i,s)}return n}}const Nm="2.7.0";function fV(e,t){if(e.dtype==null||e.dtype===t.dtype)return t;try{return ve(t,e.dtype)}catch(n){throw new q(`The dtype of the feed (${t.dtype}) can not be cast to the dtype of the key '${e.name}' (${e.dtype}).`)}}class Zo{constructor(e){if(this.id2Value={},this.id2Mask={},this.name2Id={},e instanceof Zo)for(const t in e.id2Value)this.id2Value[t]=e.id2Value[t],t in e.id2Mask&&(this.id2Mask[t]=e.id2Mask[t]);else{if(e==null)return;for(const t of e)this.add(t.key,t.value)}}add(e,t,n){if(this.id2Value[e.id]==null)this.id2Value[e.id]=fV(e,t),this.name2Id[e.name]=e.id,n!=null&&(this.id2Mask[e.id]=n);else throw new q(`Duplicate key: name=${e.name}, id=${e.id}`);return this}addFeed(e){this.add(e.key,e.value)}hasKey(e){return this.id2Value[e.id]!=null}names(){return Object.keys(this.name2Id)}getValue(e){if(e instanceof ci){if(this.id2Value[e.id]==null)throw new q(`Nonexistent key: ${e.name}`);return this.id2Value[e.id]}else{const t=this.name2Id[e];if(t==null)throw new q(`Feed dict has no SymbolicTensor name: ${e}`);return this.id2Value[t]}}getMask(e){if(e instanceof ci){if(this.id2Value[e.id]==null)throw new q(`Nonexistent key: ${e.name}`);return this.id2Mask[e.id]}else{const t=this.name2Id[e];if(t==null)throw new q(`Feed dict has no SymbolicTensor name: ${e}`);return this.id2Mask[t]}}disposeMasks(){this.id2Mask!=null&&qe(this.id2Mask)}}const aL={},fN={};function nu(e,t,n,s){const i=n==null?!1:n.training,o=Array.isArray(e),a=o?e:[e],c=a.map(L=>L.name),h=[],p=t.names();for(const L of c)p.indexOf(L)!==-1?h.push(t.getValue(L)):h.push(null);s!=null&&(s.maxNumTensors=-Infinity,s.minNumTensors=Infinity);const m=c.join(",")+"|"+t.names().join(",");let y,b;if(aL[m]==null){const L=gV(a,t);y=L.sorted,b=L.recipientCounts,aL[m]=y,fN[m]=b}y=aL[m],b={},i||Object.assign(b,fN[m]);const w=new Zo(t);for(let L=0;L<y.length;++L){if(s!=null){const j=fp().numTensors;j>s.maxNumTensors&&(s.maxNumTensors=j),j<s.minNumTensors&&(s.minNumTensors=j)}const T=y[L],v=T.sourceLayer;if(v instanceof mc)continue;const C=[],O=[],D=[];let k=!1;for(const j of T.inputs){const Z=w.getValue(j),re=w.getMask(j);C.push(Z),O.push(re),re!=null&&(k=!0),i||(b[j.name]--,b[j.name]===0&&!t.hasKey(j)&&c.indexOf(j.name)===-1&&!Z.isDisposed&&j.sourceLayer.stateful!==!0&&D.push(Z))}k&&(n=n||{},n.mask=O[0]);const F=Et(v.apply(C,n));let B=null;v.supportsMasking&&(B=v.computeMask(C,O));const $=bV(T),Y=Array.isArray($)?$:[$];for(let j=0;j<Y.length;++j){w.hasKey(Y[j])||w.add(Y[j],F[j],Array.isArray(B)?B[0]:B);const Z=c.indexOf(Y[j].name);Z!==-1&&(h[Z]=F[j])}i||qe(D)}return w.disposeMasks(),o?h:h[0]}function gV(e,t){A(e!=null&&e.length>0,()=>"Expected at least one fetch, got none");let n=[],s={};if(e.length===1){const i=gN(e[0],t);n=i.sorted,s=i.recipientMap}else{const i=new Set;for(const o of e){const{sorted:a,recipientMap:c}=gN(o,t);for(const h of a)i.has(h.name)||(n.push(h),i.add(h.name));for(const h in c)s[h]==null&&(s[h]=new Set),c[h].forEach(p=>s[h].add(p))}}return{sorted:n,recipientCounts:yV(s)}}function yV(e){const t={};for(const n in e)t[n]=e[n].size;return t}function gN(e,t){const n=new Set,s=[],i={};for(const c of t.names())n.add(c);const o=[],a=[];for(o.push(e);o.length>0;){const c=o[o.length-1];if(n.has(c.name)){o.pop();continue}const h=a[a.length-1]===o.length-1;if(c.inputs.length===0||h)o.pop(),s.push(c),n.add(c.name),h&&a.pop();else{a.push(o.length-1);for(const p of c.inputs){if(i[p.name]==null&&(i[p.name]=new Set),i[p.name].add(c.name),n.has(p.name))continue;o.push(p)}}}return{sorted:s,recipientMap:i}}function bV(e){let t;if(e.sourceLayer.inboundNodes.length===1)t=e.sourceLayer.output;else{let n=null;for(let s=0;s<e.sourceLayer.inboundNodes.length;++s)for(const i of e.sourceLayer.inboundNodes[s].outputTensors)if(i.id===e.id){n=s;break}t=e.sourceLayer.getOutputAt(n)}return t}class _i extends ht{constructor(e){super({});if(this.containerNodes=new Set,this.name=e.name,this.name==null){const C=this.getClassName().toLowerCase();this.name=fm(C)}if(this.supportsMasking=!1,this.trainable_=!0,Array.isArray(e.inputs)?this.inputs=e.inputs.slice():this.inputs=[e.inputs],Array.isArray(e.outputs)?this.outputs=e.outputs.slice():this.outputs=[e.outputs],Jr(this.inputs).length!==this.inputs.length)throw new q(`The list of inputs passed to the model is redundant. All inputs should only appear once. Found: ${this.inputs.map(C=>C.name)}`);Jr(this.outputs).length!==this.outputs.length&&console.warn(`The list of outputs passed to the model is redundant. All outputs should only appear once. Found: ${this.outputs.map(C=>C.name)}`),this.inputLayers=[],this.inputLayersNodeIndices=[],this.inputLayersTensorIndices=[],this.outputLayers=[],this.outputLayersNodeIndices=[],this.outputLayersTensorIndices=[],this.layers=[],this.internalContainerRefs=[];for(const C of this.outputs){const O=C.sourceLayer,D=C.nodeIndex,k=C.tensorIndex;this.outputLayers.push(O),this.outputLayersNodeIndices.push(D),this.outputLayersTensorIndices.push(k)}for(const C of this.inputs){const O=C.sourceLayer,D=C.nodeIndex,k=C.tensorIndex;Cs(D===0,"input layer has >1 nodes"),Cs(k===0,"input layer has >1 tensors"),this.inputLayers.push(O),this.inputLayersNodeIndices.push(D),this.inputLayersTensorIndices.push(k)}this.inputNames=[],this.outputNames=[],this.feedInputShapes=[],this.feedInputNames=[],this.feedOutputNames=[];for(let C=0;C<this.inputLayers.length;C++){const O=this.inputLayers[C];if(!(O instanceof mc))throw new TypeError(`Input layers to a LayersModel must be InputLayer objects. Received inputs: ${e.inputs}. Input ${C} (0-based) originates from layer type ${O.getClassName()}.`);this.inputNames.push(O.name),this.feedInputShapes.push(O.batchInputShape),this.feedInputNames.push(O.name)}for(const C of this.outputLayers)this.outputNames.push(C.name);this.internalInputShapes=this.inputs.map(C=>C.shape),this.internalOutputShapes=this.outputs.map(C=>C.shape);const t={},n={},s={},i={},o={},a=[],c=(C,O,D,k,F,B)=>{(k==null||F==null||B==null)&&(k=C.sourceLayer,F=C.nodeIndex,B=C.tensorIndex);const $=k.inboundNodes[F];if(D.indexOf($)!==-1)throw new ri(`The tensor ${C.name} at layer "${k.name}" is part of a cycle.`);if(O.indexOf($)!==-1)return;this.containerNodes.add(_i.nodeKey(k,F)),k.id in o||(o[k.id]=Object.keys(o).length),D.indexOf($)===-1&&D.push($);const Y=$.inboundLayers.length;for(let j=0;j<Y;j++){const Z=$.inputTensors[j],re=$.inboundLayers[j],de=$.nodeIndices[j],he=$.tensorIndices[j];c(Z,O,D,re,de,he)}for(O.push($);D.indexOf($)>=0;)D.splice(D.indexOf($),1);a.push($)},h=[],p=[];for(const C of this.outputs)c(C,h,p);const m=a.slice().reverse();for(const C of m){n[C.id]=C,C.id in t||(t[C.id]=0);let O=t[C.id];const D=s[C.outboundLayer.id]==null?0:s[C.outboundLayer.id];O=Math.max(O,D),s[C.outboundLayer.id]=O,i[C.outboundLayer.id]=C.outboundLayer,t[C.id]=O;for(let k=0;k<C.inboundLayers.length;k++){const F=C.inboundLayers[k],B=C.nodeIndices[k],$=F.inboundNodes[B],Y=t[$.id]==null?0:t[$.id];t[$.id]=Math.max(O+1,Y),n[$.id]=$}}const y={};for(const C in t){const O=t[C];O in y||(y[O]=[]),y[O].push(n[C])}const b={};for(const C in s){const O=s[C];O in b||(b[O]=[]),b[O].push(i[C])}let w=Object.keys(b).map(C=>parseInt(C,10)).sort(sm);this.layers=[];for(const C of w){const O=b[C];O.sort((D,k)=>{const F=o[D.id],B=o[k.id];return F<B?-1:F>B?1:0});for(const D of O)D instanceof _i&&this.internalContainerRefs.push(D),this.layers.push(D)}this.layersByDepth=b,w=Object.keys(y).map(C=>parseInt(C,10)).sort(sm);const L=this.inputs.slice(),T=[];for(const C of w)for(const O of y[C]){const D=O.outboundLayer;if(D!=null){for(const k of O.inputTensors)if(L.indexOf(k)===-1)throw new ri(`Graph disconnected: cannot obtain value for tensor ${k} at layer "${D.name}". The following previous layers were accessed without issue: ${T}`);for(const k of O.outputTensors)L.push(k);T.push(D.name)}}this.nodesByDepth=y;const v=this.layers.map(C=>C.name);for(const C of v){const O=v.filter(D=>D===C).length;if(O!==1)throw new ri(`The name "${C}" is used ${O} times in the model. All layer names should be unique. Layer names: `+JSON.stringify(v))}this.outboundNodes=[],this.inboundNodes=[],new bm({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:this.inputs.map(C=>null),outputMasks:this.outputs.map(C=>null),inputShapes:this.inputs.map(C=>C.shape),outputShapes:this.outputs.map(C=>C.shape)}),this.built=!0,this._refCount=1}assertNotDisposed(){if(this._refCount===0)throw new Error(`Container '${this.name}' is already disposed.`)}dispose(){this.assertNotDisposed();const e={refCountAfterDispose:null,numDisposedVariables:0};if(--this._refCount===0){for(const t of this.layers)e.numDisposedVariables+=t.dispose().numDisposedVariables;for(const t of this.internalContainerRefs)e.numDisposedVariables+=t.dispose().numDisposedVariables}return e.refCountAfterDispose=this._refCount,e}get trainable(){return this.trainable_}set trainable(e){this.layers.forEach(t=>{t._trainableWeights.forEach(n=>n.trainable=e)}),this.trainable_=e}get trainableWeights(){if(this._trainableWeights.length>0)throw new q("Container instance unexpectedly contains _trainableWeights.The trainable weights of a Container are a union of the trainable weights of its consituent Layers. Its own _trainableWeights must remain an empty Array.");if(!this.trainable)return[];let e=[];for(const t of this.layers)e=e.concat(t.trainableWeights);return e}get nonTrainableWeights(){const e=[];for(const t of this.layers)e.push(...t.nonTrainableWeights);if(!this.trainable){const t=[];for(const n of this.layers)t.push(...n.trainableWeights);return t.concat(e)}return e}get weights(){return this.trainableWeights.concat(this.nonTrainableWeights)}loadWeights(e,t=!0){const n={};let s=0;for(const o of this.layers)for(const a of o.weights){if(n[a.originalName]!=null)throw new q(`Duplicate weight name: ${a.originalName}`);n[a.originalName]=a,s++}const i=[];for(const o in e){let a=o;if(n[o]==null){const c=o.split("/"),h=c.slice(0,-2).concat([c[c.length-1]]);a=h.join("/")}if(n[a]!=null)i.push([n[a],e[o]]);else if(t)throw new q(`Provided weight data has no target variable: ${o}`);delete n[a]}if(t){const o=[];for(const a in n)o.push(a);if(o.length>0)throw new q(`${o.length} of ${s} weights are not set: ${o}`)}Zw(i)}updatedConfig(){const e=this.getConfig(),t={};return t.className=this.getClassName(),t.config=e,t.kerasVersion=`tfjs-layers ${Nm}`,t.backend="TensorFlow.js",t}toJSON(e,t=!0){const n=oL(this.updatedConfig());return t?JSON.stringify(n):n}call(e,t){return ee(()=>{e=Et(e);const n=new Zo;for(let s=0;s<this.inputs.length;++s)n.add(this.inputs[s],e[s]);return nu(this.outputs,n,t)})}computeMask(e,t){return ee(()=>{e=Et(e);let n;return t==null?n=jo(null,e.length):n=Et(t),this.runInternalGraph(e,n)[1]})}computeOutputShape(e){const t=gm(e);if(t.length!==this.inputLayers.length)throw new q(`Invalid inputShape argument ${e}: model has ${this.inputLayers.length} tensor inputs.`);const n={};for(let a=0;a<t.length;a++){const c=this.inputLayers[a],h=t[a],p=c.name+"_0_0";n[p]=h}const s=Object.keys(this.nodesByDepth).map(a=>parseInt(a,10)).sort(sm);if(s.length>1)for(const a of s){const c=this.nodesByDepth[a];for(const h of c){const p=h.outboundLayer;if(this.inputLayers.map(L=>L.id).indexOf(p.id)!==-1)continue;const m=[];for(let L=0;L<h.inboundLayers.length;L++){const T=h.inboundLayers[L],v=h.nodeIndices[L],C=h.tensorIndices[L],O=`${T.name}_${v}_${C}`,D=n[O];m.push(D)}const y=p.computeOutputShape(is(m)),b=gm(y),w=p.inboundNodes.indexOf(h);for(let L=0;L<b.length;L++){const T=`${p.name}_${w}_${L}`;n[T]=b[L]}}}const i=[],o=[];for(let a=0;a<this.outputLayers.length;a++){const c=this.outputLayers[a],h=this.outputLayersNodeIndices[a],p=this.outputLayersTensorIndices[a],m=`${c.name}_${h}_${p}`;o.push(m)}for(let a=0;a<o.length;a++){const c=o[a];Cs(c in n),i.push(n[c])}return is(i)}runInternalGraph(e,t){t==null&&(t=jo(null,e.length));const n={};for(let c=0;c<this.inputs.length;++c){const h=this.inputs[c],p=e[c],m=t[c];n[h.id]=[p,m]}const s=Object.keys(this.nodesByDepth).map(c=>parseInt(c,10)).sort(sm);for(const c of s){const h=this.nodesByDepth[c];for(const p of h){const m=p.outboundLayer,y=p.inputTensors,b=p.outputTensors,w=new Array;for(const L of y)L.id in n&&w.push(n[L.id]);if(w.length===y.length){let L={},T,v,C,O;if(p.callArgs!=null&&(L=p.callArgs),w.length===1){const[D,k]=w[0];L.mask==null&&(L.mask=k),C=Et(m.call(D,L)),O=Et(m.computeMask(D,k)),T=[D],v=[k]}else T=w.map(D=>D[0]),v=w.map(D=>D[1]),L.mask==null&&(L.mask=v),C=Et(m.call(T,L)),O=Et(m.computeMask(T,v));if(m.activityRegularizer)throw new ze("LayersModel invocation with concrete Tensor value(s) in the presence of activity regularizer(s) is not supported yet.");for(let D=0;D<b.length;++D){const k=b[D],F=C[D],B=O[D];n[k.id]=[F,B]}}}}const i=[],o=[],a=[];for(const c of this.outputs){Cs(c.id in n,`Could not compute output ${c.name} : ${c.id}`);const[h,p]=n[c.id];a.push(h.shape),i.push(h),o.push(p)}return[i,o,a]}buildNodeConversionMap(e){const t={};let n;for(const s of this.layers){n=s instanceof _i?1:0;for(let i=0;i<s.inboundNodes.length;i++){const o=_i.nodeKey(s,i);this.containerNodes.has(o)&&(t[o]=n,n+=1)}}return t}getLayer(e,t){if(t!=null){if(this.layers.length<=t)throw new q(`Was asked to retrieve layer at index ${t}, but model only has ${this.layers.length} layer(s).`);return this.layers[t]}else if(e==null)throw new q("Provide either a layer name or layer index");for(const n of this.layers)if(n.name===e)return n;throw new q(`No such layer: ${e}`)}calculateLosses(){return ee(()=>{const e=[];for(const t of this.layers)for(let n=0;n<t.inboundNodes.length;++n){const s=_i.nodeKey(t,n);this.containerNodes.has(s)&&e.push(...t.calculateLosses())}return e})}getConfig(){const e={name:this.name},t=this.buildNodeConversionMap(this.layers),n=[];for(const o of this.layers){const a=o.getClassName(),c=o.getConfig(),h=[];for(let m=0;m<o.inboundNodes.length;m++){const y=o.inboundNodes[m],b=_i.nodeKey(o,m);let w={};if(this.containerNodes.has(b)){if(y.callArgs)try{JSON.stringify(y.callArgs),w=y.callArgs}catch(L){console.warn(`Layer ${o.name} was passed non-serializable keyword arguments: ${y.callArgs}. They will not be included in the serialized model (and thus will be missing at deserialization time).`),w={}}if(y.inboundLayers.length>0){const L=[];for(let T=0;T<y.inboundLayers.length;T++){const v=y.inboundLayers[T],C=y.nodeIndices[T],O=y.tensorIndices[T],D=_i.nodeKey(v,C);let k=t[D];k==null&&(k=0),L.push([v.name,k,O,w])}h.push(L)}}}const p={};p.name=o.name,p.className=a,p.config=c,p.inboundNodes=h,n.push(p)}e.layers=n;const s=[];for(let o=0;o<this.inputLayers.length;o++){const a=this.inputLayers[o],c=this.inputLayersNodeIndices[o],h=_i.nodeKey(a,c);if(!this.containerNodes.has(h))continue;let p=t[h];p==null&&(p=0);const m=this.inputLayersTensorIndices[o];s.push([a.name,p,m])}e.inputLayers=s;const i=[];for(let o=0;o<this.outputLayers.length;o++){const a=this.outputLayers[o],c=this.outputLayersNodeIndices[o],h=_i.nodeKey(a,c);if(!this.containerNodes.has(h))continue;let p=t[h];p==null&&(p=0);const m=this.outputLayersTensorIndices[o];i.push([a.name,p,m])}return e.outputLayers=i,e}static fromConfig(e,t,n={},s=!1){const i={},o={};function a(T,v){T.name in o?o[T.name].push(v):o[T.name]=[v]}function c(T,v){const C=[];let O;for(const D of v){const k=D[0],F=D[1],B=D[2];if(O=D[3]==null?{}:D[3],!(k in i)){a(T,v);return}const $=i[k];if($.inboundNodes.length<=F){a(T,v);return}const Y=$.inboundNodes[F];C.push(Y.outputTensors[B])}C.length>0&&T.apply(is(C),O)}function h(T){const v=T.name,C=li(T,t.customObjects!=null?t.customObjects:{});C.setFastWeightInitDuringBuild(s),i[v]=C;const O=T.inboundNodes;O.forEach(D=>{if(!(D instanceof Array))throw new q(`Corrupted configuration, expected array for nodeData: ${D}`);a(C,D)})}const p=t.name,m=t.layers;for(const T of m)h(T);for(;!Kz(o);)for(const T of m){const v=i[T.name];if(v.name in o){const C=o[v.name];delete o[v.name];for(const O of C)c(v,O)}}const y=[],b=[],w=t.inputLayers;for(const T of w){const v=T[0],C=T[1],O=T[2];Cs(v in i);const D=i[v],k=D.inboundNodes[C].outputTensors;y.push(k[O])}const L=t.outputLayers;for(const T of L){const v=T[0],C=T[1],O=T[2];Cs(v in i);const D=i[v],k=D.inboundNodes[C].outputTensors;b.push(k[O])}return new e({inputs:y,outputs:b,name:p})}get stateful(){if(this._stateful)throw new q("Container instance unexpectedly has _stateful = true. The statefulness of a Container is determined by the Layers it contains. Its _stateful property must remain the default false.");for(const e of this.layers)if(e.stateful)return!0;return!1}resetStates(){ee(()=>{this.layers.forEach(e=>{e.stateful&&e.resetStates()})})}}function yN(e,t,n){const s=t.length;if(e==null||Array.isArray(e)&&e.length===0)return t.map(i=>null);if(s===1)return Array.isArray(e)&&e.length===1?e:typeof e=="object"&&t[0]in e?[e[t[0]]]:[e];if(Array.isArray(e)){if(e.length!==s)throw new Error(`Provided ${n} is an array of ${e.length} element(s), but the model has ${s} outputs. Make sure a set of weights is provided for each model output.`);return e}else if(typeof e=="object"&&Object.keys(e).length>0&&typeof e[Object.keys(e)[0]]=="object"){const i=[];return t.forEach(o=>{o in e?i.push(e[o]):i.push(null)}),i}else throw new Error(`The model has multiple (${s}) outputs, so ${n} must be either an array with ${s} elements or an object with ${t} keys. Provided ${n} not understood: ${JSON.stringify(e)}`)}function bN(e,t){return yN(e,t,"classWeight")}function hne(e,t){return yN(e,t,"sampleWeight")}async function wN(e,t,n,s){if(t!=null||s!=null)throw new Error("Support sampleWeight is not implemented yet");if(n!=null){const i=ee(()=>{if(e.shape.length===1)return e.clone();if(e.shape.length===2)if(e.shape[1]>1){const c=1;return e.argMax(c)}else{if(e.shape[1]===1)return e.reshape([e.shape[0]]);throw new Error(`Encountered unexpected last-dimension size (${e.shape[1]}) during handling of class weights. The size is expected to be >= 1.`)}else throw new Error(`Unexpected rank of target (y) tensor (${e.rank}) during handling of class weights. The rank is expected to be 1 or 2.`)}),o=Array.from(await i.data());qe(i);const a=[];return o.forEach(c=>{if(n[c]==null)throw new Error(`classWeight must contain all classes in the training data. The class ${c} exists in the data but not in classWeight`);a.push(n[c])}),ds(a,"float32")}else return null}function wV(e,t){return X(e,t)}const LV=32;function LN(e,t){let n,s;const i=t;n=i.xs,s=i.ys,A(n!=null&&s!=null,()=>`A Dataset iterator for fitDataset() is expected to generate objects of the form \`{xs: xVal, ys: yVal}\`, where the two values may be \`tf.Tensor\`, an array of Tensors, or a map of string to Tensor. The provided Dataset instead generates ${t}`);const o=SN("input",e.inputNames,n),a=SN("output",e.outputNames,s),c=o[0].shape[0];A(o.length===e.inputs.length,()=>`LayersModel has ${e.inputs.length} inputs, but the dataset provides ${o.length} inputs. (Expected input keys: ${JSON.stringify(e.inputNames)})`),A(a.length===e.outputs.length,()=>`LayersModel has ${e.outputs.length} outputs, but the dataset provides ${a.length} outputs. (Expected output keys: ${JSON.stringify(e.outputNames)})`);for(let h=0;h<o.length;h++)A(o[h].shape[0]===c,()=>`Batch size mismatch: input ${e.inputNames[h]} has ${o[h].shape[0]}; expected ${c} based on input ${e.inputNames[0]}.`);for(let h=0;h<a.length;h++)A(a[h].shape[0]===c,()=>`Batch size mismatch: output ${e.outputNames[h]} has ${a[h].shape[0]}; expected ${c} based on input ${e.inputNames[0]}.`);return{xs:o,ys:a}}function SN(e,t,n){if(n instanceof te)return[n];if(Array.isArray(n))return A(n.length===t.length,()=>`Received an array of ${n.length} Tensors, but expected ${t.length} to match the ${e} keys ${t}.`),n;{const s=[];for(const i of t){if(n[i]==null)throw new q(`The feature data generated by the dataset lacks the required ${e} key '${i}'.`);s.push(n[i])}return s}}function SV(e){if(e.length===3)throw new ze("Validation with sample weights is not implemented yet.");return{xs:e[0],ys:e[1]}}async function IV(e,t,n){const s=n.batchesPerEpoch!=null;if(A(e.optimizer!=null,()=>"You must compile a model before training/testing. Use LayersModel.compile(modelCompileConfig)."),A(n!=null,()=>"For fitDataset(), the 2nd argument (config) is required, but it is not provided in this call."),A(n.epochs!=null&&n.epochs>0&&Number.isInteger(n.epochs),()=>`For fitDataset(), config.epochs is expected to be a positive integer, but got ${n.epochs}`),A(!s||n.batchesPerEpoch>0&&Number.isInteger(n.batchesPerEpoch),()=>`For fitDataset(), config.batchesPerEpoch is expected to be a positive integer if specified, but got ${n.batchesPerEpoch}`),A(n.validationSplit==null,()=>"`validationSplit` is not supported by `fitDataset()`. Use validationData instead."),e.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");e.isTraining=!0;try{const i=n.validationData!=null;let o,a;if(i)if(IN(n.validationData))A(n.validationBatches==null||n.validationBatches>0&&Number.isInteger(n.validationBatches),()=>`For fitDataset() with dataset-based validation, config.validationBatches is expected not to be provided, or to be a positive integer, but got ${n.validationBatches}`);else{const v=SV(n.validationData);o=v.xs,a=v.ys}const c=e.makeTrainFunction(),h=e.getDedupedMetricsNames();let p;i?p=h.slice().concat(h.map(v=>"val_"+v)):p=h.slice();const m=rN(n.callbacks,n.yieldEvery),y=n.verbose==null?1:n.verbose,{callbackList:b,history:w}=oN(m,y,n.epochs,null,null,xV(t,n),null,i,p);b.setModel(e),e.history=w,await b.onTrainBegin(),e.stopTraining_=!1;let L=n.initialEpoch==null?0:n.initialEpoch,T=await t.iterator();for(;L<n.epochs;){const v={};await b.onEpochBegin(L);let C=0,O=0;for(s||(T=await t.iterator());s?C<n.batchesPerEpoch:!0;){const D=await T.next();if(s&&D.done){console.warn(`You provided \`batchesPerEpoch\` as ${n.batchesPerEpoch}, but your dataset iterator ran out of data after ${C} batches; interrupting training. Make sure that your dataset can generate at least \`batchesPerEpoch * epochs\` batches (in this case, ${n.batchesPerEpoch*n.epochs} batches). You may need to use the repeat() function when building your dataset.`);break}if(D.value!=null){const{xs:k,ys:F}=LN(e,D.value),B={};B.batch=O,B.size=k[0].shape[0],await b.onBatchBegin(O,B);const $=[];if(n.classWeight!=null){const Z=bN(n.classWeight,e.outputNames);for(let re=0;re<Z.length;++re)$.push(await wN(F[re],null,Z[re]))}const Y=k.concat(F).concat($),j=c(Y);qe(Y);for(let Z=0;Z<h.length;++Z){const re=h[Z],de=j[Z];B[re]=de,wn(de)}await b.onBatchEnd(O,B),eN(B),O++,C++}if(s?C>=n.batchesPerEpoch:D.done){if(i){let k;IN(n.validationData)?k=Et(await e.evaluateDataset(n.validationData,{batches:n.validationBatches})):k=Et(e.evaluate(o,a,{batchSize:n.validationBatchSize==null?LV:n.validationBatchSize,verbose:0}));for(let F=0;F<e.metricsNames.length;++F)v[`val_${e.metricsNames[F]}`]=k[F]}break}if(e.stopTraining_)break}if(await b.onEpochEnd(L,v),L++,e.stopTraining_)break}return await b.onTrainEnd(),await e.history.syncData(),e.history}finally{e.isTraining=!1}}function xV(e,t){let n=null;return t.batchesPerEpoch!=null?n=t.batchesPerEpoch:Number.isFinite(e.size)&&(n=e.size),n}function IN(e){return typeof e.iterator=="function"}function TV(e){return typeof e.next=="function"}async function AV(e,t,n){n=n||{};const s=n.batches!=null,i=e.testFunction;let o=[];if(n.verbose>0)throw new ze("Verbose mode is not implemented yet.");A(!s||n.batches>0&&Number.isInteger(n.batches),()=>`Test loop expects \`batches\` to be a positive integer, but received ${JSON.stringify(n.batches)}`);const a=TV(t)?t:await t.iterator();let c=0,h=0;for(;s?h<n.batches:!0;){const p=await a.next();if(o=ee(()=>{if(p.value){const{xs:m,ys:y}=LN(e,p.value),b=m.concat(y),w=ee(()=>i(b));if(qe(b),h===0)for(let T=0;T<w.length;++T)o.push(Ce(0));const L=b[0].shape[0];for(let T=0;T<w.length;++T){const v=w[T],C=o[T];o[T]=ee(()=>be(o[T],X(L,v))),h>0&&qe(C)}qe(w),c+=L,++h}return o}),p.done){s&&console.warn(`Your dataset iterator ran out of data during evaluateDataset(). Interrupting evalution. Make sure that your dataset can generate at least \`batches\` batches (in this case, ${n.batches} batches). You may need to use the repeat() function when building your dataset.`);break}}for(let p=0;p<o.length;++p){const m=o[p];o[p]=We(o[p],c),qe(m)}return is(o)}function cL(e){A(e>0&&Number.isInteger(e),()=>`batchSize is required to be a positive integer, but got ${e}`)}function su(e,t,n){return e==null?[null]:Array.isArray(e)?e.map(s=>Jo(s,t,n-t)):Jo(e,t,n-t)}function lL(e,t){return ee(()=>e==null?null:Array.isArray(e)?e.map(n=>lL(n,t)):Hv(e,t.dtype==="int32"?t:t.toInt()))}function hL(e,t){const n=[];let s=0,i=null;for(;s<e;)i=s+t,i>=e&&(i=e),n.push([s,i]),s=i;return n}async function vV(e,t,n,s,i,o,a,c,h,p,m,y,b,w,L){i==null&&(i=32),o==null&&(o=1),m==null&&(m=!0),b==null&&(b=0);let T=!1;if(h!=null&&p!=null&&(T=!0),L!=null&&(T=!0,w==null))throw new q("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");const v=e.checkNumSamples(n,i,w,"steps_per_epoch");let C;v!=null&&(C=oi(0,v)),a==null&&(a=1);const{callbackList:O,history:D}=oN(c,a,o,b,v,w,i,T,y);O.setModel(e),e.history=D,await O.onTrainBegin(),e.stopTraining_=!1;for(let k=b;k<o;++k){await O.onEpochBegin(k);const F={};if(w!=null)throw new ze("stepsPerEpoch mode is not implemented yet.");{if(m==="batch")throw new ze("batch shuffling is not implemneted yet");m&&I(C);const B=ds(C),$=hL(v,i);for(let Y=0;Y<$.length;++Y){const j={};if(await O.onBatchBegin(Y,j),ee(()=>{const Z=$[Y][0],re=$[Y][1],de=Jo(B,Z,re-Z);j.batch=Y,j.size=re-Z;const he=lL(n,de),ue=t(he);for(let me=0;me<s.length;++me){const ce=s[me],ye=ue[me];j[ce]=ye,wn(ye)}if(Y===$.length-1&&T){const me=e.testLoop(h,p,i);for(let ce=0;ce<s.length;++ce){const ye=s[ce],pe=me[ce];wn(pe),F["val_"+ye]=pe}}}),await O.onBatchEnd(Y,j),eN(j),e.stopTraining_)break}B.dispose()}if(await O.onEpochEnd(k,F),e.stopTraining_)break}return await O.onTrainEnd(),await e.history.syncData(),e.history}async function NV(e,t,n,s={}){if(e.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");e.isTraining=!0;let i,o,a,c,h,p,m;try{const y=s.batchSize==null?32:s.batchSize;cL(y);const b=!1,w=await e.standardizeUserData(t,n,s.sampleWeight,s.classWeight,b,y);i=w[0],o=w[1],m=w[2];let L=!1,T;if(s.validationData!=null&&s.validationData.length>0){if(L=!0,s.validationData.length===2)a=s.validationData[0],c=s.validationData[1];else throw s.validationData.length===3?new ze("validationData including sample weights is not supported yet."):new q(`When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; ${s.validationData} is invalid.`);const $=!0,Y=await e.standardizeUserData(a,c,null,null,$,y);h=Y[0],p=Y[1],T=h.concat(p)}else if(s.validationSplit!=null&&s.validationSplit>0&&s.validationSplit<1){L=!0;const $=Math.floor(i[0].shape[0]*(1-s.validationSplit)),Y=i[0].shape[0];h=su(i,$,Y),i=su(i,0,$),p=su(o,$,Y),o=su(o,0,$),T=h.concat(p)}else s.validationSteps!=null&&(L=!0);const v=i.concat(o).concat(m);e.checkTrainableWeightsConsistency();const C=e.makeTrainFunction(),O=e.getDedupedMetricsNames();let D,k;L?(e.makeTestFunction(),D=e.testFunction,k=O.slice().concat(O.map($=>"val_"+$))):(D=null,T=[],k=O.slice());const F=rN(s.callbacks,s.yieldEvery),B=await vV(e,C,v,O,y,s.epochs,s.verbose,F,D,T,s.shuffle,k,s.initialEpoch,null,null);return B}finally{e.isTraining=!1,Qo(i,t),Qo(o,n),Qo(h,a),Qo(p,c),m!=null&&qe(m)}}function xN(e){const t=[];e instanceof te&&(e=[e]);for(let n=0;n<e.length;++n){const s=e[n];if(s.rank===1)t.push(Jh(s,1));else{if(s.rank===0)throw new Error("Expected tensor to be at least 1D, but received a 0D tensor (scalar).");t.push(s)}}return t}function Qo(e,t){if(e==null)return;const n=[];if(t instanceof te)n.push(t.id);else if(Array.isArray(t))t.forEach(i=>n.push(i.id));else if(t!=null)for(const i in t){const o=t[i];n.push(o.id)}const s=[];if(e instanceof te)n.indexOf(e.id)===-1&&s.push(e);else if(Array.isArray(e))e.forEach(i=>{n.indexOf(i.id)===-1&&s.push(i)});else if(e!=null)for(const i in e){const o=e[i];n.indexOf(o.id)===-1&&s.push(o)}s.forEach(i=>{i.isDisposed||i.dispose()})}function CV(e){return e instanceof te}function uL(e){return Array.isArray(e)}function TN(e){return!CV(e)&&!uL(e)}function AN(e,t,n,s=!0,i=""){if(t==null||t.length===0){if(e!=null){let a=!1;if(uL(e)&&e.length>0)a=!0;else if(TN(e)){for(const c in e)if(e.hasOwnProperty(c)){a=!0;break}}else a=!0;if(a)throw new q(`Error when checking model ${i} expected no data, but got ${e}`)}return[]}if(e==null)return t.map(a=>null);let o;if(TN(e)){e=e,o=[];for(const a of t){if(e[a]==null)throw new q(`No data provided for "${a}". Need data for each key in: ${t}`);o.push(e[a])}}else if(uL(e)){if(e=e,e.length!==t.length)throw new q(`Error when checking model ${i}: the Array of Tensors that you are passing to your model is not the size the model expected. Expected to see ${t.length} Tensor(s), but instead got the following list of Tensor(s): ${e}`);o=e}else{if(e=e,t.length>1)throw new q(`The model ${i} expects ${t.length} Tensor(s), but only received one Tensor. Found: Tensor with shape ${e.shape}`);o=[e]}if(o=xN(o),n!=null)for(let a=0;a<t.length;++a){if(n[a]==null)continue;const c=o[a];if(c.shape.length!==n[a].length)throw new q(`Error when checking ${i}: expected ${t[a]} to have ${n[a].length} dimension(s). but got array with shape ${c.shape}`);for(let h=0;h<n[a].length;++h){if(h===0&&!s)continue;const p=c.shape[h],m=n[a][h];if(m!=null&&m>=0&&p!==m)throw new q(`Error when checking ${i}: expected ${t[a]} to have shape [${n[a]}], but got array with shape [${c.shape}].`)}}return o}function RV(e,t,n){const s=Jr(e.map(o=>o.shape[0]));s.sort();const i=Jr(t.map(o=>o.shape[0]));if(i.sort(),s.length>1)throw new q(`All input Tensors (x) should have the same number of samples. Got array shapes: ${JSON.stringify(e.map(o=>o.shape))}`);if(i.length>1)throw new q(`All target Tensors (y) should have the same number of samples. Got array shapes: ${JSON.stringify(t.map(o=>o.shape))}`);if(s.length>0&&i.length>0&&!ie(s,i))throw new q(`Input Tensors should have the same number of samples as target Tensors. Found ${s[0]} input sample(s) and ${i[0]} target sample(s).`)}function OV(e,t,n){const s=[hr,Sm,eu];for(let i=0;i<e.length;++i){const o=e[i],a=t[i],c=n[i];if(a==null)continue;if(a===eu&&o.shape[o.shape.length-1]===1)throw new q(`You are passing a target array of shape ${o.shape} while using a loss 'categorical_crossentropy'. 'categorical_crossentropy'expects targets to be binary matrices (1s and 0s) of shape [samples, classes].`);if(s.indexOf(a)!==-1){const h=o.shape.slice(1),p=c.slice(1);for(let m=0;m<h.length;++m){const y=h[m],b=p[m];if(b!=null&&y!==b)throw new q(`A target Tensor with shape ${o.shape} was passed for an output of shape ${c}, while using a loss function that expects targets to have the same shape as the output.`)}}}}function vN(e,t,n,s=!0,i=""){let o;if(Array.isArray(e)){if(e.length!==t.length)throw new q(`Error when checking model ${i}: the Array of Tensors that you are passing to your model is not the size the the model expected. Expected to see ${t.length} Tensor(s), but instead got ${e.length} Tensors(s).`);o=e}else{if(t.length>1)throw new q(`The model expects ${t.length} ${i} Tensors, but only received one Tensor. Found: array with shape ${JSON.stringify(e.shape)}.`);o=[e]}if(n!=null)for(let a=0;a<t.length;++a){if(n[a]==null)continue;const c=o[a];if(c.shape.length!==n[a].length)throw new q(`Error when checking ${i}: expected ${t[a]} to have ${n[a].length} dimension(s), but got array with shape ${JSON.stringify(c.shape)}`);for(let h=0;h<n[a].length;++h){if(h===0&&!s)continue;const p=c.shape[h],m=n[a][h];if(m!=null&&m!==p)throw new q(`Error when checking ${i}: expected ${t[a]} to have shape ${JSON.stringify(n[a])} but got array with shape ${JSON.stringify(c.shape)}.`)}}}function EV(e,t){if(e==null||Array.isArray(e)&&e.length===0)return t.map(s=>[]);let n;if(typeof e=="string"||typeof e=="function")n=[e];else if(Array.isArray(e)||typeof e=="object")n=e;else throw new TypeError(`Type of metrics argument not understood. Expected an string,function, Array, or Object, found: ${e}`);if(Array.isArray(n))return t.map(s=>n);{const s=[];for(const i of t){let o=n.hasOwnProperty(i)?n[i]:[];Array.isArray(o)||(o=[o]),s.push(o)}return s}}const DV="layers-model";class ur extends _i{constructor(e){super(e);this.isTraining=!1}summary(e,t,n=console.log){if(!this.built)throw new q("This model has never been called, thus its weights have not been created yet. So no summary can be displayed. Build the model first (e.g., by calling it on some test data).");hV(this,e,t,n)}compile(e){if(e.loss==null&&(e.loss=[]),this.loss=e.loss,typeof e.optimizer=="string")this.optimizer_=lV(e.optimizer),this.isOptimizerOwned=!0;else{if(!(e.optimizer instanceof or))throw new q("User-defined optimizer must be an instance of tf.Optimizer.");this.optimizer_=e.optimizer,this.isOptimizerOwned=!1}let t=[];if(!Array.isArray(e.loss)&&typeof e.loss!="string"&&typeof e.loss!="function"){e.loss=e.loss;for(const o in e.loss)if(this.outputNames.indexOf(o)===-1)throw new q(`Unknown entry in loss dictionary: "${o}". Only expected the following keys: ${this.outputNames}`);for(const o of this.outputNames)e.loss[o]==null&&console.warn(`Output "${o}" is missing from loss dictionary. We assume this was done on purpose, and we will not be expecting data to be passed to ${o} during training`),t.push(tL(e.loss[o]))}else if(Array.isArray(e.loss)){if(e.loss.length!==this.outputs.length)throw new q(`When passing an Array as loss, it should have one entry per model output. The model has ${this.outputs.length} output(s), but you passed loss=${e.loss}.`);const o=e.loss;t=o.map(a=>tL(a))}else{const o=tL(e.loss);this.outputs.forEach(a=>{t.push(o)})}this.lossFunctions=t,this.feedOutputNames=[],this.feedOutputShapes=[],this.feedLossFns=[];for(let o=0;o<this.outputs.length;++o){const a=this.internalOutputShapes[o],c=this.outputNames[o];this.feedOutputNames.push(c),this.feedOutputShapes.push(a),this.feedLossFns.push(this.lossFunctions[o])}const n=[];this.metrics=e.metrics,this.metricsNames=["loss"],this.metricsTensors=[],Xo("loss",()=>{for(let o=0;o<this.outputs.length;++o){if(n.indexOf(o)!==-1)continue;const a=this.lossFunctions[o];this.outputs.length>1&&(this.metricsTensors.push([a,o]),this.metricsNames.push(this.outputNames[o]+"_loss"))}});const s=EV(e.metrics,this.outputNames),i=(o,a,c)=>{this.outputNames.length>1&&(a=this.outputNames[o]+"_"+a),this.metricsNames.push(a),this.metricsTensors.push([c,o])};Xo("metric",()=>{for(let o=0;o<this.outputs.length;++o){if(n.indexOf(o)!==-1)continue;const a=s[o],c=h=>{const p="";let m,y,b;for(const w of h){if(typeof w=="string"&&["accuracy","acc","crossentropy","ce"].indexOf(w)!==-1){const T=this.internalOutputShapes[o];T[T.length-1]===1||this.lossFunctions[o]===Sm?["accuracy","acc"].indexOf(w)!==-1?y=nL:["crossentropy","ce"].indexOf(w)!==-1&&(y=lN):this.lossFunctions[o]===Lm?["accuracy","acc"].indexOf(w)!==-1?y=hN:["crossentropy","ce"].indexOf(w)!==-1&&(y=uN):["accuracy","acc"].indexOf(w)!==-1?y=sL:["crossentropy","ce"].indexOf(w)!==-1&&(y=iL);let v;["accuracy","acc"].indexOf(w)!==-1?v="acc":["crossentropy","ce"].indexOf(w)!==-1&&(v="ce"),b=y,m=p+v}else{const T=cV(w);b=T,m=p+Am(w)}let L;Xo(m,()=>{L=b}),i(o,m,L)}};c(a)}}),this.collectedTrainableWeights=this.trainableWeights}checkTrainableWeightsConsistency(){if(this.collectedTrainableWeights==null)return;this.trainableWeights.length!==this.collectedTrainableWeights.length&&console.warn("Discrepancy between trainableweights and collected trainable weights. Did you set `model.trainable` without calling `model.compile()` afterwards?")}evaluate(e,t,n={}){const s=n.batchSize==null?32:n.batchSize;cL(s);const i=!0,o=this.standardizeUserDataXY(e,t,i,s);try{const a=o[0].concat(o[1]);this.makeTestFunction();const c=this.testFunction,h=this.testLoop(c,a,s,n.verbose,n.steps);return is(h)}finally{Qo(o[0],e),Qo(o[1],t)}}async evaluateDataset(e,t){return this.makeTestFunction(),AV(this,e,t)}checkNumSamples(e,t,n,s="steps"){let i;if(n!=null){if(i=null,t!=null)throw new q(`If ${s} is set, batchSize must be null or undefined.Got batchSize = ${t}`)}else if(e!=null)Array.isArray(e)?i=e[0].shape[0]:i=e.shape[0];else throw new q(`Either the input data should have a defined shape, or ${s} shoud be specified.`);return i}execute(e,t){if(Array.isArray(t)&&t.length===0)throw new q("`outputs` is an empty Array, which is not allowed.");const n=Array.isArray(t),s=n?t:[t],i=this.retrieveSymbolicTensors(s),o=new Zo;if(e instanceof te&&(e=[e]),Array.isArray(e)){if(e.length!==this.inputs.length)throw new q(`The number of inputs provided (${e.length}) does not match the number of inputs of this model (${this.inputs.length}).`);for(let c=0;c<this.inputs.length;++c)o.add(this.inputs[c],e[c])}else for(const c of this.inputs){const h=e[c.name];if(h==null)throw new q(`No value is provided for the model's input ${c.name}`);o.add(c,h)}const a=nu(i,o);return n?a:a[0]}retrieveSymbolicTensors(e){const t=jo(null,e.length);let n=e.length;for(const s of this.layers){const i=Array.isArray(s.output)?s.output:[s.output],o=i.map(a=>a.name);for(let a=0;a<e.length;++a){const c=o.indexOf(e[a]);if(c!==-1&&(t[a]=i[c],n--),n===0)break}if(n===0)break}if(n>0){const s=[];throw t.forEach((i,o)=>{i==null&&s.push(e[o])}),new q(`Cannot find SymbolicTensors for output name(s): ${JSON.stringify(s)}`)}return t}predictLoop(e,t=32,n=!1){return ee(()=>{const s=this.checkNumSamples(e);if(n)throw new ze("Verbose predictLoop() is not implemented yet.");const i=hL(s,t),o=this.outputs.map(a=>[]);for(let a=0;a<i.length;++a){const c=ee(()=>{const h=i[a][0],p=i[a][1],m=su(e,h,p),y=[];if(Array.isArray(m))for(let w=0;w<m.length;++w)y.push({key:this.inputs[w],value:m[w]});else y.push({key:this.inputs[0],value:m});const b=new Zo(y);return nu(this.outputs,b)});c.forEach((h,p)=>o[p].push(h))}return is(o.map(a=>Yt(a,0)))})}predict(e,t={}){const n=xN(e);vN(n,this.inputNames,this.feedInputShapes,!1);try{const s=t.batchSize==null?32:t.batchSize;return cL(s),this.predictLoop(n,s)}finally{Qo(n,e)}}predictOnBatch(e){vN(e,this.inputNames,this.feedInputShapes,!0);const t=(Array.isArray(e)?e[0]:e).shape[0];return this.predictLoop(e,t)}standardizeUserDataXY(e,t,n=!0,s){if(this.optimizer_==null)throw new ri("You must compile a model before training/testing. Use LayersModel.compile(modelCompileArgs).");const i=[];for(let o=0;o<this.feedOutputShapes.length;++o){const a=this.feedOutputShapes[o],c=this.feedLossFns[o];c===Lm?i.push(a.slice(0,a.length-1).concat([1])):i.push(a)}if(e=AN(e,this.feedInputNames,this.feedInputShapes,!1,"input"),t=AN(t,this.feedOutputNames,i,!1,"target"),RV(e,t,null),OV(t,this.feedLossFns,this.feedOutputShapes),this.stateful&&s!=null&&s>0&&e[0].shape[0]%s!==0)throw new q(`In a stateful network, you should only pass inputs with a number of samples that is divisible by the batch size ${s}. Found: ${e[0].shape[0]} sample(s).`);return[e,t]}async standardizeUserData(e,t,n,s,i=!0,o){const[a,c]=this.standardizeUserDataXY(e,t,i,o);if(n!=null)throw new Error("sample weight is not supported yet.");let h=null;if(s!=null){const p=bN(s,this.outputNames);h=[];for(let m=0;m<p.length;++m)h.push(await wN(c[m],null,p[m]))}return[a,c,h]}testLoop(e,t,n,s=0,i){return ee(()=>{const o=this.checkNumSamples(t,n,i,"steps"),a=[];if(s>0)throw new ze("Verbose mode is not implemented yet.");if(i!=null)throw new ze("steps mode in testLoop() is not implemented yet");{const c=hL(o,n),h=ds(oi(0,o));for(let p=0;p<c.length;++p){const m=c[p][0],y=c[p][1],b=Jo(h,m,y-m),w=lL(t,b),L=e(w);if(p===0)for(let T=0;T<L.length;++T)a.push(Ce(0));for(let T=0;T<L.length;++T){const v=L[T];a[T]=be(a[T],X(y-m,v))}}for(let p=0;p<a.length;++p)a[p]=We(a[p],o)}return a})}getDedupedMetricsNames(){const e=this.metricsNames,t=[];for(let n=0;n<e.length;++n){const s=e[n];let i=s;if(Fv(e,s)>1){const o=Fv(e.slice(0,n),s);i+=`_${o}`}t.push(i)}return t}makeTrainFunction(){return e=>{const t=[],n=e.slice(0,this.inputs.length),s=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),i=e.slice(this.inputs.length+this.outputs.length,this.inputs.length+this.outputs.length*2),o=[],a=()=>{const m=[];for(let L=0;L<this.inputs.length;++L)m.push({key:this.inputs[L],value:n[L]});const y=new Zo(m),b=nu(this.outputs,y,{training:!0});let w;for(let L=0;L<this.lossFunctions.length;++L){const T=this.lossFunctions[L];let v=T(s[L],b[L]);i[L]!=null&&(v=wV(v,i[L]));const C=qt(v);t.push(C),L===0?w=v:w=be(w,v)}for(let L=0;L<this.metricsTensors.length;++L){let T;if(this.outputs.length>1&&L<this.outputs.length)T=t[L];else{const v=this.metricsTensors[L][0],C=this.metricsTensors[L][1];T=qt(v(s[C],b[C]))}wn(T),o.push(T)}return w=qt(w),this.calculateLosses().forEach(L=>{w=be(w,L)}),w},c=this.collectedTrainableWeights.map(m=>m.read()),h=!0,p=this.optimizer_.minimize(a,h,c);return[p].concat(o)}}makeTestFunction(){this.testFunction=e=>ee(()=>{const t=[];let n;const s=e.slice(0,this.inputs.length),i=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),o=[];for(let h=0;h<this.inputs.length;++h)o.push({key:this.inputs[h],value:s[h]});const a=new Zo(o),c=nu(this.outputs,a);for(let h=0;h<this.lossFunctions.length;++h){const p=this.lossFunctions[h],m=qt(p(i[h],c[h]));h===0?n=m:n=be(n,m),t.push(n)}for(let h=0;h<this.metricsTensors.length;++h){const p=this.metricsTensors[h][0],m=this.metricsTensors[h][1],y=qt(p(i[m],c[m]));t.push(y)}return t})}async fit(e,t,n={}){return NV(this,e,t,n)}async fitDataset(e,t){return IV(this,e,t)}async trainOnBatch(e,t){const n=await this.standardizeUserData(e,t),s=n[0],i=n[1],o=this.makeTrainFunction(),a=o(s.concat(i)),c=[];for(const h of a){const p=await h.data();c.push(p[0])}return qe(a),is(c)}getNamedWeights(e){const t=[],n=e!=null&&e.trainableOnly,s=n?this.trainableWeights:this.weights,i=this.getWeights(n);for(let o=0;o<s.length;++o){if(n&&!s[o].trainable)continue;t.push({name:s[o].originalName,tensor:i[o]})}return t}set stopTraining(e){this.stopTraining_=e}get stopTraining(){return this.stopTraining_}get optimizer(){return this.optimizer_}set optimizer(e){this.optimizer_!==e&&(this.optimizer_=e,this.isOptimizerOwned=!1)}dispose(){const e=super.dispose();if(e.refCountAfterDispose===0&&this.optimizer!=null&&this.isOptimizerOwned){const t=fp().numTensors;this.optimizer_.dispose(),e.numDisposedVariables+=t-fp().numTensors}return e}getLossIdentifiers(){let e;if(typeof this.loss=="string")e=lr(this.loss);else if(Array.isArray(this.loss)){for(const t of this.loss)if(typeof t!="string")throw new Error("Serialization of non-string loss is not supported.");e=this.loss.map(t=>lr(t))}else{const t=Object.keys(this.loss);e={};const n=this.loss;for(const s of t)if(typeof n[s]=="string")e[s]=lr(n[s]);else throw new Error("Serialization of non-string loss is not supported.")}return e}getMetricIdentifiers(){if(typeof this.metrics=="string"||typeof this.metrics=="function")return[lr(Am(this.metrics))];if(Array.isArray(this.metrics))return this.metrics.map(e=>lr(Am(e)));{const e={};for(const t in this.metrics)e[t]=lr(Am(this.metrics[t]));return e}}getTrainingConfig(){return{loss:this.getLossIdentifiers(),metrics:this.getMetricIdentifiers(),optimizer_config:{class_name:this.optimizer.getClassName(),config:this.optimizer.getConfig()}}}loadTrainingConfig(e){if(e.weighted_metrics!=null)throw new Error("Loading weight_metrics is not supported yet.");if(e.loss_weights!=null)throw new Error("Loading loss_weights is not supported yet.");if(e.sample_weight_mode!=null)throw new Error("Loading sample_weight_mode is not supported yet.");const t=tu(e.optimizer_config),n=li(t);let s;if(typeof e.loss=="string")s=Ko(e.loss);else if(Array.isArray(e.loss))s=e.loss.map(o=>Ko(o));else if(e.loss!=null){s={};for(const o in e.loss)s[o]=Ko(e.loss[o])}let i;if(Array.isArray(e.metrics))i=e.metrics.map(o=>Ko(o));else if(e.metrics!=null){i={};for(const o in e.metrics)i[o]=Ko(e.metrics[o])}this.compile({loss:s,metrics:i,optimizer:n})}async save(e,t){if(typeof e=="string"){const h=ab(e);if(h.length===0)throw new q(`Cannot find any save handlers for URL '${e}'`);if(h.length>1)throw new q(`Found more than one (${h.length}) save handlers for URL '${e}'`);e=h[0]}if(e.save==null)throw new q("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");const n=await rb(this.getNamedWeights(t)),s=!1,i=null,o=this.toJSON(i,s),a={modelTopology:o,format:DV,generatedBy:`TensorFlow.js tfjs-layers v${Nm}`,convertedBy:null},c=t==null?!1:t.includeOptimizer;if(c&&this.optimizer!=null){a.trainingConfig=this.getTrainingConfig();const h="optimizer",{data:p,specs:m}=await rb(await this.optimizer.getWeights(),h);n.specs.push(...m),n.data=op([n.data,p])}if(this.userDefinedMetadata!=null){const h=!0;pN(this.userDefinedMetadata,this.name,h),a.userDefinedMetadata=this.userDefinedMetadata}return a.weightData=n.data,a.weightSpecs=n.specs,e.save(a)}setUserDefinedMetadata(e){pN(e,this.name),this.userDefinedMetadata=e}getUserDefinedMetadata(){return this.userDefinedMetadata}}ur.className="Model",ge(ur);class NN extends ur{}NN.className="Functional",ge(NN);async function kV(e,t){"modelTopology"in e||(e={modelTopology:e}),e=e;let n=e.modelTopology;n.model_config!=null&&(n=n.model_config);const s=tu(n),i=li(s,t);if(e.weightsManifest!=null){const o=await eA(e.weightsManifest,e.pathPrefix,i.weights.map(c=>c.originalName)),a={};for(const c of i.weights)a[c.originalName]=o[c.originalName];i.loadWeights(a),qe(o)}return i}async function FV(e,t){if(t==null&&(t={}),typeof e=="string"){const n=cb(e,t);if(n.length===0)n.push(lp(e,t));else if(n.length>1)throw new q(`Found more than one (${n.length}) load handlers for URL '${e}'`);e=n[0]}return _V(e,void 0,t)}async function _V(e,t,n){if(n==null&&(n={}),e.load==null)throw new q("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");const s=await e.load();let i=s.modelTopology;i.model_config!=null&&(i=i.model_config);const o=n.strict==null?!0:n.strict,a=s.weightData!=null&&s.weightSpecs!=null&&o,c=li(tu(i),t,a),h=s.trainingConfig;if(h!=null&&c.loadTrainingConfig(h),s.userDefinedMetadata!=null&&c.setUserDefinedMetadata(s.userDefinedMetadata),s.weightData!=null){if(s.weightSpecs==null)throw new q("LayersModel artifacts contains weight data, but not weight specs. Therefore loading of weights cannot proceed.");const{modelWeights:p,optimizerWeights:m}=WV(s.weightData,s.weightSpecs);c.loadWeights(p,o),c.optimizer!=null&&m.length>0&&await c.optimizer.setWeights(m),qe(p),qe(m.map(y=>y.tensor))}return c}function WV(e,t){const n=rp(e,t),s={},i=[];return t.forEach(o=>{o.group==="optimizer"?i.push({name:o.name,tensor:n[o.name]}):s[o.name]=n[o.name]}),{modelWeights:s,optimizerWeights:i}}class yc extends ur{constructor(e){super({inputs:[],outputs:[]});if(e=e||{},this.trainable=!0,this.built=!1,this.name=e.name!=null?e.name:fm("sequential_"),e.layers!=null)for(const t of e.layers)this.add(t)}checkShape(e){const t=e.inboundNodes[0].outputTensors[0].shape;if(t.some(n=>n<0))throw new q(`Negative dimension size caused by adding layer ${e.name} with input shape [${e.inboundNodes[0].inputTensors[0].shape}]`)}add(e){const t=e instanceof yc||e instanceof ur;let n;if(t){if(n=e,n.outputs.length!==1)throw new q("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");if(n.inputs.length!==1)throw new q("All layers in a Sequential model should have a single input tensor. For multi-input layers, use the functional API.")}if(this.outputs.length===0){if(e.inboundNodes.length===0){if(e.batchInputShape==null)throw new q("The first layer in a Sequential model must get an `inputShape` or `batchInputShape` argument.");const s=Qv({batchShape:e.batchInputShape,dtype:e.dtype,name:e.name+"_input"});e.apply(s)}if(t)this.outputs=n.outputs,this.inputs=n.inputs;else{if(e.inboundNodes.length!==1)throw new q(`A layer added to a Sequential model must not already be connected somewhere else. LayersModel received layer ${e.name} which has ${e.inboundNodes.length} pre-existing inbound connections.`);if(e.inboundNodes[0].outputTensors.length!==1)throw new q("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(e),this.outputs=[e.inboundNodes[0].outputTensors[0]],this.inputs=Zv(this.outputs[0])}this.inboundNodes=[],new bm({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:jo(null,this.inputs.length),outputMasks:[null],inputShapes:this.inputs.map(s=>s.shape),outputShapes:this.outputs[0].shape})}else{const s=e.apply(this.outputs[0]);if(Array.isArray(s))throw new TypeError("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(e),this.outputs=[s],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}this.layers.push(e),this.built=!1}pop(){if(this.layers.length===0)throw new TypeError("There are no layers in the model.");if(this.layers.pop(),this.layers.length===0)this.outputs=[],this.inboundNodes=[],this.outboundNodes=[];else{const e=this.layers.length-1;this.layers[e].outboundNodes=[],this.outputs=[this.layers[e].output],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}}call(e,t){return this.model==null&&this.build(),this.model.call(e,t)}build(e){if(Nt(e),this.inputs.length===0||this.outputs.length===0)throw new TypeError("Sequential model cannot be built: model is empty. Add some layers first.");this.model=new ur({inputs:this.inputs,outputs:this.outputs[0],name:this.name+"_model"}),this.model.trainable=this.trainable,this.supportsMasking=this.model.supportsMasking,this.inputLayers=this.model.inputLayers,this.inputLayersNodeIndices=this.model.inputLayersNodeIndices,this.inputLayersTensorIndices=this.model.inputLayersTensorIndices,this.outputLayers=this.model.outputLayers,this.outputLayersNodeIndices=this.model.outputLayersNodeIndices,this.outputLayersTensorIndices=this.model.outputLayersTensorIndices,this.nodesByDepth=this.model.nodesByDepth,this.containerNodes=this.model.containerNodes,this.outputNames=this.model.outputNames,this.inputNames=this.model.inputNames,this.built=!0}countParams(){return this.built||this.build(),super.countParams()}summary(e,t,n=console.log){this.built||this.build(),super.summary(e,t,n)}setWeights(e){this.model==null&&this.build(),this.model.setWeights(e)}evaluate(e,t,n={}){if(!this.built)throw new ri("The model needs to be compiled before being used.");return this.model.evaluate(e,t,n)}async evaluateDataset(e,t){if(!this.built)throw new ri("The model needs to be compiled before being used.");return this.model.evaluateDataset(e,t)}predict(e,t={}){return this.model==null&&this.build(),this.model.predict(e,t)}predictOnBatch(e){return this.model==null&&this.build(),this.model.predictOnBatch(e)}compile(e){this.build(),this.model.compile(e),this.optimizer_=this.model.optimizer,this.isOptimizerOwned=this.model.isOptimizerOwned,this.loss=this.model.loss,this.metrics=this.model.metrics,this.metricsTensors=this.model.metricsTensors,this.metricsNames=this.model.metricsNames}get optimizer(){return this.model==null?void 0:this.model.optimizer}set optimizer(e){this.model.optimizer=e}async fit(e,t,n={}){if(!this.built)throw new ri("The model needs to be compiled before being used.");return this.model.fit(e,t,n)}async fitDataset(e,t){if(!this.built)throw new ri("The model needs to be compiled before being used.");return this.model.fitDataset(e,t)}async trainOnBatch(e,t){return this.model.trainOnBatch(e,t)}static fromConfig(e,t,n={},s=!1){let i,o={};if(t instanceof Array){if(!(t[0].className!=null)||t[0].className==="Merge")throw new q("Legacy serialization format not supported yet.");i=t}else A(t.layers!=null,()=>"When the config data for a Sequential model is not an Array, it must be an Object that contains the 'layers' field."),i=t.layers,delete t.layers,o=t;const a=new e(o);if(!(a instanceof yc))throw new ze(`Sequential.fromConfig called on non-Sequential input: ${a}`);for(const c of i){const h=void 0,p=li(c,h,s);s&&p.setFastWeightInitDuringBuild(!0),a.add(p)}return a}set stopTraining(e){if(this.model==null)throw new q("Cannot set the stopTraining property of a sequential model before it is compiled.");this.model.stopTraining=e}get stopTraining(){if(this.model==null)throw new q("Cannot get the stopTraining property of a sequential model before it is compiled.");return this.model.stopTraining}getConfig(){const e=[];for(const t of this.layers){const n={};n.className=t.getClassName(),n.config=t.getConfig(),e.push(n)}return{name:this.name,layers:e}}}yc.className="Sequential",ge(yc);function $V(e){return new ur(e)}function UV(e){return new yc(e)}function BV(e,t){return t==null&&(t={}),FV(e,t)}function CN(e){return Qv(e)}function MV(e,t){Gs.registerCallbackConstructor(e,t)}class ms extends Wo{getConfig(){return{}}}class RN extends ms{apply(e,t=1){return m3(e,t)}}RN.className="elu",ge(RN);class ON extends ms{apply(e){return Wp(e)}}ON.className="selu",ge(ON);class EN extends ms{apply(e){return Di(e)}}EN.className="relu",ge(EN);class DN extends ms{apply(e){return ee(()=>Po(6,Di(e)))}}DN.className="relu6",ge(DN);class kN extends ms{apply(e){return e}}kN.className="linear",ge(kN);class FN extends ms{apply(e){return Ri(e)}}FN.className="sigmoid",ge(FN);class _N extends ms{apply(e){return g3(e)}}_N.className="hardSigmoid",ge(_N);class WN extends ms{apply(e){return ec(e)}}WN.className="softplus",ge(WN);class $N extends ms{apply(e){return f3(e)}}$N.className="softsign",ge($N);class UN extends ms{apply(e){return Ka(e)}}UN.className="tanh",ge(UN);class dL extends ms{apply(e,t=-1){return Yo(e,t)}}dL.className="softmax",ge(dL);class BN extends ms{apply(e,t=-1){return Op(e,t)}}BN.className="logSoftmax",ge(BN);class MN extends ms{apply(e,t=1){return ee(()=>Ri(e.mul(t)).mul(e))}}MN.className="swish",ge(MN);function no(e){return e.getClassName()}function pL(e,t={}){return qh(e,Bs.getMap().classNameMap,t,"activation")}function so(e){if(e==null){const t={};return t.className="linear",t.config={},pL(t)}if(typeof e=="string"){const t={};return t.className=e,t.config={},pL(t)}else return e instanceof ms?e:pL(e)}function mL(e){if(e!=null&&typeof e!="object")throw new Error(`Argument to L1L2 regularizer's constructor is expected to be an object, but received: ${e}`)}class PN extends Wo{}class iu extends PN{constructor(e){super();mL(e),this.l1=e==null||e.l1==null?.01:e.l1,this.l2=e==null||e.l2==null?.01:e.l2,this.hasL1=this.l1!==0,this.hasL2=this.l2!==0}apply(e){return ee(()=>{let t=pt([1]);return this.hasL1&&(t=be(t,$e(X(this.l1,pn(e))))),this.hasL2&&(t=be(t,$e(X(this.l2,Zh(e))))),t.asScalar()})}getConfig(){return{l1:this.l1,l2:this.l2}}static fromConfig(e,t){return new e({l1:t.l1,l2:t.l2})}}iu.className="L1L2",ge(iu);function PV(e){return mL(e),new iu({l1:e!=null?e.l1:null,l2:0})}function zV(e){return mL(e),new iu({l2:e!=null?e.l2:null,l1:0})}const zN={l1l2:"L1L2"};function Ct(e){return Ew(e)}function VN(e,t={}){return qh(e,Bs.getMap().classNameMap,t,"regularizer")}function zt(e){if(e==null)return null;if(typeof e=="string"){const t=e in zN?zN[e]:e,n={className:t,config:{}};return VN(n)}else return e instanceof PN?e:VN(e)}class fL extends ht{constructor(e){super(e==null?{}:e);this.supportsMasking=!0,e!=null&&(this.maxValue=e.maxValue)}call(e,t){e=Je(e);let n=Di(e);return this.maxValue!=null&&(n=es(n,0,this.maxValue)),n}computeOutputShape(e){return e}getConfig(){const e={maxValue:this.maxValue},t=super.getConfig();return Object.assign(e,t),e}}fL.className="ReLU",ge(fL);class gL extends ht{constructor(e){super(e==null?{}:e);this.DEFAULT_ALPHA=.3,e==null&&(e={}),this.alpha=e.alpha==null?this.DEFAULT_ALPHA:e.alpha}call(e,t){const n=Je(e);return Np(n,this.alpha)}computeOutputShape(e){return e}getConfig(){const e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}}gL.className="LeakyReLU",ge(gL);class yL extends ht{constructor(e){super(e==null?{}:e);if(this.DEFAULT_ALPHA_INITIALIZER="zeros",e==null&&(e={}),this.supportsMasking=!0,this.alphaInitializer=Pt(e.alphaInitializer||this.DEFAULT_ALPHA_INITIALIZER),this.alphaRegularizer=zt(e.alphaRegularizer),this.alphaConstraint=yn(e.alphaConstraint),e.sharedAxes==null)this.sharedAxes=null;else if(Array.isArray(e.sharedAxes))this.sharedAxes=e.sharedAxes;else if(typeof e.sharedAxes=="number")this.sharedAxes=[e.sharedAxes];else throw new q(`Expected sharedAxes to be a number or an array of numbers, but got ${e.sharedAxes}`)}build(e){e=Nt(e);const t=e.slice(1);if(this.sharedAxes!=null)for(const s of this.sharedAxes)t[s-1]=1;this.alpha=this.addWeight("alpha",t,"float32",this.alphaInitializer,this.alphaRegularizer,!0,this.alphaConstraint);const n={};if(this.sharedAxes!=null)for(let s=1;s<e.length;++s)n[s]=e[s];this.inputSpec=[new Sn({ndim:e.length,axes:n})],this.built=!0}call(e,t){return e=Je(e),Eh(e,this.alpha.read())}getConfig(){const e={alphaInitializer:Kt(this.alphaInitializer),alphaRegularizer:Ct(this.alphaRegularizer),alphaConstraint:gn(this.alphaConstraint),sharedAxes:this.sharedAxes},t=super.getConfig();return Object.assign(e,t),e}}yL.className="PReLU",ge(yL);class bL extends ht{constructor(e){super(e==null?{}:e);if(this.DEFAULT_ALPHA=1,e==null&&(e={}),e.alpha!=null&&e.alpha!==this.DEFAULT_ALPHA)throw new ze(`Non-default alpha value (${e.alpha}) is not supported by the ELU layer yet.`);this.alpha=e.alpha==null?this.DEFAULT_ALPHA:e.alpha}call(e,t){const n=Je(e);return Xa(n)}computeOutputShape(e){return e}getConfig(){const e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}}bL.className="ELU",ge(bL);class wL extends ht{constructor(e){super(e==null?{}:e);this.DEFAULT_THETA=1,e==null&&(e={}),this.theta=e.theta==null?this.DEFAULT_THETA:e.theta}call(e,t){const n=Je(e);return n.mul(Xh(n.greater(this.theta),"float32"))}computeOutputShape(e){return e}getConfig(){const e={theta:this.theta},t=super.getConfig();return Object.assign(e,t),e}}wL.className="ThresholdedReLU",ge(wL);class LL extends ht{constructor(e){super(e==null?{}:e);this.DEFAULT_AXIS=1,e==null&&(e={}),this.softmax=new dL().apply,this.axis=e.axis==null?this.DEFAULT_AXIS:e.axis}call(e,t){const n=Je(e);return this.softmax(n,this.axis)}computeOutputShape(e){return e}getConfig(){const e={axis:this.axis},t=super.getConfig();return Object.assign(e,t),e}}LL.className="Softmax",ge(LL);function bc(e,t,n){if(typeof e=="number")return jo(e,t);if(e.length!==t)throw new q(`The ${n} argument must be an integer or tuple of ${t} integers. Received: ${e.length} elements.`);for(let s=0;s<t;++s){const i=e[s];if(!c3(i))throw new q(`The ${n} argument must be an integer or tuple of ${t} integers. Received: ${JSON.stringify(e)} including a non-integer number ${i}`)}return e}function hi(e,t,n,s,i=1){if(e==null)return e;const o=t+(t-1)*(i-1);let a;return n==="same"?a=e:a=e-o+1,Math.floor((a+s-1)/s)}function Cm(e,t,n,s){if(e==null)return null;if(s==="valid")e=e*t+Qr([n-t,0]);else if(s==="same")e=e*t;else throw new q(`Unsupport padding mode: ${s}.`);return e}function SL(e,t){return ee(()=>(jt(t),t==="channelsFirst"?Ye(e,[0,2,3,1]):e))}function GN(e,t){return ee(()=>(jt(t),t==="channelsFirst"?Ye(e,[0,2,3,4,1]):e))}function YN(e,t,n,s=1,i="valid",o,a=1){return ee(()=>{if(o==null&&(o=ii()),jt(o),e.shape.length!==3)throw new q(`The input of a conv1dWithBias operation should be 3, but is ${e.shape.length} instead.`);if(t.shape.length!==3)throw new q(`The kernel for a conv1dWithBias operation should be 3, but is ${t.shape.length} instead`);if(n!=null&&n.shape.length!==1)throw new q(`The bias for a conv1dWithBias operation should be 1, but is ${t.shape.length} instead`);if(o==="channelsFirst"&&(e=Ye(e,[0,2,1])),i==="causal")throw new ze("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");let c=Ip(e,t,s,i==="same"?"same":"valid","NWC",a);return n!=null&&(c=Fi(c,n)),c})}function une(e,t,n=1,s="valid",i,o=1){return ee(()=>(jt(i),YN(e,t,null,n,s,i,o)))}function dne(e,t,n=[1,1],s="valid",i,o){return ee(()=>(jt(i),IL(e,t,null,n,s,i,o)))}function IL(e,t,n,s=[1,1],i="valid",o,a,c=null){return ee(()=>{if(o==null&&(o=ii()),jt(o),e.rank!==3&&e.rank!==4)throw new q(`conv2dWithBiasActivation expects input to be of rank 3 or 4, but received ${e.rank}.`);if(t.rank!==3&&t.rank!==4)throw new q(`conv2dWithBiasActivation expects kernel to be of rank 3 or 4, but received ${e.rank}.`);let h=SL(e,o);if(i==="causal")throw new ze("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");return h=mw({x:h,filter:t,strides:s,pad:i==="same"?"same":"valid",dilations:a,dataFormat:"NHWC",bias:n,activation:c}),o==="channelsFirst"&&(h=Ye(h,[0,3,1,2])),h})}function pne(e,t,n=[1,1,1],s="valid",i,o){return ee(()=>(jt(i),HN(e,t,null,n,s,i,o)))}function HN(e,t,n,s=[1,1,1],i="valid",o,a){return ee(()=>{if(o==null&&(o=ii()),jt(o),e.rank!==4&&e.rank!==5)throw new q(`conv3dWithBias expects input to be of rank 4 or 5, but received ${e.rank}.`);if(t.rank!==4&&t.rank!==5)throw new q(`conv3dWithBias expects kernel to be of rank 4 or 5, but received ${e.rank}.`);let c=GN(e,o);if(i==="causal")throw new ze("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");return c=Bb(c,t,s,i==="same"?"same":"valid","NDHWC",a),n!=null&&(c=Fi(c,n)),o==="channelsFirst"&&(c=Ye(c,[0,4,1,2,3])),c})}class xL extends ht{constructor(e,t){super(t);if(this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",xL.verifyArgs(t),this.rank=e,Ln(this.rank,"rank"),this.rank!==1&&this.rank!==2&&this.rank!==3)throw new ze(`Convolution layer for rank other than 1, 2, or 3 (${this.rank}) is not implemented yet.`);if(this.kernelSize=bc(t.kernelSize,e,"kernelSize"),this.strides=bc(t.strides==null?1:t.strides,e,"strides"),this.padding=t.padding==null?"valid":t.padding,Rs(this.padding),this.dataFormat=t.dataFormat==null?"channelsLast":t.dataFormat,jt(this.dataFormat),this.activation=so(t.activation),this.useBias=t.useBias==null?!0:t.useBias,this.biasInitializer=Pt(t.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.biasConstraint=yn(t.biasConstraint),this.biasRegularizer=zt(t.biasRegularizer),this.activityRegularizer=zt(t.activityRegularizer),this.dilationRate=bc(t.dilationRate==null?1:t.dilationRate,e,"dilationRate"),this.rank===1&&Array.isArray(this.dilationRate)&&this.dilationRate.length!==1)throw new q(`dilationRate must be a number or an array of a single number for 1D convolution, but received ${JSON.stringify(this.dilationRate)}`);if(this.rank===2){if(typeof this.dilationRate=="number")this.dilationRate=[this.dilationRate,this.dilationRate];else if(this.dilationRate.length!==2)throw new q(`dilationRate must be a number or array of two numbers for 2D convolution, but received ${JSON.stringify(this.dilationRate)}`)}else if(this.rank===3){if(typeof this.dilationRate=="number")this.dilationRate=[this.dilationRate,this.dilationRate,this.dilationRate];else if(this.dilationRate.length!==3)throw new q(`dilationRate must be a number or array of three numbers for 3D convolution, but received ${JSON.stringify(this.dilationRate)}`)}}static verifyArgs(e){if(Cs("kernelSize"in e,"required key 'kernelSize' not in config"),typeof e.kernelSize!="number"&&!kw(e.kernelSize,"number",1,3))throw new q(`BaseConv expects config.kernelSize to be number or number[] with length 1, 2, or 3, but received ${JSON.stringify(e.kernelSize)}.`)}getConfig(){const e={kernelSize:this.kernelSize,strides:this.strides,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,activation:no(this.activation),useBias:this.useBias,biasInitializer:Kt(this.biasInitializer),biasRegularizer:Ct(this.biasRegularizer),activityRegularizer:Ct(this.activityRegularizer),biasConstraint:gn(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}}class ru extends xL{constructor(e,t){super(e,t);this.kernel=null,ru.verifyArgs(t),this.filters=t.filters,Ln(this.filters,"filters"),this.kernelInitializer=Pt(t.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.kernelConstraint=yn(t.kernelConstraint),this.kernelRegularizer=zt(t.kernelRegularizer)}build(e){e=Nt(e);const t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null)throw new q(`The channel dimension of the input should be defined. Found ${e[t]}`);const n=e[t],s=this.kernelSize.concat([n,this.filters]);this.kernel=this.addWeight("kernel",s,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[{ndim:this.rank+2,axes:{[t]:n}}],this.built=!0}call(e,t){return ee(()=>{e=Je(e);let n;const s=this.bias==null?null:this.bias.read(),i=Wv(this.activation.getClassName());if(i!=null&&this.rank===2)n=IL(e,this.kernel.read(),s,this.strides,this.padding,this.dataFormat,this.dilationRate,i);else{if(this.rank===1)n=YN(e,this.kernel.read(),s,this.strides[0],this.padding,this.dataFormat,this.dilationRate[0]);else if(this.rank===2)n=IL(e,this.kernel.read(),s,this.strides,this.padding,this.dataFormat,this.dilationRate);else if(this.rank===3)n=HN(e,this.kernel.read(),s,this.strides,this.padding,this.dataFormat,this.dilationRate);else throw new ze("convolutions greater than 3D are not implemented yet.");this.activation!=null&&(n=this.activation.apply(n))}return n})}computeOutputShape(e){e=Nt(e);const t=[],n=this.dataFormat==="channelsLast"?e.slice(1,e.length-1):e.slice(2);for(let i=0;i<n.length;++i){const o=hi(n[i],this.kernelSize[i],this.padding,this.strides[i],typeof this.dilationRate=="number"?this.dilationRate:this.dilationRate[i]);t.push(o)}let s=[e[0]];return this.dataFormat==="channelsLast"?(s=s.concat(t),s.push(this.filters)):(s.push(this.filters),s=s.concat(t)),s}getConfig(){const e={filters:this.filters,kernelInitializer:Kt(this.kernelInitializer),kernelRegularizer:Ct(this.kernelRegularizer),kernelConstraint:gn(this.kernelConstraint)},t=super.getConfig();return Object.assign(e,t),e}static verifyArgs(e){if(!("filters"in e)||typeof e.filters!="number"||e.filters<1)throw new q(`Convolution layer expected config.filters to be a 'number' > 0 but got ${JSON.stringify(e.filters)}`)}}class ou extends ru{constructor(e){super(2,e);ou.verifyArgs(e)}getConfig(){const e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if(typeof e.kernelSize!="number"&&!kw(e.kernelSize,"number",1,2))throw new q(`Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received ${JSON.stringify(e.kernelSize)}.`)}}ou.className="Conv2D",ge(ou);class Rm extends ru{constructor(e){super(3,e);Rm.verifyArgs(e)}getConfig(){const e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if(typeof e.kernelSize!="number"&&!(Array.isArray(e.kernelSize)&&(e.kernelSize.length===1||e.kernelSize.length===3)))throw new q(`Conv3D expects config.kernelSize to be number or [number, number, number], but received ${JSON.stringify(e.kernelSize)}.`)}}Rm.className="Conv3D",ge(Rm);class TL extends ou{constructor(e){super(e);if(this.inputSpec=[new Sn({ndim:4})],this.padding!=="same"&&this.padding!=="valid")throw new q(`Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(e=Nt(e),e.length!==4)throw new q("Input should have rank 4; Received input shape: "+JSON.stringify(e));const t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null)throw new q("The channel dimension of the inputs should be defined. Found `None`.");const n=e[t],s=this.kernelSize.concat([this.filters,n]);this.kernel=this.addWeight("kernel",s,"float32",this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[new Sn({ndim:4,axes:{[t]:n}})],this.built=!0}call(e,t){return ee(()=>{let n=Je(e);if(n.shape.length!==4)throw new q(`Conv2DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${n.shape.length}`);const s=n.shape,i=s[0];let o,a;this.dataFormat==="channelsFirst"?(o=2,a=3):(o=1,a=2);const c=s[o],h=s[a],p=this.kernelSize[0],m=this.kernelSize[1],y=this.strides[0],b=this.strides[1],w=Cm(c,y,p,this.padding),L=Cm(h,b,m,this.padding),T=[i,w,L,this.filters];this.dataFormat!=="channelsLast"&&(n=Ye(n,[0,2,3,1]));let v=xp(n,this.kernel.read(),T,this.strides,this.padding);return this.dataFormat!=="channelsLast"&&(v=Ye(v,[0,3,1,2])),this.bias!=null&&(v=Fi(v,this.bias.read(),this.dataFormat)),this.activation!=null&&(v=this.activation.apply(v)),v})}computeOutputShape(e){e=Nt(e);const t=e.slice();let n,s,i;this.dataFormat==="channelsFirst"?(n=1,s=2,i=3):(n=3,s=1,i=2);const o=this.kernelSize[0],a=this.kernelSize[1],c=this.strides[0],h=this.strides[1];return t[n]=this.filters,t[s]=Cm(t[s],c,o,this.padding),t[i]=Cm(t[i],h,a,this.padding),t}getConfig(){const e=super.getConfig();return delete e.dilationRate,e}}TL.className="Conv2DTranspose",ge(TL);class qN extends ru{constructor(e,t){super(e,t);if(this.DEFAULT_DEPTHWISE_INITIALIZER="glorotUniform",this.DEFAULT_POINTWISE_INITIALIZER="glorotUniform",this.depthwiseKernel=null,this.pointwiseKernel=null,t.filters==null)throw new q("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(t.kernelInitializer!=null||t.kernelRegularizer!=null||t.kernelConstraint!=null)throw new q("Fields kernelInitializer, kernelRegularizer and kernelConstraint are invalid for SeparableConv2D. Use depthwiseInitializer, depthwiseRegularizer, depthwiseConstraint, pointwiseInitializer, pointwiseRegularizer and pointwiseConstraint instead.");if(t.padding!=null&&t.padding!=="same"&&t.padding!=="valid")throw new q(`SeparableConv${this.rank}D supports only padding modes: 'same' and 'valid', but received ${JSON.stringify(t.padding)}`);this.depthMultiplier=t.depthMultiplier==null?1:t.depthMultiplier,this.depthwiseInitializer=Pt(t.depthwiseInitializer||this.DEFAULT_DEPTHWISE_INITIALIZER),this.depthwiseRegularizer=zt(t.depthwiseRegularizer),this.depthwiseConstraint=yn(t.depthwiseConstraint),this.pointwiseInitializer=Pt(t.depthwiseInitializer||this.DEFAULT_POINTWISE_INITIALIZER),this.pointwiseRegularizer=zt(t.pointwiseRegularizer),this.pointwiseConstraint=yn(t.pointwiseConstraint)}build(e){if(e=Nt(e),e.length<this.rank+2)throw new q(`Inputs to SeparableConv${this.rank}D should have rank ${this.rank+2}, but received input shape: ${JSON.stringify(e)}`);const t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null||e[t]<0)throw new q(`The channel dimension of the inputs should be defined, but found ${JSON.stringify(e[t])}`);const n=e[t],s=this.kernelSize.concat([n,this.depthMultiplier]),i=[];for(let a=0;a<this.rank;++a)i.push(1);i.push(n*this.depthMultiplier,this.filters);const o=!0;this.depthwiseKernel=this.addWeight("depthwise_kernel",s,"float32",this.depthwiseInitializer,this.depthwiseRegularizer,o,this.depthwiseConstraint),this.pointwiseKernel=this.addWeight("pointwise_kernel",i,"float32",this.pointwiseInitializer,this.pointwiseRegularizer,o,this.pointwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,o,this.biasConstraint):this.bias=null,this.inputSpec=[new Sn({ndim:this.rank+2,axes:{[t]:n}})],this.built=!0}call(e,t){return ee(()=>{e=Je(e);let n;if(this.rank===1)throw new ze("1D separable convolution is not implemented yet.");return this.rank===2&&(this.dataFormat==="channelsFirst"&&(e=Ye(e,[0,2,3,1])),n=sw(e,this.depthwiseKernel.read(),this.pointwiseKernel.read(),this.strides,this.padding,this.dilationRate,"NHWC")),this.useBias&&(n=Fi(n,this.bias.read(),this.dataFormat)),this.activation!=null&&(n=this.activation.apply(n)),this.dataFormat==="channelsFirst"&&(n=Ye(n,[0,3,1,2])),n})}getConfig(){const e=super.getConfig();return delete e.rank,delete e.kernelInitializer,delete e.kernelRegularizer,delete e.kernelConstraint,e.depthwiseInitializer=Kt(this.depthwiseInitializer),e.pointwiseInitializer=Kt(this.pointwiseInitializer),e.depthwiseRegularizer=Ct(this.depthwiseRegularizer),e.pointwiseRegularizer=Ct(this.pointwiseRegularizer),e.depthwiseConstraint=gn(this.depthwiseConstraint),e.pointwiseConstraint=gn(this.pointwiseConstraint),e}}qN.className="SeparableConv";class AL extends qN{constructor(e){super(2,e)}}AL.className="SeparableConv2D",ge(AL);class Om extends ru{constructor(e){super(1,e);Om.verifyArgs(e),this.inputSpec=[{ndim:3}]}getConfig(){const e=super.getConfig();return delete e.rank,delete e.dataFormat,e}static verifyArgs(e){if(typeof e.kernelSize!="number"&&!kw(e.kernelSize,"number",1,1))throw new q(`Conv1D expects config.kernelSize to be number or number[] with length 1, but received ${JSON.stringify(e.kernelSize)}.`)}}Om.className="Conv1D",ge(Om);class vL extends ht{constructor(e){super(e);typeof e.cropping=="number"?this.cropping=[[e.cropping,e.cropping],[e.cropping,e.cropping]]:typeof e.cropping[0]=="number"?this.cropping=[[e.cropping[0],e.cropping[0]],[e.cropping[1],e.cropping[1]]]:this.cropping=e.cropping,this.dataFormat=e.dataFormat===void 0?"channelsLast":e.dataFormat,this.inputSpec=[{ndim:4}]}computeOutputShape(e){return this.dataFormat==="channelsFirst"?[e[0],e[1],e[2]-this.cropping[0][0]-this.cropping[0][1],e[3]-this.cropping[1][0]-this.cropping[1][1]]:[e[0],e[1]-this.cropping[0][0]-this.cropping[0][1],e[2]-this.cropping[1][0]-this.cropping[1][1],e[3]]}call(e,t){return ee(()=>{if(e=Je(e),this.dataFormat==="channelsLast"){const n=rm(e,this.cropping[0][0],e.shape[1]-this.cropping[0][0]-this.cropping[0][1],2);return rm(n,this.cropping[1][0],e.shape[2]-this.cropping[1][1]-this.cropping[1][0],3)}else{const n=rm(e,this.cropping[0][0],e.shape[2]-this.cropping[0][0]-this.cropping[0][1],3);return rm(n,this.cropping[1][0],e.shape[3]-this.cropping[1][1]-this.cropping[1][0],4)}})}getConfig(){const e={cropping:this.cropping,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}vL.className="Cropping2D",ge(vL);class NL extends ht{constructor(e){super(e);this.DEFAULT_SIZE=[2,2],this.inputSpec=[{ndim:4}],this.size=e.size==null?this.DEFAULT_SIZE:e.size,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat}computeOutputShape(e){if(this.dataFormat==="channelsFirst"){const t=e[2]==null?null:this.size[0]*e[2],n=e[3]==null?null:this.size[1]*e[3];return[e[0],e[1],t,n]}else{const t=e[1]==null?null:this.size[0]*e[1],n=e[2]==null?null:this.size[1]*e[2];return[e[0],t,n,e[3]]}}call(e,t){return ee(()=>{let n=Je(e);const s=n.shape;if(this.dataFormat==="channelsFirst"){n=Ye(n,[0,2,3,1]);const i=this.size[0]*s[2],o=this.size[1]*s[3],a=n.resizeNearestNeighbor([i,o]);return Ye(a,[0,3,1,2])}else{const i=this.size[0]*s[1],o=this.size[1]*s[2];return n.resizeNearestNeighbor([i,o])}})}getConfig(){const e={size:this.size,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}NL.className="UpSampling2D",ge(NL);function VV(e,t,n=[1,1],s="valid",i,o){return ee(()=>{i==null&&(i=ii()),jt(i);let a=SL(e,i);if(e.rank!==4)throw new q(`Input for depthwiseConv2d is required to be 4-D, but is instead ${e.rank}-D`);if(t.rank!==4)throw new q(`depthwiseKernel is required to be 4-D, but is instead ${t.rank}-D`);return a=Bo(a,t,n,s==="same"?"same":"valid","NHWC",o),i==="channelsFirst"&&(a=Ye(a,[0,3,1,2])),a})}class CL extends xL{constructor(e){super(2,e);this.depthwiseKernel=null,this.depthMultiplier=e.depthMultiplier==null?1:e.depthMultiplier,this.depthwiseInitializer=Pt(e.depthwiseInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.depthwiseConstraint=yn(e.depthwiseConstraint),this.depthwiseRegularizer=zt(e.depthwiseRegularizer)}build(e){if(e=Nt(e),e.length<4)throw new q(`Inputs to DepthwiseConv2D should have rank 4. Received input shape: ${JSON.stringify(e)}.`);const t=this.dataFormat==="channelsFirst"?1:3;if(e[t]==null||e[t]<0)throw new q(`The channel dimension of the inputs to DepthwiseConv2D should be defined, but is not (${e[t]}).`);const n=e[t],s=[this.kernelSize[0],this.kernelSize[1],n,this.depthMultiplier];this.depthwiseKernel=this.addWeight("depthwise_kernel",s,null,this.depthwiseInitializer,this.depthwiseRegularizer,!0,this.depthwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[n*this.depthMultiplier],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return ee(()=>{e=Je(e);let n=VV(e,this.depthwiseKernel.read(),this.strides,this.padding,this.dataFormat,null);return this.useBias&&(n=Fi(n,this.bias.read(),this.dataFormat)),this.activation!=null&&(n=this.activation.apply(n)),n})}computeOutputShape(e){e=Nt(e);const t=this.dataFormat==="channelsFirst"?e[2]:e[1],n=this.dataFormat==="channelsFirst"?e[3]:e[2],s=this.dataFormat==="channelsFirst"?e[1]*this.depthMultiplier:e[3]*this.depthMultiplier,i=hi(t,this.kernelSize[0],this.padding,this.strides[0]),o=hi(n,this.kernelSize[1],this.padding,this.strides[1]);return this.dataFormat==="channelsFirst"?[e[0],s,i,o]:[e[0],i,o,s]}getConfig(){const e=super.getConfig();return e.depthMultiplier=this.depthMultiplier,e.depthwiseInitializer=Kt(this.depthwiseInitializer),e.depthwiseRegularizer=Ct(this.depthwiseRegularizer),e.depthwiseConstraint=gn(this.depthwiseRegularizer),e}}CL.className="DepthwiseConv2D",ge(CL);function jN(e,t,n,s){if(Array.isArray(e)){if(t!=null||n!=null)throw new q("When inputs is an array, neither initialState or constants should be provided");s!=null&&(n=e.slice(e.length-s,e.length),e=e.slice(0,e.length-s)),e.length>1&&(t=e.slice(1,e.length)),e=e[0]}function i(o){return o==null||Array.isArray(o)?o:[o]}return t=i(t),n=i(n),{inputs:e,initialState:t,constants:n}}function KN(e,t,n,s=!1,i,o,a=!1,c=!1){return ee(()=>{const h=t.shape.length;if(h<3)throw new q(`Input should be at least 3D, but is ${h}D.`);const p=[1,0].concat(oi(2,h));if(t=Ye(t,p),o!=null)throw new ze("The rnn() functoin of the deeplearn.js backend does not support constants yet.");a&&console.warn("Backend rnn(): the unroll = true option is not applicable to the imperative deeplearn.js backend."),i!=null&&(i=i.asType("bool").asType("float32"),i.rank===h-1&&(i=ts(i,-1)),i=Ye(i,p)),s&&(t=Ns(t,0),i!=null&&(i=Ns(i,0)));const m=[];let y,b=n;const w=t.shape[0],L=si(t);let T;i!=null&&(T=si(i));for(let C=0;C<w;++C){const O=L[C],D=ee(()=>e(O,b));if(i==null)y=D[0],b=D[1];else{const k=ee(()=>{const F=T[C],B=Wn(F).sub(F),$=D[0].mul(F).add(b[0].mul(B)),Y=b.map((j,Z)=>D[1][Z].mul(F).add(j.mul(B)));return{output:$,newStates:Y}});y=k.output,b=k.newStates}c&&m.push(y)}let v;if(c){const C=1;v=ss(m,C)}return[y,v,b]})}class Wi extends ht{constructor(e){super(e);let t;if(e.cell==null)throw new q("cell property is missing for the constructor of RNN.");if(Array.isArray(e.cell)?t=new km({cells:e.cell}):t=e.cell,t.stateSize==null)throw new q("The RNN cell should have an attribute `stateSize` (tuple of integers, one integer per RNN state).");this.cell=t,this.returnSequences=e.returnSequences==null?!1:e.returnSequences,this.returnState=e.returnState==null?!1:e.returnState,this.goBackwards=e.goBackwards==null?!1:e.goBackwards,this._stateful=e.stateful==null?!1:e.stateful,this.unroll=e.unroll==null?!1:e.unroll,this.supportsMasking=!0,this.inputSpec=[new Sn({ndim:3})],this.stateSpec=null,this.states_=null,this.numConstants=null,this.keptStates=[]}getStates(){if(this.states_==null){const e=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;return oi(0,e).map(t=>null)}else return this.states_}setStates(e){this.states_=e}computeOutputShape(e){Xw(e)&&(e=e[0]),e=e;let t=this.cell.stateSize;Array.isArray(t)||(t=[t]);const n=t[0];let s;if(this.returnSequences?s=[e[0],e[1],n]:s=[e[0],n],this.returnState){const i=[];for(const o of t)i.push([e[0],o]);return[s].concat(i)}else return s}computeMask(e,t){return ee(()=>{Array.isArray(t)&&(t=t[0]);const n=this.returnSequences?t:null;if(this.returnState){const s=this.states.map(i=>null);return[n].concat(s)}else return n})}get states(){if(this.states_==null){const e=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1,t=[];for(let n=0;n<e;++n)t.push(null);return t}else return this.states_}set states(e){this.states_=e}build(e){const t=null;if(this.numConstants!=null)throw new ze("Constants support is not implemented in RNN yet.");Xw(e)&&(e=e[0]),e=e;const n=this.stateful?e[0]:null,s=e.slice(2);this.inputSpec[0]=new Sn({shape:[n,null,...s]});const i=[e[0]].concat(e.slice(2));if(t!=null)throw new ze("Constants support is not implemented in RNN yet.");this.cell.build(i);let o;if(Array.isArray(this.cell.stateSize)?o=this.cell.stateSize:o=[this.cell.stateSize],this.stateSpec!=null){if(!ie(this.stateSpec.map(a=>a.shape[a.shape.length-1]),o))throw new q(`An initialState was passed that is not compatible with cell.stateSize. Received stateSpec=${this.stateSpec}; However cell.stateSize is ${this.cell.stateSize}`)}else this.stateSpec=o.map(a=>new Sn({shape:[null,a]}));this.stateful&&this.resetStates()}resetStates(e,t=!1){ee(()=>{if(!this.stateful)throw new cr("Cannot call resetStates() on an RNN Layer that is not stateful.");const n=this.inputSpec[0].shape[0];if(n==null)throw new q("If an RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: \n- If using a Sequential model, specify the batch size by passing a `batchInputShape` option to your first layer.\n- If using the functional API, specify the batch size by passing a `batchShape` option to your Input layer.");if(this.states_==null)Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(s=>pt([n,s])):this.states_=[pt([n,this.cell.stateSize])];else if(e==null)qe(this.states_),this.keptStates!=null&&(qe(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(s=>pt([n,s])):this.states_[0]=pt([n,this.cell.stateSize]);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new q(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${e.length} state value(s). Input received: ${e}`);t===!0?this.keptStates.push(this.states_.slice()):qe(this.states_);for(let s=0;s<this.states_.length;++s){const i=e[s],o=Array.isArray(this.cell.stateSize)?this.cell.stateSize[s]:this.cell.stateSize,a=[n,o];if(!ie(i.shape,a))throw new q(`State ${s} is incompatible with layer ${this.name}: expected shape=${a}, received shape=${i.shape}`);this.states_[s]=i}}this.states_=this.states_.map(s=>wn(s.clone()))})}apply(e,t){let n=t==null?null:t.initialState,s=t==null?null:t.constants;t==null&&(t={});const i=jN(e,n,s,this.numConstants);e=i.inputs,n=i.initialState,s=i.constants;let o=[],a=[];if(n!=null){t.initialState=n,o=o.concat(n),this.stateSpec=[];for(const h of n)this.stateSpec.push(new Sn({shape:h.shape}));a=a.concat(this.stateSpec)}s!=null&&(t.constants=s,o=o.concat(s),this.numConstants=s.length);const c=o[0]instanceof ci;if(c){const h=[e].concat(o),p=this.inputSpec.concat(a),m=this.inputSpec;this.inputSpec=p;const y=super.apply(h,t);return this.inputSpec=m,y}else return super.apply(e,t)}call(e,t){return ee(()=>{const n=t==null?null:t.mask,s=t==null?null:t.training;let i=t==null?null:t.initialState;e=Je(e),i==null&&(this.stateful?i=this.states_:i=this.getInitialState(e));const o=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;if(i.length!==o)throw new q(`RNN Layer has ${o} state(s) but was passed ${i.length} initial state(s).`);this.unroll&&console.warn("Ignoring unroll = true for RNN layer, due to imperative backend.");const a={training:s},c=(w,L)=>{const T=this.cell.call([w].concat(L),a);return[T[0],T.slice(1)]},h=KN(c,e,i,this.goBackwards,n,null,this.unroll,this.returnSequences),p=h[0],m=h[1],y=h[2];this.stateful&&this.resetStates(y,s);const b=this.returnSequences?m:p;return this.returnState?[b].concat(y):b})}getInitialState(e){return ee(()=>{let t=pt(e.shape);return t=$e(t,[1,2]),t=Jh(t),Array.isArray(this.cell.stateSize)?this.cell.stateSize.map(n=>n>1?Pw(t,[1,n]):t):this.cell.stateSize>1?[Pw(t,[1,this.cell.stateSize])]:[t]})}get trainableWeights(){return this.trainable?this.cell.trainableWeights:[]}get nonTrainableWeights(){return this.trainable?this.cell.nonTrainableWeights:this.cell.weights}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),this.cell!=null&&this.cell.setFastWeightInitDuringBuild(e)}getConfig(){const e=super.getConfig(),t={returnSequences:this.returnSequences,returnState:this.returnState,goBackwards:this.goBackwards,stateful:this.stateful,unroll:this.unroll};this.numConstants!=null&&(t.numConstants=this.numConstants);const n=this.cell.getConfig();return this.getClassName()===Wi.className&&(t.cell={className:this.cell.getClassName(),config:n}),Object.assign({},n,e,t)}static fromConfig(e,t,n={}){const s=t.cell,i=li(s,n);return new e(Object.assign(t,{cell:i}))}}Wi.className="RNN",ge(Wi);class wc extends ht{}class Em extends wc{constructor(e){super(e);this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",this.units=e.units,Ln(this.units,"units"),this.activation=so(e.activation==null?this.DEFAULT_ACTIVATION:e.activation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=Pt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Pt(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Pt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=zt(e.kernelRegularizer),this.recurrentRegularizer=zt(e.recurrentRegularizer),this.biasRegularizer=zt(e.biasRegularizer),this.kernelConstraint=yn(e.kernelConstraint),this.recurrentConstraint=yn(e.recurrentConstraint),this.biasConstraint=yn(e.biasConstraint),this.dropout=pc([1,Qr([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=pc([1,Qr([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=Nt(e),this.kernel=this.addWeight("kernel",[e[e.length-1],this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return ee(()=>{if(e=e,e.length!==2)throw new q(`SimpleRNNCell expects 2 input Tensors, got ${e.length}.`);let n=e[1];e=e[0];const s=t.training==null?!1:t.training;0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=io({ones:()=>Wn(e),rate:this.dropout,training:s})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=io({ones:()=>Wn(n),rate:this.recurrentDropout,training:s}));let i;const o=this.dropoutMask,a=this.recurrentDropoutMask;o!=null?i=ki(X(e,o),this.kernel.read()):i=ki(e,this.kernel.read()),this.bias!=null&&(i=Fi(i,this.bias.read())),a!=null&&(n=X(n,a));let c=be(i,ki(n,this.recurrentKernel.read()));return this.activation!=null&&(c=this.activation.apply(c)),[c,c]})}getConfig(){const e=super.getConfig(),t={units:this.units,activation:no(this.activation),useBias:this.useBias,kernelInitializer:Kt(this.kernelInitializer),recurrentInitializer:Kt(this.recurrentInitializer),biasInitializer:Kt(this.biasInitializer),kernelRegularizer:Ct(this.kernelRegularizer),recurrentRegularizer:Ct(this.recurrentRegularizer),biasRegularizer:Ct(this.biasRegularizer),activityRegularizer:Ct(this.activityRegularizer),kernelConstraint:gn(this.kernelConstraint),recurrentConstraint:gn(this.recurrentConstraint),biasConstraint:gn(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout};return Object.assign({},e,t)}}Em.className="SimpleRNNCell",ge(Em);class RL extends Wi{constructor(e){e.cell=new Em(e),super(e)}call(e,t){return ee(()=>{this.cell.dropoutMask!=null&&(qe(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(qe(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const n=t==null?null:t.mask,s=t==null?null:t.training,i=t==null?null:t.initialState;return super.call(e,{mask:n,training:s,initialState:i})})}static fromConfig(e,t){return new e(t)}}RL.className="SimpleRNN",ge(RL);class Dm extends wc{constructor(e){super(e);if(this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",e.resetAfter)throw new q("GRUCell does not support reset_after parameter set to true.");this.units=e.units,Ln(this.units,"units"),this.activation=so(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=so(e.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=Pt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Pt(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Pt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=zt(e.kernelRegularizer),this.recurrentRegularizer=zt(e.recurrentRegularizer),this.biasRegularizer=zt(e.biasRegularizer),this.kernelConstraint=yn(e.kernelConstraint),this.recurrentConstraint=yn(e.recurrentConstraint),this.biasConstraint=yn(e.biasConstraint),this.dropout=pc([1,Qr([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=pc([1,Qr([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.implementation=e.implementation,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=Nt(e);const t=e[e.length-1];this.kernel=this.addWeight("kernel",[t,this.units*3],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units*3],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[this.units*3],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return ee(()=>{if(e=e,e.length!==2)throw new q(`GRUCell expects 2 input Tensors (inputs, h, c), got ${e.length}.`);const n=t.training==null?!1:t.training;let s=e[1];e=e[0],0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=io({ones:()=>Wn(e),rate:this.dropout,training:n,count:3})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=io({ones:()=>Wn(s),rate:this.recurrentDropout,training:n,count:3}));const i=this.dropoutMask,o=this.recurrentDropoutMask;let a,c,h;0<this.dropout&&this.dropout<1&&(e=X(e,i[0]));let p=ki(e,this.kernel.read());this.useBias&&(p=Fi(p,this.bias.read())),0<this.recurrentDropout&&this.recurrentDropout<1&&(s=X(s,o[0]));const m=this.recurrentKernel.read(),[y,b]=ps(m,[2*this.units,this.units],m.rank-1),w=ki(s,y),[L,T,v]=ps(p,3,p.rank-1),[C,O]=ps(w,2,w.rank-1);a=this.recurrentActivation.apply(be(L,C)),c=this.recurrentActivation.apply(be(T,O));const D=ki(X(c,s),b);h=this.activation.apply(be(v,D));const k=be(X(a,s),X(be(1,Ht(a)),h));return[k,k]})}getConfig(){const e=super.getConfig(),t={units:this.units,activation:no(this.activation),recurrentActivation:no(this.recurrentActivation),useBias:this.useBias,kernelInitializer:Kt(this.kernelInitializer),recurrentInitializer:Kt(this.recurrentInitializer),biasInitializer:Kt(this.biasInitializer),kernelRegularizer:Ct(this.kernelRegularizer),recurrentRegularizer:Ct(this.recurrentRegularizer),biasRegularizer:Ct(this.biasRegularizer),activityRegularizer:Ct(this.activityRegularizer),kernelConstraint:gn(this.kernelConstraint),recurrentConstraint:gn(this.recurrentConstraint),biasConstraint:gn(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation,resetAfter:!1};return Object.assign({},e,t)}}Dm.className="GRUCell",ge(Dm);class OL extends Wi{constructor(e){e.implementation===0&&console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."),e.cell=new Dm(e),super(e)}call(e,t){return ee(()=>{this.cell.dropoutMask!=null&&(qe(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(qe(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const n=t==null?null:t.mask,s=t==null?null:t.training,i=t==null?null:t.initialState;return super.call(e,{mask:n,training:s,initialState:i})})}static fromConfig(e,t){return t.implmentation===0&&(t.implementation=1),new e(t)}}OL.className="GRU",ge(OL);class au extends wc{constructor(e){super(e);this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",this.units=e.units,Ln(this.units,"units"),this.activation=so(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=so(e.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=Pt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Pt(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Pt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.unitForgetBias=e.unitForgetBias,this.kernelRegularizer=zt(e.kernelRegularizer),this.recurrentRegularizer=zt(e.recurrentRegularizer),this.biasRegularizer=zt(e.biasRegularizer),this.kernelConstraint=yn(e.kernelConstraint),this.recurrentConstraint=yn(e.recurrentConstraint),this.biasConstraint=yn(e.biasConstraint),this.dropout=pc([1,Qr([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=pc([1,Qr([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.implementation=e.implementation,this.stateSize=[this.units,this.units],this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){var t;e=Nt(e);const n=e[e.length-1];this.kernel=this.addWeight("kernel",[n,this.units*4],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units*4],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint);let s;if(this.useBias){if(this.unitForgetBias){const i=this.biasInitializer,o=this.units;s=new(t=class extends Vs{apply(c,h){const p=i.apply([o]),m=new am().apply([o]),y=i.apply([o*2]);return Yv(Yv(p,m),y)}},t.className="CustomInit",t)}else s=this.biasInitializer;this.bias=this.addWeight("bias",[this.units*4],null,s,this.biasRegularizer,!0,this.biasConstraint)}else this.bias=null;this.built=!0}call(e,t){return ee(()=>{const n=t.training==null?!1:t.training;if(e=e,e.length!==3)throw new q(`LSTMCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);let s=e[1];const i=e[2];e=e[0],0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=io({ones:()=>Wn(e),rate:this.dropout,training:n,count:4})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=io({ones:()=>Wn(s),rate:this.recurrentDropout,training:n,count:4}));const o=this.dropoutMask,a=this.recurrentDropoutMask;let c,h,p,m;0<this.dropout&&this.dropout<1&&(e=X(e,o[0]));let y=ki(e,this.kernel.read());0<this.recurrentDropout&&this.recurrentDropout<1&&(s=X(s,a[0])),y=be(y,ki(s,this.recurrentKernel.read())),this.useBias&&(y=Fi(y,this.bias.read()));const[b,w,L,T]=ps(y,4,y.rank-1);c=this.recurrentActivation.apply(b),h=this.recurrentActivation.apply(w),p=be(X(h,i),X(c,this.activation.apply(L))),m=this.recurrentActivation.apply(T);const v=X(m,this.activation.apply(p));return[v,v,p]})}getConfig(){const e=super.getConfig(),t={units:this.units,activation:no(this.activation),recurrentActivation:no(this.recurrentActivation),useBias:this.useBias,kernelInitializer:Kt(this.kernelInitializer),recurrentInitializer:Kt(this.recurrentInitializer),biasInitializer:Kt(this.biasInitializer),unitForgetBias:this.unitForgetBias,kernelRegularizer:Ct(this.kernelRegularizer),recurrentRegularizer:Ct(this.recurrentRegularizer),biasRegularizer:Ct(this.biasRegularizer),activityRegularizer:Ct(this.activityRegularizer),kernelConstraint:gn(this.kernelConstraint),recurrentConstraint:gn(this.recurrentConstraint),biasConstraint:gn(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation};return Object.assign({},e,t)}}au.className="LSTMCell",ge(au);class EL extends Wi{constructor(e){e.implementation===0&&console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."),e.cell=new au(e),super(e)}call(e,t){return ee(()=>{this.cell.dropoutMask!=null&&(qe(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(qe(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const n=t==null?null:t.mask,s=t==null?null:t.training,i=t==null?null:t.initialState;return super.call(e,{mask:n,training:s,initialState:i})})}static fromConfig(e,t){return t.implmentation===0&&(t.implementation=1),new e(t)}}EL.className="LSTM",ge(EL);class km extends wc{constructor(e){super(e);this.cells=e.cells}get stateSize(){const e=[];for(const t of this.cells.slice().reverse())Array.isArray(t.stateSize)?e.push(...t.stateSize):e.push(t.stateSize);return e}call(e,t){return ee(()=>{e=e;let n=e.slice(1);const s=[];for(const a of this.cells.slice().reverse())Array.isArray(a.stateSize)?s.push(n.splice(0,a.stateSize.length)):s.push(n.splice(0,1));s.reverse();const i=[];let o;for(let a=0;a<this.cells.length;++a){const c=this.cells[a];n=s[a],a===0?o=[e[0]].concat(n):o=[o[0]].concat(n),o=c.call(o,t),i.push(o.slice(1))}n=[];for(const a of i.slice().reverse())n.push(...a);return[o[0]].concat(n)})}build(e){Xw(e)&&(e=e[0]),e=e;let t;this.cells.forEach((n,s)=>{Xo(`RNNCell_${s}`,()=>{n.build(e),Array.isArray(n.stateSize)?t=n.stateSize[0]:t=n.stateSize,e=[e[0],t]})}),this.built=!0}getConfig(){const e=super.getConfig(),t=i=>({className:i.getClassName(),config:i.getConfig()}),n=this.cells.map(t),s={cells:n};return Object.assign({},e,s)}static fromConfig(e,t,n={}){const s=[];for(const i of t.cells)s.push(li(i,n));return new e({cells:s})}get trainableWeights(){if(!this.trainable)return[];const e=[];for(const t of this.cells)e.push(...t.trainableWeights);return e}get nonTrainableWeights(){const e=[];for(const t of this.cells)e.push(...t.nonTrainableWeights);if(!this.trainable){const t=[];for(const n of this.cells)t.push(...n.trainableWeights);return t.concat(e)}return e}getWeights(){const e=[];for(const t of this.cells)e.push(...t.weights);return Jw(e)}setWeights(e){const t=[];for(const n of this.cells){const s=n.weights.length,i=e.splice(s);for(let o=0;o<n.weights.length;++o)t.push([n.weights[o],i[o]])}Zw(t)}}km.className="StackedRNNCells",ge(km);function io(e){const{ones:t,rate:n,training:s=!1,count:i=1}=e,o=()=>qv(t(),n),a=()=>Qh(o,t,s);if(!i||i<=1)return wn(a().clone());const c=Array(i).fill(void 0).map(a);return c.map(h=>wn(h.clone()))}var GV=function(e,t){var n={};for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.indexOf(s)<0&&(n[s]=e[s]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,s=Object.getOwnPropertySymbols(e);i<s.length;i++)t.indexOf(s[i])<0&&Object.prototype.propertyIsEnumerable.call(e,s[i])&&(n[s[i]]=e[s[i]]);return n};class mne extends wc{}class XN extends Wi{constructor(e){if(e.unroll)throw new ze("Unrolling is not possible with convolutional RNNs.");if(Array.isArray(e.cell))throw new ze("It is not possible at the moment to stack convolutional cells.");super(e);this.inputSpec=[new Sn({ndim:5})]}call(e,t){return ee(()=>{if(this.cell.dropoutMask!=null&&(qe(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(qe(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null),t&&t.constants)throw new q("ConvRNN2D cell does not support constants");const n=t==null?null:t.mask,s=t==null?null:t.training,i=t==null?null:t.initialState;return super.call(e,{mask:n,training:s,initialState:i})})}computeOutputShape(e){let t=this.computeSingleOutputShape(e);return this.returnSequences||(t=[t[0],...t.slice(2)]),this.returnState&&(t=[t,...Array(2).fill([e[0],...t.slice(-3)])]),t}getInitialState(e){return ee(()=>{const{stateSize:t}=this.cell,n=e.shape,s=this.computeSingleOutputShape(n),i=[s[0],...s.slice(2)],o=pt(i);return Array.isArray(t)?Array(t.length).fill(o):[o]})}resetStates(e,t=!1){ee(()=>{if(!this.stateful)throw new cr("Cannot call resetStates() on an RNN Layer that is not stateful.");const n=this.inputSpec[0].shape,s=this.computeSingleOutputShape(n),i=[s[0],...s.slice(2)],o=n[0];if(o==null)throw new q("If an RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: \n- If using a Sequential model, specify the batch size by passing a `batchInputShape` option to your first layer.\n- If using the functional API, specify the batch size by passing a `batchShape` option to your Input layer.");if(this.getStates()==null)Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(()=>pt(i)):this.states_=[pt(i)];else if(e==null)qe(this.states_),this.keptStates!=null&&(qe(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(()=>pt(i)):this.states_[0]=pt(i);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new q(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${e.length} state value(s). Input received: ${e}`);t?this.keptStates.push(this.states_.slice()):qe(this.states_);for(let a=0;a<this.states_.length;++a){const c=e[a],h=i;if(!ie(c.shape,h))throw new q(`State ${a} is incompatible with layer ${this.name}: expected shape=${h}, received shape=${c.shape}`);this.states_[a]=c}}this.states_=this.states_.map(a=>wn(a.clone()))})}computeSingleOutputShape(e){const{dataFormat:t,filters:n,kernelSize:s,padding:i,strides:o,dilationRate:a}=this.cell,c=t==="channelsFirst",h=e[c?3:2],p=e[c?4:3],m=hi(h,s[0],i,o[0],a[0]),y=hi(p,s[1],i,o[1],a[1]),b=[...e.slice(0,2),...c?[n,m,y]:[m,y,n]];return b}}XN.className="ConvRNN2D";class Fm extends au{constructor(e){const{filters:t,kernelSize:n,strides:s,padding:i,dataFormat:o,dilationRate:a}=e;super(Object.assign({},e,{units:t}));this.filters=t,Ln(this.filters,"filters"),this.kernelSize=bc(n,2,"kernelSize"),this.kernelSize.forEach(c=>Ln(c,"kernelSize")),this.strides=bc(s||1,2,"strides"),this.strides.forEach(c=>Ln(c,"strides")),this.padding=i||"valid",Rs(this.padding),this.dataFormat=o||"channelsLast",jt(this.dataFormat),this.dilationRate=bc(a||1,2,"dilationRate"),this.dilationRate.forEach(c=>Ln(c,"dilationRate"))}build(e){var t;e=Nt(e);const n=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[n]==null)throw new q(`The channel dimension of the input should be defined. Found ${e[n]}`);const s=e[n],i=4,o=this.kernelSize.concat([s,this.filters*i]);this.kernel=this.addWeight("kernel",o,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint);const a=this.kernelSize.concat([this.filters,this.filters*i]);if(this.recurrentKernel=this.addWeight("recurrent_kernel",a,null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias){let c;if(this.unitForgetBias){const h=this.biasInitializer,p=this.filters;c=new(t=class extends Vs{apply(y,b){const w=h.apply([p]),L=ti([p]),T=h.apply([p*2]);return Mw([w,L,T])}},t.className="CustomInit",t)}else c=this.biasInitializer;this.bias=this.addWeight("bias",[this.filters*i],null,c,this.biasRegularizer,!0,this.biasConstraint)}this.built=!0}call(e,t){return ee(()=>{if(e.length!==3)throw new q(`ConvLSTM2DCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);const n=t.training||!1,s=e[0],i=e[1],o=e[2],a=4;0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=io({ones:()=>Wn(s),rate:this.dropout,training:n,count:a}));const c=this.dropoutMask,h=(Le,Se,xe)=>!Se||!Se[xe]?Le:X(Se[xe],Le);let p=h(s,c,0),m=h(s,c,1),y=h(s,c,2),b=h(s,c,3);0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=io({ones:()=>Wn(i),rate:this.recurrentDropout,training:n,count:a}));const w=this.recurrentDropoutMask;let L=h(i,w,0),T=h(i,w,1),v=h(i,w,2),C=h(i,w,3);const O=3,[D,k,F,B]=ps(this.kernel.read(),a,O),[$,Y,j,Z]=this.useBias?ps(this.bias.read(),a):[null,null,null,null];p=this.inputConv(p,D,$,this.padding),m=this.inputConv(m,k,Y,this.padding),y=this.inputConv(y,F,j,this.padding),b=this.inputConv(b,B,Z,this.padding);const[re,de,he,ue]=ps(this.recurrentKernel.read(),a,O);L=this.recurrentConv(L,re),T=this.recurrentConv(T,de),v=this.recurrentConv(v,he),C=this.recurrentConv(C,ue);const me=this.recurrentActivation.apply(be(p,L)),ce=this.recurrentActivation.apply(be(m,T)),ye=be(X(ce,o),X(me,this.activation.apply(be(y,v)))),pe=X(this.recurrentActivation.apply(be(b,C)),this.activation.apply(ye));return[pe,pe,ye]})}getConfig(){const e=super.getConfig(),{units:t}=e,n=GV(e,["units"]),s={filters:this.filters,kernelSize:this.kernelSize,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,strides:this.strides};return Object.assign({},n,s)}inputConv(e,t,n,s){const i=sr(e,t,this.strides,s||"valid",this.dataFormat==="channelsFirst"?"NCHW":"NHWC",this.dilationRate);return n?Fi(i,n,this.dataFormat):i}recurrentConv(e,t){const n=1;return sr(e,t,n,"same",this.dataFormat==="channelsFirst"?"NCHW":"NHWC")}}Fm.className="ConvLSTM2DCell",ge(Fm);class DL extends XN{constructor(e){const t=new Fm(e);super(Object.assign({},e,{cell:t}))}static fromConfig(e,t){return new e(t)}}DL.className="ConvLSTM2D",ge(DL);class _m extends ht{constructor(e){super(e);this.rate=Math.max(Math.min(e.rate,1),0),this.noiseShape=e.noiseShape,this.seed=e.seed,this.supportsMasking=!0}getNoiseShape(e){if(this.noiseShape==null)return this.noiseShape;const t=e.shape,n=[];for(let s=0;s<this.noiseShape.length;++s)n.push(this.noiseShape[s]==null?t[s]:this.noiseShape[s]);return n}call(e,t){return ee(()=>{this.invokeCallHook(e,t);const n=Je(e);if(0<this.rate&&this.rate<1){const s=t.training==null?!1:t.training,i=this.getNoiseShape(n),o=Qh(()=>qv(n,this.rate,i,this.seed),()=>n,s);return o}return e})}getConfig(){const e={rate:this.rate,noiseShape:this.noiseShape,seed:this.seed},t=super.getConfig();return Object.assign(e,t),e}dispose(){return super.dispose()}}_m.className="Dropout",ge(_m);class kL extends _m{constructor(e){super(e);this.inputSpec=[{ndim:3}]}getNoiseShape(e){const t=e.shape;return[t[0],1,t[2]]}}kL.className="SpatialDropout1D",ge(kL);class FL extends ht{constructor(e){super(e);if(this.activation=null,this.useBias=!0,this.kernel=null,this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",e.batchInputShape==null&&e.inputShape==null&&e.inputDim!=null){let t=null;e.batchSize!=null&&(t=e.batchSize),this.batchInputShape=[t,e.inputDim]}this.units=e.units,Ln(this.units,"units"),this.activation=so(e.activation),e.useBias!=null&&(this.useBias=e.useBias),this.kernelInitializer=Pt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.biasInitializer=Pt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelConstraint=yn(e.kernelConstraint),this.biasConstraint=yn(e.biasConstraint),this.kernelRegularizer=zt(e.kernelRegularizer),this.biasRegularizer=zt(e.biasRegularizer),this.activityRegularizer=zt(e.activityRegularizer),this.supportsMasking=!0,this.inputSpec=[{minNDim:2}]}build(e){e=Nt(e);const t=e[e.length-1];this.kernel==null&&(this.kernel=this.addWeight("kernel",[t,this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint))),this.inputSpec=[{minNDim:2,axes:{[-1]:t}}],this.built=!0}computeOutputShape(e){e=Nt(e);const t=e.slice();return t[t.length-1]=this.units,t}call(e,t){return ee(()=>{this.invokeCallHook(e,t);const n=Je(e),s=Wv(this.activation.getClassName());let i;return s!=null?i=ki(n,this.kernel.read(),s,this.bias?this.bias.read():null):(i=ki(n,this.kernel.read()),this.bias!=null&&(i=Fi(i,this.bias.read())),this.activation!=null&&(i=this.activation.apply(i))),i})}getConfig(){const e={units:this.units,activation:no(this.activation),useBias:this.useBias,kernelInitializer:Kt(this.kernelInitializer),biasInitializer:Kt(this.biasInitializer),kernelRegularizer:Ct(this.kernelRegularizer),biasRegularizer:Ct(this.biasRegularizer),activityRegularizer:Ct(this.activityRegularizer),kernelConstraint:gn(this.kernelConstraint),biasConstraint:gn(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}}FL.className="Dense",ge(FL);class _L extends ht{constructor(e){e=e||{},super(e),this.inputSpec=[{minNDim:3}],this.dataFormat=e.dataFormat}computeOutputShape(e){e=Nt(e);for(const t of e.slice(1))if(t==null)throw new q(`The shape of the input to "Flatten" is not fully defined (got ${e.slice(1)}). Make sure to pass a complete "input_shape" or "batch_input_shape" argument to the first layer in your model.`);return[e[0],Zr(e,1)]}call(e,t){return ee(()=>{this.invokeCallHook(e,t);let n=Je(e);if(this.dataFormat==="channelsFirst"&&n.rank>1){const s=[0];for(let i=2;i<n.rank;++i)s.push(i);s.push(1),n=n.transpose(s)}return p3(n)})}getConfig(){const e={};this.dataFormat!=null&&(e.dataFormat=this.dataFormat);const t=super.getConfig();return Object.assign(e,t),e}}_L.className="Flatten",ge(_L);class WL extends ht{constructor(e){super(e);this.supportsMasking=!0,this.activation=so(e.activation)}call(e,t){return ee(()=>{this.invokeCallHook(e,t);const n=Je(e);return this.activation.apply(n)})}getConfig(){const e={activation:no(this.activation)},t=super.getConfig();return Object.assign(e,t),e}}WL.className="Activation",ge(WL);class $L extends ht{constructor(e){super(e);this.n=e.n,this.inputSpec=[{ndim:2}]}computeOutputShape(e){return[e[0],this.n,e[1]]}call(e,t){return ee(()=>(e=Je(e),u3(e,this.n)))}getConfig(){const e={n:this.n},t=super.getConfig();return Object.assign(e,t),e}}$L.className="RepeatVector",ge($L);class UL extends ht{constructor(e){super(e);this.targetShape=e.targetShape;for(let t=0;t<this.targetShape.length;++t)this.isUnknown(this.targetShape[t])&&(this.targetShape[t]=null)}isUnknown(e){return e<0||e==null}fixUnknownDimension(e,t){const n="Total size of new array must be unchanged.",s=t.slice();let i=1,o=null;for(let c=0;c<s.length;++c){const h=s[c];if(this.isUnknown(h))if(o===null)o=c;else throw new q("Can only specifiy one unknown dimension.");else i*=h}const a=Zr(e);if(o!==null){if(i===0||a%i!==0)throw new q(n);s[o]=a/i}else if(a!==i)throw new q(n);return s}computeOutputShape(e){let t=!1;for(let n=0;n<e.length;++n)if(this.isUnknown(e[n])){t=!0;break}return t?e.slice(0,1).concat(this.targetShape):e.slice(0,1).concat(this.fixUnknownDimension(e.slice(1),this.targetShape))}call(e,t){return ee(()=>{this.invokeCallHook(e,t);const n=Je(e),s=n.shape,i=s.slice(0,1).concat(this.fixUnknownDimension(s.slice(1),this.targetShape));return n.reshape(i)})}getConfig(){const e={targetShape:this.targetShape},t=super.getConfig();return Object.assign(e,t),e}}UL.className="Reshape",ge(UL);class BL extends ht{constructor(e){super(e);if(e.dims==null)throw new Error("Required configuration field `dims` is missing during Permute constructor call.");if(!Array.isArray(e.dims))throw new Error(`Permute constructor requires \`dims\` to be an Array, but received ${e.dims} instead.`);const t=oi(1,e.dims.length+1);if(!ie(e.dims.slice().sort(),t))throw new Error("Invalid permutation `dims`: "+JSON.stringify(e.dims)+" `dims` must contain consecutive integers starting from 1.");this.dims=e.dims,this.dimsIncludingBatch=[0].concat(this.dims),this.inputSpec=[new Sn({ndim:this.dims.length+1})]}computeOutputShape(e){e=Nt(e);const t=e.slice();return this.dims.forEach((n,s)=>{t[s+1]=e[n]}),t}call(e,t){return Ye(Je(e),this.dimsIncludingBatch)}getConfig(){const e={dims:this.dims},t=super.getConfig();return Object.assign(e,t),e}}BL.className="Permute",ge(BL);class ML extends ht{constructor(e){super(e==null?{}:e);this.supportsMasking=!0,e!=null?this.maskValue=e.maskValue==null?0:e.maskValue:this.maskValue=0}computeOutputShape(e){return e}getConfig(){const e=super.getConfig(),t={maskValue:this.maskValue};return Object.assign(t,e),t}computeMask(e,t){const n=Je(e),s=-1;return bh(qr(n,this.maskValue),s)}call(e,t){return ee(()=>{this.invokeCallHook(e,t);const n=Je(e),s=-1,i=!0,o=bh(qr(n,this.maskValue),s,i),a=n.mul(o.asType(n.dtype));return a})}}ML.className="Masking",ge(ML);class PL extends ht{constructor(e){super(e);if(this.embeddings=null,this.DEFAULT_EMBEDDINGS_INITIALIZER="randomUniform",e.batchInputShape==null&&e.inputShape==null){let t=null;e.batchSize!=null&&(t=e.batchSize),e.inputLength==null?this.batchInputShape=[t,null]:this.batchInputShape=[t].concat(Et(e.inputLength))}this.inputDim=e.inputDim,Ln(this.inputDim,"inputDim"),this.outputDim=e.outputDim,Ln(this.outputDim,"outputDim"),this.embeddingsInitializer=Pt(e.embeddingsInitializer||this.DEFAULT_EMBEDDINGS_INITIALIZER),this.embeddingsRegularizer=zt(e.embeddingsRegularizer),this.activityRegularizer=zt(e.activityRegularizer),this.embeddingsConstraint=yn(e.embeddingsConstraint),this.maskZero=e.maskZero,this.supportsMasking=e.maskZero,this.inputLength=e.inputLength}build(e){this.embeddings=this.addWeight("embeddings",[this.inputDim,this.outputDim],this.dtype,this.embeddingsInitializer,this.embeddingsRegularizer,!0,this.embeddingsConstraint),this.built=!0}warnOnIncompatibleInputShape(e){}computeMask(e,t){return ee(()=>this.maskZero?(e=Je(e),qr(e,tt(e))):null)}computeOutputShape(e){if(e=Nt(e),this.inputLength==null)return[...e,this.outputDim];const t=Et(this.inputLength);if(t.length!==e.length-1)throw new q(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);{let n=0;for(let s=0;s<t.length;++s){const i=t[s],o=e[s+1];if(i!=null&&o!=null&&i!==o)throw new q(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);i==null&&(t[n]=o),n++}}return[e[0],...t,this.outputDim]}call(e,t){return ee(()=>{this.invokeCallHook(e,t);let n=Je(e);n.dtype!=="int32"&&(n=Xh(n,"int32"));const s=Hv(this.embeddings.read(),n.as1D());return s.reshape(Nt(this.computeOutputShape(n.shape)))})}getConfig(){const e={inputDim:this.inputDim,outputDim:this.outputDim,embeddingsInitializer:Kt(this.embeddingsInitializer),embeddingsRegularizer:Ct(this.embeddingsRegularizer),activityRegularizer:Ct(this.activityRegularizer),embeddingsConstraint:gn(this.embeddingsConstraint),maskZero:this.maskZero,inputLength:this.inputLength},t=super.getConfig();return Object.assign(e,t),e}}PL.className="Embedding",ge(PL);class ea extends ht{constructor(e){super(e||{});this.supportsMasking=!0}mergeFunction(e){throw new ze}computeElementwiseOpOutputShape(e,t){if(e==null||t==null)return null;if(e.length<t.length)return this.computeElementwiseOpOutputShape(t,e);if(t.length===0)return e;const n=e.slice(0,e.length-t.length);for(let s=0;s<t.length;++s){const i=e[e.length-t.length+s],o=t[s];if(i==null||o==null||i<0||o<0)n.push(null);else if(i===1)n.push(o);else if(o===1)n.push(i);else{if(i!==o)throw new q("Operands could not be broadcast together with shapes "+JSON.stringify(e)+" "+JSON.stringify(t));n.push(i)}}return n}build(e){if(Array.isArray(e)&&!Array.isArray(e[0])&&(e=[Nt(e)]),e=e,e.length<2)throw new q(`A merge layer should be called on an Array of at least 2 inputs. Got ${e.length} input(s).`);let t=[];for(const i of e)i!=null&&i[0]!==null&&t.push(i[0]);if(t=Jr(t),t.length>1)throw new q(`Can not merge tensors with different batch sizes. Got tensors with shapes: ${JSON.stringify(e)}.`);let n=e[0]==null?null:e[0].slice(1);for(let i=1;i<e.length;++i){const o=e[i]==null?null:e[i].slice(1);n=this.computeElementwiseOpOutputShape(n,o)}const s=e.map(i=>i.length);e.indexOf(null)===-1&&Jr(s).length===1?this.reshapeRequired=!1:this.reshapeRequired=!0}call(e,t){return ee(()=>{if(e=e,this.reshapeRequired){const n=[],s=e.map(i=>i.rank);if(s.indexOf(null)===-1){const i=Qr(s);for(let o of e){const a=o.rank;for(let c=0;c<i-a;++c)o=Jh(o,1);n.push(o)}return this.mergeFunction(n)}else{let i=!1;for(const c of e){const h=c.rank;if(h==null){const p=c.shape,m=p[0],y=p.slice(1).concat([m]);let b=c.reshape([m].concat(Zr(p.slice(1))));b=Ye(b,[1,0]),b=b.reshape(y),n.push(b),i=!0}else if(h>1){const p=oi(1,h).concat([0]);n.push(Ye(c,p)),i=!0}else n.push(c)}let o=this.mergeFunction(n);const a=o.rank;if(i){if(a==null){const c=o.shape,h=c.length,p=c[h-1],m=[p].concat(c.slice(0,c.length-1));o=Ye(o.reshape([-1,p]),[1,0]).reshape(m)}else if(a>1){const c=[a-1].concat(oi(0,a-1));o=Ye(o,c)}}return o}}else return this.mergeFunction(e)})}computeOutputShape(e){e=e;let t;e[0]==null?t=null:t=e[0].slice(1);for(let s=1;s<e.length;++s){const i=e[s]==null?null:e[s].slice(1);t=this.computeElementwiseOpOutputShape(t,i)}let n=[];for(const s of e)s!=null&&s[0]!==null&&n.push(s[0]);return n=Jr(n),n.length===1?t=n.concat(t):t=[null].concat(t),t}computeMask(e,t){return ee(()=>{if(t==null)return null;if(!Array.isArray(t))throw new q("`mask` should be an Array");if(!Array.isArray(e))throw new q("`inputs` should be an Array");if(t.length!==e.length)throw new q(`The Array 'inputs' and 'mask' are expected to have the same length, but have different lengths (${e.length} vs ${t.length})`);if(t.every(s=>s==null))return null;t=t.map(s=>s==null?s:ts(s,0));let n=t[0];for(let s=1;s<t.length-1;++s)n=Ps(n,t[s]);return n})}}class cu extends ea{constructor(e){super(e)}mergeFunction(e){return ee(()=>{let t=e[0].clone();for(let n=1;n<e.length;++n)t=be(t,e[n]);return t})}}cu.className="Add",ge(cu);function fne(e){if(Array.isArray(e)){const t=new cu({});return t.apply(e)}else return new cu(e)}class lu extends ea{constructor(e){super(e)}mergeFunction(e){return ee(()=>{let t=e[0].clone();for(let n=1;n<e.length;++n)t=X(t,e[n]);return t})}}lu.className="Multiply",ge(lu);function gne(e){if(Array.isArray(e)){const t=new lu({});return t.apply(e)}else return new lu(e)}class hu extends ea{constructor(e){super(e)}mergeFunction(e){return ee(()=>{let t=e[0].clone();for(let n=1;n<e.length;++n)t=be(t,e[n]);return X(1/e.length,t)})}}hu.className="Average",ge(hu);function yne(e){if(Array.isArray(e)){const t=new hu({});return t.apply(e)}else return new hu(e)}class uu extends ea{constructor(e){super(e)}mergeFunction(e){return ee(()=>{let t=e[0];for(let n=1;n<e.length;++n)t=Ms(t,e[n]);return t})}}uu.className="Maximum",ge(uu);function bne(e){if(Array.isArray(e)){const t=new uu({});return t.apply(e)}else return new uu(e)}class du extends ea{constructor(e){super(e)}mergeFunction(e){return ee(()=>{let t=e[0];for(let n=1;n<e.length;++n)t=Po(t,e[n]);return t})}}du.className="Minimum",ge(du);function wne(e){if(Array.isArray(e)){const t=new du({});return t.apply(e)}else return new du(e)}class pu extends ea{constructor(e){super(e);this.DEFAULT_AXIS=-1,e==null&&(e={}),this.axis=e.axis==null?this.DEFAULT_AXIS:e.axis,this.supportsMasking=!0,this.reshapeRequired=!1}build(e){if(!(Array.isArray(e)&&Array.isArray(e[0]))||e.length===1)throw new q("A `Concatenate` layer should be called on a list of at least 2 inputs");e=e;let t=!0;for(const s of e)if(s!=null){t=!1;break}if(t)return;const n=[];for(let s=0;s<e.length;++s){const i=e[s].slice();i.splice(this.axis,1);let o=!1;for(const a of n)if(ie(a,i)){o=!0;break}o||n.push(i)}if(n.length>1)throw new q("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(e))}mergeFunction(e){return ee(()=>Mw(e,this.axis))}computeOutputShape(e){if(!(Array.isArray(e)&&Array.isArray(e[0])))throw new q("A `Concatenate` layer should be called on a list of inputs.");const t=e,n=t[0].slice(),s=this.axis<0?n.length+this.axis:this.axis;for(const i of t.slice(1)){if(n[s]==null||i[s]==null){n[s]=null;break}n[s]+=i[s]}return n}computeMask(e,t){if(t==null)return null;if(!Array.isArray(t))throw new q("`mask` should be an array for Concatenate");if(!Array.isArray(e))throw new q("`inputs` should be an array for Concatenate");if(t.length!==e.length)throw new q(`Mismatch in the length of mask (${t.length}) and the legnth of inputs (${e.length})`);return ee(()=>{let n=!0;if(t.forEach(o=>{if(o!=null){n=!1;return}}),n)return null;const s=[];for(let o=0;o<e.length;++o)t[o]==null?s.push(Wn(e[o]).asType("bool")):t[o].rank<e[o].rank?s.push(ts(t[o],-1)):s.push(t[o]);const i=Yt(s,this.axis);return yp(i,-1,!1)})}getConfig(){const e={axis:this.axis},t=super.getConfig();return Object.assign(e,t),e}}pu.className="Concatenate",ge(pu);function Lne(e){if(Array.isArray(e)){const t=new pu({});return t.apply(e)}else return new pu(e)}function mu(e,t){for(;e<0;)e+=t;return e}function YV(e,t,n){if(e.shape.length>3||t.shape.length>3)throw new ze("batchDot is not implemented for tensors of 4D or higher rank yet");if(A(e.shape.length>=2,()=>`batchDot requires the rank of x to be >= 2, but got ${e.shape.length}`),A(e.shape.length>=2,()=>`batchDot requires the rank of y to be >= 2, but got ${t.shape.length}`),typeof n=="number"&&(n=[n,n]),e.dtype==="complex64"||t.dtype==="complex64")throw new ze("batchDot is not implemented for complex64-type Tensors yet.");const s=e.shape.length,i=t.shape.length;n==null&&(n=[s-1,i-2]);const o=n;return ee(()=>{let a;if(s>i){a=s-i;const h=[];for(let p=0;p<a;++p)h.push(1);t=t.reshape(t.shape.concat(h))}else if(i>s){a=i-s;const h=[];for(let p=0;p<a;++p)h.push(1);e=e.reshape(e.shape.concat(h))}else a=0;let c;if(e.shape.length===2&&t.shape.length===2)o[0]===o[1]?c=e.mul(t).sum(o[0]):c=e.transpose([1,0]).mul(t).sum(o[1]);else{const h=o[0]!==e.shape.length-1,p=o[1]===t.shape.length-1;c=e.matMul(t,h,p)}if(a>0){let h;s>i?h=s+i-3:h=s-1;const p=[];for(let m=h;m<h+a;++m)p.push(m);c=c.squeeze(p)}return c.shape.length===1&&(c=c.expandDims(1)),c})}class zL extends ea{constructor(e){super(e);this.axes=e.axes,this.normalize=e.normalize==null?!1:e.normalize,this.supportsMasking=!0,this.reshapeRequired=!1}build(e){A(Array.isArray(e)&&e.length===2&&Array.isArray(e[0])&&Array.isArray(e[1]),()=>"A `Dot` layer should be called on a list of exactly 2 inputs.");const t=e[0],n=e[1];if(t.length>3||n.length>3)throw new ze("Dot layer does not support tensors of 4D or higher rank yet.");const s=this.interpretAxes(t,n);if(t[s[0]]!==n[s[1]])throw new q(`Dimension incompatibility: ${t[s[0]]} !== ${n[s[1]]}`)}mergeFunction(e){if(e.length!==2)throw new q(`A \`Dot\` layer must be called on exactly 2 inputs, but received ${e.length} input(s).`);let t=e[0],n=e[1],s;return Array.isArray(this.axes)?s=this.axes.map((i,o)=>mu(i,e[o].shape.length)):s=[mu(this.axes,t.shape.length),mu(this.axes,n.shape.length)],this.normalize&&(t=wm(t,s[0]),n=wm(n,s[1])),YV(t,n,s)}interpretAxes(e,t){let n;return Array.isArray(this.axes)?n=this.axes:n=[mu(this.axes,e.length),mu(this.axes,t.length)],n}computeOutputShape(e){A(Array.isArray(e)&&e.length===2&&Array.isArray(e[0])&&Array.isArray(e[1]),()=>"A `Dot` layer should be called on a list of exactly 2 inputs.");const t=e[0].slice(),n=e[1].slice();if(t.length>3||n.length>3)throw new ze("Dot layer does not support tensors of 4D or higher rank yet.");const s=this.interpretAxes(t,n);t.splice(s[0],1),n.splice(s[1],1),n.splice(0,1);const i=t.concat(n);return i.length===1&&i.push(1),i}computeMask(e,t){return null}getConfig(){const e={axes:this.axes,normalize:this.normalize},t=super.getConfig();return Object.assign(e,t),e}}zL.className="Dot",ge(zL);class VL extends ht{constructor(e){super(e);this.supportsMasking=!0,this.stddev=e.stddev}computeOutputShape(e){return e}getConfig(){const e=super.getConfig(),t={stddev:this.stddev};return Object.assign(t,e),t}call(e,t){return ee(()=>{this.invokeCallHook(e,t);const n=Je(e),s=()=>om(n.shape,0,this.stddev).add(n),i=Qh(s,()=>n,t.training||!1);return i})}}VL.className="GaussianNoise",ge(VL);class GL extends ht{constructor(e){super(e);this.supportsMasking=!0,this.rate=e.rate}computeOutputShape(e){return e}getConfig(){const e=super.getConfig(),t={rate:this.rate};return Object.assign(t,e),t}call(e,t){return ee(()=>{this.invokeCallHook(e,t);const n=Je(e);if(this.rate>0&&this.rate<1){const s=()=>{const i=Math.sqrt(this.rate/(1-this.rate));return n.mul(om(n.shape,1,i))};return Qh(s,()=>n,t.training||!1)}return n})}}GL.className="GaussianDropout",ge(GL);class YL extends ht{constructor(e){super(e);this.supportsMasking=!0,this.rate=e.rate,this.noiseShape=e.noiseShape}_getNoiseShape(e){return this.noiseShape||Je(e).shape}computeOutputShape(e){return e}getConfig(){const e=super.getConfig(),t={rate:this.rate};return Object.assign(t,e),t}call(e,t){return ee(()=>{if(this.rate<1&&this.rate>0){const n=this._getNoiseShape(e),s=()=>{const i=Je(e),o=1.6732632423543772,a=1.0507009873554805,c=-o*a;let h=ir(Go(n),this.rate);h=Xh(h,"float32");const p=((1-this.rate)*(1+this.rate*c**2))**-.5,m=-p*c*this.rate,y=i.mul(h).add(h.add(-1).mul(c));return y.mul(p).add(m)};return Qh(s,()=>Je(e),t.training||!1)}return e})}}YL.className="AlphaDropout",ge(YL);function fu(e,t,n,s,i,o=.001){let a;if(e.rank===2)a=SA(e,t,n,s,i,o);else if(e.rank===3)a=IA(e,t,n,s,i,o);else if(e.rank===4)a=xA(e,t,n,s,i,o);else throw new ze(`batchNormalization is not implemented for array of rank ${e.rank} yet`);return a}function HV(e,t,n,s,i=.001){return ee(()=>{const o=kp(e,s),a=o.mean,c=o.variance,h=fu(e,a,c,n,t,i);return[h,a,c]})}function qV(e,t,n,s,i=.001){return ee(()=>{const o=kp(e,s),a=o.mean,c=o.variance,h=[];for(const L of oi(0,e.rank))s.indexOf(L)!==-1?h.push(1):h.push(e.shape[L]);const p=a.reshape(h),m=c.reshape(h),y=t==null?null:t.reshape(h),b=n==null?null:n.reshape(h),w=fu(e,p,m,b,y,i);return[w,a,c]})}function jV(e,t,n,s,i=.001){return ie(s.slice().sort(),oi(0,e.rank-1))?HV(e,t,n,s,i):qV(e,t,n,s,i)}class HL extends ht{constructor(e){e==null&&(e={}),super(e),this.supportsMasking=!0,this.axis=e.axis==null?-1:e.axis,this.momentum=e.momentum==null?.99:e.momentum,this.epsilon=e.epsilon==null?.001:e.epsilon,this.center=e.center==null?!0:e.center,this.scale=e.scale==null?!0:e.scale,this.betaInitializer=Pt(e.betaInitializer||"zeros"),this.gammaInitializer=Pt(e.gammaInitializer||"ones"),this.movingMeanInitializer=Pt(e.movingMeanInitializer||"zeros"),this.movingVarianceInitializer=Pt(e.movingVarianceInitializer||"ones"),this.betaConstraint=yn(e.betaConstraint),this.gammaConstraint=yn(e.gammaConstraint),this.betaRegularizer=zt(e.betaRegularizer),this.gammaRegularizer=zt(e.gammaRegularizer)}build(e){e=Nt(e);const t=this.axis>=0?this.axis:this.axis+e.length,n=e[t];if(n==null)throw new q(`Axis ${t} of input tensor should have a defined dimension but the layer received an input with shape ${JSON.stringify(e)}.`);this.inputSpec=[new Sn({ndim:e.length,axes:{[t]:n}})];const s=[n];this.scale&&(this.gamma=this.addWeight("gamma",s,null,this.gammaInitializer,this.gammaRegularizer,!0,this.gammaConstraint)),this.center&&(this.beta=this.addWeight("beta",s,null,this.betaInitializer,this.betaRegularizer,!0,this.betaConstraint)),this.movingMean=this.addWeight("moving_mean",s,null,this.movingMeanInitializer,null,!1),this.movingVariance=this.addWeight("moving_variance",s,null,this.movingVarianceInitializer,null,!1),this.built=!0}call(e,t){return ee(()=>{const n=t.training==null?!1:t.training,s=Je(e),i=s.shape,o=i.length,a=oi(0,o),c=this.axis>=0?this.axis:this.axis+o;a.splice(c,1);const h=jo(1,o);h[c]=i[c];const p=a.slice();p.sort();const m=!ie(p,oi(0,o).slice(0,o-1)),y=()=>{if(m){const C=this.movingMean.read().reshape(h),O=this.movingVariance.read().reshape(h),D=this.center?this.beta.read().reshape(h):null,k=this.scale?this.gamma.read().reshape(h):null;return fu(s,C,O,D,k,this.epsilon)}else return fu(s,this.movingMean.read(),this.movingVariance.read(),this.beta==null?null:this.beta.read(),this.gamma==null?null:this.gamma.read(),this.epsilon)};if(!n)return y();const[b,w,L]=jV(s,this.gamma.read(),this.beta.read(),a,this.epsilon),T=(C,O,D)=>{ee(()=>{const k=1-D,F=C.read(),B=F.sub(O).mul(k);C.write(F.sub(B))})},v=()=>{T(this.movingMean,w,this.momentum),T(this.movingVariance,L,this.momentum)};return v(),b})}getConfig(){const e={axis:this.axis,momentum:this.momentum,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:Kt(this.betaInitializer),gammaInitializer:Kt(this.gammaInitializer),movingMeanInitializer:Kt(this.movingMeanInitializer),movingVarianceInitializer:Kt(this.movingVarianceInitializer),betaRegularizer:Ct(this.betaRegularizer),gammaRegularizer:Ct(this.gammaRegularizer),betaConstraint:gn(this.betaConstraint),gammaConstraint:gn(this.gammaConstraint)},t=super.getConfig();return Object.assign(e,t),e}}HL.className="BatchNormalization",ge(HL);class qL extends ht{constructor(e){if(e==null&&(e={}),super(e),this.axis=e.axis==null?-1:e.axis,typeof this.axis=="number"){if(!Number.isInteger(this.axis))throw new Error(`Expected axis to be an integer, but received ${this.axis}`)}else if(Array.isArray(this.axis)){for(const t of this.axis)if(!Number.isInteger(t))throw new Error(`Expected axis to be an array of integers, but received ${JSON.stringify(this.axis)}`)}else throw new Error(`Expected axis to be an integer or an array of integers, but received ${JSON.stringify(this.axis)}`);this.epsilon=e.epsilon==null?.001:e.epsilon,this.center=e.center==null?!0:e.center,this.scale=e.scale==null?!0:e.scale,this.betaInitializer=Pt(e.betaInitializer||"zeros"),this.gammaInitializer=Pt(e.gammaInitializer||"ones"),this.betaRegularizer=zt(e.betaRegularizer),this.gammaRegularizer=zt(e.gammaRegularizer),this.supportsMasking=!0}build(e){e=Nt(e);const t=e.length;typeof this.axis=="number"&&(this.axis=[this.axis]);for(let i=0;i<this.axis.length;++i)this.axis[i]<0&&(this.axis[i]+=t);for(const i of this.axis)if(i<0||i>=t)throw new Error(`Invalid axis: ${i}`);if(this.axis.length!==Jr(this.axis).length)throw new Error(`Found duplicate axes in: ${this.axis}`);const n=this.axis.map(i=>e[i]),s=!0;this.scale?this.gamma=this.addWeight("gamma",n,"float32",this.gammaInitializer,this.gammaRegularizer,s):this.gamma=null,this.center?this.beta=this.addWeight("beta",n,"float32",this.betaInitializer,this.betaRegularizer,s):this.beta=null,this.built=!0}call(e,t){const n=Je(e),s=n.shape,i=s.length;return ee(()=>{const o=!0;let{mean:a,variance:c}=kp(n,this.axis,o);const h=jo(1,i);for(const L of this.axis)h[L]=s[L];const p=L=>L!=null&&L.shape.length!==i&&this.axis!==[i-1]?L.reshape(h):L;let m=p(this.gamma.read()),y=p(this.beta.read());const b=[],w=[];for(let L=0;L<i;++L)this.axis.indexOf(L)!==-1?(b.push(s[L]),w.push(1)):(b.push(1),w.push(s[L]));return a=a.tile(b),c=c.tile(b),m=m.tile(w),y=y.tile(w),fu(n,a,c,y,m,this.epsilon)})}getConfig(){const e={axis:this.axis,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:Kt(this.betaInitializer),gammaInitializer:Kt(this.gammaInitializer),betaRegularizer:Ct(this.betaRegularizer),gammaRegularizer:Ct(this.gammaRegularizer)},t=super.getConfig();return Object.assign(e,t),e}}qL.className="LayerNormalization",ge(qL);function Sne(e,t){return ee(()=>{if(e.rank!==3)throw new q(`temporalPadding expects input tensor to be 3-D, but received a ${e.rank}-D tensor.`);if(t==null&&(t=[1,1]),t.length!==2)throw new q(`temporalPadding expects input padding pattern to be a length-2 array, but received a length-${t.length} array.`);const n=[[0,0],t,[0,0]];return Ei(e,n)})}function KV(e,t,n){return ee(()=>{if(e.rank!==4)throw new q(`temporalPadding expects input tensor to be 4-D, but received a ${e.rank}-D tensor.`);if(t==null&&(t=[[1,1],[1,1]]),t.length!==2||t[0].length!==2||t[1].length!==2)throw new q("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");if(n==null&&(n=ii()),n!=="channelsLast"&&n!=="channelsFirst")throw new q(`Unknown data format: ${n}. Supported data formats are 'channelsLast' and 'channelsFirst.`);let s;return n==="channelsFirst"?s=[[0,0],[0,0],t[0],t[1]]:s=[[0,0],t[0],t[1],[0,0]],Ei(e,s)})}class jL extends ht{constructor(e){if(e==null&&(e={}),super(e),this.dataFormat=e.dataFormat==null?ii():e.dataFormat,e.padding==null)this.padding=[[1,1],[1,1]];else if(typeof e.padding=="number")this.padding=[[e.padding,e.padding],[e.padding,e.padding]];else{if(e.padding=e.padding,e.padding.length!==2)throw new q(`ZeroPadding2D expects padding to be a length-2 array, but received a length-${e.padding.length} array.`);let t,n;if(typeof e.padding[0]=="number")t=[e.padding[0],e.padding[0]],n=[e.padding[1],e.padding[1]];else{if(e.padding=e.padding,e.padding[0].length!==2)throw new q(`ZeroPadding2D expects height padding to be a length-2 array, but received a length-${e.padding[0].length} array.`);if(t=e.padding[0],e.padding[1].length!==2)throw new q(`ZeroPadding2D expects width padding to be a length-2 array, but received a length-${e.padding[1].length} array.`);n=e.padding[1]}this.padding=[t,n]}this.inputSpec=[new Sn({ndim:4})]}computeOutputShape(e){e=Nt(e);let t,n;return this.dataFormat==="channelsFirst"?(e[2]!=null&&e[2]>=0?t=e[2]+this.padding[0][0]+this.padding[0][1]:t=null,e[3]!=null&&e[3]>=0?n=e[3]+this.padding[1][0]+this.padding[1][1]:n=null,[e[0],e[1],t,n]):(e[1]!=null&&e[1]>=0?t=e[1]+this.padding[0][0]+this.padding[0][1]:t=null,e[2]!=null&&e[2]>=0?n=e[2]+this.padding[1][0]+this.padding[1][1]:n=null,[e[0],t,n,e[3]])}call(e,t){return ee(()=>KV(Je(e),this.padding,this.dataFormat))}getConfig(){const e={padding:this.padding,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}jL.className="ZeroPadding2D",ge(jL);function Wm(e,t,n,s,i,o){return ee(()=>{jt(i),Bv(o),Rs(s),n==null&&(n=[1,1]),s==null&&(s="valid"),i==null&&(i=ii()),o==null&&(o="max"),e=SL(e,i);let a;const c=s==="same"?"same":"valid";return o==="max"?a=Rh(e,t,n,c):a=Sh(e,t,n,c),i==="channelsFirst"&&(a=Ye(a,[0,3,1,2])),a})}function JN(e,t,n,s,i,o){return ee(()=>{jt(i),Bv(o),Rs(s),n==null&&(n=[1,1,1]),s==null&&(s="valid"),i==null&&(i=ii()),o==null&&(o="max"),e=GN(e,i);let a;const c=s==="same"?"same":"valid";return o==="max"?a=Kb(e,t,n,c):a=Wb(e,t,n,c),i==="channelsFirst"&&(a=Ye(a,[0,4,1,2,3])),a})}class ZN extends ht{constructor(e){if(e.poolSize==null&&(e.poolSize=2),super(e),typeof e.poolSize=="number")this.poolSize=[e.poolSize];else if(Array.isArray(e.poolSize)&&e.poolSize.length===1&&typeof e.poolSize[0]=="number")this.poolSize=e.poolSize;else throw new q(`poolSize for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.poolSize)}`);if(Ln(this.poolSize,"poolSize"),e.strides==null)this.strides=this.poolSize;else if(typeof e.strides=="number")this.strides=[e.strides];else if(Array.isArray(e.strides)&&e.strides.length===1&&typeof e.strides[0]=="number")this.strides=e.strides;else throw new q(`strides for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.strides)}`);Ln(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,Rs(this.padding),this.inputSpec=[new Sn({ndim:3})]}computeOutputShape(e){e=Nt(e);const t=hi(e[1],this.poolSize[0],this.padding,this.strides[0]);return[e[0],t,e[2]]}call(e,t){return ee(()=>{this.invokeCallHook(e,t),e=Jh(Je(e),2);const n=this.poolingFunction(Je(e),[this.poolSize[0],1],[this.strides[0],1],this.padding,"channelsLast");return jr(n,[2])})}getConfig(){const e={poolSize:this.poolSize,padding:this.padding,strides:this.strides},t=super.getConfig();return Object.assign(e,t),e}}class KL extends ZN{constructor(e){super(e)}poolingFunction(e,t,n,s,i){return jt(i),Rs(s),Wm(e,t,n,s,i,"max")}}KL.className="MaxPooling1D",ge(KL);class XL extends ZN{constructor(e){super(e)}poolingFunction(e,t,n,s,i){return jt(i),Rs(s),Wm(e,t,n,s,i,"avg")}}XL.className="AveragePooling1D",ge(XL);class QN extends ht{constructor(e){if(e.poolSize==null&&(e.poolSize=[2,2]),super(e),this.poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize],e.strides==null)this.strides=this.poolSize;else if(Array.isArray(e.strides)){if(e.strides.length!==2)throw new q(`If the strides property of a 2D pooling layer is an Array, it is expected to have a length of 2, but received length ${e.strides.length}.`);this.strides=e.strides}else this.strides=[e.strides,e.strides];Ln(this.poolSize,"poolSize"),Ln(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,jt(this.dataFormat),Rs(this.padding),this.inputSpec=[new Sn({ndim:4})]}computeOutputShape(e){e=Nt(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],n=this.dataFormat==="channelsFirst"?e[3]:e[2];return t=hi(t,this.poolSize[0],this.padding,this.strides[0]),n=hi(n,this.poolSize[1],this.padding,this.strides[1]),this.dataFormat==="channelsFirst"?[e[0],e[1],t,n]:[e[0],t,n,e[3]]}call(e,t){return ee(()=>(this.invokeCallHook(e,t),this.poolingFunction(Je(e),this.poolSize,this.strides,this.padding,this.dataFormat)))}getConfig(){const e={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}class JL extends QN{constructor(e){super(e)}poolingFunction(e,t,n,s,i){return jt(i),Rs(s),Wm(e,t,n,s,i,"max")}}JL.className="MaxPooling2D",ge(JL);class ZL extends QN{constructor(e){super(e)}poolingFunction(e,t,n,s,i){return jt(i),Rs(s),Wm(e,t,n,s,i,"avg")}}ZL.className="AveragePooling2D",ge(ZL);class e0 extends ht{constructor(e){if(e.poolSize==null&&(e.poolSize=[2,2,2]),super(e),this.poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize,e.poolSize],e.strides==null)this.strides=this.poolSize;else if(Array.isArray(e.strides)){if(e.strides.length!==3)throw new q(`If the strides property of a 3D pooling layer is an Array, it is expected to have a length of 3, but received length ${e.strides.length}.`);this.strides=e.strides}else this.strides=[e.strides,e.strides,e.strides];Ln(this.poolSize,"poolSize"),Ln(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,jt(this.dataFormat),Rs(this.padding),this.inputSpec=[new Sn({ndim:5})]}computeOutputShape(e){e=Nt(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],n=this.dataFormat==="channelsFirst"?e[3]:e[2],s=this.dataFormat==="channelsFirst"?e[4]:e[3];return t=hi(t,this.poolSize[0],this.padding,this.strides[0]),n=hi(n,this.poolSize[1],this.padding,this.strides[1]),s=hi(s,this.poolSize[2],this.padding,this.strides[2]),this.dataFormat==="channelsFirst"?[e[0],e[1],t,n,s]:[e[0],t,n,s,e[4]]}call(e,t){return ee(()=>(this.invokeCallHook(e,t),this.poolingFunction(Je(e),this.poolSize,this.strides,this.padding,this.dataFormat)))}getConfig(){const e={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}class QL extends e0{constructor(e){super(e)}poolingFunction(e,t,n,s,i){return jt(i),Rs(s),JN(e,t,n,s,i,"max")}}QL.className="MaxPooling3D",ge(QL);class eS extends e0{constructor(e){super(e)}poolingFunction(e,t,n,s,i){return jt(i),Rs(s),JN(e,t,n,s,i,"avg")}}eS.className="AveragePooling3D",ge(eS);class t0 extends ht{constructor(e){super(e);this.inputSpec=[new Sn({ndim:3})]}computeOutputShape(e){return[e[0],e[2]]}call(e,t){throw new ze}}class tS extends t0{constructor(e){super(e||{})}call(e,t){return ee(()=>{const n=Je(e);return qt(n,1)})}}tS.className="GlobalAveragePooling1D",ge(tS);class nS extends t0{constructor(e){super(e||{})}call(e,t){return ee(()=>{const n=Je(e);return ns(n,1)})}}nS.className="GlobalMaxPooling1D",ge(nS);class n0 extends ht{constructor(e){super(e);this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,jt(this.dataFormat),this.inputSpec=[new Sn({ndim:4})]}computeOutputShape(e){return e=e,this.dataFormat==="channelsLast"?[e[0],e[3]]:[e[0],e[1]]}call(e,t){throw new ze}getConfig(){const e={dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}class sS extends n0{call(e,t){return ee(()=>{const n=Je(e);return this.dataFormat==="channelsLast"?qt(n,[1,2]):qt(n,[2,3])})}}sS.className="GlobalAveragePooling2D",ge(sS);class iS extends n0{call(e,t){return ee(()=>{const n=Je(e);return this.dataFormat==="channelsLast"?ns(n,[1,2]):ns(n,[2,3])})}}iS.className="GlobalMaxPooling2D",ge(iS);class s0 extends ht{constructor(e){super(e);this.layer=e.layer}build(e){this.built=!0}get trainable(){return this.layer!=null?this.layer.trainable:!1}set trainable(e){this.layer!=null&&(this.layer.trainable=e)}get trainableWeights(){return this.layer.trainableWeights}get nonTrainableWeights(){return this.layer.nonTrainableWeights}get updates(){return this.layer._updates}get losses(){return this.layer.losses}getWeights(){return this.layer.getWeights()}setWeights(e){this.layer.setWeights(e)}getConfig(){const e={layer:{className:this.layer.getClassName(),config:this.layer.getConfig()}},t=super.getConfig();return Object.assign(e,t),e}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),this.layer!=null&&this.layer.setFastWeightInitDuringBuild(e)}static fromConfig(e,t,n={}){const s=t.layer,i=li(s,n);delete t.layer;const o={layer:i};return Object.assign(o,t),new e(o)}}class rS extends s0{constructor(e){super(e);this.supportsMasking=!0}build(e){if(e=Nt(e),e.length<3)throw new q(`TimeDistributed layer expects an input shape >= 3D, but received input shape ${JSON.stringify(e)}`);this.inputSpec=[{shape:e}];const t=[e[0]].concat(e.slice(2));this.layer.built||(this.layer.build(t),this.layer.built=!0),super.build(e)}computeOutputShape(e){e=Nt(e);const t=[e[0]].concat(e.slice(2)),n=this.layer.computeOutputShape(t),s=e[1];return[n[0],s].concat(n.slice(1))}call(e,t){return ee(()=>{e=Je(e);const n=(o,a)=>{const c=Je(this.layer.call(o,t));return[c,[]]},s=KN(n,e,[],!1,null,null,!1,!0),i=s[1];return i})}}rS.className="TimeDistributed",ge(rS);function XV(e){uc(r3,"BidirectionalMergeMode",e)}const JV="concat";class oS extends s0{constructor(e){super(e);const t=e.layer.getConfig(),n={};n.className=e.layer.getClassName(),n.config=t,this.forwardLayer=li(n),t.goBackwards=!(t.goBackwards===!0);const s={};if(s.className=e.layer.getClassName(),s.config=t,this.backwardLayer=li(s),this.forwardLayer.name="forward_"+this.forwardLayer.name,this.backwardLayer.name="backward_"+this.backwardLayer.name,this.mergeMode=e.mergeMode===void 0?JV:e.mergeMode,XV(this.mergeMode),e.weights)throw new ze("weights support is not implemented for Bidirectional layer yet.");this._stateful=e.layer.stateful,this.returnSequences=e.layer.returnSequences,this.returnState=e.layer.returnState,this.supportsMasking=!0,this._trainable=!0,this.inputSpec=e.layer.inputSpec,this.numConstants=null}get trainable(){return this._trainable}set trainable(e){this._trainable=e,this.forwardLayer!=null&&(this.forwardLayer.trainable=e),this.backwardLayer!=null&&(this.backwardLayer.trainable=e)}getWeights(){return this.forwardLayer.getWeights().concat(this.backwardLayer.getWeights())}setWeights(e){const t=e.length,n=Math.floor(t/2);this.forwardLayer.setWeights(e.slice(0,n)),this.backwardLayer.setWeights(e.slice(n))}computeOutputShape(e){let t=this.forwardLayer.computeOutputShape(e);Array.isArray(t)&&Array.isArray(t[0])||(t=[t]),t=t;let n,s,i;return this.returnState&&(i=t.slice(1)),n=t[0],n=n,this.mergeMode==="concat"?(n[n.length-1]*=2,s=[n]):this.mergeMode==null?s=[n,n.slice()]:s=[n],this.returnState?this.mergeMode==null?s.concat(i).concat(i.slice()):[n].concat(i).concat(i.slice()):is(s)}apply(e,t){let n=t==null?null:t.initialState,s=t==null?null:t.constants;t==null&&(t={});const i=jN(e,n,s,this.numConstants);if(e=i.inputs,n=i.initialState,s=i.constants,Array.isArray(e)&&(n=e.slice(1),e=e[0]),(n==null||n.length===0)&&s==null)return super.apply(e,t);const o=[],a=[];if(n!=null){const h=n.length;if(h%2>0)throw new q("When passing `initialState` to a Bidrectional RNN, the state should be an Array containing the states of the underlying RNNs.");t.initialState=n,o.push(...n);const p=n.map(m=>new Sn({shape:m.shape}));this.forwardLayer.stateSpec=p.slice(0,h/2),this.backwardLayer.stateSpec=p.slice(h/2),a.push(...p)}if(s!=null)throw new ze("Support for constants in Bidirectional layers is not implemented yet.");const c=o[0]instanceof ci;for(const h of o)if(h instanceof ci!==c)throw new q("The initial state of a Bidirectional layer cannot be specified as a mix of symbolic and non-symbolic tensors");if(c){const h=[e].concat(o),p=this.inputSpec.concat(a),m=this.inputSpec;this.inputSpec=p;const y=super.apply(h,t);return this.inputSpec=m,y}else return super.apply(e,t)}call(e,t){return ee(()=>{const n=t.initialState;let s,i;if(n==null)s=this.forwardLayer.call(e,t),i=this.backwardLayer.call(e,t);else{const c=n.slice(0,n.length/2),h=n.slice(n.length/2);s=this.forwardLayer.call(e,Object.assign(t,{initialState:c})),i=this.backwardLayer.call(e,Object.assign(t,{initialState:h}))}let o;this.returnState&&(Array.isArray(s)&&(o=s.slice(1).concat(i.slice(1))),s=s[0],i=i[0]),this.returnSequences&&(i=Ns(i,1));let a;return this.mergeMode==="concat"?a=Mw([s,i]):this.mergeMode==="sum"?a=be(s,i):this.mergeMode==="ave"?a=X(.5,be(s,i)):this.mergeMode==="mul"?a=X(s,i):this.mergeMode==null&&(a=[s,i]),this.returnState?this.mergeMode==null?a.concat(o):[a].concat(o):a})}resetStates(e){this.forwardLayer.resetStates(),this.backwardLayer.resetStates()}build(e){Xo(this.forwardLayer.name,()=>{this.forwardLayer.build(e)}),Xo(this.backwardLayer.name,()=>{this.backwardLayer.build(e)}),this.built=!0}computeMask(e,t){Array.isArray(t)&&(t=t[0]);let n;if(this.returnSequences?this.mergeMode==null?n=[t,t]:n=t:this.mergeMode==null?n=[null,null]:n=null,this.returnState){const s=this.forwardLayer.states,i=s.map(o=>null);return Array.isArray(n)?n.concat(i).concat(i):[n].concat(i).concat(i)}else return n}get trainableWeights(){return this.forwardLayer.trainableWeights.concat(this.backwardLayer.trainableWeights)}get nonTrainableWeights(){return this.forwardLayer.nonTrainableWeights.concat(this.backwardLayer.nonTrainableWeights)}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),this.forwardLayer!=null&&this.forwardLayer.setFastWeightInitDuringBuild(e),this.backwardLayer!=null&&this.backwardLayer.setFastWeightInitDuringBuild(e)}getConfig(){const e={mergeMode:this.mergeMode},t=super.getConfig();return Object.assign(e,t),e}static fromConfig(e,t){const n=li(t.layer);if(delete t.layer,t.numConstants!=null)throw new ze("Deserialization of a Bidirectional layer with numConstants present is not supported yet.");const s=t;return s.layer=n,new e(s)}}oS.className="Bidirectional",ge(oS);function ZV(e){return new mc(e)}function QV(e){return new bL(e)}function eG(e){return new fL(e)}function tG(e){return new gL(e)}function nG(e){return new yL(e)}function sG(e){return new LL(e)}function iG(e){return new wL(e)}function rG(e){return new Om(e)}function oG(e){return new ou(e)}function aG(e){return new TL(e)}function cG(e){return new Rm(e)}function lG(e){return new AL(e)}function hG(e){return new vL(e)}function uG(e){return new NL(e)}function dG(e){return new CL(e)}function pG(e){return new WL(e)}function mG(e){return new FL(e)}function fG(e){return new _m(e)}function gG(e){return new kL(e)}function yG(e){return new _L(e)}function bG(e){return new $L(e)}function wG(e){return new UL(e)}function LG(e){return new BL(e)}function SG(e){return new PL(e)}function IG(e){return new cu(e)}function xG(e){return new hu(e)}function TG(e){return new pu(e)}function AG(e){return new uu(e)}function vG(e){return new du(e)}function NG(e){return new lu(e)}function CG(e){return new zL(e)}function RG(e){return new HL(e)}function OG(e){return new qL(e)}function EG(e){return new jL(e)}function aS(e){return new XL(e)}function DG(e){return aS(e)}function kG(e){return aS(e)}function cS(e){return new ZL(e)}function FG(e){return cS(e)}function _G(e){return cS(e)}function lS(e){return new eS(e)}function WG(e){return lS(e)}function $G(e){return lS(e)}function UG(e){return new tS(e)}function BG(e){return new sS(e)}function i0(e){return new nS(e)}function r0(e){return new iS(e)}function o0(e){return new KL(e)}function a0(e){return new JL(e)}function MG(e){return new QL(e)}function PG(e){return new OL(e)}function zG(e){return new Dm(e)}function VG(e){return new EL(e)}function GG(e){return new au(e)}function YG(e){return new RL(e)}function HG(e){return new Em(e)}function qG(e){return new DL(e)}function jG(e){return new Fm(e)}function KG(e){return new Wi(e)}function XG(e){return new km(e)}function JG(e){return new oS(e)}function ZG(e){return new rS(e)}const QG=i0,eY=r0,tY=o0,nY=a0;function sY(e){return new VL(e)}function iY(e){return new GL(e)}function rY(e){return new YL(e)}function oY(e){return new ML(e)}var aY=Object.freeze({__proto__:null,inputLayer:ZV,elu:QV,reLU:eG,leakyReLU:tG,prelu:nG,softmax:sG,thresholdedReLU:iG,conv1d:rG,conv2d:oG,conv2dTranspose:aG,conv3d:cG,separableConv2d:lG,cropping2D:hG,upSampling2d:uG,depthwiseConv2d:dG,activation:pG,dense:mG,dropout:fG,spatialDropout1d:gG,flatten:yG,repeatVector:bG,reshape:wG,permute:LG,embedding:SG,add:IG,average:xG,concatenate:TG,maximum:AG,minimum:vG,multiply:NG,dot:CG,batchNormalization:RG,layerNormalization:OG,zeroPadding2d:EG,averagePooling1d:aS,avgPool1d:DG,avgPooling1d:kG,averagePooling2d:cS,avgPool2d:FG,avgPooling2d:_G,averagePooling3d:lS,avgPool3d:WG,avgPooling3d:$G,globalAveragePooling1d:UG,globalAveragePooling2d:BG,globalMaxPooling1d:i0,globalMaxPooling2d:r0,maxPooling1d:o0,maxPooling2d:a0,maxPooling3d:MG,gru:PG,gruCell:zG,lstm:VG,lstmCell:GG,simpleRNN:YG,simpleRNNCell:HG,convLstm2d:qG,convLstm2dCell:jG,rnn:KG,stackedRNNCells:XG,bidirectional:JG,timeDistributed:ZG,globalMaxPool1d:QG,globalMaxPool2d:eY,maxPool1d:tY,maxPool2d:nY,Layer:ht,RNN:Wi,RNNCell:wc,input:CN,gaussianNoise:sY,gaussianDropout:iY,alphaDropout:rY,masking:oY});function cY(e,t){return nL(e,t)}function lY(e,t){return lN(e,t)}function hY(e,t){return hN(e,t)}function uY(e,t){return sL(e,t)}function dY(e,t){return iL(e,t)}function pY(e,t){return cN(e,t)}function mY(e,t){return eV(e,t)}function fY(e,t){return Im(e,t)}function gY(e,t){return gc(e,t)}function yY(e,t){return to(e,t)}function bY(e,t){return to(e,t)}function wY(e,t){return to(e,t)}function LY(e,t){return hr(e,t)}function SY(e,t){return hr(e,t)}function IY(e,t){return hr(e,t)}var xY=Object.freeze({__proto__:null,binaryAccuracy:cY,binaryCrossentropy:lY,sparseCategoricalAccuracy:hY,categoricalAccuracy:uY,categoricalCrossentropy:dY,precision:pY,recall:mY,cosineProximity:fY,meanAbsoluteError:gY,meanAbsolutePercentageError:yY,MAPE:bY,mape:wY,meanSquaredError:LY,MSE:SY,mse:IY});var TY=Object.freeze({__proto__:null,modelFromJSON:kV});function AY(e){return new iu(e)}function vY(e){return PV(e)}function NY(e){return zV(e)}var CY=Object.freeze({__proto__:null,l1l2:AY,l1:vY,l2:NY});class c0 extends fc{constructor(){super(...arguments);this.model=null}setModel(e){if(!(e instanceof ur))throw new Error("model must be a LayersModel, not some other Container");this.model=e}}function $m(e,t){return e<t}function l0(e,t){return e>t}class h0 extends c0{constructor(e){super();if(e==null&&(e={}),e.restoreBestWeights)throw new ze("restoreBestWeights = True is not implemented in EarlyStopping yet.");this.monitor=e.monitor||"val_loss",this.minDelta=Math.abs(e.minDelta||0),this.patience=e.patience||0,this.verbose=e.verbose||0,this.mode=e.mode||"auto",this.baseline=e.baseline,["auto","min","max"].indexOf(this.mode)===-1&&(console.warn(`EarlyStopping mode '${this.mode}' is invalid. Falling back to mode 'auto'.`),this.mode="auto"),this.mode==="min"?this.monitorFunc=$m:this.mode==="max"?this.monitorFunc=l0:this.monitor.indexOf("acc")!==-1?this.monitorFunc=l0:this.monitorFunc=$m,this.monitorFunc===$m&&(this.minDelta*=-1)}async onTrainBegin(e){this.wait=0,this.stoppedEpoch=0,this.baseline!=null?this.best=this.baseline:this.best=this.monitorFunc===$m?Infinity:-Infinity}async onEpochEnd(e,t){await eo(t);const n=this.getMonitorValue(t);if(n==null)return;this.monitorFunc(n-this.minDelta,this.best)?(this.best=n,this.wait=0):(this.wait++,this.wait>=this.patience&&(this.stoppedEpoch=e,this.model.stopTraining=!0))}async onTrainEnd(e){this.stoppedEpoch>0&&this.verbose&&console.log(`Epoch ${this.stoppedEpoch}: early stopping.`)}getMonitorValue(e){e==null&&(e={});const t=e[this.monitor];return t==null&&console.warn(`Metric for EarlyStopping ${this.monitor} is not available. Available metrics are: ${Object.keys(e)}`),t}}function RY(e){return new h0(e)}const OY={earlyStopping:RY};var ui;(function(e){e[e.DT_INVALID=0]="DT_INVALID",e[e.DT_FLOAT=1]="DT_FLOAT",e[e.DT_DOUBLE=2]="DT_DOUBLE",e[e.DT_INT32=3]="DT_INT32",e[e.DT_UINT8=4]="DT_UINT8",e[e.DT_INT16=5]="DT_INT16",e[e.DT_INT8=6]="DT_INT8",e[e.DT_STRING=7]="DT_STRING",e[e.DT_COMPLEX64=8]="DT_COMPLEX64",e[e.DT_INT64=9]="DT_INT64",e[e.DT_BOOL=10]="DT_BOOL",e[e.DT_QINT8=11]="DT_QINT8",e[e.DT_QUINT8=12]="DT_QUINT8",e[e.DT_QINT32=13]="DT_QINT32",e[e.DT_BFLOAT16=14]="DT_BFLOAT16",e[e.DT_FLOAT_REF=101]="DT_FLOAT_REF",e[e.DT_DOUBLE_REF=102]="DT_DOUBLE_REF",e[e.DT_INT32_REF=103]="DT_INT32_REF",e[e.DT_UINT8_REF=104]="DT_UINT8_REF",e[e.DT_INT16_REF=105]="DT_INT16_REF",e[e.DT_INT8_REF=106]="DT_INT8_REF",e[e.DT_STRING_REF=107]="DT_STRING_REF",e[e.DT_COMPLEX64_REF=108]="DT_COMPLEX64_REF",e[e.DT_INT64_REF=109]="DT_INT64_REF",e[e.DT_BOOL_REF=110]="DT_BOOL_REF",e[e.DT_QINT8_REF=111]="DT_QINT8_REF",e[e.DT_QUINT8_REF=112]="DT_QUINT8_REF",e[e.DT_QINT32_REF=113]="DT_QINT32_REF",e[e.DT_BFLOAT16_REF=114]="DT_BFLOAT16_REF"})(ui||(ui={}));var u0;(function(e){let t;(function(n){n[n.LEGACY=0]="LEGACY",n[n.V1=1]="V1",n[n.V2=2]="V2"})(t=e.CheckpointFormatVersion||(e.CheckpointFormatVersion={}))})(u0||(u0={}));const hS={};function EY(e,t){const n={tfOpName:e,category:"custom",inputs:[],attrs:[],customExecutor:t};hS[e]=n}function d0(e){return hS[e]}function DY(e){delete hS[e]}function R(e,t,n,s,i){const o=t.inputParams[e];if(o&&o.inputIndexStart!==void 0){const c=o.inputIndexStart,h=o.inputIndexEnd===0?void 0:o.inputIndexEnd===void 0?c+1:o.inputIndexEnd;if(o.type==="tensor")return os(t.inputNames[o.inputIndexStart],n,s,i);if(o.type==="tensors"){const y=t.inputNames.slice(c,h);return y.map(b=>os(b,n,s,i))}const p=os(t.inputNames.slice(c)[0],n,s,i),m=p.dataSync();return o.type==="number"?m[0]:xs(p.shape,m)}const a=t.attrParams[e];return a&&a.value}function os(e,t,n,s){const[i,o]=fs(e);if(s!=null){const c=s.getHashTableHandleByName(i);if(c!=null)return c}const a=n.currentContextIds.find(c=>!!t[Um(i,c)]);return a!==void 0?t[Um(i,a)][o]:void 0}function kY(e,t,n){return t[Um(e,n.currentContextId)]}function dr(e,t){const[n,s]=fs(e);return[Um(n,t&&t.currentContextId),s]}function Um(e,t){return t?`${e}-${t}`:e}function fs(e){const t=e.split(":");if(t.length===1)return[e,0];const n=t[0];return[n,Number(t[t.length-1])]}function Ine(e,t){const n=[];for(let s=0;s<e.length;s+=t)n.push(e.slice(s,s+t));return n}function Bm(e,t,n){let s=R("pad",e,t,n);if(s==="explicit"){s=R("explicitPaddings",e,t,n);const i=[[0,0],[0,0],[0,0],[0,0]];for(let o=0;o<4;o++)i[o][0]=s[o*2],i[o][1]=s[o*2+1];return i}return s}function pr(e){return e.kept?e:Pr(e)}const FY=[{tfOpName:"Add",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AddV2",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AddN",category:"arithmetic",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}]},{tfOpName:"BiasAdd",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sub",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"RealDiv",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Div",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"DivNoNan",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"FloorDiv",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Mul",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Maximum",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}]},{tfOpName:"Minimum",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}]},{tfOpName:"Pow",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SquaredDifference",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Mod",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"FloorMod",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}];var _Y=Object.freeze({__proto__:null,json:FY});const WY=[{tfOpName:"Abs",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Acos",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Asin",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atan2",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Ceil",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ClipByValue",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"clip_value_min",name:"clipValueMin",type:"number"},{tfName:"clip_value_max",name:"clipValueMax",type:"number"}]},{tfOpName:"Complex",category:"basic_math",inputs:[{start:0,name:"real",type:"tensor"},{start:1,name:"imag",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ComplexAbs",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cos",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cosh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Elu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Exp",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Floor",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Log",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Imag",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"Tout",name:"outputType",type:"dtype",notSupported:!0}]},{tfOpName:"Neg",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Real",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"Tout",name:"outputType",type:"dtype",notSupported:!0}]},{tfOpName:"Prelu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"alpha",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Relu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Relu6",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"clipValueMin",name:"clipValueMin",type:"number",defaultValue:0},{tfName:"clipValueMax",name:"clipValueMax",type:"number",defaultValue:6}]},{tfOpName:"Selu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sigmoid",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sin",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sinh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sqrt",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Rsqrt",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Square",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Tan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Tanh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sign",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Round",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Expm1",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Log1p",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Reciprocal",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Softplus",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Asinh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Acosh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atanh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Erf",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Prod",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axes",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool",notSupported:!0},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LeakyRelu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"alpha",name:"alpha",type:"number",defaultValue:.2},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}];var $Y=Object.freeze({__proto__:null,json:WY});const UY=[{tfOpName:"LoopCond",category:"control",inputs:[{start:0,name:"pred",type:"tensor"}]},{tfOpName:"Switch",category:"control",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"pred",type:"tensor"}]},{tfOpName:"Merge",category:"control",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}]},{tfOpName:"Enter",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"frame_name",name:"frameName",type:"string"},{tfName:"is_constant",name:"isConstant",type:"bool"}]},{tfOpName:"Exit",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"NextIteration",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayV3",category:"control",inputs:[{start:0,name:"size",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"dynamic_size",name:"dynamicSize",type:"bool"},{tfName:"clear_after_read",name:"clearAfterRead",type:"bool"},{tfName:"identical_element_shapes",name:"identicalElementShapes",type:"bool"},{tfName:"tensor_array_name",name:"name",type:"string"}]},{tfOpName:"TensorArrayWriteV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"tensor",type:"tensor"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayReadV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayGatherV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape",name:"elementShape",type:"shape"}]},{tfOpName:"TensorArrayScatterV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"tensor",type:"tensor"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"TensorArrayConcatV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape_except0",name:"elementShapeExcept0",type:"shape",notSupported:!0}]},{tfOpName:"TensorArraySplitV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"tensor",type:"tensor"},{start:2,name:"lengths",type:"number[]"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"TensorArraySizeV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"flowIn",type:"number"}]},{tfOpName:"TensorArrayCloseV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"}]},{tfOpName:"StatelessIf",category:"control",inputs:[{start:0,name:"cond",type:"tensor"},{start:1,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"then_branch",name:"thenBranch",type:"func"},{tfName:"else_branch",name:"elseBranch",type:"func"}]},{tfOpName:"If",category:"control",inputs:[{start:0,name:"cond",type:"tensor"},{start:1,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"then_branch",name:"thenBranch",type:"func"},{tfName:"else_branch",name:"elseBranch",type:"func"}]},{tfOpName:"StatelessWhile",category:"control",inputs:[{start:0,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"cond",name:"cond",type:"func"},{tfName:"body",name:"body",type:"func"}]},{tfOpName:"While",category:"control",inputs:[{start:0,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"cond",name:"cond",type:"func"},{tfName:"body",name:"body",type:"func"}]},{tfOpName:"TensorListScatter",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListScatterV2",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"},{start:3,name:"numElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListGather",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListGetItem",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListSetItem",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"tensor",type:"tensor"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListReserve",category:"control",inputs:[{start:0,name:"elementShape",type:"shape"},{start:1,name:"numElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListFromTensor",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListStack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"},{tfName:"num_elements",name:"numElements",type:"dtype"}]},{tfOpName:"TensorListSplit",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"elementShape",type:"shape"},{start:2,name:"lengths",type:"number[]"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListConcat",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"}],attrs:[{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListPopBack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListPushBack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"tensor",type:"tensor"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]}];var BY=Object.freeze({__proto__:null,json:UY});const MY=[{tfOpName:"AvgPool",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPool",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPoolWithArgmax",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"include_batch_in_index",name:"includeBatchInIndex",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AvgPool3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPool3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Conv1D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"stride",name:"stride",type:"number"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NWC"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"dilation",name:"dilation",type:"number",defaultValue:1}]},{tfOpName:"Conv2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"useCudnnOnGpu",name:"useCudnnOnGpu",type:"bool"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"_FusedConv2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"use_cudnn_on_gpu",name:"useCudnnOnGpu",type:"bool",defaultValue:!0},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]",defaultValue:[1,1,1,1]},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:1e-4}]},{tfOpName:"Conv2DBackpropInput",category:"convolution",inputs:[{start:2,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:0,name:"outputShape",type:"number[]"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]}]},{tfOpName:"DepthwiseConv2d",category:"convolution",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"DepthwiseConv2dNative",category:"convolution",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"FusedDepthwiseConv2dNative",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]",defaultValue:[1,1,1,1]},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]}]},{tfOpName:"Conv3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"Dilation2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"rates",name:"dilations",type:"number[]"},{tfName:"padding",name:"pad",type:"string"}]}];var PY=Object.freeze({__proto__:null,json:MY});const zY=[{tfOpName:"Fill",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"},{start:1,name:"value",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"LinSpace",category:"creation",inputs:[{start:0,name:"start",type:"number"},{start:1,name:"stop",type:"number"},{start:2,name:"num",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"OneHot",category:"creation",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"depth",type:"number"},{start:2,name:"onValue",type:"number",defaultValue:1},{start:3,name:"offValue",type:"number",defaultValue:0}],attrs:[{tfName:"axis",name:"axis",type:"number",notSupported:!0},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Ones",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"OnesLike",category:"creation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"RandomUniform",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"minval",name:"minval",type:"number",defaultValue:0},{tfName:"maxval",name:"maxval",type:"number",defaultValue:1},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"seed",name:"seed",type:"number",defaultValue:0},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"Range",category:"creation",inputs:[{start:0,name:"start",type:"number"},{start:1,name:"stop",type:"number"},{start:2,name:"step",type:"number",defaultValue:0}],attrs:[{tfName:"Tidx",name:"dtype",type:"dtype"}]},{tfOpName:"TruncatedNormal",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"means",name:"mean",type:"number",defaultValue:0},{tfName:"stddev",name:"stdDev",type:"number",defaultValue:1},{tfName:"seed",name:"seed",type:"number"},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"Zeros",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"ZerosLike",category:"creation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"Multinomial",category:"creation",inputs:[{start:0,name:"logits",type:"tensor"},{start:1,name:"numSamples",type:"number"}],attrs:[{tfName:"seed",name:"seed",type:"number"},{tfName:"seed2",name:"seed2",type:"number"},{tfName:"T",name:"dtype",type:"dtype"},{tfName:"output_dtype",name:"output_dtype",type:"dtype"}]}];var VY=Object.freeze({__proto__:null,json:zY});const GY=[{tfOpName:"NonMaxSuppressionV2",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"}]},{tfOpName:"NonMaxSuppressionV3",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"}]},{tfOpName:"NonMaxSuppressionV4",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"T_threshold",name:"threshold",type:"dtype",notSupported:!0},{tfName:"pad_to_max_output_size",name:"padToMaxOutputSize",type:"bool"}]},{tfOpName:"NonMaxSuppressionV5",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"},{start:5,name:"softNmsSigma",type:"number"}]},{tfOpName:"Where",category:"dynamic",inputs:[{start:0,name:"condition",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ListDiff",category:"dynamic",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}];var YY=Object.freeze({__proto__:null,json:GY});const HY=[{tfOpName:"TopKV2",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"k",type:"number"}],attrs:[{tfName:"sorted",name:"sorted",type:"bool"}]},{tfOpName:"Unique",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"UniqueV2",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]}];var qY=Object.freeze({__proto__:null,json:HY});const jY=[{tfOpName:"PlaceholderWithDefault",category:"graph",inputs:[{start:0,name:"default",type:"tensor"}],attrs:[{tfName:"shape",name:"shape",type:"shape"},{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"Placeholder",category:"graph",attrs:[{tfName:"shape",name:"shape",type:"shape"},{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"Const",category:"graph"},{tfOpName:"Identity",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"IdentityN",category:"graph",inputs:[{start:0,end:0,name:"x",type:"tensors"}]},{tfOpName:"Snapshot",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Rank",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Size",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Shape",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"ShapeN",category:"graph",inputs:[{start:0,end:0,name:"x",type:"tensors"}]},{tfOpName:"Print",category:"graph",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"data",type:"tensors"}],attrs:[{tfName:"message",name:"message",type:"string"},{tfName:"first_n",name:"firstN",type:"number",notSupported:!0},{tfName:"summarize",name:"summarize",type:"number",defaultValue:3}]},{tfOpName:"NoOp",category:"graph",inputs:[]},{tfOpName:"StopGradient",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"FakeQuantWithMinMaxVars",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"min",name:"min",type:"number"},{tfName:"max",name:"max",type:"number"}]}];var KY=Object.freeze({__proto__:null,json:jY});const XY=[{tfOpName:"HashTable",category:"hash_table",inputs:[],attrs:[{tfName:"shared_name",name:"sharedName",type:"string"},{tfName:"use_node_name_sharing",name:"useNodeNameSharing",type:"bool"},{tfName:"key_dtype",name:"keyDType",type:"dtype"},{tfName:"value_dtype",name:"valueDType",type:"dtype"}]},{tfOpName:"HashTableV2",category:"hash_table",inputs:[],attrs:[{tfName:"shared_name",name:"sharedName",type:"string"},{tfName:"use_node_name_sharing",name:"useNodeNameSharing",type:"bool"},{tfName:"key_dtype",name:"keyDType",type:"dtype"},{tfName:"value_dtype",name:"valueDType",type:"dtype"}]},{tfOpName:"LookupTableImport",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableImportV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableFind",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableFindV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]}];var JY=Object.freeze({__proto__:null,json:XY});const ZY=[{tfOpName:"ResizeBilinear",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"size",type:"number[]"}],attrs:[{tfName:"align_corners",name:"alignCorners",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ResizeNearestNeighbor",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"size",type:"number[]"}],attrs:[{tfName:"align_corners",name:"alignCorners",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"CropAndResize",category:"image",inputs:[{start:0,name:"image",type:"tensor"},{start:1,name:"boxes",type:"tensor"},{start:2,name:"boxInd",type:"tensor"},{start:3,name:"cropSize",type:"number[]"}],attrs:[{tfName:"method",name:"method",type:"string"},{tfName:"extrapolation_value",name:"extrapolationValue",type:"number"}]}];var QY=Object.freeze({__proto__:null,json:ZY});const eH=[{tfOpName:"Equal",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"NotEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Greater",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"GreaterEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Less",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LessEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalAnd",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalNot",category:"logical",inputs:[{start:0,name:"a",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalOr",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Select",category:"logical",inputs:[{start:0,name:"condition",type:"tensor"},{start:1,name:"a",type:"tensor"},{start:2,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SelectV2",category:"logical",inputs:[{start:0,name:"condition",type:"tensor"},{start:1,name:"a",type:"tensor"},{start:2,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}];var tH=Object.freeze({__proto__:null,json:eH});const nH=[{tfOpName:"_FusedMatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:1e-4},{tfName:"transpose_a",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"transpose_b",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"transpose_a",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"transpose_b",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BatchMatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"adj_x",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"adj_y",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BatchMatMulV2",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"adj_x",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"adj_y",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Transpose",category:"matrices",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"perm",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}];var sH=Object.freeze({__proto__:null,json:nH});const iH=[{tfOpName:"FusedBatchNorm",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"FusedBatchNormV2",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"FusedBatchNormV3",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"LRN",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"depth_radius",name:"radius",type:"number",defaultValue:5},{tfName:"bias",name:"bias",type:"number",defaultValue:1},{tfName:"alpha",name:"alpha",type:"number",defaultValue:1},{tfName:"beta",name:"beta",type:"number",defaultValue:.5}]},{tfOpName:"Softmax",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"LogSoftmax",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"SparseToDense",category:"normalization",inputs:[{start:0,name:"sparseIndices",type:"tensor"},{start:1,name:"outputShape",type:"number[]"},{start:2,name:"sparseValues",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",defaultValue:!0,notSupported:!0}]}];var rH=Object.freeze({__proto__:null,json:iH});const oH=[{tfOpName:"Max",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Mean",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Min",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Sum",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"All",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Any",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"ArgMax",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"ArgMin",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"Prod",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Cumsum",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}],attrs:[{tfName:"exclusive",name:"exclusive",type:"bool"},{tfName:"reverse",name:"reverse",type:"bool"}]}];var aH=Object.freeze({__proto__:null,json:oH});const cH=[{tfOpName:"ConcatV2",category:"slice_join",inputs:[{start:0,end:-1,name:"tensors",type:"tensors"},{start:-1,name:"axis",type:"number"}],attrs:[{tfName:"N",name:"n",type:"number",defaultValue:2}]},{tfOpName:"Concat",category:"slice_join",inputs:[{start:1,end:0,name:"tensors",type:"tensors"},{start:0,name:"axis",type:"number"}],attrs:[{tfName:"N",name:"n",type:"number",defaultValue:2}]},{tfOpName:"GatherV2",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"axis",type:"number",defaultValue:0}]},{tfOpName:"Gather",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0},{tfName:"validate_indices",name:"validateIndices",type:"bool",notSupported:!0}]},{tfOpName:"Reverse",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"dims",type:"bool",notSupported:!0}]},{tfOpName:"ReverseV2",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}]},{tfOpName:"Slice",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"begin",type:"number[]"},{start:2,name:"size",type:"number[]"}]},{tfOpName:"StridedSlice",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"begin",type:"number[]"},{start:2,name:"end",type:"number[]"},{start:3,name:"strides",type:"number[]"}],attrs:[{tfName:"begin_mask",name:"beginMask",type:"number",defaultValue:0},{tfName:"end_mask",name:"endMask",type:"number",defaultValue:0},{tfName:"new_axis_mask",name:"newAxisMask",type:"number",defaultValue:0},{tfName:"ellipsis_mask",name:"ellipsisMask",type:"number",defaultValue:0},{tfName:"shrink_axis_mask",name:"shrinkAxisMask",type:"number",defaultValue:0}]},{tfOpName:"Pack",category:"slice_join",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0}]},{tfOpName:"Unpack",category:"slice_join",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0},{tfName:"num",name:"num",type:"number",defaultValue:0,notSupported:!0}]},{tfOpName:"Tile",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"reps",type:"number[]"}]},{tfOpName:"Split",category:"slice_join",inputs:[{start:0,name:"axis",type:"number",defaultValue:0},{start:1,name:"x",type:"tensor"}],attrs:[{tfName:"num_split",name:"numOrSizeSplits",type:"number",defaultValue:1}]},{tfOpName:"SplitV",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"numOrSizeSplits",type:"number[]"},{start:2,name:"axis",type:"number",defaultValue:0}]},{tfOpName:"ScatterNd",category:"slice_join",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"values",type:"tensor"},{start:2,name:"shape",type:"number[]"}]},{tfOpName:"GatherNd",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"}]},{tfOpName:"SparseToDense",category:"slice_join",inputs:[{start:0,name:"sparseIndices",type:"tensor"},{start:1,name:"outputShape",type:"number[]"},{start:2,name:"sparseValues",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",defaultValue:!1,notSupported:!0}]}];var lH=Object.freeze({__proto__:null,json:cH});const hH=[{tfOpName:"FFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"IFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"RFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"fft_length",type:"number",notSupported:!0}]},{tfOpName:"IRFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"fft_length",type:"number",notSupported:!0}]}];var uH=Object.freeze({__proto__:null,json:hH});const dH=[{tfOpName:"Cast",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"SrcT",name:"sdtype",type:"dtype",notSupported:!0},{tfName:"DstT",name:"dtype",type:"dtype"}]},{tfOpName:"ExpandDims",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"MirrorPad",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"}],attrs:[{tfName:"mode",name:"mode",type:"string"}]},{tfOpName:"Pad",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"}],attrs:[{tfName:"constant_value",name:"constantValue",type:"number",defaultValue:0}]},{tfOpName:"PadV2",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"},{start:2,name:"constantValue",type:"number",defaultValue:0}]},{tfOpName:"Reshape",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"shape",type:"number[]"}]},{tfOpName:"Squeeze",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"axis",tfDeprecatedName:"squeeze_dims",name:"axis",type:"number[]"}]},{tfOpName:"SpaceToBatchND",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"blockShape",type:"number[]"},{start:2,name:"paddings",type:"number[]"}]},{tfOpName:"BatchToSpaceND",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"blockShape",type:"number[]"},{start:2,name:"crops",type:"number[]"}]},{tfOpName:"DepthToSpace",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"block_size",name:"blockSize",type:"number"},{tfName:"data_format",name:"dataFormat",type:"string"}]},{tfOpName:"BroadcastTo",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"shape",type:"number[]"}],attrs:[]}];var pH=Object.freeze({__proto__:null,json:dH});class p0{static get Instance(){return this._instance||(this._instance=new this)}constructor(){const e=[_Y,$Y,BY,PY,VY,YY,qY,tH,QY,KY,sH,rH,aH,lH,uH,pH,JY],t=[].concat(...e.map(n=>n.json));this.opMappers=t.reduce((n,s)=>(n[s.tfOpName]=s,n),{})}transformGraph(e,t={}){const n=e.node,s=[],i=[],o=[],a=n.reduce((L,T)=>(L[T.name]=this.mapNode(T),T.op.startsWith("Placeholder")?s.push(L[T.name]):T.op==="Const"?i.push(L[T.name]):(T.input==null||T.input.length===0)&&o.push(L[T.name]),L),{});let c=[];const h=[];let p={},m={};t!=null&&(p=this.mapSignatureEntries(t.inputs),m=this.mapSignatureEntries(t.outputs));const y=Object.keys(a);y.forEach(L=>{const T=a[L];T.inputNames.forEach(v=>{const[C]=dr(v);T.inputs.push(a[C]),a[C].children.push(T)})}),Object.keys(m).length===0?y.forEach(L=>{const T=a[L];T.children.length===0&&h.push(T)}):Object.keys(m).forEach(L=>{const[T]=dr(L),v=a[T];v!=null&&(v.signatureKey=m[L],h.push(v))}),Object.keys(p).length>0?Object.keys(p).forEach(L=>{const[T]=dr(L),v=a[T];v&&(v.signatureKey=p[L],c.push(v))}):c=s;let b={};e.library!=null&&e.library.function!=null&&(b=e.library.function.reduce((L,T)=>(L[T.signature.name]=this.mapFunction(T),L),{}));const w={nodes:a,inputs:c,outputs:h,weights:i,placeholders:s,signature:t,functions:b};return o.length>0&&(w.initNodes=o),w}mapSignatureEntries(e){return Object.keys(e||{}).reduce((t,n)=>(t[e[n].name]=n,t),{})}mapNode(e){const t=d0(e.op)||this.opMappers[e.op]||{};e.attr==null&&(e.attr={});const n={name:e.name,op:e.op,category:t.category,inputNames:(e.input||[]).map(s=>s.startsWith("^")?s.substr(1):s),inputs:[],children:[],inputParams:{},attrParams:{},rawAttrs:e.attr};return t.inputs!=null&&(n.inputParams=t.inputs.reduce((s,i)=>(s[i.name]={type:i.type,inputIndexStart:i.start,inputIndexEnd:i.end},s),{})),t.attrs!=null&&(n.attrParams=t.attrs.reduce((s,i)=>{const o=i.type;let a;switch(i.type){case"string":a=uS(e.attr,i.tfName,i.defaultValue),a===void 0&&!!i.tfDeprecatedName&&(a=uS(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"string[]":a=wS(e.attr,i.tfName,i.defaultValue),a===void 0&&!!i.tfDeprecatedName&&(a=wS(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"number":a=pS(e.attr,i.tfName,i.defaultValue||0),a===void 0&&!!i.tfDeprecatedName&&(a=pS(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"number[]":a=bS(e.attr,i.tfName,i.defaultValue),a===void 0&&!!i.tfDeprecatedName&&(a=bS(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"bool":a=dS(e.attr,i.tfName,i.defaultValue),a===void 0&&!!i.tfDeprecatedName&&(a=dS(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"bool[]":a=SS(e.attr,i.tfName,i.defaultValue),a===void 0&&!!i.tfDeprecatedName&&(a=SS(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"shape":a=yS(e.attr,i.tfName,i.defaultValue),a===void 0&&!!i.tfDeprecatedName&&(a=yS(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"shape[]":a=LS(e.attr,i.tfName,i.defaultValue),a===void 0&&!!i.tfDeprecatedName&&(a=LS(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"dtype":a=fS(e.attr,i.tfName,i.defaultValue),a===void 0&&!!i.tfDeprecatedName&&(a=fS(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"dtype[]":a=gS(e.attr,i.tfName,i.defaultValue),a===void 0&&!!i.tfDeprecatedName&&(a=gS(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"func":a=f0(e.attr,i.tfName,i.defaultValue),a===void 0&&!!i.tfDeprecatedName&&(a=f0(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"tensor":case"tensors":break;default:throw new Error(`Unsupported param type: ${i.type} for op: ${e.op}`)}return s[i.name]={value:a,type:o},s},{})),n}mapFunction(e){const t=e.nodeDef,n=[],s=[];let i={};t!=null&&(i=t.reduce((m,y)=>(m[y.name]=this.mapNode(y),y.op==="Const"&&s.push(m[y.name]),m),{}));const o=[],a=[];e.signature.inputArg.forEach(m=>{const[y]=dr(m.name),b={name:y,op:"Placeholder",inputs:[],inputNames:[],category:"graph",inputParams:{},attrParams:{dtype:{value:mS(m.type),type:"dtype"}},children:[]};b.signatureKey=m.name,o.push(b),i[y]=b});const c=Object.keys(i);c.forEach(m=>{const y=i[m];y.inputNames.forEach(b=>{const[w]=dr(b);y.inputs.push(i[w]),i[w].children.push(y)})});const h=e.ret;e.signature.outputArg.forEach(m=>{const[y,b]=dr(h[m.name]),w=i[y];w!=null&&(w.defaultOutput=b,a.push(w))});const p=this.mapArgsToSignature(e);return{nodes:i,inputs:o,outputs:a,weights:s,placeholders:n,signature:p}}mapArgsToSignature(e){return{methodName:e.signature.name,inputs:e.signature.inputArg.reduce((t,n)=>(t[n.name]=this.mapArgToTensorInfo(n),t),{}),outputs:e.signature.outputArg.reduce((t,n)=>(t[n.name]=this.mapArgToTensorInfo(n,e.ret),t),{})}}mapArgToTensorInfo(e,t){let n=e.name;return t!=null&&(n=t[n]),{name:n,dtype:e.type}}}function mH(e){const t=ae().global;if(typeof t.atob!="undefined")return t.atob(e);if(typeof Buffer!="undefined")return new Buffer(e,"base64").toString();throw new Error("Unable to decode base64 in this environment. Missing built-in atob() or Buffer()")}function m0(e,t){const n=Array.isArray(e)?String.fromCharCode.apply(null,e):mH(e);return t?n:n.toLowerCase()}function uS(e,t,n,s=!1){const i=e[t];return i!=null?m0(i.s,s):n}function dS(e,t,n){const s=e[t];return s?s.b:n}function pS(e,t,n){const s=e[t]||{},i=s.i!=null?s.i:s.f!=null?s.f:n;return typeof i=="number"?i:parseInt(i,10)}function mS(e){typeof e=="string"&&(e=ui[e]);switch(e){case ui.DT_FLOAT:return"float32";case ui.DT_INT32:case ui.DT_INT64:case ui.DT_INT8:case ui.DT_UINT8:return"int32";case ui.DT_BOOL:return"bool";case ui.DT_DOUBLE:return"float32";case ui.DT_STRING:return"string";default:return null}}function f0(e,t,n){const s=e[t];return s&&s.func?s.func.name:n}function fS(e,t,n){const s=e[t];return s&&s.type?mS(s.type):n}function gS(e,t,n){const s=e[t];return s&&s.list&&s.list.type?s.list.type.map(i=>mS(i)):n}function g0(e){return e.unknownRank?void 0:e.dim!=null?e.dim.map(t=>typeof t.size=="number"?t.size:parseInt(t.size,10)):[]}function yS(e,t,n){const s=e[t];return s&&s.shape?g0(s.shape):n}function bS(e,t,n){const s=e[t];return s?((s.list.f&&s.list.f.length?s.list.f:s.list.i)||[]).map(i=>typeof i=="number"?i:parseInt(i,10)):n}function wS(e,t,n,s=!1){const i=e[t];return i&&i.list&&i.list.s?i.list.s.map(o=>m0(o,s)):n}function LS(e,t,n){const s=e[t];return s&&s.list&&s.list.shape?s.list.shape.map(i=>g0(i)):n}function SS(e,t,n){const s=e[t];return s&&s.list&&s.list.b?s.list.b:n}class fH{constructor(e,t,n){this.node=e,this.tensorMap=t,this.context=n,this.inputs=[],this.attrs={},this.inputs=e.inputNames.map(s=>this.getInput(s)),e.rawAttrs!=null&&(this.attrs=Object.keys(e.rawAttrs).reduce((s,i)=>(s[i]=this.getAttr(i),s),{}))}getInput(e){return os(e,this.tensorMap,this.context)}getAttr(e,t){const n=this.node.rawAttrs[e];if(n.tensor!=null)return os(e,this.tensorMap,this.context);if(n.i!=null||n.f!=null)return pS(this.node.rawAttrs,e,t);if(n.s!=null)return uS(this.node.rawAttrs,e,t);if(n.b!=null)return dS(this.node.rawAttrs,e,t);if(n.shape!=null)return yS(this.node.rawAttrs,e,t);if(n.type!=null)return fS(this.node.rawAttrs,e,t);if(n.list!=null){if(n.list.i!=null||n.list.f!=null)return bS(this.node.rawAttrs,e,t);if(n.list.s!=null)return wS(this.node.rawAttrs,e,t);if(n.list.shape!=null)return LS(this.node.rawAttrs,e,t);if(n.list.b!=null)return SS(this.node.rawAttrs,e,t);if(n.list.type!=null)return gS(this.node.rawAttrs,e,t)}return t}}const gH=(e,t,n)=>{switch(e.op){case"BiasAdd":case"AddV2":case"Add":return[be(R("a",e,t,n),R("b",e,t,n))];case"AddN":return[wA(R("tensors",e,t,n))];case"FloorMod":case"Mod":return[Dp(R("a",e,t,n),R("b",e,t,n))];case"Mul":return[X(R("a",e,t,n),R("b",e,t,n))];case"RealDiv":case"Div":return[We(R("a",e,t,n),R("b",e,t,n))];case"DivNoNan":return[zb(R("a",e,t,n),R("b",e,t,n))];case"FloorDiv":return[gp(R("a",e,t,n),R("b",e,t,n))];case"Sub":return[Re(R("a",e,t,n),R("b",e,t,n))];case"Minimum":return[Po(R("a",e,t,n),R("b",e,t,n))];case"Maximum":return[Ms(R("a",e,t,n),R("b",e,t,n))];case"Pow":return[ni(R("a",e,t,n),R("b",e,t,n))];case"SquaredDifference":return[Wh(R("a",e,t,n),R("b",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},xne="arithmetic";const yH=(e,t,n)=>{switch(e.op){case"Abs":case"ComplexAbs":return[pn(R("x",e,t,n))];case"Acos":return[Ab(R("x",e,t,n))];case"Acosh":return[vb(R("x",e,t,n))];case"Asin":return[Rb(R("x",e,t,n))];case"Asinh":return[Ob(R("x",e,t,n))];case"Atan":return[Eb(R("x",e,t,n))];case"Atan2":return[Db(R("x",e,t,n),R("y",e,t,n))];case"Atanh":return[kb(R("x",e,t,n))];case"Ceil":return[$b(R("x",e,t,n))];case"Complex":return[er(R("real",e,t,n),R("imag",e,t,n))];case"Cos":return[Th(R("x",e,t,n))];case"Cosh":return[Tp(R("x",e,t,n))];case"Elu":return[Xa(R("x",e,t,n))];case"Erf":return[Vb(R("x",e,t,n))];case"Exp":return[As(R("x",e,t,n))];case"Expm1":return[Gb(R("x",e,t,n))];case"Floor":return[Za(R("x",e,t,n))];case"Log":return[us(R("x",e,t,n))];case"Log1p":return[Cp(R("x",e,t,n))];case"Imag":return[vh(R("x",e,t,n))];case"Neg":return[Ht(R("x",e,t,n))];case"Reciprocal":return[ew(R("x",e,t,n))];case"Real":return[nc(R("x",e,t,n))];case"Relu":return[Di(R("x",e,t,n))];case"Round":return[nw(R("x",e,t,n))];case"Selu":return[Wp(R("x",e,t,n))];case"Sigmoid":return[Ri(R("x",e,t,n))];case"Sin":return[$p(R("x",e,t,n))];case"Sign":return[iw(R("x",e,t,n))];case"Sinh":return[Up(R("x",e,t,n))];case"Softplus":return[ec(R("x",e,t,n))];case"Sqrt":return[Cn(R("x",e,t,n))];case"Square":return[At(R("x",e,t,n))];case"Tanh":return[Ka(R("x",e,t,n))];case"Tan":return[aw(R("x",e,t,n))];case"Relu6":case"ClipByValue":return[es(R("x",e,t,n),R("clipValueMin",e,t,n),R("clipValueMax",e,t,n))];case"Rsqrt":return[_p(os(e.inputNames[0],t,n))];case"Prod":return[Fp(R("x",e,t,n),R("axes",e,t,n))];case"LeakyRelu":return[Np(R("x",e,t,n),R("alpha",e,t,n))];case"Prelu":return[Eh(R("x",e,t,n),R("alpha",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},Tne="basic_math";function Ys(e,t,n=""){A(bH(e,t),()=>n+` Shapes ${e} and ${t} must match`)}function bH(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==-1&&t[n]!==-1&&e[n]!==t[n])return!1;return!0}class wH{constructor(e,t,n,s,i,o,a){this.name=e,this.dtype=t,this.maxSize=n,this.elementShape=s,this.identicalElementShapes=i,this.dynamicSize=o,this.clearAfterRead=a,this.tensors=[],this.closed_=!1,this.idTensor=Ce(0),wn(this.idTensor)}get id(){return this.idTensor.id}get closed(){return this.closed_}clearAndClose(e){this.tensors.forEach(t=>{(e==null||!e.has(t.tensor.id))&&t.tensor.dispose()}),this.tensors=[],this.closed_=!0,this.idTensor.dispose()}size(){return this.tensors.length}read(e){if(this.closed_)throw new Error(`TensorArray ${this.name} has already been closed.`);if(e<0||e>=this.size())throw new Error(`Tried to read from index ${e}, but array size is: ${this.size()}`);const t=this.tensors[e];if(t.cleared)throw new Error(`TensorArray ${this.name}: Could not read index ${e} twice because it was cleared after a previous read (perhaps try setting clear_after_read = false?).`);return this.clearAfterRead&&(t.cleared=!0),t.read=!0,t.tensor}readMany(e){return e.map(t=>this.read(t))}write(e,t){if(this.closed_)throw new Error(`TensorArray ${this.name} has already been closed.`);if(e<0||!this.dynamicSize&&e>=this.maxSize)throw new Error(`Tried to write to index ${e}, but array is not resizeable and size is: ${this.maxSize}`);const n=this.tensors[e]||{};if(t.dtype!==this.dtype)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e},
because the value dtype is ${t.dtype}, but TensorArray dtype is ${this.dtype}.`);if(this.size()===0&&(this.elementShape==null||this.elementShape.length===0)&&(this.elementShape=t.shape),Ys(this.elementShape,t.shape,`TensorArray ${this.name}: Could not write to TensorArray index ${e}.`),n.read)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been read.`);if(n.written)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been written.`);n.tensor=t,wn(t),n.written=!0,this.tensors[e]=n}writeMany(e,t){if(e.length!==t.length)throw new Error(`TensorArray ${this.name}: could not write multiple tensors,because the index size: ${e.length} is not the same as tensors size: ${t.length}.`);e.forEach((n,s)=>this.write(n,t[s]))}gather(e,t){if(!!t&&t!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but gather requested dtype ${t}`);if(e)e=e.slice(0,this.size());else{e=[];for(let s=0;s<this.size();s++)e.push(s)}if(e.length===0)return sn([],[0].concat(this.elementShape));const n=this.readMany(e);return Ys(this.elementShape,n[0].shape,"TensorArray shape mismatch: "),ss(n,0)}concat(e){if(!!e&&e!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but concat requested dtype ${e}`);if(this.size()===0)return sn([],[0].concat(this.elementShape));const t=[];for(let s=0;s<this.size();s++)t.push(s);const n=this.readMany(t);return Ys(this.elementShape,n[0].shape,`TensorArray shape mismatch: tensor array shape (${this.elementShape}) vs first tensor shape (${n[0].shape})`),Yt(n,0)}scatter(e,t){if(t.dtype!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${t.dtype}`);if(e.length!==t.shape[0])throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${e.length} vs. ${t.shape[0]}`);const n=Math.max(...e);if(!this.dynamicSize&&n>=this.maxSize)throw new Error(`Max index must be < array size (${n} vs. ${this.maxSize})`);this.writeMany(e,si(t,0))}split(e,t){if(t.dtype!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${t.dtype}`);let n=0;const s=e.map(c=>(n+=c,n));if(n!==t.shape[0])throw new Error(`Expected sum of lengths to be equal to
tensor.shape[0], but sum of lengths is
${n}, and tensor's shape is: ${t.shape}`);if(!this.dynamicSize&&e.length!==this.maxSize)throw new Error(`TensorArray's size is not equal to the size of lengths (${this.maxSize} vs. ${e.length}), and the TensorArray is not marked as dynamically resizeable`);const i=n===0?0:t.size/n,o=[];ee(()=>{t=K(t,[1,n,i]);for(let c=0;c<e.length;++c){const h=c===0?0:s[c-1],p=[0,h,0],m=[1,e[c],i];o[c]=K(nt(t,p,m),this.elementShape)}return o});const a=[];for(let c=0;c<e.length;c++)a[c]=c;this.writeMany(a,o)}}class gu{constructor(e,t,n,s=-1){this.tensors=e,this.elementShape=t,this.elementDtype=n,e!=null&&e.forEach(i=>{if(n!==i.dtype)throw new Error(`Invalid data types; op elements ${n}, but list elements ${i.dtype}`);Ys(t,i.shape,"TensorList shape mismatch: "),wn(i)}),this.idTensor=Ce(0),this.maxNumElements=s,wn(this.idTensor)}get id(){return this.idTensor.id}copy(){return new gu([...this.tensors],this.elementShape,this.elementDtype)}clearAndClose(e){this.tensors.forEach(t=>{(e==null||!e.has(t.id))&&t.dispose()}),this.tensors.length=0,this.idTensor.dispose()}size(){return this.tensors.length}stack(e,t,n=-1){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);if(n!==-1&&this.tensors.length!==n)throw new Error(`Operation expected a list with ${n} elements but got a list with ${this.tensors.length} elements.`);return Ys(e,this.elementShape,"TensorList shape mismatch: "),ee(()=>{const s=this.tensors.map(i=>K(i,e));return ss(s,0)})}popBack(e,t){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);if(this.size()===0)throw new Error("Trying to pop from an empty list.");const n=this.tensors.pop();return Ys(n.shape,e,"TensorList shape mismatch: "),K(n,e)}pushBack(e){if(e.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${this.elementDtype}`);if(Ys(e.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");wn(e),this.tensors.push(e)}resize(e){if(e<0)throw new Error(`TensorListResize expects size to be non-negative. Got: ${e}`);if(this.maxNumElements!==-1&&e>this.maxNumElements)throw new Error(`TensorListResize input size ${e} is greater maxNumElement ${this.maxNumElements}.`);this.tensors.length=e}getItem(e,t,n){if(n!==this.elementDtype)throw new Error(`Invalid data types; op elements ${n}, but list elements ${this.elementDtype}`);if(e<0||e>this.tensors.length)throw new Error(`Trying to access element ${e} in a list with ${this.tensors.length} elements.`);if(this.tensors[e]==null)throw new Error(`element at index ${e} is null.`);return Ys(this.tensors[e].shape,t,"TensorList shape mismatch: "),this.tensors[e]}setItem(e,t){if(t.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t.dtype}, but list elements ${this.elementDtype}`);if(e<0||this.maxNumElements!==-1&&e>=this.maxNumElements)throw new Error(`Trying to set element ${e} in a list with max ${this.maxNumElements} elements.`);Ys(this.elementShape,t.shape,"TensorList shape mismatch: "),wn(t),this.tensors[e]=t}gather(e,t,n){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);return Ys(this.elementShape,n,"TensorList shape mismatch: "),e=e.slice(0,this.size()),e.length===0?sn([],[0].concat(this.elementShape)):ee(()=>{const s=e.map(i=>K(this.tensors[i],n));return ss(s,0)})}concat(e,t){if(!!e&&e!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${e}`);return Ys(this.elementShape,t,"TensorList shape mismatch: "),this.size()===0?sn([],[0].concat(this.elementShape)):ee(()=>{const n=this.tensors.map(s=>K(s,t));return Yt(n,0)})}}function LH(e,t,n){const s=e.dtype;if(e.shape.length<1)throw new Error(`Tensor must be at least a vector, but saw shape: ${e.shape}`);if(e.dtype!==n)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${n}`);const i=e.shape.slice(1);Ys(i,t,"TensorList shape mismatch: ");const o=si(e);return new gu(o,t,s)}function SH(e,t,n){return new gu([],e,t,n)}function IH(e,t,n,s){if(t.length!==e.shape[0])throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${t.length} vs. ${e.shape[0]}`);const i=Math.max(...t);if(s!=null&&s!==-1&&i>=s)throw new Error(`Max index must be < array size (${i} vs. ${s})`);const o=new gu([],n,e.dtype,s),a=si(e,0);return t.forEach((c,h)=>{o.setItem(c,a[h])}),o}function xH(e,t,n){let s=0;const i=t.map(h=>(s+=h,s));if(s!==e.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: ${e.shape}`);const o=s===0?0:e.size/s,a=ee(()=>{const h=[];e=K(e,[1,s,o]);for(let p=0;p<t.length;++p){const m=p===0?0:i[p-1],y=[0,m,0],b=[1,t[p],o];h[p]=K(nt(e,y,b),n)}return e.dispose(),h}),c=new gu([],n,e.dtype,t.length);for(let h=0;h<a.length;h++)c.setItem(h,a[h]);return c}const TH=async(e,t,n)=>{switch(e.op){case"If":case"StatelessIf":{const s=R("thenBranch",e,t,n),i=R("elseBranch",e,t,n),o=R("cond",e,t,n),a=R("args",e,t,n),c=await o.data();return c[0]?n.functionMap[s].executeFunctionAsync(a,n.tensorArrayMap,n.tensorListMap):n.functionMap[i].executeFunctionAsync(a,n.tensorArrayMap,n.tensorListMap)}case"While":case"StatelessWhile":{const s=R("body",e,t,n),i=R("cond",e,t,n),o=R("args",e,t,n),a=await n.functionMap[i].executeFunctionAsync(o,n.tensorArrayMap,n.tensorListMap),c=o.map(m=>m.id);let h=await a[0].data();a.forEach(m=>{!m.kept&&c.indexOf(m.id)===-1&&m.dispose()});let p=o;for(;h[0];){const m=p;p=await n.functionMap[s].executeFunctionAsync(p,n.tensorArrayMap,n.tensorListMap);const y=p.map(w=>w.id);m.forEach(w=>{!w.kept&&c.indexOf(w.id)===-1&&y.indexOf(w.id)===-1&&w.dispose()});const b=await n.functionMap[i].executeFunctionAsync(p,n.tensorArrayMap,n.tensorListMap);h=await b[0].data(),b.forEach(w=>{!w.kept&&c.indexOf(w.id)===-1&&y.indexOf(w.id)===-1&&w.dispose()})}return p}case"LoopCond":{const s=R("pred",e,t,n);return[pr(s)]}case"Switch":{const s=R("pred",e,t,n);let i=R("data",e,t,n);return i.kept||(i=pr(i)),(await s.data())[0]?[void 0,i]:[i,void 0]}case"Merge":{const s=e.inputNames.find(i=>os(i,t,n)!==void 0);if(s){const i=os(s,t,n);return[pr(i)]}return}case"Enter":{const s=R("frameName",e,t,n),i=R("tensor",e,t,n);return n.enterFrame(s),[pr(i)]}case"Exit":{const s=R("tensor",e,t,n);return n.exitFrame(),[pr(s)]}case"NextIteration":{const s=R("tensor",e,t,n);return n.nextIteration(),[pr(s)]}case"TensorArrayV3":{const s=R("size",e,t,n),i=R("dtype",e,t,n),o=R("elementShape",e,t,n),a=R("dynamicSize",e,t,n),c=R("clearAfterRead",e,t,n),h=R("identicalElementShapes",e,t,n),p=R("name",e,t,n),m=new wH(p,i,s,o,h,a,c);return n.addTensorArray(m),[m.idTensor,Ce(1)]}case"TensorArrayWriteV3":{const s=R("tensorArrayId",e,t,n),i=R("index",e,t,n),o=R("tensor",e,t,n),a=n.getTensorArray(s.id);return a.write(i,o),[a.idTensor]}case"TensorArrayReadV3":{const s=R("tensorArrayId",e,t,n),i=R("index",e,t,n),o=n.getTensorArray(s.id);return[o.read(i)]}case"TensorArrayGatherV3":{const s=R("tensorArrayId",e,t,n),i=R("indices",e,t,n),o=R("dtype",e,t,n),a=n.getTensorArray(s.id);return[a.gather(i,o)]}case"TensorArrayScatterV3":{const s=R("tensorArrayId",e,t,n),i=R("indices",e,t,n),o=R("tensor",e,t,n),a=n.getTensorArray(s.id);return a.scatter(i,o),[a.idTensor]}case"TensorArrayConcatV3":{const s=R("tensorArrayId",e,t,n),i=n.getTensorArray(s.id),o=R("dtype",e,t,n);return[i.concat(o)]}case"TensorArraySplitV3":{const s=R("tensorArrayId",e,t,n),i=R("tensor",e,t,n),o=R("lengths",e,t,n),a=n.getTensorArray(s.id);return a.split(o,i),[a.idTensor]}case"TensorArraySizeV3":{const s=R("tensorArrayId",e,t,n),i=n.getTensorArray(s.id);return[Ce(i.size(),"int32")]}case"TensorArrayCloseV3":{const s=R("tensorArrayId",e,t,n),i=n.getTensorArray(s.id);return i.clearAndClose(),[i.idTensor]}case"TensorListSetItem":{const s=R("tensorListId",e,t,n),i=R("index",e,t,n),o=R("tensor",e,t,n),a=n.getTensorList(s.id);return a.setItem(i,o),[a.idTensor]}case"TensorListGetItem":{const s=R("tensorListId",e,t,n),i=R("index",e,t,n),o=R("elementShape",e,t,n),a=R("elementDType",e,t,n),c=n.getTensorList(s.id);return[c.getItem(i,o,a)]}case"TensorListScatterV2":case"TensorListScatter":{const s=R("indices",e,t,n),i=R("tensor",e,t,n),o=R("elementShape",e,t,n),a=R("numElements",e,t,n),c=IH(i,s,o,a);return n.addTensorList(c),[c.idTensor]}case"TensorListReserve":{const s=R("elementShape",e,t,n),i=R("elementDType",e,t,n),o=R("numElements",e,t,n),a=SH(s,i,o);return n.addTensorList(a),[a.idTensor]}case"TensorListGather":{const s=R("tensorListId",e,t,n),i=R("indices",e,t,n),o=R("elementShape",e,t,n),a=R("elementDType",e,t,n),c=n.getTensorList(s.id);return[c.gather(i,a,o)]}case"TensorListStack":{const s=R("tensorListId",e,t,n),i=R("elementShape",e,t,n),o=R("elementDType",e,t,n),a=R("numElements",e,t,n),c=n.getTensorList(s.id);return[c.stack(i,o,a)]}case"TensorListFromTensor":{const s=R("tensor",e,t,n),i=R("elementShape",e,t,n),o=R("elementDType",e,t,n),a=LH(s,i,o);return n.addTensorList(a),[a.idTensor]}case"TensorListConcat":{const s=R("tensorListId",e,t,n),i=n.getTensorList(s.id),o=R("dtype",e,t,n),a=R("elementShape",e,t,n);return[i.concat(o,a)]}case"TensorListPushBack":{const s=R("tensorListId",e,t,n),i=R("tensor",e,t,n),o=n.getTensorList(s.id);return o.pushBack(i),[o.idTensor]}case"TensorListPopBack":{const s=R("tensorListId",e,t,n),i=R("elementShape",e,t,n),o=R("elementDType",e,t,n),a=n.getTensorList(s.id);return[a.popBack(i,o)]}case"TensorListSplit":{const s=R("tensor",e,t,n),i=R("elementShape",e,t,n),o=R("lengths",e,t,n),a=xH(s,o,i);return n.addTensorList(a),[a.idTensor]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},Ane="control";function y0(e,t,n){const[s,i]=R("fusedOps",e,t,n),o=s==="biasadd",a=i==="prelu",c=s==="fusedbatchnorm",h=R("numArgs",e,t,n);if(o){if(a&&h!==2)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!a&&h!==1)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd must have one extra argument: bias.")}if(c)throw new Error("FusedConv2d and DepthwiseConv2d with FusedBatchNorm is not supported.");const p=R("strides",e,t,n),m=Bm(e,t,n),y=R("dataFormat",e,t,n).toUpperCase(),b=R("dilations",e,t,n),[w,L]=R("args",e,t,n);return{stride:p,pad:m,dataFormat:y,dilations:b,biasArg:w,preluArg:L,activationFunc:i}}const AH=(e,t,n)=>{switch(e.op){case"Conv1D":{const s=R("stride",e,t,n),i=R("pad",e,t,n),o=R("dataFormat",e,t,n).toUpperCase(),a=R("dilation",e,t,n);return[Ip(R("x",e,t,n),R("filter",e,t,n),s,i,o,a)]}case"Conv2D":{const s=R("strides",e,t,n),i=Bm(e,t,n),o=R("dataFormat",e,t,n).toUpperCase(),a=R("dilations",e,t,n);return[sr(R("x",e,t,n),R("filter",e,t,n),[s[1],s[2]],i,o,[a[1],a[2]])]}case"_FusedConv2D":{const{stride:s,pad:i,dataFormat:o,dilations:a,biasArg:c,preluArg:h,activationFunc:p}=y0(e,t,n);return[mw({x:R("x",e,t,n),filter:R("filter",e,t,n),strides:[s[1],s[2]],pad:i,dataFormat:o,dilations:[a[1],a[2]],bias:c,activation:p,preluActivationWeights:h})]}case"FusedDepthwiseConv2dNative":{const{stride:s,pad:i,dataFormat:o,dilations:a,biasArg:c,preluArg:h,activationFunc:p}=y0(e,t,n);return[uv({x:R("x",e,t,n),filter:R("filter",e,t,n),strides:[s[1],s[2]],pad:i,dataFormat:o,dilations:[a[1],a[2]],bias:c,activation:p,preluActivationWeights:h})]}case"Conv2DBackpropInput":case"Conv2dTranspose":{const s=R("outputShape",e,t,n),i=R("strides",e,t,n),o=Bm(e,t,n);return[xp(R("x",e,t,n),R("filter",e,t,n),s,[i[1],i[2]],o)]}case"DepthwiseConv2dNative":case"DepthwiseConv2d":{const s=R("strides",e,t,n),i=Bm(e,t,n),o=R("dilations",e,t,n),a=R("dataFormat",e,t,n).toUpperCase();return[Bo(R("input",e,t,n),R("filter",e,t,n),[s[1],s[2]],i,a,[o[1],o[2]])]}case"Conv3D":{const s=R("strides",e,t,n),i=R("pad",e,t,n),o=R("dataFormat",e,t,n).toUpperCase(),a=R("dilations",e,t,n);return[Bb(R("x",e,t,n),R("filter",e,t,n),[s[1],s[2],s[3]],i,o,[a[1],a[2],a[3]])]}case"AvgPool":{const s=R("strides",e,t,n),i=R("pad",e,t,n),o=R("kernelSize",e,t,n);return[Sh(R("x",e,t,n),[o[1],o[2]],[s[1],s[2]],i)]}case"MaxPool":{const s=R("strides",e,t,n),i=R("pad",e,t,n),o=R("kernelSize",e,t,n);return[Rh(R("x",e,t,n),[o[1],o[2]],[s[1],s[2]],i)]}case"MaxPoolWithArgmax":{const s=R("strides",e,t,n),i=R("pad",e,t,n),o=R("kernelSize",e,t,n),a=R("includeBatchInIndex",e,t,n),{result:c,indexes:h}=$A(R("x",e,t,n),[o[1],o[2]],[s[1],s[2]],i,a);return[c,h]}case"AvgPool3D":{const s=R("strides",e,t,n),i=R("pad",e,t,n),o=R("kernelSize",e,t,n);return[Wb(R("x",e,t,n),[o[1],o[2],o[3]],[s[1],s[2],s[3]],i)]}case"MaxPool3D":{const s=R("strides",e,t,n),i=R("pad",e,t,n),o=R("kernelSize",e,t,n);return[Kb(R("x",e,t,n),[o[1],o[2],o[3]],[s[1],s[2],s[3]],i)]}case"Dilation2D":{const s=R("strides",e,t,n),i=R("pad",e,t,n),o=R("dilations",e,t,n),a=s[1],c=s[2],h=o[1],p=o[2];return[Pb(R("x",e,t,n),R("filter",e,t,n),[a,c],i,[h,p],"NHWC")]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},vne="convolution";const vH=(e,t,n)=>{switch(e.op){case"Fill":{const s=R("shape",e,t,n),i=R("dtype",e,t,n),o=R("value",e,t,n);return[Ja(s,o,i)]}case"LinSpace":{const s=R("start",e,t,n),i=R("stop",e,t,n),o=R("num",e,t,n);return[FA(s,i,o)]}case"Multinomial":{const s=R("logits",e,t,n),i=R("numSamples",e,t,n),o=R("seed",e,t,n);return[UA(s,i,o)]}case"OneHot":{const s=R("indices",e,t,n),i=R("depth",e,t,n),o=R("onValue",e,t,n),a=R("offValue",e,t,n);return[_o(s,i,o,a)]}case"Ones":return[ti(R("shape",e,t,n),R("dtype",e,t,n))];case"OnesLike":return[Wn(R("x",e,t,n))];case"RandomUniform":return[Go(R("shape",e,t,n),R("minval",e,t,n),R("maxval",e,t,n),R("dtype",e,t,n))];case"Range":{const s=R("start",e,t,n),i=R("stop",e,t,n),o=R("step",e,t,n);return[Dh(s,i,o,R("dtype",e,t,n))]}case"TruncatedNormal":{const s=R("shape",e,t,n),i=R("mean",e,t,n),o=R("stdDev",e,t,n),a=R("seed",e,t,n);return[$h(s,i,o,R("dtype",e,t,n),a)]}case"Zeros":return[pt(R("shape",e,t,n),R("dtype",e,t,n))];case"ZerosLike":return[tt(R("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},Nne="creation";function IS(e,t,n){const s=R("boxes",e,t,n),i=R("scores",e,t,n),o=R("maxOutputSize",e,t,n),a=R("iouThreshold",e,t,n),c=R("scoreThreshold",e,t,n),h=R("softNmsSigma",e,t,n);return{boxes:s,scores:i,maxOutputSize:o,iouThreshold:a,scoreThreshold:c,softNmsSigma:h}}const NH=async(e,t,n)=>{switch(e.op){case"NonMaxSuppressionV5":{const{boxes:s,scores:i,maxOutputSize:o,iouThreshold:a,scoreThreshold:c,softNmsSigma:h}=IS(e,t,n),p=await Xr.nonMaxSuppressionWithScoreAsync(s,i,o,a,c,h);return[p.selectedIndices,p.selectedScores]}case"NonMaxSuppressionV4":{const{boxes:s,scores:i,maxOutputSize:o,iouThreshold:a,scoreThreshold:c}=IS(e,t,n),h=R("padToMaxOutputSize",e,t,n),p=await Xr.nonMaxSuppressionPaddedAsync(s,i,o,a,c,h);return[p.selectedIndices,p.validOutputs]}case"NonMaxSuppressionV3":case"NonMaxSuppressionV2":{const{boxes:s,scores:i,maxOutputSize:o,iouThreshold:a,scoreThreshold:c}=IS(e,t,n);return[await Xr.nonMaxSuppressionAsync(s,i,o,a,c)]}case"Where":{const s=ve(R("condition",e,t,n),"bool"),i=[await hw(s)];return s.dispose(),i}case"ListDiff":return MA(R("x",e,t,n),R("y",e,t,n));default:throw TypeError(`Node type ${e.op} is not implemented`)}},Cne="dynamic";const CH=(e,t,n)=>{switch(e.op){case"TopKV2":{const s=R("x",e,t,n),i=R("k",e,t,n),o=R("sorted",e,t,n),a=cw(s,i,o);return[a.values,a.indices]}case"Unique":{const s=R("x",e,t,n),i=zp(s);return[i.values,i.indices]}case"UniqueV2":{const s=R("x",e,t,n),i=R("axis",e,t,n),o=zp(s,i);return[o.values,o.indices]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},Rne="evaluation";const RH=(e,t,n)=>{switch(e.op){case"Const":return t[e.name];case"PlaceholderWithDefault":const s=R("default",e,t,n);return[os(e.name,t,n)||s];case"Placeholder":return[os(e.name,t,n)];case"Identity":case"StopGradient":case"FakeQuantWithMinMaxVars":{const p=R("x",e,t,n);return[pr(p)]}case"IdentityN":return R("x",e,t,n).map(p=>pr(p));case"Snapshot":const i=R("x",e,t,n);return[pr(i)];case"Shape":return[ds(R("x",e,t,n).shape,"int32")];case"ShapeN":return R("x",e,t,n).map(p=>ds(p.shape));case"Size":return[Ce(R("x",e,t,n).size,"int32")];case"Rank":return[Ce(R("x",e,t,n).rank,"int32")];case"NoOp":return[Ce(1)];case"Print":const o=R("x",e,t,n),a=R("data",e,t,n),c=R("message",e,t,n),h=R("summarize",e,t,n);console.warn("The graph has a tf.print() operation,usually used for debugging, which slows down performance."),console.log(c);for(let p=0;p<a.length;p++)console.log(Array.prototype.slice.call(a[p].dataSync()).slice(0,h));return[o];default:throw TypeError(`Node type ${e.op} is not implemented`)}},One="graph";class OH{constructor(e,t){this.keyDType=e,this.valueDType=t,this.handle=Ce(0),this.tensorMap=new Map,wn(this.handle)}get id(){return this.handle.id}clearAndClose(){this.tensorMap.forEach(e=>e.dispose()),this.tensorMap.clear(),this.handle.dispose()}size(){return this.tensorMap.size}async import(e,t){this.checkKeyAndValueTensor(e,t);const n=await e.data();return this.tensorMap.forEach(s=>s.dispose()),this.tensorMap.clear(),ee(()=>{const s=si(t),i=n.length,o=s.length;A(i===o,()=>`The number of elements doesn't match, keys has ${i} elements, the values has ${o} elements.`);for(let a=0;a<i;a++){const c=n[a],h=s[a];wn(h),this.tensorMap.set(c,h)}return this.handle})}async find(e,t){this.checkKeyAndValueTensor(e,t);const n=await e.data();return ee(()=>{const s=[];for(let i=0;i<n.length;i++){const o=n[i],a=this.findWithDefault(o,t);s.push(a)}return ss(s)})}findWithDefault(e,t){const n=this.tensorMap.get(e);return n!=null?n:t}checkKeyAndValueTensor(e,t){if(e.dtype!==this.keyDType)throw new Error(`Expect key dtype ${this.keyDType}, but got ${e.dtype}`);if(t.dtype!==this.valueDType)throw new Error(`Expect value dtype ${this.valueDType}, but got ${t.dtype}`)}}const EH=async(e,t,n,s)=>{switch(e.op){case"HashTable":case"HashTableV2":{const i=R("keyDType",e,t,n),o=R("valueDType",e,t,n),a=new OH(i,o);return s.addHashTable(e.name,a),[a.handle]}case"LookupTableImport":case"LookupTableImportV2":{const i=R("tableHandle",e,t,n,s),o=R("keys",e,t,n),a=R("values",e,t,n),c=s.getHashTableById(i.id);return[await c.import(o,a)]}case"LookupTableFind":case"LookupTableFindV2":{const i=R("tableHandle",e,t,n,s),o=R("keys",e,t,n),a=R("defaultValue",e,t,n),c=s.getHashTableById(i.id);return[await c.find(o,a)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},Ene="hash_table";const DH=(e,t,n)=>{switch(e.op){case"ResizeBilinear":{const s=R("images",e,t,n),i=R("size",e,t,n),o=R("alignCorners",e,t,n);return[Xr.resizeBilinear(s,[i[0],i[1]],o)]}case"ResizeNearestNeighbor":{const s=R("images",e,t,n),i=R("size",e,t,n),o=R("alignCorners",e,t,n);return[Xr.resizeNearestNeighbor(s,[i[0],i[1]],o)]}case"CropAndResize":{const s=R("image",e,t,n),i=R("boxes",e,t,n),o=R("boxInd",e,t,n),a=R("cropSize",e,t,n),c=R("method",e,t,n),h=R("extrapolationValue",e,t,n);return[Xr.cropAndResize(s,i,o,a,c,h)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},Dne="image";const kH=(e,t,n)=>{switch(e.op){case"Equal":return[ei(R("a",e,t,n),R("b",e,t,n))];case"NotEqual":return[qr(R("a",e,t,n),R("b",e,t,n))];case"Greater":return[vs(R("a",e,t,n),R("b",e,t,n))];case"GreaterEqual":return[ir(R("a",e,t,n),R("b",e,t,n))];case"Less":return[Nh(R("a",e,t,n),R("b",e,t,n))];case"LessEqual":return[Hr(R("a",e,t,n),R("b",e,t,n))];case"LogicalAnd":return[Ps(R("a",e,t,n),R("b",e,t,n))];case"LogicalNot":return[Ch(R("a",e,t,n))];case"LogicalOr":return[Ep(R("a",e,t,n),R("b",e,t,n))];case"Select":case"SelectV2":return[Pn(R("condition",e,t,n),R("a",e,t,n),R("b",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},kne="logical";const FH=(e,t,n)=>{switch(e.op){case"BatchMatMul":case"BatchMatMulV2":case"MatMul":return[lt(R("a",e,t,n),R("b",e,t,n),R("transposeA",e,t,n),R("transposeB",e,t,n))];case"Transpose":return[Ye(R("x",e,t,n),R("perm",e,t,n))];case"_FusedMatMul":const[s,i]=R("fusedOps",e,t,n),o=s==="biasadd",a=i==="prelu",c=R("numArgs",e,t,n);if(o){if(a&&c!==2)throw new Error("Fused MatMul with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!a&&c!==1)throw new Error("Fused MatMul with BiasAdd must have one extra argument: bias.")}const[h,p]=R("args",e,t,n);return[Kp({a:R("a",e,t,n),b:R("b",e,t,n),transposeA:R("transposeA",e,t,n),transposeB:R("transposeB",e,t,n),bias:h,activation:i,preluActivationWeights:p})];default:throw TypeError(`Node type ${e.op} is not implemented`)}},Fne="matrices";const _H=(e,t,n)=>{switch(e.op){case"FusedBatchNorm":case"FusedBatchNormV2":return[Uo(R("x",e,t,n),R("mean",e,t,n),R("variance",e,t,n),R("offset",e,t,n),R("scale",e,t,n),R("epsilon",e,t,n))];case"FusedBatchNormV3":return[Uo(R("x",e,t,n),R("mean",e,t,n),R("variance",e,t,n),R("offset",e,t,n),R("scale",e,t,n),R("epsilon",e,t,n))];case"LRN":return[Hb(R("x",e,t,n),R("radius",e,t,n),R("bias",e,t,n),R("alpha",e,t,n),R("beta",e,t,n))];case"Softmax":return[Yo(R("x",e,t,n))];case"LogSoftmax":return[Op(R("x",e,t,n))];case"SparseToDense":return[uw(R("sparseIndices",e,t,n),R("outputShape",e,t,n),R("sparseValues",e,t,n),R("defaultValue",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},_ne="normalization";const WH=(e,t,n)=>{switch(e.op){case"Max":{const s=R("axis",e,t,n),i=R("keepDims",e,t,n);return[ns(R("x",e,t,n),s,i)]}case"Mean":{const s=R("axis",e,t,n),i=R("keepDims",e,t,n);return[qt(R("x",e,t,n),s,i)]}case"Min":{const s=R("axis",e,t,n),i=R("keepDims",e,t,n);return[tc(R("x",e,t,n),s,i)]}case"Sum":{const s=R("axis",e,t,n),i=R("keepDims",e,t,n);return[$e(R("x",e,t,n),s,i)]}case"All":{const s=R("axis",e,t,n),i=R("keepDims",e,t,n);return[yp(R("x",e,t,n),s,i)]}case"Any":{const s=R("axis",e,t,n),i=R("keepDims",e,t,n);return[bh(R("x",e,t,n),s,i)]}case"ArgMax":{const s=R("axis",e,t,n);return[wh(R("x",e,t,n),s)]}case"ArgMin":{const s=R("axis",e,t,n);return[Cb(R("x",e,t,n),s)]}case"Prod":{const s=R("axis",e,t,n),i=R("keepDims",e,t,n);return[Fp(R("x",e,t,n),s,i)]}case"Cumsum":{const s=R("axis",e,t,n),i=R("exclusive",e,t,n),o=R("reverse",e,t,n);return[Ap(R("x",e,t,n),s,i,o)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},Wne="reduction";const $H=(e,t,n)=>{switch(e.op){case"ConcatV2":case"Concat":{const s=R("n",e,t,n),i=R("axis",e,t,n);let o=R("tensors",e,t,n);return o=o.slice(0,s),[Yt(o,i)]}case"GatherV2":case"Gather":{const s=R("axis",e,t,n),i=R("x",e,t,n),o=R("indices",e,t,n);return[Qa(i,ve(o,"int32"),s)]}case"ReverseV2":case"Reverse":{const s=R("axis",e,t,n),i=R("x",e,t,n);return[Ns(i,s)]}case"Slice":{const s=R("begin",e,t,n),i=R("size",e,t,n);return[nt(R("x",e,t,n),s,i)]}case"StridedSlice":{const s=R("begin",e,t,n),i=R("end",e,t,n),o=R("strides",e,t,n),a=R("beginMask",e,t,n),c=R("endMask",e,t,n),h=R("ellipsisMask",e,t,n),p=R("newAxisMask",e,t,n),m=R("shrinkAxisMask",e,t,n),y=R("x",e,t,n);return[ow(y,s,i,o,a,c,h,p,m)]}case"Pack":return ee(()=>{const s=R("axis",e,t,n),i=R("tensors",e,t,n),o=i[0].shape,a=jr(i[0]).shape,c=i.map(h=>{const p=ie(h.shape,o);if(!p&&!ie(jr(h).shape,a))throw new Error("the input tensors shape does not match");return p?h:K(h,o)});return[ss(c,s)]});case"Unpack":{const s=R("axis",e,t,n),i=R("tensor",e,t,n);return si(i,s)}case"Tile":{const s=R("reps",e,t,n);return[Yr(R("x",e,t,n),s)]}case"Split":case"SplitV":{const s=R("axis",e,t,n),i=R("numOrSizeSplits",e,t,n),o=R("x",e,t,n);return ps(o,i,s)}case"ScatterNd":{const s=R("indices",e,t,n),i=R("values",e,t,n),o=R("shape",e,t,n);return[rv(s,i,o)]}case"GatherNd":{const s=R("x",e,t,n),i=R("indices",e,t,n);return[ov(s,i)]}case"SparseToDense":{const s=R("sparseIndices",e,t,n),i=R("outputShape",e,t,n),o=R("sparseValues",e,t,n),a=R("defaultValue",e,t,n);return[uw(s,o,i,o.dtype===a.dtype?a:ve(a,o.dtype))]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},$ne="slice_join";const UH=(e,t,n)=>{switch(e.op){case"FFT":return[Fh(R("x",e,t,n))];case"IFFT":return[rc(R("x",e,t,n))];case"RFFT":return[_h(R("x",e,t,n))];case"IRFFT":return[Pp(R("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},Une="spectral";const BH=(e,t,n)=>{switch(e.op){case"Cast":return[ve(R("x",e,t,n),R("dtype",e,t,n))];case"ExpandDims":{const s=R("axis",e,t,n);return[ts(R("x",e,t,n),s)]}case"Squeeze":{const s=R("axis",e,t,n);return[jr(R("x",e,t,n),s)]}case"Reshape":return[K(R("x",e,t,n),R("shape",e,t,n))];case"MirrorPad":return[Xb(R("x",e,t,n),R("padding",e,t,n),R("mode",e,t,n))];case"PadV2":case"Pad":return[Ei(R("x",e,t,n),R("padding",e,t,n),R("constantValue",e,t,n))];case"SpaceToBatchND":{const s=R("blockShape",e,t,n),i=R("paddings",e,t,n);return[Oh(R("x",e,t,n),s,i)]}case"BatchToSpaceND":{const s=R("blockShape",e,t,n),i=R("crops",e,t,n);return[Ih(R("x",e,t,n),s,i)]}case"DepthToSpace":{const s=R("blockSize",e,t,n),i=R("dataFormat",e,t,n).toUpperCase();return[Mb(R("x",e,t,n),s,i)]}case"BroadcastTo":return[xh(R("x",e,t,n),R("shape",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},Bne="transformation";function b0(e,t,n,s){const i=((o,a,c)=>{switch(o.category){case"arithmetic":return ee(()=>gH(o,a,c));case"basic_math":return ee(()=>yH(o,a,c));case"control":return TH(o,a,c);case"convolution":return ee(()=>AH(o,a,c));case"creation":return ee(()=>vH(o,a,c));case"dynamic":return NH(o,a,c);case"evaluation":return ee(()=>CH(o,a,c));case"image":return ee(()=>DH(o,a,c));case"graph":return ee(()=>RH(o,a,c));case"logical":return ee(()=>kH(o,a,c));case"matrices":return ee(()=>FH(o,a,c));case"normalization":return ee(()=>_H(o,a,c));case"reduction":return ee(()=>WH(o,a,c));case"slice_join":return ee(()=>$H(o,a,c));case"spectral":return ee(()=>UH(o,a,c));case"transformation":return ee(()=>BH(o,a,c));case"hash_table":return EH(o,a,c,s);case"custom":const h=d0(o.op);if(h&&h.customExecutor)return h.customExecutor(new fH(o,a,c));throw TypeError(`Custom op ${o.op} is not registered.`);default:throw TypeError(`Unknown op '${o.op}'. File an issue at https://github.com/tensorflow/tfjs/issues so we can add it, or register a custom execution with tf.registerOp()`)}})(e,t,n);return Ro(i)?i.then(o=>[].concat(o)):[].concat(i)}class w0{constructor(e={},t={},n={},s={}){this.weightMap=e,this.tensorArrayMap=t,this.tensorListMap=n,this.functionMap=s,this.rootContext={id:0,frameName:"",iterationId:0},this.contexts=[this.rootContext],this.lastId=0,this.generateCurrentContextIds()}newFrame(e,t){return{id:e,frameName:t,iterationId:0}}set currentContext(e){this.contexts!==e&&(this.contexts=e,this.generateCurrentContextIds())}get currentContext(){return this.contexts}get currentContextId(){return this._currentContextIds[0]}get currentContextIds(){return this._currentContextIds}generateCurrentContextIds(){const e=[];for(let t=0;t<this.contexts.length-1;t++){const n=this.contexts.slice(0,this.contexts.length-t);e.push(this.contextIdforContexts(n))}e.push(""),this._currentContextIds=e}contextIdforContexts(e){return e?e.map(t=>t.id===0&&t.iterationId===0?"":`${t.frameName}-${t.iterationId}`).join("/"):""}enterFrame(e){this.contexts&&(this.lastId++,this.contexts=this.contexts.slice(),this.contexts.push(this.newFrame(this.lastId,e)),this._currentContextIds.unshift(this.contextIdforContexts(this.contexts)))}exitFrame(){if(this.contexts&&this.contexts.length>1)this.contexts=this.contexts.slice(),this.contexts.splice(-1),this.currentContextIds.shift();else throw new Error("Cannot exit frame, the context is empty")}nextIteration(){if(this.contexts&&this.contexts.length>0){this.contexts=this.contexts.slice(),this.lastId++;const e=Object.assign({},this.contexts[this.contexts.length-1]);e.iterationId+=1,e.id=this.lastId,this.contexts.splice(-1,1,e),this._currentContextIds.splice(0,1,this.contextIdforContexts(this.contexts))}else throw new Error("Cannot increase frame iteration, the context is empty")}getWeight(e){return this.weightMap[e]}addTensorArray(e){this.tensorArrayMap[e.id]=e}getTensorArray(e){return this.tensorArrayMap[e]}addTensorList(e){this.tensorListMap[e.id]=e}getTensorList(e){return this.tensorListMap[e]}dispose(e){for(const t in this.tensorArrayMap)this.tensorArrayMap[t].clearAndClose(e);for(const t in this.tensorListMap)this.tensorListMap[t].clearAndClose(e)}}function L0(e,t,n,s){const i=new Set,o=[];let a=null,c=null;const h=new Set,p=Object.keys(e).map(b=>fs(b)[0]);let m=[];s!=null&&(m=s.map(b=>fs(b.name)[0]));const y=[...t];for(;y.length>0;){const b=y.pop();if((S0(b)||GH(b)||YH(b))&&(a==null&&(a=b,c=a.children.map(w=>w.name).filter(w=>i.has(w)))),i.add(b.name),n[b.name]!=null)continue;if(p.indexOf(b.name)!==-1)continue;if(m.indexOf(b.name)!==-1)continue;if(b.inputs.length===0){o.push(b.name);continue}b.inputs.forEach(w=>{if(h.has(w.name))return;h.add(w.name),y.push(w)})}return{inputs:e,outputs:t,usedNodes:i,missingInputs:o,dynamicNode:a,syncInputs:c}}function MH(e,t,n){const{usedNodes:s,inputs:i}=n,o=[],a=Object.keys(i).map(m=>fs(m)[0]).map(m=>e.nodes[m]),c=e.initNodes;a.forEach(m=>{s.has(m.name)&&o.push(m)}),e.weights.forEach(m=>{s.has(m.name)&&o.push(m)}),c!=null&&c.forEach(m=>{s.has(m.name)&&o.push(m)});const h=new Set,p=[];for(;o.length>0;){const m=o.pop();h.add(m.name),t[m.name]||p.push(m),m.children.forEach(y=>{!h.has(y.name)&&s.has(y.name)&&y.inputs.every(b=>h.has(b.name))&&o.push(y)})}return p}const PH=["Switch","Merge","Enter","Exit","NextIteration","StatelessIf","StatelessWhile","if","While"],zH=["NonMaxSuppressionV2","NonMaxSuppressionV3","NonMaxSuppressionV5","Where"],VH=["HashTable","HashTableV2","LookupTableImport","LookupTableImportV2","LookupTableFind","LookupTableFindV2"];function S0(e){return PH.indexOf(e.op)>=0}function GH(e){return zH.indexOf(e.op)>=0}function YH(e){return VH.indexOf(e.op)>=0}class xS{constructor(e,t){this.graph=e,this.parent=t,this.compiledMap=new Map,this._weightMap={},this.SEPERATOR=",",this._functions={},this._functionExecutorMap={},this._outputs=e.outputs,this._inputs=e.inputs,this._initNodes=e.initNodes,this._signature=e.signature,this._functions=e.functions,e.functions!=null&&Object.keys(e.functions).forEach(n=>{this._functionExecutorMap[n]=new xS(e.functions[n],this)})}get weightIds(){return this.parent?this.parent.weightIds:this._weightIds}get functionExecutorMap(){return this.parent?this.parent.functionExecutorMap:this._functionExecutorMap}get weightMap(){return this.parent?this.parent.weightMap:this._weightMap}set weightMap(e){const t=Object.keys(e).map(n=>e[n].map(s=>s.id));this._weightIds=[].concat(...t),this._weightMap=e}set resourceManager(e){this._resourceManager=e}get inputs(){return this._inputs.map(e=>({name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0}))}get outputs(){return this._outputs.map(e=>({name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0}))}get inputNodes(){return this._inputs.map(e=>e.signatureKey||e.name)}get outputNodes(){return this._outputs.map(e=>{const t=e.signatureKey||e.name;return e.defaultOutput?`${t}:${e.defaultOutput}`:t})}get functions(){return Object.keys(this._functions).reduce((e,t)=>(e[t]=this._functions[t].signature,e),{})}getCompilationKey(e,t){const n=e.map(i=>i.name).sort(),s=t.map(i=>i.name).sort();return n.join(this.SEPERATOR)+"--"+s.join(this.SEPERATOR)}compile(e,t){const n=L0(e,t,this.weightMap,this._initNodes),{missingInputs:s,dynamicNode:i,syncInputs:o}=n;if(i!=null)throw new Error(`This execution contains the node '${i.name}', which has the dynamic op '${i.op}'. Please use model.executeAsync() instead. Alternatively, to avoid the dynamic ops, specify the inputs [${o}]`);if(s.length>0){const a=t.map(h=>h.name),c=Object.keys(e);throw new Error(`Cannot compute the outputs [${a}] from the provided inputs [${c}]. Missing the following inputs: [${s}]`)}return MH(this.graph,this.weightMap,n)}execute(e,t){e=this.mapInputs(e);const n=Object.keys(e).sort();this.checkInputs(e),this.checkInputShapeAndType(e),t=this.mapOutputs(t),this.checkOutputs(t);const s=n.map(m=>this.graph.nodes[fs(m)[0]]),i=t.map(m=>fs(m)[0]);let o=i.map(m=>this.graph.nodes[m]);o.length===0&&(o=this._outputs);const a=this.getCompilationKey(s,o);let c=this.compiledMap.get(a);c==null&&(c=this.compile(e,o),this.compiledMap.set(a,c));const h={},p={};return ee(()=>{const m=new w0(this.weightMap,h,p,this.functionExecutorMap),y=Object.assign({},this.weightMap);Object.keys(e).forEach(L=>{const[T,v]=fs(L),C=[];C[v]=e[L],y[T]=C});const b=this.getFrozenTensorIds(y),w={};for(let L=0;L<c.length;L++){const T=c[L];if(!y[T.name]){const v=b0(T,y,m,this._resourceManager);if(Ro(v))throw new Error(`The execution of the op '${T.op}' returned a promise. Please use model.executeAsync() instead.`);y[T.name]=v,this.checkTensorForDisposal(T.name,T,y,m,b,i,w)}}return this.parent==null&&m.dispose(b),t.map(L=>os(L,y,m))})}getFrozenTensorIds(e){const t=[].concat.apply([],Object.keys(e).map(n=>e[n]).map(n=>n.map(s=>s.id)));return new Set(t)}checkTensorForDisposal(e,t,n,s,i,o,a){if(t.category==="control"||o.indexOf(e)!==-1)return;n[e].forEach(c=>{c!=null&&(a[c.id]=(a[c.id]||0)+t.children.length)}),t.inputs.forEach(c=>{if(c.category!=="control"){const h=kY(c.name,n,s);h!=null&&h.forEach(p=>{if(p&&!i.has(p.id)){const m=a[p.id];m===1?(p.dispose(),delete a[p.id]):m!=null&&a[p.id]--}})}})}async executeAsync(e,t){return this._executeAsync(e,t)}async _executeAsync(e,t,n=!1,s={},i={}){n||(e=this.mapInputs(e),this.checkInputs(e),this.checkInputShapeAndType(e),t=this.mapOutputs(t),this.checkOutputs(t));const o=new w0(this.weightMap,s,i,this.functionExecutorMap),a=await this.executeWithControlFlow(e,o,t,n),c=t.map(y=>os(y,a,o)),h=c.map(y=>y.id),p=Object.keys(e).map(y=>e[y].id),m=new Set([...h,...p,...this.weightIds]);return Object.keys(a).forEach(y=>{const b=a[y];b.forEach(w=>{w&&!w.isDisposed&&!m.has(w.id)&&w.dispose()})}),this.parent==null&&o.dispose(m),c}async executeFunctionAsync(e,t,n){const s=e.reduce((i,o,a)=>(i[this.inputs[a].name]=o,i),{});return this._executeAsync(s,this.outputNodes,!0,t,n)}async executeWithControlFlow(e,t,n,s){const i=Object.keys(e),o=i.map(O=>this.graph.nodes[fs(O)[0]]),a=n.map(O=>fs(O)[0]);let c=a.map(O=>this.graph.nodes[O]);c.length===0&&(c=this._outputs);const{usedNodes:h,missingInputs:p,dynamicNode:m,syncInputs:y}=L0(e,c,this.weightMap,this._initNodes),b=[...o,...this.graph.weights,...this._initNodes||[]].map(O=>({node:O,contexts:t.currentContext})),w=Object.assign({},this.weightMap);Object.keys(e).forEach(O=>{const[D,k]=fs(O),F=[];F[k]=e[O],w[D]=F});const L={},T=this.getFrozenTensorIds(w),v={};for(;b.length>0;){const O=this.processStack(o,b,t,w,v,T,a,L,h);await Promise.all(O)}m==null&&!s&&console.warn("This model execution did not contain any nodes with control flow or dynamic output shapes. You can use model.execute() instead.");const C=c.filter(O=>!S0(O)&&!os(O.name,w,t)).map(O=>O.name);if(C.length>0){let O="";throw m!=null&&(O=`Alternatively, to avoid the dynamic ops, use model.execute() and specify the inputs [${y}]`),new Error(`Cannot compute the outputs [${C}] from the provided inputs [${i}]. Consider providing the following inputs: [${p}]. ${O}`)}return w}processStack(e,t,n,s,i,o,a,c,h){const p=[];for(;t.length>0;){const m=t.pop();n.currentContext=m.contexts;let y="";if(m.node.op==="Enter"&&R("isConstant",m.node,s,n)&&([y]=dr(m.node.name,n)),s[m.node.name]==null){const b=b0(m.node,s,n,this._resourceManager);y||([y]=dr(m.node.name,n));const w=n.currentContext;Ro(b)?p.push(b.then(L=>(s[y]=L,n.currentContext=w,this.checkTensorForDisposal(y,m.node,s,n,o,a,c),this.processChildNodes(m.node,t,n,s,i,h),L))):(s[y]=b,this.checkTensorForDisposal(y,m.node,s,n,o,a,c),this.processChildNodes(m.node,t,n,s,i,h))}else this.processChildNodes(m.node,t,n,s,i,h)}return p}processChildNodes(e,t,n,s,i,o){e.children.forEach(a=>{const[c]=dr(a.name,n);if(i[c]||!o.has(a.name))return;a.op==="Merge"?a.inputNames.some(h=>!!os(h,s,n))&&(i[c]=!0,t.push({contexts:n.currentContext,node:a})):a.inputNames.every(h=>!!os(h,s,n))&&(i[c]=!0,t.push({contexts:n.currentContext,node:a}))})}dispose(){Object.keys(this.weightMap).forEach(e=>this.weightMap[e].forEach(t=>t.dispose()))}checkInputShapeAndType(e){Object.keys(e).forEach(t=>{const n=e[t],[s]=fs(t),i=this.graph.nodes[s];if(i.attrParams.shape&&i.attrParams.shape.value){const o=i.attrParams.shape.value,a=o.length===n.shape.length&&n.shape.every((c,h)=>o[h]===-1||o[h]===c);A(a,()=>`The shape of dict['${i.name}'] provided in model.execute(dict) must be [${o}], but was [${n.shape}]`)}i.attrParams.dtype&&i.attrParams.dtype.value&&A(n.dtype===i.attrParams.dtype.value,()=>`The dtype of dict['${i.name}'] provided in model.execute(dict) must be ${i.attrParams.dtype.value}, but was ${n.dtype}`)})}mapInputs(e){const t={};for(const n in e)if(this._signature!=null&&this._signature.inputs!=null&&this._signature.inputs[n]!=null){const s=this._signature.inputs[n];t[s.name]=e[n]}else t[n]=e[n];return t}checkInputs(e){const t=Object.keys(e).filter(n=>{const[s]=fs(n);return this.graph.nodes[s]==null});if(t.length>0)throw new Error(`The dict provided in model.execute(dict) has keys: [${t}] that are not part of graph`)}mapOutputs(e){return e.map(t=>{if(this._signature!=null&&this._signature.outputs!=null&&this._signature.outputs[t]!=null){const n=this._signature.outputs[t];return n.name}return t},{})}checkOutputs(e){e.forEach(t=>{const[n]=fs(t);if(!this.graph.nodes[n])throw new Error(`The output '${t}' is not found in the graph`)})}}class HH{constructor(e={},t={}){this.hashTableNameToHandle=e,this.hashTableMap=t}addHashTable(e,t){this.hashTableNameToHandle[e]=t.handle,this.hashTableMap[t.id]=t}getHashTableHandleByName(e){return this.hashTableNameToHandle[e]}getHashTableById(e){return this.hashTableMap[e]}dispose(){for(const e in this.hashTableMap)this.hashTableMap[e].clearAndClose(),delete this.hashTableMap[e];for(const e in this.hashTableNameToHandle)this.hashTableNameToHandle[e].dispose(),delete this.hashTableNameToHandle[e]}}const qH="?tfjs-format=file",jH="model.json";class I0{constructor(e,t={}){this.modelUrl=e,this.loadOptions=t,this.version="n/a",t==null&&(this.loadOptions={}),this.resourceManager=new HH}get modelVersion(){return this.version}get inputNodes(){return this.executor.inputNodes}get outputNodes(){return this.executor.outputNodes}get inputs(){return this.executor.inputs}get outputs(){return this.executor.outputs}get weights(){return this.executor.weightMap}findIOHandler(){const e=this.modelUrl;if(e.load!=null)this.handler=e;else if(this.loadOptions.requestInit!=null)this.handler=lp(e,this.loadOptions);else{const t=cb(e,this.loadOptions);if(t.length===0)t.push(lp(e,this.loadOptions));else if(t.length>1)throw new Error(`Found more than one (${t.length}) load handlers for URL '${[e]}'`);this.handler=t[0]}}async load(){if(this.findIOHandler(),this.handler.load==null)throw new Error("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");const e=await this.handler.load();return this.loadSync(e)}loadSync(e){this.artifacts=e;const t=this.artifacts.modelTopology;let n={};this.artifacts.userDefinedMetadata!=null&&(n=this.artifacts.userDefinedMetadata.signature),this.version=`${t.versions.producer}.${t.versions.minConsumer}`;const s=rp(this.artifacts.weightData,this.artifacts.weightSpecs);if(this.executor=new xS(p0.Instance.transformGraph(t,n)),this.executor.weightMap=this.convertTensorMapToTensorsMap(s),this.executor.resourceManager=this.resourceManager,e.modelInitializer!=null){const i=p0.Instance.transformGraph(e.modelInitializer);this.initializer=new xS(i),this.initializer.weightMap=this.executor.weightMap,this.initializer.resourceManager=this.resourceManager,this.initializer.executeAsync({},[])}return!0}async save(e,t){if(typeof e=="string"){const n=ab(e);if(n.length===0)throw new Error(`Cannot find any save handlers for URL '${e}'`);if(n.length>1)throw new Error(`Found more than one (${n.length}) save handlers for URL '${e}'`);e=n[0]}if(e.save==null)throw new Error("GraphModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");return e.save(this.artifacts)}predict(e,t){return this.execute(e,this.outputNodes)}normalizeInputs(e){if(!(e instanceof te)&&!Array.isArray(e))return e;if(e=Array.isArray(e)?e:[e],e.length!==this.inputNodes.length)throw new Error(`Input tensor count mismatch,the graph model has ${this.inputNodes.length} placeholders, while there are ${e.length} input tensors.`);return this.inputNodes.reduce((t,n,s)=>(t[n]=e[s],t),{})}normalizeOutputs(e){return e=e||this.outputNodes,Array.isArray(e)?e:[e]}execute(e,t){e=this.normalizeInputs(e),t=this.normalizeOutputs(t);const n=this.executor.execute(e,t);return n.length>1?n:n[0]}async executeAsync(e,t){e=this.normalizeInputs(e),t=this.normalizeOutputs(t);const n=await this.executor.executeAsync(e,t);return n.length>1?n:n[0]}convertTensorMapToTensorsMap(e){return Object.keys(e).reduce((t,n)=>(t[n]=[e[n]],t),{})}dispose(){this.executor.dispose(),this.initializer&&this.initializer.dispose(),this.resourceManager.dispose()}}async function KH(e,t={}){if(e==null)throw new Error("modelUrl in loadGraphModel() cannot be null. Please provide a url or an IOHandler that loads the model");t==null&&(t={}),t.fromTFHub&&(e.load==null&&(e.endsWith("/")||(e=e+"/"),e=`${e}${jH}${qH}`));const n=new I0(e,t);return await n.load(),n}const x0="2.7.0";function XH(e,t){return Mm(e,t)}function Mm(e,t,n=new Map,s=new Set){if(e==null)return null;if(s.has(e))throw new Error("Circular references are not supported.");if(n.has(e))return n.get(e);const i=t(e);if(i.recurse&&i.value!==null)throw new Error("A deep map function may not return both a value and recurse=true.");if(i.recurse)if(Lc(e)){const o=Array.isArray(e)?[]:{};s.add(e);for(const a in e){const c=e[a],h=Mm(c,t,n,s);o[a]=h}return s.delete(e),o}else throw new Error(`Can't recurse into non-iterable type: ${e}`);else return n.set(e,i.value),i.value}function JH(e,t=A0){return T0(e,t)}function T0(e,t,n=new Set){const s=e[0];if(n.has(s))throw new Error("Circular references are not supported.");const i=t(e);if(i.recurse&&i.value!==null)throw new Error("A deep zip function may not return both a value and recurse=true.");if(i.recurse)if(Lc(s)){const o=Array.isArray(s)?[]:{};n.add(s);for(const a in s){const c=e.map(p=>p[a]),h=T0(c,t,n);o[a]=h}return n.delete(s),o}else throw new Error(`Can't recurse into non-iterable type: ${s}`);else return i.value}function A0(e){return e===null?null:Lc(e[0])?{value:null,recurse:!0}:{value:e,recurse:!1}}async function v0(e,t){const n=new Map;Mm(e,t,n);for(const i of Array.from(n.keys())){const o=n.get(i);if(Ro(o)){const a=await o;n.set(i,a)}}const s=Mm(e,t,n);return s}function Lc(e){return e!=null&&!ArrayBuffer.isView(e)&&(Array.isArray(e)||typeof e=="object"&&!(e instanceof te))}function ZH(e){return e==null||QH(e)||Array.isArray(e)||typeof e=="object"&&e instanceof te||un(e)}function QH(e){return e===null||typeof e!="object"&&typeof e!="function"}function eq(e){return XH(e,tq)}function tq(e){return e instanceof te?{value:e.clone(),recurse:!1}:Lc(e)?{value:null,recurse:!0}:{value:e,recurse:!1}}class N0{constructor(e){if(this.capacity=e,this.begin=0,this.end=0,e==null)throw new RangeError("Can't create a ring buffer of unknown capacity.");if(e<1)throw new RangeError("Can't create ring buffer of capacity < 1.");this.data=new Array(e),this.doubledCapacity=2*e}wrap(e){for(;e<0;)e+=this.doubledCapacity;return e%this.doubledCapacity}get(e){if(e<0)throw new RangeError("Can't get item at a negative index.");return this.data[e%this.capacity]}set(e,t){if(e<0)throw new RangeError("Can't set item at a negative index.");this.data[e%this.capacity]=t}length(){let e=this.end-this.begin;return e<0&&(e=this.doubledCapacity+e),e}isFull(){return this.length()===this.capacity}isEmpty(){return this.length()===0}push(e){if(this.isFull())throw new RangeError("Ring buffer is full.");this.set(this.end,e),this.end=this.wrap(this.end+1)}pushAll(e){for(const t of e)this.push(t)}pop(){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");this.end=this.wrap(this.end-1);const e=this.get(this.end);return this.set(this.end,void 0),e}unshift(e){if(this.isFull())throw new RangeError("Ring buffer is full.");this.begin=this.wrap(this.begin-1),this.set(this.begin,e)}shift(){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");const e=this.get(this.begin);return this.set(this.begin,void 0),this.begin=this.wrap(this.begin+1),e}shuffleExcise(e){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");const t=this.wrap(this.begin+e),n=this.get(t);return this.set(t,this.pop()),n}}class TS extends N0{constructor(){super(TS.INITIAL_CAPACITY)}isFull(){return!1}push(e){super.isFull()&&this.expand(),super.push(e)}unshift(e){super.isFull()&&this.expand(),super.unshift(e)}expand(){const e=this.capacity*2,t=new Array(e),n=this.length();for(let s=0;s<n;s++)t[s]=this.get(this.wrap(this.begin+s));this.data=t,this.capacity=e,this.doubledCapacity=2*this.capacity,this.begin=0,this.end=n}}TS.INITIAL_CAPACITY=32;function C0(e){return new sq(e)}function Mne(e){let t=e;return yu(()=>({value:t++,done:!1}))}function yu(e){return new iq(e)}function R0(e,t){return new E0(e,t)}function Pne(e,t,n){return R0(yu(e).take(t),n)}function nq(e,t=ro.FAIL){return new pq(e,t)}class In{async toArray(){const e=[];let t=await this.next();for(;!t.done;)e.push(t.value),t=await this.next();return e}async toArrayForTest(){const e=this.prefetch(100),t=[];let n=await e.next();for(;!n.done;)t.push(n.value),n=await e.next();return t}async resolveFully(){let e=await this.next();for(;!e.done;)e=await this.next()}async resolveWhile(e){let t=await this.next(),n=e(t.value);for(;!t.done&&n;)t=await this.next(),n=e(t.value)}handleErrors(e){return new uq(this,e)}filter(e){return new lq(this,e)}map(e){return new hq(this,e)}mapAsync(e){return new O0(this,e)}serialMapAsync(e){return new O0(this,e).serial()}flatmap(e){return new dq(this,e)}async forEachAsync(e){return this.map(e).resolveFully()}async serialForEach(e){return this.serialMapAsync(e).resolveWhile(t=>t===!0)}rowMajorBatch(e,t=!0){return new cq(this,e,t)}columnMajorBatch(e,t=!0,n=A0){const s=this.rowMajorBatch(e,t);return s.map(i=>JH(i,n))}concatenate(e,t){return new E0(C0([this,e]),t)}take(e){return e<0||e==null?this:new aq(this,e)}skip(e){return e<0||e==null?this:new oq(this,e)}prefetch(e){return new D0(this,e)}shuffle(e,t){return new mq(this,e,t)}serial(){return new rq(this)}}class sq extends In{constructor(e){super();this.items=e,this.trav=0}summary(){return`Array of ${this.items.length} items`}async next(){if(this.trav>=this.items.length)return{value:null,done:!0};const e=this.items[this.trav];return this.trav++,{value:eq(e),done:!1}}}class iq extends In{constructor(e){super();this.nextFn=e}summary(){return"Function call"}async next(){try{return this.nextFn()}catch(e){throw e.message=`Error thrown while iterating through a dataset: ${e.message}`,e}}}class rq extends In{constructor(e){super();this.upstream=e,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> Serial`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){return this.upstream.next()}}class oq extends In{constructor(e,t){super();this.upstream=e,this.maxCount=t,this.count=0,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> Skip`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){for(;this.count++<this.maxCount;){const e=await this.upstream.next();if(e.done)return e;qe(e.value)}return this.upstream.next()}}class aq extends In{constructor(e,t){super();this.upstream=e,this.maxCount=t,this.count=0}summary(){return`${this.upstream.summary()} -> Take`}async next(){return this.count++>=this.maxCount?{value:null,done:!0}:this.upstream.next()}}class cq extends In{constructor(e,t,n=!0){super();this.upstream=e,this.batchSize=t,this.enableSmallLastBatch=n,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> RowMajorBatch`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){const e=[];for(;e.length<this.batchSize;){const t=await this.upstream.next();if(t.done)return this.enableSmallLastBatch&&e.length>0?{value:e,done:!1}:{value:null,done:!0};e.push(t.value)}return{value:e,done:!1}}}class lq extends In{constructor(e,t){super();this.upstream=e,this.predicate=t,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> Filter`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){for(;;){const e=await this.upstream.next();if(e.done||this.predicate(e.value))return e;qe(e.value)}}}class hq extends In{constructor(e,t){super();this.upstream=e,this.transform=t}summary(){return`${this.upstream.summary()} -> Map`}async next(){const e=await this.upstream.next();if(e.done)return{value:null,done:!0};const t=Zi(e.value),n=this.transform(e.value),s=Zi(n);for(const i of t)sp(i,s)||i.dispose();return{value:n,done:!1}}}class uq extends In{constructor(e,t){super();this.upstream=e,this.handler=t,this.count=0,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> handleErrors`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){for(;;)try{return await this.upstream.next()}catch(e){if(!this.handler(e))return{value:null,done:!0}}}}class O0 extends In{constructor(e,t){super();this.upstream=e,this.transform=t}summary(){return`${this.upstream.summary()} -> AsyncMap`}async next(){const e=await this.upstream.next();if(e.done)return{value:null,done:!0};const t=Zi(e.value),n=await this.transform(e.value),s=Zi(n);for(const i of t)sp(i,s)||i.dispose();return{value:n,done:!1}}}class AS extends In{constructor(){super();this.outputQueue=new TS,this.lastRead=Promise.resolve({value:null,done:!1})}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){for(;this.outputQueue.length()===0;)if(!await this.pump())return{value:null,done:!0};return{value:this.outputQueue.shift(),done:!1}}}class dq extends AS{constructor(e,t){super();this.upstream=e,this.transform=t}summary(){return`${this.upstream.summary()} -> Flatmap`}async pump(){const e=await this.upstream.next();if(e.done)return!1;const t=Zi(e.value),n=this.transform(e.value),s=Zi(n);this.outputQueue.pushAll(n);for(const i of t)sp(i,s)||i.dispose();return!0}}class E0 extends In{constructor(e,t){super();this.baseErrorHandler=t,this.lastRead=null,this.iterator=null,this.moreIterators=e}summary(){const e="TODO: fill in upstream of chained summaries";return`${e} -> Chained`}async next(){return this.lastRead=this.readFromChain(this.lastRead),this.lastRead}async readFromChain(e){if(await e,this.iterator==null){const n=await this.moreIterators.next();if(n.done)return{value:null,done:!0};this.iterator=n.value,this.baseErrorHandler!=null&&(this.iterator=this.iterator.handleErrors(this.baseErrorHandler))}const t=await this.iterator.next();return t.done?(this.iterator=null,this.readFromChain(e)):t}}var ro;(function(e){e[e.FAIL=0]="FAIL",e[e.SHORTEST=1]="SHORTEST",e[e.LONGEST=2]="LONGEST"})(ro||(ro={}));class pq extends In{constructor(e,t=ro.FAIL){super();this.iterators=e,this.mismatchMode=t,this.count=0,this.currentPromise=null}summary(){const e="TODO: fill in upstream of zip summaries";return`{${e}} -> Zip`}async nextState(e){await e;let t=0,n=0;function s(o){if(o instanceof In){const a=o.next();return{value:a.then(c=>(t++,c.done&&n++,c.value)),recurse:!1}}else return{value:null,recurse:!0}}const i=await v0(this.iterators,s);if(t===n)return{value:null,done:!0};if(n>0)switch(this.mismatchMode){case ro.FAIL:throw new Error(`Zipped streams should have the same length. Mismatched at element ${this.count}.`);case ro.SHORTEST:return{value:null,done:!0};case ro.LONGEST:default:}return this.count++,{value:i,done:!1}}async next(){return this.currentPromise=this.nextState(this.currentPromise),this.currentPromise}}class D0 extends In{constructor(e,t){super();this.upstream=e,this.bufferSize=t,this.buffer=new N0(t)}summary(){return`${this.upstream.summary()} -> Prefetch`}refill(){for(;!this.buffer.isFull();){const e=this.upstream.next();this.buffer.push(e)}}next(){return this.refill(),this.buffer.shift()}}class mq extends D0{constructor(e,t,n){super(e,t);this.upstream=e,this.windowSize=t,this.upstreamExhausted=!1,this.random=ic(n||Jn().toString()),this.lastRead=Promise.resolve({value:null,done:!1})}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}randomInt(e){return Math.floor(this.random()*e)}chooseIndex(){return this.randomInt(this.buffer.length())}async serialNext(){for(this.upstreamExhausted||this.refill();!this.buffer.isEmpty();){const e=this.chooseIndex(),t=await this.buffer.shuffleExcise(e);if(t.done)this.upstreamExhausted=!0;else return this.refill(),t}return{value:null,done:!0}}}class Sc{constructor(){this.size=null}batch(e,t=!0){const n=this;A(e>0,()=>`batchSize needs to be positive, but it is
${e}`);let s;return this.size===Infinity||this.size==null?s=this.size:t?s=Math.ceil(this.size/e):s=Math.floor(this.size/e),gs(async()=>(await n.iterator()).columnMajorBatch(e,t,yq),s)}concatenate(e){const t=this;let n;return this.size===Infinity||e.size===Infinity?n=Infinity:this.size!=null&&e.size!=null?n=this.size+e.size:n=null,gs(async()=>(await t.iterator()).concatenate(await e.iterator()),n)}filter(e){const t=this;let n;return this.size===Infinity?n=Infinity:n=null,gs(async()=>(await t.iterator()).filter(s=>ee(()=>e(s))),n)}async forEachAsync(e){return(await this.iterator()).forEachAsync(e)}map(e){const t=this;return gs(async()=>(await t.iterator()).map(n=>ee(()=>e(n))),this.size)}mapAsync(e){const t=this;return gs(async()=>(await t.iterator()).mapAsync(e),this.size)}prefetch(e){if(e==null)throw new RangeError("`Dataset.prefetch()` requires bufferSize to be specified.");const t=this;return gs(async()=>(await t.iterator()).prefetch(e),this.size)}repeat(e){const t=this;let n;return this.size!=null&&e>0?n=this.size*e:e===0?n=0:this.size!=null&&(e===void 0||e<0)?n=Infinity:n=null,gs(async()=>{const s=yu(async()=>({value:await t.iterator(),done:!1}));return R0(s.take(e))},n)}skip(e){const t=this;let n;return this.size!=null&&e>=0&&this.size>=e?n=this.size-e:this.size!=null&&(this.size<e||e===void 0||e<0)?n=0:n=null,gs(async()=>(await t.iterator()).skip(e),n)}shuffle(e,t,n=!0){if(e==null||e<0)throw this.size==null?new RangeError("`Dataset.shuffle()` requires bufferSize to be specified."):new RangeError(`\`Dataset.shuffle()\` requires bufferSize to be specified. If your data fits in main memory (for regular JS objects), and/or GPU memory (for \`tf.Tensor\`s), consider setting bufferSize to the dataset size (${this.size} elements)`);const s=this,i=ic(t||Jn().toString());return gs(async()=>{let o=i.int32();return n&&(o+=i.int32()),(await s.iterator()).shuffle(e,o.toString())},this.size)}take(e){const t=this;let n;return this.size!=null&&this.size>e?n=e:this.size!=null&&this.size<=e?n=this.size:n=null,gs(async()=>(await t.iterator()).take(e),n)}async toArray(){if(this.size===Infinity)throw new Error("Can not convert infinite data stream to array.");return(await this.iterator()).toArray()}async toArrayForTest(){if(this.size===Infinity)throw new Error("Can not convert infinite data stream to array.");return(await this.iterator()).toArrayForTest()}}Sc.MAX_BUFFER_SIZE=1e4;function gs(e,t=null){return new class extends Sc{constructor(){super(...arguments);this.size=t}async iterator(){return e()}}}function fq(e){return gs(async()=>C0(e),e.length)}function gq(e){if(!Lc(e))throw new Error("The argument to zip() must be an object or array.");let t;if(Array.isArray(e))for(let n=0;n<e.length;n++)t=t==null?e[n].size:Math.min(t,e[n].size);else if(e instanceof Object)for(const n in e)t=t==null?e[n].size:Math.min(t,e[n].size);return gs(async()=>{const n=await v0(e,s=>{if(s instanceof Sc)return{value:s.iterator(),recurse:!1};if(Lc(s))return{value:null,recurse:!0};throw new Error("Leaves of the structure passed to zip() must be Datasets, not primitives.")});return nq(n,ro.SHORTEST)},t)}function yq(e){if(e===null)return null;const t=e[0];if(ZH(t)){const n=bq(e);return{value:n,recurse:!1}}return{value:null,recurse:!0}}function bq(e){if(e.length===0)throw new Error("Can't make a batch of zero elements.");return e[0]instanceof te?ss(e):sn(e)}class k0 extends Sc{constructor(e){super();this.input=e}async iterator(){const e=await this.input.iterator(),t=e.decodeUTF8(),n=t.split(`
`).map(s=>(s.endsWith("\r")&&(s=s.slice(0,-1)),s));return n}}const Pm='"',bu=Symbol("out"),F0=Symbol("field"),zm=Symbol("quote"),vS=Symbol("quoteafterquote"),_0=Symbol("quoteinquote");class W0 extends Sc{constructor(e,t){super();this.input=e,this.hasHeader=!0,this.fullColumnNames=null,this.columnNamesValidated=!1,this.columnConfigs=null,this.configuredColumnsOnly=!1,this.delimiter=",",this.delimWhitespace=!1,this.base=new k0(e),t||(t={}),this.hasHeader=!(t.hasHeader===!1),this.fullColumnNames=t.columnNames,this.columnConfigs=t.columnConfigs,this.configuredColumnsOnly=t.configuredColumnsOnly,t.delimWhitespace?(A(t.delimiter==null,()=>"Delimiter should not be provided when delimWhitespace is true."),this.delimWhitespace=!0,this.delimiter=" "):this.delimiter=t.delimiter?t.delimiter:","}async columnNames(){return this.columnNamesValidated||await this.setColumnNames(),this.configuredColumnsOnly?Object.keys(this.columnConfigs):this.fullColumnNames}async setColumnNames(){const e=await this.maybeReadHeaderLine();if(!this.fullColumnNames&&!e)throw new Error("Column names must be provided if there is no header line.");this.fullColumnNames&&e&&A(e.length===this.fullColumnNames.length,()=>"The length of provided columnNames ("+this.fullColumnNames.length.toString()+") does not match the length of the header line read from file ("+e.length.toString()+")."),this.fullColumnNames||(this.fullColumnNames=e);const t=this.fullColumnNames.reduce((s,i)=>(s[i]=s[i]+1||1,s),{}),n=Object.keys(t).filter(s=>t[s]>1);if(A(n.length===0,()=>"Duplicate column names found: "+n.toString()),this.columnConfigs)for(const s of Object.keys(this.columnConfigs)){const i=this.fullColumnNames.indexOf(s);if(i===-1)throw new Error('The key "'+s+'" provided in columnConfigs does not match any of the column names ('+this.fullColumnNames.toString()+").")}this.columnNamesValidated=!0}async maybeReadHeaderLine(){if(this.hasHeader){const e=await this.base.iterator(),t=await e.next();if(t.done)throw new Error("No data was found for CSV parsing.");const n=t.value,s=this.parseRow(n,!1);return s}else return null}async iterator(){this.columnNamesValidated||await this.setColumnNames();let e=await this.base.iterator();return this.hasHeader&&(e=e.skip(1)),e.map(t=>this.makeDataElement(t))}makeDataElement(e){const t=this.parseRow(e),n={},s={};for(let i=0;i<this.fullColumnNames.length;i++){const o=this.fullColumnNames[i],a=this.columnConfigs?this.columnConfigs[o]:null;if(this.configuredColumnsOnly&&!a)continue;{const c=t[i];let h=null;if(c==="")if(a&&a.default!==void 0)h=a.default;else{if(a&&(a.required||a.isLabel))throw new Error(`Required column ${o} is empty in this line: ${e}`);h=void 0}else{const p=Number(c);if(isNaN(p))a&&a.dtype==="bool"?h=this.getBoolean(c):h=c;else if(!a||!a.dtype)h=p;else switch(a.dtype){case"float32":h=p;break;case"int32":h=Math.floor(p);break;case"bool":h=this.getBoolean(c);break;default:h=p}}a&&a.isLabel?s[o]=h:n[o]=h}}return Object.keys(s).length===0?n:{xs:n,ys:s}}getBoolean(e){return e==="1"||e.toLowerCase()==="true"?1:0}parseRow(e,t=!0){const n=[];let s=0;const i=e.length;let o=bu;for(let a=0;a<i;a++)switch(o){case bu:switch(e.charAt(a)){case Pm:s=a+1,o=zm;break;case this.delimiter:if(s=a+1,this.delimiter===" "&&this.delimWhitespace)break;n.push(""),o=bu;break;default:o=F0,s=a;break}break;case F0:switch(e.charAt(a)){case this.delimiter:n.push(e.substring(s,a)),o=bu,s=a+1;break;default:}break;case zm:switch(e.charAt(a)){case Pm:o=vS;break;default:}break;case vS:switch(e.charAt(a)){case this.delimiter:n.push(e.substring(s,a-1)),o=bu,s=a+1;break;case Pm:o=zm;break;default:o=_0;break}break;case _0:switch(e.charAt(a)){case Pm:o=zm;break;default:}break;default:}if(o===vS?n.push(e.substring(s,i-1)):n.push(e.substring(s)),t&&n.length!==this.fullColumnNames.length)throw new Error(`Invalid row in csv file. Should have ${this.fullColumnNames.length} elements in a row, but got ${n}`);return n}}class $0 extends In{constructor(e){super();this.microphoneConfig=e,this.isClosed=!1,this.fftSize=e.fftSize||1024;const t=Math.log2(this.fftSize);if(this.fftSize<0||t<4||t>14||!Number.isInteger(t))throw new Error(`Invalid fftSize: it must be a power of 2 between 2 to 4 and 2 to 14, but got ${this.fftSize}`);if(this.numFrames=e.numFramesPerSpectrogram||43,this.sampleRateHz=e.sampleRateHz,this.columnTruncateLength=e.columnTruncateLength||this.fftSize,this.audioTrackConstraints=e.audioTrackConstraints,this.smoothingTimeConstant=e.smoothingTimeConstant||0,this.includeSpectrogram=!(e.includeSpectrogram===!1),this.includeWaveform=e.includeWaveform===!0,!this.includeSpectrogram&&!this.includeWaveform)throw new Error("Both includeSpectrogram and includeWaveform are false. At least one type of data should be returned.")}summary(){return"microphone"}static async create(e={}){if(ae().get("IS_NODE"))throw new Error("microphone API is only supported in browser environment.");const t=new $0(e);return await t.start(),t}async start(){try{this.stream=await navigator.mediaDevices.getUserMedia({audio:this.audioTrackConstraints==null?!0:this.audioTrackConstraints,video:!1})}catch(n){throw new Error(`Error thrown while initializing video stream: ${n.message}`)}if(!this.stream)throw new Error("Could not obtain audio from microphone.");const e=window.AudioContext||window.webkitAudioContext;if(this.audioContext=new e,!this.sampleRateHz)this.sampleRateHz=this.audioContext.sampleRate;else if(this.audioContext.sampleRate!==this.sampleRateHz)throw new Error(`Mismatch in sampling rate: Expected: ${this.sampleRateHz}; Actual: ${this.audioContext.sampleRate}`);const t=this.audioContext.createMediaStreamSource(this.stream);this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=this.fftSize*2,this.analyser.smoothingTimeConstant=this.smoothingTimeConstant,t.connect(this.analyser),this.freqData=new Float32Array(this.fftSize),this.timeData=new Float32Array(this.fftSize);return}async next(){if(this.isClosed)return{value:null,done:!0};let e,t;const n=await this.getAudioData();if(this.includeSpectrogram){const s=this.flattenQueue(n.freqDataQueue);e=this.getTensorFromAudioDataArray(s,[this.numFrames,this.columnTruncateLength,1])}if(this.includeWaveform){const s=this.flattenQueue(n.timeDataQueue);t=this.getTensorFromAudioDataArray(s,[this.numFrames*this.fftSize,1])}return{value:{spectrogram:e,waveform:t},done:!1}}async capture(){return(await this.next()).value}async getAudioData(){const e=[],t=[];let n=0;return new Promise(s=>{const i=setInterval(()=>{this.includeSpectrogram&&(this.analyser.getFloatFrequencyData(this.freqData),this.freqData[0]===-Infinity&&s({freqDataQueue:e,timeDataQueue:t}),e.push(this.freqData.slice(0,this.columnTruncateLength))),this.includeWaveform&&(this.analyser.getFloatTimeDomainData(this.timeData),t.push(this.timeData.slice())),++n===this.numFrames&&(clearInterval(i),s({freqDataQueue:e,timeDataQueue:t}))},this.fftSize/this.sampleRateHz*1e3)})}stop(){this.isClosed||(this.isClosed=!0,this.analyser.disconnect(),this.audioContext.close(),this.stream!=null&&this.stream.getTracks().length>0&&this.stream.getTracks()[0].stop())}toArray(){throw new Error("Can not convert infinite audio stream to array.")}getSampleRate(){return this.sampleRateHz}flattenQueue(e){const t=e[0].length,n=new Float32Array(e.length*t);return e.forEach((s,i)=>n.set(s,i*t)),n}getTensorFromAudioDataArray(e,t){const n=new Float32Array(M(t));return n.set(e,n.length-e.length),sn(n,t)}}class U0 extends In{constructor(e,t){super();if(this.webcamVideoElement=e,this.webcamConfig=t,this.isClosed=!0,this.resize=!1,this.needToResize())if(this.resize=!0,this.cropSize=[this.webcamConfig.resizeHeight,this.webcamConfig.resizeWidth],this.cropBoxInd=ds([0],"int32"),this.webcamConfig.centerCrop){const n=this.webcamConfig.resizeWidth*1/this.webcamVideoElement.width,s=this.webcamConfig.resizeHeight*1/this.webcamVideoElement.height,i=(1-n)/2,o=(1-s)/2,a=i+n,c=s+o;this.cropBox=Kr([o,i,c,a],[1,4])}else this.cropBox=Kr([0,0,1,1],[1,4])}summary(){return"webcam"}static async create(e,t={}){if(ae().get("IS_NODE"))throw new Error("tf.data.webcam is only supported in browser environment.");if(!e){if(e=document.createElement("video"),!t.resizeWidth||!t.resizeHeight)throw new Error("Please provide webcam video element, or resizeWidth and resizeHeight to create a hidden video element.");e.width=t.resizeWidth,e.height=t.resizeHeight}const n=new U0(e,t);return await n.start(),n}async start(){this.webcamConfig.facingMode&&A(this.webcamConfig.facingMode==="user"||this.webcamConfig.facingMode==="environment",()=>`Invalid webcam facing mode: ${this.webcamConfig.facingMode}. Please provide 'user' or 'environment'`);try{this.stream=await navigator.mediaDevices.getUserMedia({video:{deviceId:this.webcamConfig.deviceId,facingMode:this.webcamConfig.facingMode?this.webcamConfig.facingMode:"user",width:this.webcamVideoElement.width,height:this.webcamVideoElement.height}})}catch(e){throw e.message=`Error thrown while initializing video stream: ${e.message}`,e}if(!this.stream)throw new Error("Could not obtain video from webcam.");try{this.webcamVideoElement.srcObject=this.stream}catch(e){console.log(e),this.webcamVideoElement.src=window.URL.createObjectURL(this.stream)}return this.webcamVideoElement.play(),this.isClosed=!1,new Promise(e=>{this.webcamVideoElement.onloadedmetadata=()=>{e()}})}async next(){if(this.isClosed)return{value:null,done:!0};let e;try{e=iA(this.webcamVideoElement)}catch(t){throw new Error(`Error thrown converting video to pixels: ${JSON.stringify(t)}`)}if(this.resize)try{return{value:this.cropAndResizeFrame(e),done:!1}}catch(t){throw new Error(`Error thrown cropping the video: ${t.message}`)}finally{e.dispose()}else return{value:e,done:!1}}needToResize(){return!!(this.webcamConfig.resizeWidth&&this.webcamConfig.resizeHeight&&(this.webcamVideoElement.width!==this.webcamConfig.resizeWidth||this.webcamVideoElement.height!==this.webcamConfig.resizeHeight))}cropAndResizeFrame(e){return ee(()=>{const t=e.toFloat().expandDims(0);let n;n=Xr.cropAndResize(t,this.cropBox,this.cropBoxInd,this.cropSize,"bilinear");const s=n.shape;return n.reshape(s.slice(1))})}async capture(){return(await this.next()).value}stop(){const e=this.stream.getTracks();e.forEach(t=>t.stop());try{this.webcamVideoElement.srcObject=null}catch(t){console.log(t),this.webcamVideoElement.src=null}this.isClosed=!0}toArray(){throw new Error("Can not convert infinite video stream to array.")}}class B0{}class M0 extends In{split(e){return new wq(this,e)}}class wq extends M0{constructor(e,t){super();this.upstream=e,this.impl=new Lq(e,t)}summary(){return this.impl.summary()}async next(){return this.impl.next()}}class Lq extends AS{constructor(e,t){super();this.upstream=e,this.separator=t,this.carryover=""}summary(){return`${this.upstream.summary()} -> Split('${this.separator}')`}async pump(){const e=await this.upstream.next();if(e.done)return this.carryover===""?!1:(this.outputQueue.push(this.carryover),this.carryover="",!0);const t=e.value.split(this.separator);t[0]=this.carryover+t[0];for(const n of t.slice(0,-1))this.outputQueue.push(n);return this.carryover=t[t.length-1],!0}}class Sq extends In{decodeUTF8(){return new Iq(this)}}class Iq extends M0{constructor(e){super();this.upstream=e,this.impl=new xq(e)}summary(){return this.impl.summary()}async next(){return this.impl.next()}}class xq extends AS{constructor(e){super();if(this.upstream=e,ae().get("IS_BROWSER"))this.decoder=new TextDecoder("utf-8");else{const{StringDecoder:t}=require("string_decoder");this.decoder=new t("utf8")}}summary(){return`${this.upstream.summary()} -> Utf8`}async pump(){const e=await this.upstream.next();let t;if(e.done)return!1;t=e.value;let n;return ae().get("IS_BROWSER")?n=this.decoder.decode(t,{stream:!0}):n=this.decoder.write(Buffer.from(t.buffer)),this.outputQueue.push(n),!0}}class P0 extends Sq{constructor(e,t={}){super();this.file=e,this.options=t,A(e instanceof Uint8Array||(ae().get("IS_BROWSER")?e instanceof File||e instanceof Blob:!1),()=>"FileChunkIterator only supports File, Blob and Uint8Array right now."),this.offset=t.offset||0,this.chunkSize=t.chunkSize||1024*1024}summary(){return`FileChunks ${this.file}`}async next(){if(this.offset>=(this.file instanceof Uint8Array?this.file.byteLength:this.file.size))return{value:null,done:!0};const e=new Promise((t,n)=>{const s=this.offset+this.chunkSize;if(this.file instanceof Uint8Array)t(new Uint8Array(this.file.slice(this.offset,s)));else{const i=new FileReader;i.onload=a=>{let c=i.result;if(c instanceof ArrayBuffer&&(c=new Uint8Array(c)),!(c instanceof Uint8Array))return n(new TypeError("FileReader returned unknown type."));t(c)},i.onabort=a=>n(new Error("Aborted")),i.onerror=a=>n(new Error(a.type));const o=this.file.slice(this.offset,s);i.readAsArrayBuffer(o)}this.offset=s});return{value:await e,done:!1}}}async function Tq(e,t={}){let n,s;typeof e=="string"?n=e:(n=e.url,s=Aq(e));const i=await OT(n,s);if(i.ok){const o=new Uint8Array(await i.arrayBuffer());return new P0(o,t)}else throw new Error(i.statusText)}const Aq=e=>{const t={method:e.method,headers:e.headers,body:e.body,mode:e.mode,credentials:e.credentials,cache:e.cache,redirect:e.redirect,referrer:e.referrer,integrity:e.integrity};return t};function z0(e){return typeof e=="string"&&e.substr(0,7)==="file://"}class V0 extends B0{constructor(e,t={}){super();this.input=e,this.options=t}async iterator(){if(z0(this.input)&&ae().get("IS_NODE")){const e=require("fs");this.input=e.readFileSync(this.input.substr(7))}return new P0(this.input,this.options)}}class G0 extends B0{constructor(e,t={}){super();this.url=e,this.fileOptions=t}async iterator(){return z0(this.url)?new V0(this.url,this.fileOptions).iterator():Tq(this.url,this.fileOptions)}}function vq(e,t={}){return new W0(new G0(e),t)}function Nq(e){const t=yu(e);return gs(async()=>t)}function Cq(e){return gs(async()=>{const t=await e();return yu(()=>t.next())})}async function Rq(e,t){return U0.create(e,t)}async function Oq(e){return $0.create(e)}const Y0="2.7.0";var Eq=Object.freeze({__proto__:null,array:fq,Dataset:Sc,zip:gq,CSVDataset:W0,TextLineDataset:k0,csv:vq,func:Nq,generator:Cq,microphone:Oq,webcam:Rq,FileDataSource:V0,URLDataSource:G0,version_data:Y0});function Te(e,t){Array.isArray(e)||(e=[e]),e.forEach(n=>{n!=null&&A(n.dtype!=="complex64",()=>`${t} does not support complex64 tensors in the CPU backend.`)})}const Dq=Xp,kq=Cw,Fq=Rw,_q=Ow,Wq=Vp;class $q extends f{constructor(){super();this.blockSize=48,this.firstUse=!0,this.data=new d(this,tr())}write(e,t,n){this.firstUse&&(this.firstUse=!1,ae().get("IS_NODE")&&hc(`
============================
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 s={};return this.data.set(s,{values:e,dtype:n,refCount:1}),s}makeTensorInfo(e,t,n){let s;if(t==="string"&&n!=null&&n.length>0&&Ji(n[0])){const i=n.map(o=>ep(o));s=this.write(i,e,t)}else s=this.write(n,e,t);return{dataId:s,shape:e,dtype:t}}incRef(e){const t=this.data.get(e);t.refCount++}decRef(e){if(this.data.has(e)){const t=this.data.get(e);t.refCount--}}move(e,t,n,s){this.data.set(e,{values:t,dtype:s,refCount:1})}numDataIds(){return this.data.numDataIds()}async read(e){return this.readSync(e)}readSync(e){const{dtype:t,complexTensorInfos:n}=this.data.get(e);if(t==="complex64"){const s=this.readSync(n.real.dataId),i=this.readSync(n.imag.dataId);return ar(s,i)}return this.data.get(e).values}bufferSync(e){const t=this.readSync(e.dataId);let n=t;if(e.dtype==="string")try{n=t.map(s=>lh(s))}catch(s){throw new Error("Failed to decode encoded string bytes into utf-8")}return wt(e.shape,e.dtype,n)}makeOutput(e,t,n){const s=this.write(e,t,n);return tr().makeTensorFromDataId(s,t,n,this)}disposeData(e){if(this.data.has(e)){const{complexTensorInfos:t}=this.data.get(e);t!=null&&(this.disposeData(t.real.dataId),this.disposeData(t.imag.dataId)),this.data.delete(e)}}disposeIntermediateTensorInfo(e){const t=e.dataId;if(this.data.has(t)){const n=this.data.get(t);n.refCount--,n.refCount<1&&this.disposeData(t)}}async time(e){const t=Jn();e();const n=Jn()-t;return{kernelMs:n}}memory(){return{unreliable:!0,reasons:["The reported memory is an upper bound. Due to automatic garbage collection, the true allocated memory may be less."]}}stridedSlice(e,t,n,s){Te(e,"stridedSlice");const i=dp(t,n,s);if(i.some(c=>c===0))return sn([],i);const o=wt(i,e.dtype),a=this.bufferSync(e);for(let c=0;c<o.size;c++){const h=o.indexToLoc(c),p=new Array(h.length);for(let m=0;m<p.length;m++)p[m]=h[m]*s[m]+t[m];o.set(a.get(...p),...h)}return o.toTensor()}diag(e){const t=this.readSync(e.dataId),n=wt([e.size,e.size],e.dtype),s=n.values;for(let i=0;i<t.length;i++)s[i*e.size+i]=t[i];return n.toTensor()}unstack(e,t){const n=e.shape[t],s=new Array(e.rank-1);let i=0;for(let h=0;h<e.rank;h++)h!==t&&(s[i++]=e.shape[h]);const o=new Array(e.rank).fill(0),a=e.shape.slice();a[t]=1;const c=new Array(n);for(let h=0;h<c.length;h++)o[t]=h,c[h]=nt(e,o,a).reshape(s);return c}reverse(e,t){Te(e,"reverse");const n=wt(e.shape,e.dtype),s=this.bufferSync(e);for(let i=0;i<n.size;i++){const o=n.indexToLoc(i),a=o.slice();t.forEach(c=>a[c]=e.shape[c]-1-a[c]),n.set(s.get(...a),...o)}return n.toTensor()}neg(e){return Te(e,"neg"),X(Ce(-1),e)}addN(e){Te(e,"addN");const t=e.map(i=>this.readSync(i.dataId)),n=wt(e[0].shape,e[0].dtype),s=n.values;for(let i=0;i<e.length;i++){const o=t[i];for(let a=0;a<s.length;a++)s[a]+=o[a]}return n.toTensor()}softmax(e,t){const n=je([t],e.shape),s=ns(e,n),i=Nn(s.shape,n),o=Re(e,s.reshape(i)),a=As(o),c=this.sum(a,n).reshape(i);return We(a,c)}pow(e,t){return Te([e,t],"pow"),this.broadcastedBinaryOp(e,t,e.dtype,(n,s)=>Math.pow(n,s))}floorDiv(e,t){Te([e,t],"floorDiv");const n=(i,o)=>Math.floor(i/o),s="int32";return this.broadcastedBinaryOp(e,t,s,n)}sum(e,t){Te(e,"sum"),Zn("sum",t,e.rank);const[n,s]=vn(e.shape,t),i=Bn(e.dtype,"int32"),o=pt(n,i),a=M(s),c=this.readSync(o.dataId),h=this.readSync(e.dataId);for(let p=0;p<c.length;++p){const m=p*a;let y=0;for(let b=0;b<a;++b)y+=h[m+b];c[p]=y}return o}prod(e,t){Te(e,"sum");const[n,s]=vn(e.shape,t),i=Bn(e.dtype,"int32"),o=pt(n,i),a=M(s),c=this.readSync(o.dataId),h=this.readSync(e.dataId);for(let p=0;p<c.length;++p){const m=p*a;let y=1;for(let b=0;b<a;++b)y*=h[m+b];c[p]=y}return o}unsortedSegmentSum(e,t,n){Te(e,"unsortedSegmentSum");const s=[],i=e.rank-t.rank;for(let o=0;o<i;++o)t=t.expandDims(o+1);for(let o=0;o<n;++o){const a=Ce(o,"int32"),c=ei(a,t).asType("float32"),h=c.mul(e).sum(0);s.push(h)}return ss(s)}argMin(e,t){Te(e,"argMin");const n=[t];Zn("argMin",n,e.rank);const[s,i]=vn(e.shape,n),o=pt(s,"int32"),a=M(i),c=this.readSync(o.dataId),h=this.readSync(e.dataId);for(let p=0;p<c.length;++p){const m=p*a;let y=h[m],b=0;for(let w=0;w<a;++w){const L=h[m+w];L<y&&(y=L,b=w)}c[p]=b}return o}argMax(e,t){Te(e,"argMax");const n=[t];Zn("argMax",n,e.rank);const[s,i]=vn(e.shape,n),o=pt(s,"int32"),a=M(i),c=this.readSync(o.dataId),h=this.readSync(e.dataId);for(let p=0;p<c.length;++p){const m=p*a;let y=h[m],b=0;for(let w=0;w<a;++w){const L=h[m+w];L>y&&(y=L,b=w)}c[p]=b}return o}cumsum(e,t,n,s){if(Te(e,"cumsum"),t!==e.rank-1)throw new Error(`backend.cumsum in CPU expects an inner-most axis=${e.rank-1} but got axis=${t}`);const i=Bn(e.dtype,"int32"),o=pt(e.shape,i),a=this.readSync(o.dataId),c=this.readSync(e.dataId),h=e.shape[e.rank-1],p=s?(m,y)=>m+h-y-1:(m,y)=>m+y;for(let m=0;m<c.length;m+=h)for(let y=0;y<h;y++){const b=p(m,y);if(y===0)a[b]=n?0:c[b];else{const w=p(m,y-1);a[b]=n?c[w]+a[w]:c[b]+a[w]}}return o}equal(e,t){return Te([e,t],"equal"),this.broadcastedBinaryOp(e,t,"bool",(n,s)=>n===s?1:0)}notEqual(e,t){return Te([e,t],"notEqual"),this.broadcastedBinaryOp(e,t,"bool",(n,s)=>n!==s?1:0)}less(e,t){return Te([e,t],"less"),this.broadcastedBinaryOp(e,t,"bool",(n,s)=>n<s?1:0)}lessEqual(e,t){return Te([e,t],"lessEqual"),this.broadcastedBinaryOp(e,t,"bool",(n,s)=>n<=s?1:0)}greater(e,t){return Te([e,t],"greater"),this.broadcastedBinaryOp(e,t,"bool",(n,s)=>n>s?1:0)}greaterEqual(e,t){return Te([e,t],"greaterEqual"),this.broadcastedBinaryOp(e,t,"bool",(n,s)=>n>=s?1:0)}logicalAnd(e,t){return Te([e,t],"logicalAnd"),this.broadcastedBinaryOp(e,t,"bool",(n,s)=>n&&s)}logicalOr(e,t){return Te([e,t],"logicalOr"),this.broadcastedBinaryOp(e,t,"bool",(n,s)=>n||s)}select(e,t,n){Te([e,t,n],"select");const s=this.readSync(e.dataId),i=this.readSync(t.dataId),o=this.readSync(n.dataId),a=pt(t.shape,Bn(t.dtype,n.dtype)),c=this.readSync(a.dataId);let h=0;const p=e.rank===0||e.rank>1||t.rank===1?1:M(t.shape.slice(1));for(let m=0;m<s.length;m++)for(let y=0;y<p;y++)s[m]===1?c[h++]=i[m]:c[h++]=o[m];return a}where(e){Te([e],"where");const t=this.readSync(e.dataId);return Wq(e.shape,t)}topk(e,t,n){Te(e,"topk");const s=this.readSync(e.dataId);return _q(s,e.shape,e.dtype,t,n)}min(e,t){Te(e,"min"),Zn("min",t,e.rank);const[n,s]=vn(e.shape,t),i=pt(n,e.dtype),o=M(s),a=this.readSync(i.dataId),c=this.readSync(e.dataId);for(let h=0;h<a.length;++h){const p=h*o;let m=c[p];for(let y=0;y<o;++y){const b=c[p+y];b<m&&(m=b)}a[h]=m}return i}minimum(e,t){return Te([e,t],"minimum"),this.broadcastedBinaryOp(e,t,e.dtype,(n,s)=>Math.min(n,s))}mod(e,t){return Te([e,t],"mod"),this.broadcastedBinaryOp(e,t,e.dtype,(n,s)=>{const i=n%s;return n<0&&s<0||n>=0&&s>=0?i:(i+s)%s})}maximum(e,t){return Te([e,t],"maximum"),this.broadcastedBinaryOp(e,t,e.dtype,(n,s)=>Math.max(n,s))}all(e,t){Te(e,"all"),Zn("all",t,e.rank);const[n,s]=vn(e.shape,t),i=pt(n,e.dtype),o=M(s),a=this.readSync(i.dataId),c=this.readSync(e.dataId);for(let h=0;h<a.length;++h){const p=h*o;let m=c[p];for(let y=0;y<o;++y){const b=c[p+y];m=m&&b}a[h]=m}return i}any(e,t){Te(e,"any"),Zn("any",t,e.rank);const[n,s]=vn(e.shape,t),i=pt(n,e.dtype),o=M(s),a=this.readSync(i.dataId),c=this.readSync(e.dataId);for(let h=0;h<a.length;++h){const p=h*o;let m=c[p];for(let y=0;y<o;++y){const b=c[p+y];m=m||b}a[h]=m}return i}squaredDifference(e,t){return Te([e,t],"squaredDifference"),this.broadcastedBinaryOp(e,t,e.dtype,(n,s)=>{const i=n-s;return i*i})}eluDer(e,t){Te([e,t],"eluDer");const n=new Float32Array(t.size),s=this.readSync(t.dataId),i=this.readSync(e.dataId);for(let o=0;o<s.length;++o){const a=s[o];a>=1?n[o]=i[o]:n[o]=i[o]*(a+1)}return this.makeOutput(n,t.shape,"float32")}atan2(e,t){return Te([e,t],"atan2"),this.broadcastedBinaryOp(e,t,e.dtype,(n,s)=>Math.atan2(n,s))}tile(e,t){return Te(e,"tile"),Fq(this.bufferSync(e),t)}gather(e,t,n){Te([e,t],"gather");const s=e.shape.slice(),i=this.readSync(t.dataId);s[n]=i.length;const o=wt(s,e.dtype),a=this.bufferSync(e);for(let c=0;c<o.size;++c){const h=o.indexToLoc(c),p=h.slice();p[n]=i[h[n]];const m=a.locToIndex(p);o.values[c]=a.values[m]}return o.toTensor()}batchToSpaceND(e,t,n){Te([e],"batchToSpaceND");const s=t.reduce((p,m)=>p*m),i=Gh(e.shape,t,s),o=Yh(i.length,t.length),a=Hh(e.shape,t,s),c=yw(n,t.length),h=bw(a,n,t.length);return Ye(e.reshape(i),o).reshape(a).slice(c,h)}pool3d(e,t,n){Te(e,"pool3d");const s=t.strideDepth,i=t.strideHeight,o=t.strideWidth,a=t.dilationDepth,c=t.dilationHeight,h=t.dilationWidth,p=t.effectiveFilterDepth,m=t.effectiveFilterHeight,y=t.effectiveFilterWidth,b=t.padInfo.front,w=t.padInfo.top,L=t.padInfo.left,T=n==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,v=this.readSync(e.dataId),C=wt(t.outShape,e.dtype),O=C.values,D=t.outShape[1]*t.outShape[2]*t.outShape[3]*t.outShape[4],k=t.outShape[2]*t.outShape[3]*t.outShape[4],F=t.outShape[3]*t.outShape[4],B=t.outShape[4];for(let $=0;$<t.batchSize;++$){const Y=$*D,j=$*e.strides[0];for(let Z=0;Z<t.inChannels;++Z)for(let re=0;re<t.outDepth;++re){const de=re*s-b;let he=de;for(;he<0;)he+=a;const ue=Math.min(t.inDepth,p+de),me=Y+re*k;for(let ce=0;ce<t.outHeight;++ce){const ye=ce*i-w;let pe=ye;for(;pe<0;)pe+=c;const Le=Math.min(t.inHeight,m+ye),Se=me+ce*F;for(let xe=0;xe<t.outWidth;++xe){const Oe=xe*o-L;let Ne=Oe;for(;Ne<0;)Ne+=h;const De=Math.min(t.inWidth,y+Oe),Ue=Se+xe*B;let Ve=T,ut=0,rt=0;for(let mt=he;mt<ue;mt+=a){const dt=j+mt*e.strides[1];for(let Dt=pe;Dt<Le;Dt+=c){const rn=dt+Dt*e.strides[2];for(let Ut=Ne;Ut<De;Ut+=h){const kt=rn+Ut*e.strides[3],Ft=v[kt+Z];if(n==="max"&&Ft>Ve?Ve=Ft:n==="avg"&&(ut+=Ft,rt++),isNaN(Ve))break}if(isNaN(Ve))break}if(isNaN(Ve))break}const ot=Ue+Z;O[ot]=n==="avg"?ut/rt:Ve}}}}return C.toTensor()}avgPool3d(e,t){return Te(e,"avgPool3d"),this.pool3d(e,t,"avg").toFloat()}avgPool3dBackprop(e,t,n){Te([e,t],"avgPool3dBackprop");const s=n.strideDepth,i=n.strideHeight,o=n.strideWidth,a=n.filterDepth,c=n.filterHeight,h=n.filterWidth,p=n.dilationDepth,m=n.dilationHeight,y=n.dilationWidth,b=n.effectiveFilterDepth,w=n.effectiveFilterHeight,L=n.effectiveFilterWidth,T=b-1-n.padInfo.front,v=L-1-n.padInfo.left,C=w-1-n.padInfo.top,O=wt(t.shape,"float32"),D=1/(a*c*h),k=this.bufferSync(e);for(let F=0;F<n.batchSize;++F)for(let B=0;B<n.inChannels;++B)for(let $=0;$<n.inDepth;++$)for(let Y=0;Y<n.inHeight;++Y)for(let j=0;j<n.inWidth;++j){const Z=$-T,re=Y-C,de=j-v;let he=0;for(let ue=0;ue<b;ue+=p){const me=(Z+ue)/s;if(me<0||me>=n.outDepth||Math.floor(me)!==me)continue;for(let ce=0;ce<w;ce+=m){const ye=(re+ce)/i;if(ye<0||ye>=n.outHeight||Math.floor(ye)!==ye)continue;for(let pe=0;pe<L;pe+=y){const Le=(de+pe)/o;if(Le<0||Le>=n.outWidth||Math.floor(Le)!==Le)continue;const Se=k.get(F,me,ye,Le,B);he+=Se}}}O.set(he*D,F,$,Y,j,B)}return O.toTensor()}maxPool3d(e,t){return Te(e,"maxPool3d"),this.pool3d(e,t,"max").toFloat()}maxPool3dPositions(e,t){const n=wt(t.outShape,"int32"),s=t.strideDepth,i=t.strideHeight,o=t.strideWidth,a=t.dilationDepth,c=t.dilationHeight,h=t.dilationWidth,p=t.effectiveFilterDepth,m=t.effectiveFilterHeight,y=t.effectiveFilterWidth,b=t.padInfo.front,w=t.padInfo.top,L=t.padInfo.left,T=this.bufferSync(e);for(let v=0;v<t.batchSize;++v)for(let C=0;C<t.inChannels;++C)for(let O=0;O<t.outDepth;++O){const D=O*s-b;let k=D;for(;k<0;)k+=a;const F=Math.min(t.inDepth,p+D);for(let B=0;B<t.outHeight;++B){const $=B*i-w;let Y=$;for(;Y<0;)Y+=c;const j=Math.min(t.inHeight,m+$);for(let Z=0;Z<t.outWidth;++Z){const re=Z*o-L;let de=re;for(;de<0;)de+=h;const he=Math.min(t.inWidth,y+re);let ue=Number.NEGATIVE_INFINITY,me=-1;for(let ce=k;ce<F;ce+=a){const ye=ce-D;for(let pe=Y;pe<j;pe+=c){const Le=pe-$;for(let Se=de;Se<he;Se+=h){const xe=Se-re,Oe=T.get(v,ce,pe,Se,C);Oe>=ue&&(ue=Oe,me=ye*m*y+Le*m+xe)}}}n.set(me,v,O,B,Z,C)}}}return n.toTensor()}maxPool3dBackprop(e,t,n,s){Te([t,n],"maxPool3dBackprop");const i=this.maxPool3dPositions(t,s),o=s.strideDepth,a=s.strideHeight,c=s.strideWidth,h=s.dilationDepth,p=s.dilationHeight,m=s.dilationWidth,y=s.effectiveFilterDepth,b=s.effectiveFilterHeight,w=s.effectiveFilterWidth,L=y-1-s.padInfo.front,T=w-1-s.padInfo.left,v=b-1-s.padInfo.top,C=wt(t.shape,"float32"),O=this.bufferSync(i),D=this.bufferSync(e);for(let k=0;k<s.batchSize;++k)for(let F=0;F<s.inChannels;++F)for(let B=0;B<s.inDepth;++B)for(let $=0;$<s.inHeight;++$)for(let Y=0;Y<s.inWidth;++Y){const j=B-L,Z=$-v,re=Y-T;let de=0;for(let he=0;he<y;he+=h){const ue=(j+he)/o;if(ue<0||ue>=s.outDepth||Math.floor(ue)!==ue)continue;for(let me=0;me<b;me+=p){const ce=(Z+me)/a;if(ce<0||ce>=s.outHeight||Math.floor(ce)!==ce)continue;for(let ye=0;ye<w;ye+=m){const pe=(re+ye)/c;if(pe<0||pe>=s.outWidth||Math.floor(pe)!==pe)continue;const Le=y*b*w-1-O.get(k,ue,ce,pe,F),Se=he*b*w+me*w+ye,xe=Le===Se?1:0;if(xe===0)continue;const Oe=D.get(k,ue,ce,pe,F);de+=Oe*xe}}}C.set(de,k,B,$,Y,F)}return C.toTensor()}resizeBilinear(e,t,n,s){Te(e,"resizeBilinear");const[i,o,a,c]=e.shape,h=this.readSync(e.dataId),p=new Float32Array(M([i,t,n,c])),m=[s&&t>1?o-1:o,s&&n>1?a-1:a],y=[s&&t>1?t-1:t,s&&n>1?n-1:n];let b=0;const w=m[0]/y[0],L=m[1]/y[1];for(let T=0;T<i;T++)for(let v=0;v<t;v++){const C=w*v,O=Math.floor(C),D=C-O,k=Math.min(o-1,Math.ceil(C)),F=T*e.strides[0]+O*e.strides[1],B=T*e.strides[0]+k*e.strides[1];for(let $=0;$<n;$++){const Y=L*$,j=Math.floor(Y),Z=Y-j,re=Math.min(a-1,Math.ceil(Y)),de=F+j*e.strides[2],he=B+j*e.strides[2],ue=F+re*e.strides[2],me=B+re*e.strides[2];for(let ce=0;ce<c;ce++){const ye=h[de+ce],pe=h[he+ce],Le=h[ue+ce],Se=h[me+ce],xe=ye+(Le-ye)*Z,Oe=pe+(Se-pe)*Z,Ne=xe+(Oe-xe)*D;p[b++]=Ne}}}return sn(p,[i,t,n,c])}resizeBilinearBackprop(e,t,n){Te([e,t],"resizeBilinearBackprop");const[s,i,o,a]=t.shape,[,c,h]=e.shape,p=new Float32Array(s*i*o*a),m=[n&&c>1?i-1:i,n&&h>1?o-1:o],y=[n&&c>1?c-1:c,n&&h>1?h-1:h],b=m[0]/y[0],w=m[1]/y[1],L=this.readSync(e.dataId);let T=0;for(let v=0;v<s;v++){const C=v*t.strides[0];for(let O=0;O<c;O++){const D=O*b,k=Math.floor(D),F=Math.min(Math.ceil(D),i-1),B=C+k*t.strides[1],$=C+F*t.strides[1],Y=D-k,j=1-Y;for(let Z=0;Z<h;Z++){const re=Z*w,de=Math.floor(re),he=Math.min(Math.ceil(re),o-1),ue=re-de,me=1-ue,ce=B+de*t.strides[2],ye=B+he*t.strides[2],pe=$+de*t.strides[2],Le=$+he*t.strides[2],Se=j*me,xe=j*ue,Oe=Y*me,Ne=Y*ue;for(let De=0;De<a;De++){const Ue=L[T++];p[ce+De]+=Ue*Se,p[ye+De]+=Ue*xe,p[pe+De]+=Ue*Oe,p[Le+De]+=Ue*Ne}}}}return ac(p,[s,o,i,a],t.dtype)}resizeNearestNeighbor(e,t,n,s){Te(e,"resizeNearestNeighbor");const[i,o,a,c]=e.shape,h=this.readSync(e.dataId),p=new Float32Array(i*t*n*c),m=[s&&t>1?o-1:o,s&&n>1?a-1:a],y=[s&&t>1?t-1:t,s&&n>1?n-1:n],b=m[0]/y[0],w=m[1]/y[1];let L=0;for(let T=0;T<i;T++){const v=T*e.strides[0];for(let C=0;C<t;C++){const O=b*C,D=Math.min(o-1,s?Math.round(O):Math.floor(O)),k=v+D*e.strides[1];for(let F=0;F<n;F++){const B=w*F,$=Math.min(a-1,s?Math.round(B):Math.floor(B)),Y=k+$*e.strides[2];for(let j=0;j<c;j++){const Z=h[Y+j];p[L++]=Z}}}}return sn(p,[i,t,n,c],e.dtype)}resizeNearestNeighborBackprop(e,t,n){Te([e,t],"resizeNearestNeighborBackprop");const[s,i,o,a]=t.shape,[,c,h]=e.shape,p=new Float32Array(s*i*o*a),m=this.readSync(e.dataId),y=[n&&c>1?i-1:i,n&&h>1?o-1:o],b=[n&&c>1?c-1:c,n&&h>1?h-1:h],w=y[0]/b[0],L=y[1]/b[1],T=1/w,v=1/L,C=Math.ceil(T)*2+2,O=Math.ceil(v)*2+2;for(let D=0;D<s;D++){const k=D*t.strides[0];for(let F=0;F<i;F++){const B=k+F*t.strides[1],$=Math.floor(F*T),Y=Math.floor($-C/2);for(let j=0;j<o;j++){const Z=B+j*t.strides[2],re=Math.floor(j*v),de=Math.floor(re-O/2);for(let he=0;he<a;he++){let ue=0;for(let me=0;me<C;me++){const ce=me+Y;if(ce<0||ce>=c)continue;const ye=k+ce*e.strides[1],pe=ce*w,Le=Math.min(i-1,n?Math.round(pe):Math.floor(pe));if(F!==Le)continue;for(let Se=0;Se<O;Se++){const xe=Se+de;if(xe<0||xe>=h)continue;const Oe=ye+xe*e.strides[2],Ne=xe*L,De=Math.min(o-1,n?Math.round(Ne):Math.floor(Ne));j===De&&(ue+=m[Oe+he])}}p[Z+he]=ue}}}}return ac(p,t.shape,t.dtype)}localResponseNormalization4D(e,t,n,s,i){Te(e,"localResponseNormalization4D");const o=e.shape[3],a=o-1,c=this.readSync(e.dataId),h=e.size,p=new Float32Array(h);function m(y){const b=y%o;let w=y-b+Math.max(0,b-t);const L=y-b+Math.min(b+t,a);let T=0;for(;w<=L;w++){const v=c[w];T+=v*v}return T}for(let y=0;y<h;y++){const b=m(y),w=c[y]*Math.pow(n+s*b,-i);p[y]=w}return ac(p,e.shape)}LRNGrad(e,t,n,s,i,o,a){Te(e,"LRNGrad");const c=e.shape[3],h=this.readSync(e.dataId),p=this.readSync(t.dataId),m=this.readSync(n.dataId),y=new Float32Array(e.size),b=e.size;for(let w=0;w<b;w++){const L=w%c,T=w-L+Math.max(0,L-s),v=w-L+Math.min(c,L+s+1);let C=0;for(let O=T;O<v;O++)C+=Math.pow(p[O],2);C=o*C+i;for(let O=T;O<v;O++){let D=-2*o*a*p[O]*m[w]/C;w===O&&(D+=Math.pow(C,-a)),D*=h[w],y[O]+=D}}return ac(y,e.shape)}multinomial(e,t,n,s){Te(e,"multinomial");const i=t?e:Yo(e),o=i.shape[0],a=i.shape[1],c=pt([o,n],"int32"),h=this.readSync(c.dataId),p=this.readSync(i.dataId);for(let m=0;m<o;++m){const y=m*a,b=new Float32Array(a-1);b[0]=p[y];for(let T=1;T<b.length;++T)b[T]=b[T-1]+p[y+T];const w=ic(s.toString()),L=m*n;for(let T=0;T<n;++T){const v=w();h[L+T]=b.length;for(let C=0;C<b.length;C++)if(v<b[C]){h[L+T]=C;break}}}return c}oneHot(e,t,n,s){Te(e,"oneHot");const i=new Float32Array(e.size*t);i.fill(s);const o=this.readSync(e.dataId);for(let a=0;a<e.size;++a)o[a]>=0&&o[a]<t&&(i[a*t+o[a]]=n);return Kr(i,[e.size,t],"int32")}nonMaxSuppression(e,t,n,s,i){Te(e,"nonMaxSuppression");const o=this.readSync(e.dataId),a=this.readSync(t.dataId);return Dq(o,a,n,s,i)}depthToSpace(e,t,n){A(n==="NHWC",()=>`Only NHWC dataFormat supported on CPU for depthToSpace. Got ${n}`),A(t>1,()=>`blockSize should be > 1 for depthToSpace, but was: ${t}`);const s=e.shape[0],i=e.shape[1],o=e.shape[2],a=e.shape[3],c=i*t,h=o*t,p=a/(t*t),m=this.readSync(e.dataId),y=new Float32Array(s*c*h*p);let b=0;for(let w=0;w<s;++w)for(let L=0;L<c;++L){const T=Math.floor(L/t),v=L%t;for(let C=0;C<h;++C){const O=Math.floor(C/t),D=C%t,k=(v*t+D)*p;for(let F=0;F<p;++F){const B=F+k,$=B+a*(O+o*(T+i*w));y[b++]=m[$]}}}return ac(y,[s,c,h,p])}broadcastedBinaryOp(e,t,n,s){const i=st(e.shape,t.shape),o=wt(i,n),a=this.readSync(e.dataId),c=this.readSync(t.dataId),h=Mo(e.shape,i),p=Mo(t.shape,i),m=o.values;if(h.length+p.length===0)for(let y=0;y<m.length;++y)m[y]=s(a[y%a.length],c[y%c.length]);else{const y=this.bufferSync(e),b=this.bufferSync(t);for(let w=0;w<m.length;++w){const L=o.indexToLoc(w),T=L.slice(-e.rank);h.forEach(D=>T[D]=0);const v=y.locToIndex(T),C=L.slice(-t.rank);p.forEach(D=>C[D]=0);const O=b.locToIndex(C);m[w]=s(a[v],c[O])}}return o.toTensor()}split(e,t,n){return kq(e,t,n)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}cropAndResize(e,t,n,s,i,o){const[a,c,h,p]=e.shape,m=t.shape[0],[y,b]=s,w=wt([m,y,b,p],"float32"),L=this.readSync(t.dataId),T=this.readSync(n.dataId),v=this.readSync(e.dataId),C=e.strides,O=w.strides;for(let D=0;D<m;D++){const k=D*4,F=L[k],B=L[k+1],$=L[k+2],Y=L[k+3],j=T[D];if(j>=a)continue;const Z=y>1?($-F)*(c-1)/(y-1):0,re=b>1?(Y-B)*(h-1)/(b-1):0;for(let de=0;de<y;de++){const he=y>1?F*(c-1)+de*Z:.5*(F+$)*(c-1);if(he<0||he>c-1){for(let ue=0;ue<b;ue++)for(let me=0;me<p;me++){const ce=me+ue*O[2]+de*O[1]+D*O[0];w.values[ce]=o}continue}if(i==="bilinear"){const ue=Math.floor(he),me=Math.ceil(he),ce=he-ue;for(let ye=0;ye<b;ye++){const pe=b>1?B*(h-1)+ye*re:.5*(B+Y)*(h-1);if(pe<0||pe>h-1){for(let Oe=0;Oe<p;Oe++){const Ne=Oe+ye*O[2]+de*O[1]+D*O[0];w.values[Ne]=o}continue}const Le=Math.floor(pe),Se=Math.ceil(pe),xe=pe-Le;for(let Oe=0;Oe<p;Oe++){let Ne=Oe+Le*C[2]+ue*C[1]+j*C[0];const De=v[Ne];Ne=Oe+Se*C[2]+ue*C[1]+j*C[0];const Ue=v[Ne];Ne=Oe+Le*C[2]+me*C[1]+j*C[0];const Ve=v[Ne];Ne=Oe+Se*C[2]+me*C[1]+j*C[0];const ut=v[Ne],rt=De+(Ue-De)*xe,ot=Ve+(ut-Ve)*xe;Ne=Oe+ye*O[2]+de*O[1]+D*O[0],w.values[Ne]=rt+(ot-rt)*ce}}}else for(let ue=0;ue<b;++ue){const me=b>1?B*(h-1)+ue*re:.5*(B+Y)*(h-1);if(me<0||me>h-1){for(let pe=0;pe<p;pe++){const Le=pe+ue*O[2]+de*O[1]+D*O[0];w.values[Le]=o}continue}const ce=Math.round(me),ye=Math.round(he);for(let pe=0;pe<p;pe++){const Le=pe+ce*C[2]+ye*C[1]+j*C[0],Se=pe+ue*O[2]+de*O[1]+D*O[0];w.values[Se]=v[Le]}}}}return w.toTensor()}sparseToDense(e,t,n,s){const{sliceRank:i,numUpdates:o,sliceSize:a,strides:c,outputSize:h}=qa(t,e,n),p=!1;return this.scatter(e,t,n,h,a,o,i,c,s,p)}gatherND(e,t){const n=t.shape,s=n[n.length-1],[i,o,a,c]=hp(e,t);if(o===0)return sn([],i,e.dtype);const h=new an([o,a],e.dtype),p=this.readSync(t.dataId),m=this.readSync(e.dataId);for(let y=0;y<o;y++){const b=[];let w=0;for(let L=0;L<s;L++){const T=p[y*s+L];w+=T*c[L],b.push(T)}if(w<0||w>=e.size/a)throw new Error(`Invalid indices: ${b} does not index into ${e.shape}`);for(let L=0;L<a;L++)h.values[y*a+L]=m[w*a+L]}return h.toTensor().reshape(i)}scatterND(e,t,n){const{sliceRank:s,numUpdates:i,sliceSize:o,strides:a,outputSize:c}=qa(t,e,n),h=Ce(0),p=!0;return this.scatter(e,t,n,c,o,i,s,a,h,p)}onesLike(e){if(e.dtype==="string")throw new Error("onesLike is not supported for string tensors");return Ja(e.shape,1,e.dtype)}zerosLike(e){const t=Is(e.dtype,M(e.shape));return this.makeOutput(t,e.shape,e.dtype)}linspace(e,t,n){return vw(e,t,n)}scatter(e,t,n,s,i,o,a,c,h,p){const m=[s/i,i],y=this.readSync(e.dataId),b=this.readSync(t.dataId);if(s===0)return sn([],n,t.dtype);const w=new an(m,t.dtype);w.values.fill(this.readSync(h.dataId)[0]);for(let L=0;L<o;L++){const T=[];let v=0;for(let C=0;C<a;C++){const O=y[L*a+C];T.push(O),v+=O*c[C]}if(v<0||v>=s/i)throw new Error(`Invalid indices: ${T} does not index into ${n}`);for(let C=0;C<i;C++)p?w.values[v*i+C]+=b[L*i+C]:w.values[v*i+C]=t.rank===0?b[0]:b[L*i+C]}return w.toTensor().reshape(n)}}function H0(e){const t=new Float32Array(e.length);for(let n=0;n<e.length;++n)t[n]=Math.abs(e[n]);return t}const Uq=e=>{const{x:t}=e.inputs,n=e.backend;let s=new Float32Array(M(t.shape));if(t.dtype!=="complex64"){const i=n.data.get(t.dataId).values;s=H0(i)}else{const i=n.data.get(t.dataId),o=i.complexTensorInfos.real,a=i.complexTensorInfos.imag,c=n.data.get(o.dataId).values,h=n.data.get(a.dataId).values;for(let p=0;p<c.length;p++){const m=c[p],y=h[p];s[p]=Math.hypot(m,y)}}return n.makeOutput(s,t.shape,"float32")},Bq={kernelName:wd,backendName:"cpu",kernelFunc:Uq};function oo(e){return(t,n,s,i,o)=>{const a=st(t,n),c=a.length,h=Ke(a),p=M(a),m=bt(o,p),y=t.length,b=n.length,w=Ke(t),L=Ke(n),T=Mo(t,a),v=Mo(n,a);if(T.length+v.length===0)for(let C=0;C<m.length;++C)m[C]=e(s[C%s.length],i[C%i.length]);else for(let C=0;C<m.length;++C){const O=Co(C,c,h),D=O.slice(-y);T.forEach($=>D[$]=0);const k=Us(D,y,w),F=O.slice(-b);v.forEach($=>F[$]=0);const B=Us(F,b,L);m[C]=e(s[k],i[B])}return[m,a]}}function di(e){const{inputs:t,backend:n}=e,{real:s,imag:i}=t,o=n.data.get(s.dataId).values,a=n.data.get(i.dataId).values,c=n.makeTensorInfo(s.shape,"complex64"),h=n.data.get(c.dataId);return h.complexTensorInfos={real:n.makeTensorInfo(s.shape,"float32",o),imag:n.makeTensorInfo(i.shape,"float32",a)},c}const Mq={kernelName:xd,backendName:"cpu",kernelFunc:di};function ta(e){const{inputs:t,backend:n}=e,{x:s}=t;return n.incRef(s.dataId),{dataId:s.dataId,shape:s.shape,dtype:s.dtype}}const Pq={kernelName:$l,backendName:"cpu",kernelFunc:ta};function wu(e){const{inputs:t,backend:n}=e,{input:s}=t,i=n.data.get(s.dataId).complexTensorInfos.real,o=n.data.get(i.dataId).values;return n.makeTensorInfo(i.shape,i.dtype,o)}const zq={kernelName:zd,backendName:"cpu",kernelFunc:wu};function Lu(e){const{inputs:t,backend:n,attrs:s}=e,{x:i}=t,{dtype:o}=s;if(o==="complex64"){if(i.dtype==="complex64")return ta({inputs:{x:i},backend:n});const a=pt(i.shape),c=Lu({inputs:{x:i},backend:n,attrs:{dtype:"float32"}}),h=di({inputs:{real:c,imag:a},backend:n});return a.dispose(),n.disposeIntermediateTensorInfo(c),h}if(i.dtype==="complex64"){const a=wu({inputs:{input:i},backend:n}),c=Lu({inputs:{x:a},backend:n,attrs:{dtype:o}});return n.disposeIntermediateTensorInfo(a),c}if(!Oa(i.dtype,o)){const a=ta({inputs:{x:i},backend:n});return{dataId:a.dataId,shape:a.shape,dtype:o}}if(o==="int32"){const a=n.data.get(i.dataId).values,c=Int32Array.from(a);return n.makeTensorInfo(i.shape,"int32",c)}if(o==="bool"){const a=n.data.get(i.dataId).values,c=Ur([0],i.dtype),[h,p]=oo((m,y)=>m!==y?1:0)(i.shape,[],a,c,"bool");return n.makeTensorInfo(p,"bool",h)}throw new Error(`Error in Cast: failed to cast ${i.dtype} to ${o}`)}const Vq={kernelName:ka,backendName:"cpu",kernelFunc:Lu};function Ic(e,t,n,s){return n==null?({inputs:i,backend:o})=>{const{a,b:c}=i,h=o;Te([a,c],e);const p=h.data.get(a.dataId).values,m=h.data.get(c.dataId).values,y=s||a.dtype,[b,w]=t(a.shape,c.shape,p,m,y);return h.makeTensorInfo(w,y,b)}:({inputs:i,backend:o})=>{const{a,b:c}=i,h=o;if(a.dtype==="complex64"||c.dtype==="complex64"){const p=Lu({inputs:{x:a},backend:h,attrs:{dtype:"complex64"}}),m=h.data.get(p.dataId),y=m.complexTensorInfos.real,b=m.complexTensorInfos.imag,w=h.data.get(y.dataId).values,L=h.data.get(b.dataId).values,T=Lu({inputs:{x:c},backend:h,attrs:{dtype:"complex64"}}),v=h.data.get(T.dataId),C=v.complexTensorInfos.real,O=v.complexTensorInfos.imag,D=h.data.get(C.dataId).values,k=h.data.get(O.dataId).values,[F,B,$]=n(a.shape,c.shape,w,L,D,k),Y=h.makeTensorInfo($,"float32",F),j=h.makeTensorInfo($,"float32",B),Z=di({inputs:{real:Y,imag:j},backend:h});return h.disposeIntermediateTensorInfo(p),h.disposeIntermediateTensorInfo(T),h.disposeIntermediateTensorInfo(Y),h.disposeIntermediateTensorInfo(j),Z}else{const p=h.data.get(a.dataId).values,m=h.data.get(c.dataId).values,y=s||a.dtype,[b,w]=t(a.shape,c.shape,p,m,y);return h.makeTensorInfo(w,y,b)}}}function NS(e){return(t,n,s,i,o,a)=>{const c=st(t,n),h=M(c),p=c.length,m=Ke(c),y=bt("float32",h),b=bt("float32",h),w=Mo(t,c),L=Mo(n,c),T=ar(s,i),v=ar(o,a),C=t.length,O=Ke(t),D=n.length,k=Ke(n);if(w.length+L.length===0)for(let F=0;F<y.length;F++){const B=F%T.length,$=F%v.length,Y=e(T[B*2],T[B*2+1],v[$*2],v[$*2+1]);y[F]=Y.real,b[F]=Y.imag}else for(let F=0;F<y.length;F++){const B=Co(F,p,m),$=B.slice(-C);w.forEach(de=>$[de]=0);const Y=Us($,C,O),j=B.slice(-D);L.forEach(de=>j[de]=0);const Z=Us(j,D,k),re=e(T[Y*2],T[Y*2+1],v[Z*2],v[Z*2+1]);y[F]=re.real,b[F]=re.imag}return[y,b,c]}}const q0=oo((e,t)=>e+t),Gq=NS((e,t,n,s)=>({real:e+n,imag:t+s})),Su=Ic(Oo,q0,Gq),Yq={kernelName:Oo,backendName:"cpu",kernelFunc:Su};function xc(e){return(t,n,s)=>{const i=bt(n,t.length);for(let o=0;o<t.length;++o)i[o]=e(t[o],s);return i}}function xt(e,t,n){return({inputs:s,attrs:i,backend:o})=>{const{x:a}=s;if(Te(a,e),a.dtype==="string"||n==="string")throw new Error("unaryKernelFunc does not support string input/output");const c=o,h=c.data.get(a.dataId).values,p=M(a.shape),m=n||a.dtype,y=Is(m,p);for(let b=0;b<p;++b)y[b]=t(h[b],i);return c.makeTensorInfo(a.shape,m,y)}}function Tc(e,t,n){return({inputs:s,attrs:i,backend:o})=>{const{x:a}=s;if(Te(a,e),a.dtype==="string"||n==="string")throw new Error("unaryKernelFunc does not support string input/output");const c=o,h=c.data.get(a.dataId).values,p=n||a.dtype,m=t(h,p,i);return c.makeTensorInfo(a.shape,p,m)}}const j0=xc(e=>Math.ceil(e)),Hq=Tc(Nl,j0),qq={kernelName:Nl,backendName:"cpu",kernelFunc:Hq};const K0=xc(e=>Math.exp(e)),jq=Tc(kl,K0),Kq={kernelName:kl,backendName:"cpu",kernelFunc:jq};const X0=xc(e=>Math.expm1(e)),Xq=Tc(Fl,X0),Jq={kernelName:Fl,backendName:"cpu",kernelFunc:Xq};const J0=xc(e=>Math.floor(e)),Zq=Tc(_l,J0),Qq={kernelName:_l,backendName:"cpu",kernelFunc:Zq};const Z0=xc(e=>Math.log(e)),e4=Tc(Pl,Z0),t4={kernelName:Pl,backendName:"cpu",kernelFunc:e4};function Q0(e,t,n,s){const i=bt(s,M(n));for(let o=0;o<i.length;++o){const a=o*t;let c=e[a];for(let h=0;h<t;++h){const p=e[a+h];p>c&&(c=p)}i[o]=c}return i}const eC=oo((e,t)=>e*t),n4=NS((e,t,n,s)=>({real:e*n-t*s,imag:e*s+t*n})),tC=Ic(Wa,eC,n4),s4={kernelName:Wa,backendName:"cpu",kernelFunc:tC};const nC=oo((e,t)=>e!==t?1:0),i4=Ic(Hl,nC,null,"bool"),r4={kernelName:Hl,backendName:"cpu",kernelFunc:i4};const sC=xc(e=>1/Math.sqrt(e)),o4=Tc(Zl,sC),a4={kernelName:Zl,backendName:"cpu",kernelFunc:o4};function iC(e,t,n,s,i){const o=wb(s,t,n),a=M(n),c=Ke(s);if(o){const p=Lb(t,c);return e.subarray(p,p+a)}const h=bt(i,a);for(let p=0;p<a;++p){const m=n.length,y=Ke(n),b=Co(p,m,y),w=b.map((T,v)=>T+t[v]),L=Us(w,s.length,c);h[p]=e[L]}return h}function CS(e){const{inputs:t,backend:n,attrs:s}=e,{x:i}=t,{begin:o,size:a}=s;Te(i,"slice");const[c,h]=pp(i,o,a);bb(i,c,h);const p=n.data.get(i.dataId).values,m=iC(p,c,h,i.shape,i.dtype);return n.makeTensorInfo(h,i.dtype,m)}const c4={kernelName:Vd,backendName:"cpu",kernelFunc:CS};const rC=oo((e,t)=>{const n=e-t;return n*n}),l4=Ic(Ua,rC),h4={kernelName:Ua,backendName:"cpu",kernelFunc:l4};const oC=oo((e,t)=>e-t),u4=NS((e,t,n,s)=>({real:e-n,imag:t-s})),aC=Ic(Ba,oC,u4),d4={kernelName:Ba,backendName:"cpu",kernelFunc:aC};function RS(e,t,n,s,i){const o=t.length,a=M(t),c=Ke(t),h=Ke(i),p=bt(n,M(i));for(let m=0;m<a;++m){const y=Co(m,o,c),b=new Array(y.length);for(let L=0;L<b.length;L++)b[L]=y[s[L]];const w=Us(b,o,h);p[w]=e[m]}return p}function cC(e,t,n,s){const i=je(t,n)[0],o=[1,n[0],1];for(let L=0;L<i;L++)o[0]*=n[L];o[1]=n[i];for(let L=i+1;L<n.length;L++)o[2]*=n[L];const a={},c=new Int32Array(n[i]),h=new an(o,s,e),p=[],m=o[0]===1&&o[2]===1;for(let L=0;L<n[i];L++){let T;if(m)T=e[L].toString();else{const v=[];for(let C=0;C<o[0];C++)for(let O=0;O<o[2];O++)v.push(h.get(C,L,O));T=v.join(",")}if(a[T]!==void 0)c[L]=a[T];else{const v=Object.keys(a).length;a[T]=v,c[L]=v,p.push(L)}}const y=o.slice();y[1]=Object.keys(a).length;const b=new an(y,s);p.forEach((L,T)=>{for(let v=0;v<o[0];v++)for(let C=0;C<o[2];C++)b.set(h.get(v,L,C),v,T,C)});const w=n.slice();return w[i]=y[1],{outputValues:b.values,outputShape:w,indices:c}}var p4=Object.freeze({__proto__:null,simpleAbsImpl:H0,addImpl:q0,ceilImpl:j0,expImpl:K0,expm1Impl:X0,floorImpl:J0,logImpl:Z0,maxImpl:Q0,multiplyImpl:eC,notEqualImpl:nC,rsqrtImpl:sC,sliceImpl:iC,squaredDifferenceImpl:rC,subImpl:oC,transposeImpl:RS,uniqueImpl:cC});const m4="2.7.0";Tb("cpu",()=>new $q,1);const lC=xt(El,e=>e>=0?e:Math.exp(e)-1),f4={kernelName:El,backendName:"cpu",kernelFunc:lC};const g4=oo((e,t)=>e<0?t*e:e);function hC(e){const{inputs:t,backend:n}=e,{x:s,alpha:i}=t;Te([s,i],"prelu");const o=n.data.get(s.dataId).values,a=n.data.get(i.dataId).values,[c,h]=g4(s.shape,i.shape,o,a,s.dtype);return n.makeTensorInfo(h,s.dtype,c)}const y4={kernelName:Pd,backendName:"cpu",kernelFunc:hC};const uC=xt(jl,e=>Math.max(0,e)),b4={kernelName:jl,backendName:"cpu",kernelFunc:uC};const dC=xt(Xl,e=>Math.min(Math.max(0,e),6)),w4={kernelName:Xl,backendName:"cpu",kernelFunc:dC};function OS(e,t,n,s){if(n==="linear")return ta({inputs:{x:t},backend:e});if(n==="relu")return uC({inputs:{x:t},backend:e});if(n==="elu")return lC({inputs:{x:t},backend:e});if(n==="relu6")return dC({inputs:{x:t},backend:e});if(n==="prelu")return hC({inputs:{x:t,alpha:s},backend:e});throw new Error(`Activation ${n} has not been implemented for the CPU backend.`)}function $i(e){const{inputs:t,backend:n,attrs:s}=e,{x:i}=t,{shape:o}=s,a=M(i.shape),c=Vt(o,a),h=M(c);A(a===h,()=>`The new shape (${c}) has ${h} elements and the old shape (${i.shape}) has ${a} elements. The new shape and old shape must have the same number of elements.`),n.incRef(i.dataId);const p=n.data.get(i.dataId);if(p.complexTensorInfos!=null){const m=p.complexTensorInfos.real,y=p.complexTensorInfos.imag;m.shape=c,y.shape=c}return{dataId:i.dataId,shape:c,dtype:i.dtype}}const L4={kernelName:Kl,backendName:"cpu",kernelFunc:$i};function pC(e){const{inputs:t,backend:n,attrs:s}=e,{a:i,b:o}=t,{transposeA:a,transposeB:c}=s;Te([i,o],"matMul");const h=i.shape.length,p=o.shape.length,m=a?i.shape[h-2]:i.shape[h-1],y=c?o.shape[p-1]:o.shape[p-2],b=a?i.shape[h-1]:i.shape[h-2],w=c?o.shape[p-2]:o.shape[p-1],L=i.shape.slice(0,-2),T=o.shape.slice(0,-2),v=M(L),C=M(T),O=v===C||v===1||C===1;A(h>=2&&p>=2&&O,()=>`Error in matMul: the input batch dimensions must either be the same or at least one input batch dimension must be 1. Got input batch dimensions of (${L}) and (${T}).`);const D=v>C?i.shape.slice(0,-2):o.shape.slice(0,-2),k=D.concat([b,w]);A(m===y,()=>`Error in matMul: inner shapes (${m}) and (${y}) of Tensors with shapes ${i.shape} and ${o.shape} and transposeA=${a} and transposeB=${c} must match.`);const F=a?[v,m,b]:[v,b,m],B=c?[C,w,y]:[C,y,w],$=$i({inputs:{x:i},backend:n,attrs:{shape:F}}),Y=$i({inputs:{x:o},backend:n,attrs:{shape:B}}),j=a?$.shape[1]:$.shape[2],Z=a?$.shape[2]:$.shape[1],re=c?Y.shape[1]:Y.shape[2],de=Math.max(v,C),he=n.data.get($.dataId).values,ue=n.data.get(Y.dataId).values,me=Ke($.shape),ce=Ke(Y.shape),[ye,pe,Le]=a?[me[0],1,me[1]]:[me[0],me[1],1],[Se,xe,Oe]=c?[1,ce[1],ce[0]]:[ce[1],1,ce[0]],Ne=Z*re,De=wt([de,Z,re],$.dtype),Ue=De.values,Ve=n.blockSize;for(let ut=0;ut<de;ut++)for(let rt=0;rt<Z;rt+=Ve)for(let ot=0;ot<re;ot+=Ve)for(let mt=0;mt<j;mt+=Ve){const dt=Math.min(rt+Ve,Z),Dt=Math.min(ot+Ve,re),rn=Math.min(mt+Ve,j);for(let Ut=rt;Ut<dt;Ut++)for(let kt=ot;kt<Dt;kt++){let Ft=0;for(let Xt=mt;Xt<rn;Xt++){const On=Math.min(ut,v-1)*ye,wr=Math.min(ut,C-1)*Oe,En=he[On+Ut*pe+Xt*Le],pi=ue[Xt*Se+kt*xe+wr];Ft+=En*pi}Ue[ut*Ne+(Ut*re+kt)]+=Ft}}return n.disposeIntermediateTensorInfo($),n.disposeIntermediateTensorInfo(Y),n.makeTensorInfo(k,De.dtype,De.values)}const S4={kernelName:Id,backendName:"cpu",kernelFunc:pC};function I4(e){const{inputs:t,backend:n,attrs:s}=e,{a:i,b:o,bias:a,preluActivationWeights:c}=t,{transposeA:h,transposeB:p,activation:m}=s;let y,b,w;const L=[],T=pC({inputs:{a:i,b:o},attrs:{transposeA:h,transposeB:p},backend:n});y=T,a&&(b=Su({inputs:{a:y,b:a},backend:n}),L.push(y),y=b),m&&(w=OS(n,y,m,c),L.push(y),y=w);for(const v of L)n.disposeIntermediateTensorInfo(v);return y}const x4={kernelName:Kd,backendName:"cpu",kernelFunc:I4};const T4=xt(Ll,e=>Math.acos(e)),A4={kernelName:Ll,backendName:"cpu",kernelFunc:T4};const v4=xt(Sl,e=>Math.acosh(e)),N4={kernelName:Sl,backendName:"cpu",kernelFunc:v4};const C4=xt(Il,e=>Math.asin(e)),R4={kernelName:Il,backendName:"cpu",kernelFunc:C4};const O4=xt(xl,e=>Math.asinh(e)),E4={kernelName:xl,backendName:"cpu",kernelFunc:O4};const D4=xt(Tl,e=>Math.atan(e)),k4={kernelName:Tl,backendName:"cpu",kernelFunc:D4};const F4=xt(Al,e=>Math.atanh(e)),_4={kernelName:Al,backendName:"cpu",kernelFunc:F4};function ES(e,t,n,s,i,o){const a=i.strideHeight,c=i.strideWidth,h=i.dilationHeight,p=i.dilationWidth,m=i.effectiveFilterHeight,y=i.effectiveFilterWidth,b=i.padInfo.top,w=i.padInfo.left,L=o==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,T=wt(i.outShape,n),v=T.values,C=i.outShape[1]*i.outShape[2]*i.outShape[3],O=i.outShape[2]*i.outShape[3],D=i.outShape[3];for(let k=0;k<i.batchSize;++k){const F=k*C,B=k*s[0];for(let $=0;$<i.inChannels;++$)for(let Y=0;Y<i.outHeight;++Y){const j=Y*a-b,Z=Math.max(0,j),re=Math.min(i.inHeight,m+j),de=F+Y*O;for(let he=0;he<i.outWidth;++he){const ue=he*c-w,me=Math.max(0,ue),ce=Math.min(i.inWidth,y+ue);let ye=L,pe=0,Le=0;for(let xe=Z;xe<re;xe+=h){const Oe=B+xe*s[1];for(let Ne=me;Ne<ce;Ne+=p){const De=Oe+Ne*s[2],Ue=e[De+$];o==="max"&&Ue>ye?ye=Ue:o==="avg"&&(pe+=Ue,Le++)}if(isNaN(ye))break}const Se=de+he*D+$;v[Se]=o==="avg"?pe/Le:ye}}}return T}function mC(e,t,n,s,i=!1,o=!1){const a=wt(s.outShape,"int32"),c=s.strideHeight,h=s.strideWidth,p=s.dilationHeight,m=s.dilationWidth,y=s.effectiveFilterHeight,b=s.effectiveFilterWidth,w=s.padInfo.top,L=s.padInfo.left,T=wt(t,n,e);for(let v=0;v<s.batchSize;++v)for(let C=0;C<s.inChannels;++C)for(let O=0;O<s.outHeight;++O){const D=O*c-w;let k=D;for(;k<0;)k+=p;const F=Math.min(s.inHeight,y+D);for(let B=0;B<s.outWidth;++B){const $=B*h-L;let Y=$;for(;Y<0;)Y+=m;const j=Math.min(s.inWidth,b+$);let Z=Number.NEGATIVE_INFINITY,re=-1;for(let de=k;de<F;de+=p){const he=de-D;for(let ue=Y;ue<j;ue+=m){const me=ue-$,ce=T.get(v,de,ue,C);ce>Z&&(Z=ce,i?re=o?((v*s.inHeight+de)*s.inWidth+ue)*s.inChannels+C:(de*s.inWidth+ue)*s.inChannels+C:re=he*b+me)}}a.set(re,v,O,B,C)}}return a}function W4(e){const{inputs:t,backend:n,attrs:s}=e,{x:i}=t;Te(i,"avgPool");const{filterSize:o,strides:a,pad:c,dimRoundingMode:h}=s,p=1;A(cn(a,p),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${p}'`);const m=Mn(i.shape,o,a,p,c,h);let y;if(m.filterWidth===1&&m.filterHeight===1&&ie(m.inShape,m.outShape))y=ta({inputs:{x:i},backend:n});else{const b=n.data.get(i.dataId).values,w=Ke(i.shape),L=ES(b,i.shape,i.dtype,w,m,"avg");y=n.makeTensorInfo(m.outShape,i.dtype,L.values)}return y}const $4={kernelName:vl,backendName:"cpu",kernelFunc:W4};function U4(e){const{inputs:t,backend:n,attrs:s}=e,{dy:i,input:o}=t,a=o;Te([i,o],"avgPoolBackprop");const{filterSize:c,strides:h,pad:p}=s,m=Mn(a.shape,c,h,1,p),y=m.strideHeight,b=m.strideWidth,w=m.filterHeight,L=m.filterWidth,T=m.dilationHeight,v=m.dilationWidth,C=m.effectiveFilterHeight,O=m.effectiveFilterWidth,D=O-1-m.padInfo.left,k=C-1-m.padInfo.top,F=wt(a.shape,"float32"),B=1/(w*L),$=n.data.get(i.dataId).values,Y=wt(i.shape,"float32",$);for(let j=0;j<m.batchSize;++j)for(let Z=0;Z<m.inChannels;++Z)for(let re=0;re<m.inHeight;++re)for(let de=0;de<m.inWidth;++de){const he=re-k,ue=de-D;let me=0;for(let ce=0;ce<C;ce+=T){const ye=(he+ce)/y;if(ye<0||ye>=m.outHeight||Math.floor(ye)!==ye)continue;for(let pe=0;pe<O;pe+=v){const Le=(ue+pe)/b;if(Le<0||Le>=m.outWidth||Math.floor(Le)!==Le)continue;const Se=Y.get(j,ye,Le,Z);me+=Se}}F.set(me*B,j,re,de,Z)}return n.makeTensorInfo(F.shape,F.dtype,F.values)}const B4={kernelName:Sd,backendName:"cpu",kernelFunc:U4};function M4(e){const{inputs:t,backend:n,attrs:s}=e,{x:i,scale:o,offset:a,mean:c,variance:h}=t;A(c.shape.length===h.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),A(a==null||c.shape.length===a.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),A(o==null||c.shape.length===o.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks."),Te([i,c,h,o,a],"batchNorm");let{varianceEpsilon:p}=s;p==null&&(p=.001);const m=n.data.get(i.dataId).values,y=n.data.get(c.dataId).values,b=n.data.get(h.dataId).values,w=o?n.data.get(o.dataId).values:new Float32Array([1]),L=a?n.data.get(a.dataId).values:new Float32Array([0]),T=new Float32Array(m.length),v=L.length,C=w.length,O=b.length,D=y.length;let k=0,F=0,B=0,$=0;for(let Y=0;Y<m.length;++Y)T[Y]=L[k++]+(m[Y]-y[F++])*w[B++]/Math.sqrt(b[$++]+p),k>=v&&(k=0),F>=D&&(F=0),B>=C&&(B=0),$>=O&&($=0);return n.makeTensorInfo(i.shape,i.dtype,T)}const P4={kernelName:Wl,backendName:"cpu",kernelFunc:M4};const z4=xt(Cl,(e,t)=>{const n=t;return e>n.clipValueMax?n.clipValueMax:e<n.clipValueMin?n.clipValueMin:e}),V4={kernelName:Cl,backendName:"cpu",kernelFunc:z4};function Vm(e){const{inputs:t,backend:n}=e,{input:s}=t,i=n.data.get(s.dataId).complexTensorInfos.imag,o=n.data.get(i.dataId).values;return n.makeTensorInfo(i.shape,i.dtype,o)}const G4={kernelName:Fd,backendName:"cpu",kernelFunc:Vm};function Iu(e){const{inputs:t,backend:n,attrs:s}=e,{axis:i}=s,o=je(i,t[0].shape)[0];let a=nr(t.map(w=>w.shape),o);if(M(a)===0)return n.makeTensorInfo(a,t[0].dtype,[]);const c=t.filter(w=>M(w.shape)>0);if(c.length===1)return c[0];const h=c.map(w=>w.shape);if(Lp(h,o),c[0].dtype==="complex64"){const w=c.map(O=>wu({inputs:{input:O},backend:n})),L=c.map(O=>Vm({inputs:{input:O},backend:n})),T=Iu({inputs:w,backend:n,attrs:{axis:o}}),v=Iu({inputs:L,backend:n,attrs:{axis:o}}),C=di({inputs:{real:T,imag:v},backend:n});return w.forEach(O=>n.disposeIntermediateTensorInfo(O)),L.forEach(O=>n.disposeIntermediateTensorInfo(O)),n.disposeIntermediateTensorInfo(T),n.disposeIntermediateTensorInfo(v),C}const p=c.map(w=>{const L=M(w.shape.slice(o)),T=[-1,L];return $i({inputs:{x:w},backend:n,attrs:{shape:T}})});a=nr(p.map(w=>w.shape),1);const m=bt(c[0].dtype,M(a));if(p[0].shape[0]===1){let w=0;p.forEach(L=>{const T=n.data.get(L.dataId).values,v=M(L.shape);m.set(T,w),w+=v})}else{let w=0;p.forEach(L=>{const T=n.data.get(L.dataId).values;let v=0;for(let C=0;C<L.shape[0];++C){const O=C*a[1]+w;for(let D=0;D<L.shape[1];++D)m[O+D]=T[v++]}w+=L.shape[1]})}const y=nr(c.map(w=>w.shape),o),b=n.makeTensorInfo(y,t[0].dtype,m);return p.forEach(w=>n.disposeIntermediateTensorInfo(w)),b}const Y4={kernelName:Rl,backendName:"cpu",kernelFunc:Iu};function fC(e){const{inputs:t,backend:n,attrs:s}=e,{x:i,filter:o}=t,{strides:a,pad:c,dataFormat:h,dilations:p,dimRoundingMode:m}=s;Te([i,o],"conv2d");const y=Gr(h),b=_n(i.shape,o.shape,a,p,c,m,!1,y),w=b.filterHeight,L=b.filterWidth,T=b.dilationHeight,v=b.dilationWidth,C=b.padInfo.left,O=b.padInfo.top,D=b.dataFormat==="channelsLast",k=new an(b.outShape,i.dtype),F=Ke(i.shape),B=Ke(o.shape),$=F[0],Y=D?F[1]:F[2],j=D?F[2]:1,Z=D?1:F[1],re=k.strides[0],de=D?k.strides[1]:k.strides[2],he=D?k.strides[2]:1,ue=D?1:k.strides[1],me=n.data.get(i.dataId).values,ce=n.data.get(o.dataId).values,ye=k.values;for(let pe=0;pe<b.batchSize;++pe){const Le=pe*$,Se=pe*re;for(let xe=0;xe<b.outHeight;++xe){const Oe=Se+xe*de,Ne=xe*b.strideHeight-O;for(let De=0;De<w;++De){const Ue=Ne+De*T;if(Ue<0||Ue>=b.inHeight)continue;const Ve=De*B[0],ut=Le+Ue*Y;for(let rt=0;rt<b.outWidth;++rt){const ot=Oe+rt*he,mt=rt*b.strideWidth-C;for(let dt=0;dt<L;++dt){const Dt=mt+dt*v;if(Dt<0||Dt>=b.inWidth)continue;const rn=Ve+dt*B[1],Ut=ut+Dt*j;let kt=rn;for(let Ft=0;Ft<b.inChannels;++Ft){const Xt=me[Ut+Ft*Z];for(let On=0;On<b.outChannels;++On)ye[ot+On*ue]+=Xt*ce[kt+On];kt+=b.outChannels}}}}}}return n.makeTensorInfo(k.shape,k.dtype,ye)}const H4={kernelName:Td,backendName:"cpu",kernelFunc:fC};function q4(e){const{inputs:t,backend:n,attrs:s}=e,{x:i,dy:o}=t,{strides:a,pad:c,dataFormat:h,dimRoundingMode:p,filterShape:m}=s;Te([i,o],"conv2dBackpropFilter");const y=Gr(h),b=_n(i.shape,m,a,1,c,p,!1,y),{strideHeight:w,strideWidth:L,filterHeight:T,filterWidth:v}=b,C=b.dataFormat==="channelsLast",O=new an(b.filterShape,"float32"),D=b.padInfo.left,k=b.padInfo.top,F=n.data.get(i.dataId).values,B=n.data.get(o.dataId).values,$=new an(i.shape,i.dtype,F),Y=new an(o.shape,o.dtype,B);for(let j=0;j<T;++j){const Z=Math.max(0,Math.ceil((k-j)/w)),re=Math.min(b.outHeight,(b.inHeight+k-j)/w);for(let de=0;de<v;++de){const he=Math.max(0,Math.ceil((D-de)/L)),ue=Math.min(b.outWidth,(b.inWidth+D-de)/L);for(let me=0;me<b.inChannels;++me)for(let ce=0;ce<b.outChannels;++ce){let ye=0;for(let pe=0;pe<b.batchSize;++pe)for(let Le=Z;Le<re;++Le){const Se=j+Le*w-k;for(let xe=he;xe<ue;++xe){const Oe=de+xe*L-D;C?ye+=$.get(pe,Se,Oe,me)*Y.get(pe,Le,xe,ce):ye+=$.get(pe,me,Se,Oe)*Y.get(pe,ce,Le,xe)}}O.set(ye,j,de,me,ce)}}}return n.makeTensorInfo(O.shape,O.dtype,O.values)}const j4={kernelName:fy,backendName:"cpu",kernelFunc:q4};function K4(e){const{inputs:t,backend:n,attrs:s}=e,{dy:i,filter:o}=t,{inputShape:a,strides:c,pad:h,dataFormat:p,dimRoundingMode:m}=s;Te([i,o],"conv2dBackpropInput");const y=Ke(o.shape),b=Ke(i.shape);let w=Gr(p);const L=_n(a,o.shape,c,1,h,m,!1,w),T=new an(L.inShape,"float32"),v=T.values,C=n.data.get(i.dataId).values,O=n.data.get(o.dataId).values,[D,k,F]=y,{batchSize:B,filterHeight:$,filterWidth:Y,inChannels:j,inHeight:Z,inWidth:re,outChannels:de,outHeight:he,outWidth:ue,strideHeight:me,strideWidth:ce}=L;w=L.dataFormat;const ye=$-1-L.padInfo.top,pe=Y-1-L.padInfo.left,Le=w==="channelsLast",Se=T.strides[0],xe=Le?T.strides[1]:T.strides[2],Oe=Le?T.strides[2]:1,Ne=Le?1:T.strides[1],De=b[0],Ue=Le?b[1]:b[2],Ve=Le?b[2]:1,ut=Le?1:b[1];for(let rt=0;rt<B;++rt)for(let ot=0;ot<j;++ot)for(let mt=0;mt<Z;++mt){const dt=mt-ye,Dt=Math.max(0,Math.ceil(dt/me)),rn=Math.min(he,($+dt)/me);for(let Ut=0;Ut<re;++Ut){const kt=Ut-pe,Ft=Math.max(0,Math.ceil(kt/ce)),Xt=Math.min(ue,(Y+kt)/ce);let On=0;for(let En=Dt;En<rn;++En){const pi=En*me-dt;for(let Es=Ft;Es<Xt;++Es){const ia=Es*ce-kt,mi=De*rt+Ue*En+Ve*Es,Bi=D*($-1-pi)+k*(Y-1-ia)+F*ot;for(let co=0;co<de;++co){const lo=C[mi+ut*co],ho=O[Bi+co];On+=lo*ho}}}const wr=Se*rt+xe*mt+Oe*Ut+Ne*ot;v[wr]=On}}return n.makeTensorInfo(T.shape,T.dtype,T.values)}const X4={kernelName:Ad,backendName:"cpu",kernelFunc:K4};function J4(e){const{inputs:t,backend:n,attrs:s}=e,{x:i,filter:o}=t,{strides:a,pad:c,dilations:h}=s;Te([i,o],"conv3d");const p=zr(i.shape,o.shape,a,h,c),{filterDepth:m,filterHeight:y,filterWidth:b,dilationDepth:w,dilationHeight:L,dilationWidth:T,padInfo:v}=p,C=v.front,O=v.left,D=v.top,k=new an(p.outShape,i.dtype),F=n.data.get(i.dataId).values,B=n.data.get(o.dataId).values,$=k.values,Y=Ke(i.shape),j=Ke(o.shape);for(let Z=0;Z<p.batchSize;++Z){const re=Z*Y[0],de=Z*k.strides[0];for(let he=0;he<p.outDepth;++he){const ue=de+he*k.strides[1],me=he*p.strideDepth-C;for(let ce=0;ce<m;++ce){const ye=me+ce*w;if(ye<0||ye>=p.inDepth)continue;const pe=ce*j[0],Le=re+ye*Y[1];for(let Se=0;Se<p.outHeight;++Se){const xe=ue+Se*k.strides[2],Oe=Se*p.strideHeight-D;for(let Ne=0;Ne<y;++Ne){const De=Oe+Ne*L;if(De<0||De>=p.inHeight)continue;const Ue=pe+Ne*j[1],Ve=Le+De*Y[2];for(let ut=0;ut<p.outWidth;++ut){const rt=xe+ut*p.outChannels,ot=ut*p.strideWidth-O;for(let mt=0;mt<b;++mt){const dt=ot+mt*T;if(dt<0||dt>=p.inWidth)continue;const Dt=Ue+mt*j[2],rn=Ve+dt*p.inChannels;let Ut=Dt;for(let kt=0;kt<p.inChannels;++kt){const Ft=F[rn+kt];for(let Xt=0;Xt<p.outChannels;++Xt)$[rt+Xt]+=Ft*B[Ut+Xt];Ut+=p.outChannels}}}}}}}}return n.makeTensorInfo(k.shape,k.dtype,k.values)}const Z4={kernelName:vd,backendName:"cpu",kernelFunc:J4};function Q4(e){const{inputs:t,backend:n,attrs:s}=e,{x:i,dy:o}=t,{strides:a,pad:c,filterShape:h}=s;Te([i,o],"conv3dBackpropFilterV2");const p=Ke(i.shape),m=Ke(o.shape),y=zr(i.shape,h,a,1,c),b=y.strideDepth,w=y.strideHeight,L=y.strideWidth,T=y.filterDepth,v=y.filterHeight,C=y.filterWidth,O=new an(y.filterShape,"float32"),D=O.values,[k,F,B,$]=O.strides,Y=n.data.get(o.dataId).values,[j,Z,re,de]=m,he=n.data.get(i.dataId).values,[ue,me,ce,ye]=p,pe=y.padInfo.front,Le=y.padInfo.left,Se=y.padInfo.top;for(let xe=0;xe<T;++xe){const Oe=Math.max(0,Math.ceil((pe-xe)/b)),Ne=Math.min(y.outDepth,(y.inDepth+pe-xe)/b),De=xe*k;for(let Ue=0;Ue<v;++Ue){const Ve=Math.max(0,Math.ceil((Se-Ue)/w)),ut=Math.min(y.outHeight,(y.inHeight+Se-Ue)/w),rt=Ue*F+De;for(let ot=0;ot<C;++ot){const mt=Math.max(0,Math.ceil((Le-ot)/L)),dt=Math.min(y.outWidth,(y.inWidth+Le-ot)/L),Dt=ot*B+rt;for(let rn=0;rn<y.inChannels;++rn){const Ut=rn*$+Dt;for(let kt=0;kt<y.outChannels;++kt){let Ft=0;for(let Xt=0;Xt<y.batchSize;++Xt){const On=Xt*ue,wr=Xt*j;for(let En=Oe;En<Ne;++En){const pi=xe+En*b-pe,Es=pi*me+On,ia=En*Z+wr;for(let mi=Ve;mi<ut;++mi){const Bi=Ue+mi*w-Se,co=Bi*ce+Es,lo=mi*re+ia;for(let ho=mt;ho<dt;++ho){const Wc=ot+ho*L-Le,jS=Wc*ye+co,KS=ho*de+lo;Ft+=he[jS+rn]*Y[KS+kt]}}}}D[Ut+kt]=Ft}}}}}return n.makeTensorInfo(O.shape,O.dtype,O.values)}const ej={kernelName:gy,backendName:"cpu",kernelFunc:Q4};function tj(e){const{inputs:t,backend:n,attrs:s}=e,{dy:i,filter:o}=t,{pad:a,strides:c,inputShape:h}=s;Te([i],"conv3dBackpropInputV2");const p=Ke(i.shape),m=Ke(o.shape),y=zr(h,o.shape,c,1,a),b=new an(y.inShape,"float32"),w=b.values,[L,T,v,C]=b.strides,O=n.data.get(i.dataId).values,[D,k,F,B]=p,$=n.data.get(o.dataId).values,[Y,j,Z,re]=m,{batchSize:de,filterDepth:he,filterHeight:ue,filterWidth:me,inChannels:ce,inDepth:ye,inHeight:pe,inWidth:Le,outChannels:Se,outDepth:xe,outHeight:Oe,outWidth:Ne,strideDepth:De,strideHeight:Ue,strideWidth:Ve}=y,ut=he-1-y.padInfo.front,rt=ue-1-y.padInfo.top,ot=me-1-y.padInfo.left;for(let mt=0;mt<de;++mt)for(let dt=0;dt<ce;++dt)for(let Dt=0;Dt<ye;++Dt){const rn=Dt-ut,Ut=Math.max(0,Math.ceil(rn/De)),kt=Math.min(xe,(he+rn)/De);for(let Ft=0;Ft<pe;++Ft){const Xt=Ft-rt,On=Math.max(0,Math.ceil(Xt/Ue)),wr=Math.min(Oe,(ue+Xt)/Ue);for(let En=0;En<Le;++En){const pi=En-ot,Es=Math.max(0,Math.ceil(pi/Ve)),ia=Math.min(Ne,(me+pi)/Ve);let mi=0;for(let Bi=Ut;Bi<kt;++Bi){const co=Bi*De-rn;for(let lo=On;lo<wr;++lo){const ho=lo*Ue-Xt;for(let Wc=Es;Wc<ia;++Wc){const jS=Wc*Ve-pi,KS=D*mt+k*Bi+F*lo+B*Wc,QJ=Y*(he-1-co)+j*(ue-1-ho)+Z*(me-1-jS)+re*dt;for(let sf=0;sf<Se;++sf){const e9=O[KS+sf],t9=$[QJ+sf];mi+=e9*t9}}}}w[L*mt+T*Dt+v*Ft+C*En+dt]=mi}}}return n.makeTensorInfo(b.shape,b.dtype,b.values)}const nj={kernelName:yy,backendName:"cpu",kernelFunc:tj};const sj=xt(Fa,e=>Math.cos(e)),ij={kernelName:Fa,backendName:"cpu",kernelFunc:sj};const rj=xt(Ol,e=>Math.cosh(e)),oj={kernelName:Ol,backendName:"cpu",kernelFunc:rj};function gC(e){const{inputs:t,backend:n,attrs:s}=e,{x:i,filter:o}=t,{strides:a,pad:c,dilations:h,dimRoundingMode:p}=s;Te([i,o],"depthwiseConv2DNative");const m=Ke(i.shape),y=Ke(o.shape);let b=h;b==null&&(b=[1,1]),A(cn(a,b),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${a} and dilations '${b}'`);const w=_n(i.shape,o.shape,a,b,c,p,!0),{filterHeight:L,filterWidth:T,dilationHeight:v,dilationWidth:C,padInfo:O}=w,D=O.left,k=O.top,F=w.outChannels/w.inChannels,B=new an(w.outShape,i.dtype),$=n.data.get(i.dataId).values,Y=n.data.get(o.dataId).values,j=B.values;for(let Z=0;Z<w.batchSize;++Z){const re=Z*m[0],de=Z*B.strides[0];for(let he=0;he<w.outHeight;++he){const ue=de+he*B.strides[1],me=he*w.strideHeight-D;for(let ce=0;ce<L;++ce){const ye=me+ce*v;if(ye<0||ye>=w.inHeight)continue;const pe=ce*y[0],Le=re+ye*m[1];for(let Se=0;Se<w.outWidth;++Se){const xe=ue+Se*B.strides[2],Oe=Se*w.strideWidth-k;for(let Ne=0;Ne<T;++Ne){const De=Oe+Ne*C;if(De<0||De>=w.inWidth)continue;const Ue=pe+Ne*y[1],Ve=Le+De*w.inChannels;let ut=xe,rt=Ue;for(let ot=0;ot<w.inChannels;++ot){const mt=$[Ve+ot];for(let dt=0;dt<F;++dt)j[ut+dt]+=mt*Y[rt+dt];ut+=F,rt+=F}}}}}}return n.makeTensorInfo(B.shape,B.dtype,B.values)}const aj={kernelName:Nd,backendName:"cpu",kernelFunc:gC};function cj(e){const{inputs:t,backend:n,attrs:s}=e,{x:i,dy:o}=t,{strides:a,dilations:c,pad:h,dimRoundingMode:p,filterShape:m}=s;Te([i,o],"depthwiseConv2dNativeBackpropFilter");const y=_n(i.shape,m,a,c,h,p,!0),{strideHeight:b,strideWidth:w,filterHeight:L,filterWidth:T}=y,v=new an(y.filterShape,"float32"),C=y.padInfo.left,O=y.padInfo.top,D=y.outChannels/y.inChannels,k=n.data.get(i.dataId).values,F=new an(i.shape,i.dtype,k),B=n.data.get(o.dataId).values,$=new an(o.shape,o.dtype,B);for(let Y=0;Y<L;++Y){const j=Math.max(0,Math.ceil((O-Y)/b)),Z=Math.min(y.outHeight,(y.inHeight+O-Y)/b);for(let re=0;re<T;++re){const de=Math.max(0,Math.ceil((C-re)/w)),he=Math.min(y.outWidth,(y.inWidth+C-re)/w);for(let ue=0;ue<y.outChannels;++ue){const me=Math.trunc(ue/D),ce=ue%D;let ye=0;for(let pe=0;pe<y.batchSize;++pe)for(let Le=j;Le<Z;++Le){const Se=Y+Le*b-O;for(let xe=de;xe<he;++xe){const Oe=re+xe*w-C;ye+=F.get(pe,Se,Oe,me)*$.get(pe,Le,xe,ue)}}v.set(ye,Y,re,me,ce)}}}return n.makeTensorInfo(v.shape,v.dtype,v.values)}const lj={kernelName:wy,backendName:"cpu",kernelFunc:cj};function hj(e){const{inputs:t,backend:n,attrs:s}=e,{dy:i,filter:o}=t,{strides:a,dilations:c,pad:h,dimRoundingMode:p,inputShape:m}=s;Te([i,o],"depthwiseConv2DNativeBackpropInput");const y=Ke(i.shape),b=Ke(o.shape),w=_n(m,o.shape,a,c,h,p,!0),L=new an(w.inShape,"float32"),T=L.values,[v,C,O]=L.strides,D=n.data.get(i.dataId).values,[k,F,B]=y,$=n.data.get(o.dataId).values,[Y,j,Z]=b,{batchSize:re,filterHeight:de,filterWidth:he,inChannels:ue,inHeight:me,inWidth:ce,outChannels:ye,outHeight:pe,outWidth:Le,strideHeight:Se,strideWidth:xe}=w,Oe=de-1-w.padInfo.top,Ne=he-1-w.padInfo.left,De=ye/ue;for(let Ue=0;Ue<re;++Ue)for(let Ve=0;Ve<ue;++Ve)for(let ut=0;ut<me;++ut){const rt=ut-Oe,ot=Math.max(0,Math.ceil(rt/Se)),mt=Math.min(pe,(de+rt)/Se);for(let dt=0;dt<ce;++dt){const Dt=dt-Ne,rn=Math.max(0,Math.ceil(Dt/xe)),Ut=Math.min(Le,(he+Dt)/xe);let kt=0;for(let Ft=ot;Ft<mt;++Ft){const Xt=Ft*Se-rt;for(let On=rn;On<Ut;++On){const wr=On*xe-Dt,En=k*Ue+F*Ft+B*On,pi=Y*(de-1-Xt)+j*(he-1-wr)+Z*Ve;for(let Es=0;Es<De;++Es){const ia=Ve*De+Es,mi=D[En+ia],Bi=$[pi+Es];kt+=mi*Bi}}}T[v*Ue+C*ut+O*dt+Ve]=kt}}return n.makeTensorInfo(L.shape,L.dtype,L.values)}const uj={kernelName:Ly,backendName:"cpu",kernelFunc:hj};const dj={kernelName:Cd,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:s,filter:i}=e,{strides:o,pad:a,dilations:c}=n,h=t,p=h.data.get(s.dataId).values,m=s.shape.length,y=h.data.get(i.dataId).values,b=i.shape.length,{batchSize:w,inHeight:L,inWidth:T,inChannels:v,outHeight:C,outWidth:O,padInfo:D,strideHeight:k,strideWidth:F,filterHeight:B,filterWidth:$,dilationHeight:Y,dilationWidth:j,outShape:Z}=bp(s.shape,i.shape,o,a,"NHWC",c),re=M(Z),de=Z.length,he=Is(s.dtype,re);for(let me=0;me<w;++me)for(let ce=0;ce<C;++ce){const ye=ce*k-D.top;for(let pe=0;pe<O;++pe){const Le=pe*F-D.left;for(let Se=0;Se<v;++Se){let xe=Number.MIN_SAFE_INTEGER;for(let Ne=0;Ne<B;++Ne){const De=ye+Ne*Y;if(De>=0&&De<L)for(let Ue=0;Ue<$;++Ue){const Ve=Le+Ue*j;if(Ve>=0&&Ve<T){const ut=Us([me,De,Ve,Se],m,Ke(s.shape)),rt=Us([Ne,Ue,Se],b,Ke(i.shape)),ot=p[ut]+y[rt];ot>xe&&(xe=ot)}}}const Oe=Us([me,ce,pe,Se],de,Ke(Z));he[Oe]=xe}}}const ue=h.write(Ur(he,s.dtype),Z,s.dtype);return{dataId:ue,shape:Z,dtype:s.dtype}}};const pj={kernelName:Od,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:s,filter:i,dy:o}=e,{strides:a,pad:c,dilations:h}=n,p=t,m=xs(s.shape,p.data.get(s.dataId).values),y=xs(i.shape,p.data.get(i.dataId).values),{batchSize:b,inHeight:w,inWidth:L,inChannels:T,outHeight:v,outWidth:C,padInfo:O,strideHeight:D,strideWidth:k,filterHeight:F,filterWidth:B,dilationHeight:$,dilationWidth:Y,outShape:j}=bp(s.shape,i.shape,a,c,"NHWC",h);A(o.rank===j.length,()=>`Error in ${Od}, dy must have the same rank as output ${j.length}, but got ${o.rank}`);const Z=xs(j,p.data.get(o.dataId).values),re=oy(i.shape,i.dtype);for(let he=0;he<b;++he)for(let ue=0;ue<v;++ue){const me=ue*D-O.top;for(let ce=0;ce<C;++ce){const ye=ce*k-O.left;for(let pe=0;pe<T;++pe){let Le=Number.MIN_SAFE_INTEGER,Se=0,xe=0;for(let Oe=0;Oe<F;++Oe){const Ne=me+Oe*$;if(Ne>=0&&Ne<w)for(let De=0;De<B;++De){const Ue=ye+De*Y;if(Ue>=0&&Ue<L){const Ve=m[he][Ne][Ue][pe]+y[Oe][De][pe];Ve>Le&&(Le=Ve,Se=Oe,xe=De)}}}re[Se][xe][pe]+=Z[he][ue][ce][pe]}}}const de=p.write(Ur(re,s.dtype),i.shape,i.dtype);return{dataId:de,shape:i.shape,dtype:i.dtype}}};const mj={kernelName:Rd,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:s,filter:i,dy:o}=e,{strides:a,pad:c,dilations:h}=n,p=t,m=xs(s.shape,p.data.get(s.dataId).values),y=xs(i.shape,p.data.get(i.dataId).values),{batchSize:b,inHeight:w,inWidth:L,inChannels:T,outHeight:v,outWidth:C,padInfo:O,strideHeight:D,strideWidth:k,filterHeight:F,filterWidth:B,dilationHeight:$,dilationWidth:Y,outShape:j}=bp(s.shape,i.shape,a,c,"NHWC",h);A(o.rank===j.length,()=>`Error in ${Rd}, dy must have the same rank as output ${j.length}, but got ${o.rank}`);const Z=xs(j,p.data.get(o.dataId).values),re=oy(s.shape,s.dtype);for(let he=0;he<b;++he)for(let ue=0;ue<v;++ue){const me=ue*D-O.top;for(let ce=0;ce<C;++ce){const ye=ce*k-O.left;for(let pe=0;pe<T;++pe){let Le=Number.MIN_SAFE_INTEGER,Se=me<0?0:me,xe=ye<0?0:ye;for(let Oe=0;Oe<F;++Oe){const Ne=me+Oe*$;if(Ne>=0&&Ne<w)for(let De=0;De<B;++De){const Ue=ye+De*Y;if(Ue>=0&&Ue<L){const Ve=m[he][Ne][Ue][pe]+y[Oe][De][pe];Ve>Le&&(Le=Ve,Se=Ne,xe=Ue)}}}re[he][Se][xe][pe]+=Z[he][ue][ce][pe]}}}const de=p.write(Ur(re,s.dtype),s.shape,s.dtype);return{dataId:de,shape:s.shape,dtype:s.dtype}}};const fj=oo((e,t)=>e/t),gj=Ic(_a,fj),DS={kernelName:_a,backendName:"cpu",kernelFunc:gj};const yj=ww,bj=Lw,wj=Sw,Lj=Iw,Sj=xw,Ij=Tw,xj=xt(Dl,e=>{const t=Math.sign(e),n=Math.abs(e),s=1/(1+yj*n);return t*(1-((((Ij*s+Sj)*s+Lj)*s+wj)*s+bj)*s*Math.exp(-n*n))}),Tj={kernelName:Dl,backendName:"cpu",kernelFunc:xj};function yC(e,t,n){const s=e.shape,i=s[0],o=s[1],a=n.data.get(e.dataId),c=a.complexTensorInfos.real,h=a.complexTensorInfos.imag,p=[i,o],m=M(p),y=bt("float32",m),b=bt("float32",m);for(let v=0;v<i;v++){const C=CS({inputs:{x:c},backend:n,attrs:{begin:[v,0],size:[1,o]}}),O=CS({inputs:{x:h},backend:n,attrs:{begin:[v,0],size:[1,o]}}),D=di({inputs:{real:C,imag:O},backend:n}),{real:k,imag:F}=Aj(D,t,n),B=ar(k,F);for(let $=0;$<o;$++){const Y=Aw(B,$);y[v*o+$]=Y.real,b[v*o+$]=Y.imag}n.disposeIntermediateTensorInfo(C),n.disposeIntermediateTensorInfo(O),n.disposeIntermediateTensorInfo(D)}const w=n.makeTensorInfo(p,"float32",y),L=n.makeTensorInfo(p,"float32",b),T=di({inputs:{real:w,imag:L},backend:n});return n.disposeIntermediateTensorInfo(w),n.disposeIntermediateTensorInfo(L),T}function Aj(e,t,n){const s=M(e.shape),i=n.data.get(e.dataId),o=n.data.get(i.complexTensorInfos.real.dataId).values,a=n.data.get(i.complexTensorInfos.imag.dataId).values;if(vj(s)){const c=kS(o,a,s,t,n),h=[e.shape[0],e.shape[1]];if(t){const p=n.makeTensorInfo(h,"float32",c.real),m=n.makeTensorInfo(h,"float32",c.imag),y=n.makeTensorInfo([],"float32",RT(s,"float32")),b=ta({inputs:{x:y},backend:n}),w=DS.kernelFunc({inputs:{a:p,b:y},backend:n}),L=DS.kernelFunc({inputs:{a:m,b},backend:n}),T=n.data.get(w.dataId).values,v=n.data.get(L.dataId).values;return n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(y),n.disposeIntermediateTensorInfo(b),n.disposeIntermediateTensorInfo(w),n.disposeIntermediateTensorInfo(L),{real:T,imag:v}}return c}else{const c=ar(o,a),h=Nj(c,s,t);return wv(h)}}function vj(e){return(e&e-1)===0}function kS(e,t,n,s,i){if(n===1)return{real:e,imag:t};const o=ar(e,t),a=n/2,c=Lv(o),h=c.real,p=c.imag,m=[h.length],y=i.makeTensorInfo(m,"float32",h),b=i.makeTensorInfo(m,"float32",p),w=di({inputs:{real:y,imag:b},backend:i}),L=Sv(o),T=L.real,v=L.imag,C=[T.length],O=i.makeTensorInfo(C,"float32",T),D=i.makeTensorInfo(C,"float32",v),k=di({inputs:{real:O,imag:D},backend:i}),F=kS(h,p,a,s,i),B=F.real,$=F.imag,Y=[B.length],j=i.makeTensorInfo(Y,"float32",B),Z=i.makeTensorInfo(Y,"float32",$),re=di({inputs:{real:j,imag:Z},backend:i}),de=kS(T,v,a,s,i),he=de.real,ue=de.imag,me=[he.length],ce=i.makeTensorInfo(me,"float32",he),ye=i.makeTensorInfo(me,"float32",ue),pe=di({inputs:{real:ce,imag:ye},backend:i}),Le=xv(n,s),Se=[Le.real.length],xe=i.makeTensorInfo(Se,"float32",Le.real),Oe=i.makeTensorInfo(Se,"float32",Le.imag),Ne=di({inputs:{real:xe,imag:Oe},backend:i}),De=tC({inputs:{a:Ne,b:pe},backend:i}),Ue=Su({inputs:{a:re,b:De},backend:i}),Ve=aC({inputs:{a:re,b:De},backend:i}),ut=wu({inputs:{input:Ue},backend:i}),rt=wu({inputs:{input:Ve},backend:i}),ot=Vm({inputs:{input:Ue},backend:i}),mt=Vm({inputs:{input:Ve},backend:i}),dt=Iu({inputs:[ut,rt],backend:i,attrs:{axis:0}}),Dt=Iu({inputs:[ot,mt],backend:i,attrs:{axis:0}}),rn=i.data.get(dt.dataId).values,Ut=i.data.get(Dt.dataId).values;return i.disposeIntermediateTensorInfo(y),i.disposeIntermediateTensorInfo(b),i.disposeIntermediateTensorInfo(w),i.disposeIntermediateTensorInfo(O),i.disposeIntermediateTensorInfo(D),i.disposeIntermediateTensorInfo(k),i.disposeIntermediateTensorInfo(j),i.disposeIntermediateTensorInfo(Z),i.disposeIntermediateTensorInfo(re),i.disposeIntermediateTensorInfo(ce),i.disposeIntermediateTensorInfo(ye),i.disposeIntermediateTensorInfo(pe),i.disposeIntermediateTensorInfo(xe),i.disposeIntermediateTensorInfo(Oe),i.disposeIntermediateTensorInfo(Ne),i.disposeIntermediateTensorInfo(De),i.disposeIntermediateTensorInfo(Ue),i.disposeIntermediateTensorInfo(Ve),i.disposeIntermediateTensorInfo(ut),i.disposeIntermediateTensorInfo(ot),i.disposeIntermediateTensorInfo(rt),i.disposeIntermediateTensorInfo(mt),i.disposeIntermediateTensorInfo(dt),i.disposeIntermediateTensorInfo(Dt),{real:rn,imag:Ut}}function Nj(e,t,n){const s=new Float32Array(t*2);for(let i=0;i<t;i++){let o=0,a=0;for(let c=0;c<t;c++){const h=Tv(i*c,t,n),p=Aw(e,c);o+=p.real*h.real-p.imag*h.imag,a+=p.real*h.imag+p.imag*h.real}n&&(o/=t,a/=t),Iv(s,o,a,i)}return s}function Cj(e){const{inputs:t,backend:n}=e,{input:s}=t,i=M(s.shape),o=s.shape[s.shape.length-1],a=i/o,c=$i({inputs:{x:s},backend:n,attrs:{shape:[a,o]}}),h=yC(c,!1,n),p=$i({inputs:{x:h},backend:n,attrs:{shape:s.shape}});return n.disposeIntermediateTensorInfo(c),n.disposeIntermediateTensorInfo(h),p}const Rj={kernelName:Ed,backendName:"cpu",kernelFunc:Cj};function Oj(e){const{backend:t,attrs:n}=e,{shape:s,value:i,dtype:o}=n,a=o||Ea(i),c=Is(a,M(s));return Dj(c,i,a),t.makeTensorInfo(s,a,c)}const Ej={kernelName:Sy,backendName:"cpu",kernelFunc:Oj};function Dj(e,t,n){n==="string",e.fill(t)}const kj={kernelName:Dd,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{image:s}=e,i=n,o=bt(s.dtype,M(s.shape)),[a,c,h,p]=s.shape,m=i.data.get(s.dataId).values;for(let b=0;b<a;b++){const w=b*h*c*p;for(let L=0;L<c;L++){const T=L*(h*p);for(let v=0;v<h;v++){const C=v*p;for(let O=0;O<p;O++){const D=[a,L,v,O],k=D[2],F=Math.round(h-k),B=w+T+C+O;let $=m[B];if(F>=0&&F<h){const Y=F*p,j=w+T+Y+O;$=m[j]}o[B]=$}}}}const y=i.write(o,s.shape,s.dtype);return{dataId:y,shape:s.shape,dtype:s.dtype}}};function Fj(e){const{inputs:t,backend:n,attrs:s}=e,{x:i,filter:o,bias:a,preluActivationWeights:c}=t,{strides:h,pad:p,dataFormat:m,dilations:y,dimRoundingMode:b,activation:w}=s;let L=fC({inputs:{x:i,filter:o},backend:n,attrs:{strides:h,pad:p,dataFormat:m,dilations:y,dimRoundingMode:b}});if(a){const T=L;L=Su({inputs:{a:L,b:a},backend:n}),n.disposeIntermediateTensorInfo(T)}if(w){const T=L;L=OS(n,L,w,c),n.disposeIntermediateTensorInfo(T)}return L}const _j={kernelName:Xd,backendName:"cpu",kernelFunc:Fj};function Wj(e){const{inputs:t,backend:n,attrs:s}=e,{x:i,filter:o,bias:a,preluActivationWeights:c}=t,{strides:h,pad:p,dataFormat:m,dilations:y,dimRoundingMode:b,activation:w}=s;let L=gC({inputs:{x:i,filter:o},backend:n,attrs:{strides:h,pad:p,dataFormat:m,dilations:y,dimRoundingMode:b}});if(a){const T=L;L=Su({inputs:{a:L,b:a},backend:n}),n.disposeIntermediateTensorInfo(T)}if(w){const T=L;L=OS(n,L,w,c),n.disposeIntermediateTensorInfo(T)}return L}const $j={kernelName:Jd,backendName:"cpu",kernelFunc:Wj};function Uj(e){const{inputs:t,backend:n}=e,{input:s}=t,i=M(s.shape),o=s.shape[s.shape.length-1],a=i/o,c=$i({inputs:{x:s},backend:n,attrs:{shape:[a,o]}}),h=yC(c,!0,n),p=$i({inputs:{x:h},backend:n,attrs:{shape:s.shape}});return n.disposeIntermediateTensorInfo(c),n.disposeIntermediateTensorInfo(h),p}const Bj={kernelName:kd,backendName:"cpu",kernelFunc:Uj};const Mj=xt(Ul,e=>Number.isFinite(e)?1:0,"bool"),Pj={kernelName:Ul,backendName:"cpu",kernelFunc:Mj};const zj=xt(Bl,e=>Math.abs(e)===Infinity?1:0,"bool"),Vj={kernelName:Bl,backendName:"cpu",kernelFunc:zj};const Gj=xt(Ml,e=>Number.isNaN(e)?1:0,"bool"),Yj={kernelName:Ml,backendName:"cpu",kernelFunc:Gj};const Hj=xt(zl,e=>Math.log1p(e)),qj={kernelName:zl,backendName:"cpu",kernelFunc:Hj};const jj=xt(_d,e=>e?0:1,"bool"),Kj={kernelName:_d,backendName:"cpu",kernelFunc:jj};const Xj={kernelName:Vl,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:s}=e,{reductionIndices:i,keepDims:o}=t,a=n;let c=s.shape;const h=c.length,p=je(i,c);let m=p;const y=Qn(m,h);let b=a.data.get(s.dataId).values;if(y!=null){const D=new Array(h);for(let k=0;k<D.length;k++)D[k]=c[y[k]];b=RS(b,c,s.dtype,y,D),m=hs(m.length,h),c=D}Te(s,"max"),Zn("max",m,h);const[w,L]=vn(c,m),T=M(L),v=Q0(b,T,w,s.dtype),C=a.write(v,w,s.dtype);let O=w;if(o){const D=Nn(w,p);O=D}return{dataId:C,shape:O,dtype:s.dtype}}};function Jj(e){const{inputs:t,backend:n,attrs:s}=e,{x:i}=t;Te(i,"maxPool");const{filterSize:o,strides:a,pad:c,dimRoundingMode:h}=s,p=1;A(cn(a,p),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${p}'`);const m=Mn(i.shape,o,a,p,c,h);let y;if(m.filterWidth===1&&m.filterHeight===1&&ie(m.inShape,m.outShape))y=ta({inputs:{x:i},backend:n});else{const b=n.data.get(i.dataId).values,w=Ke(i.shape),L=ES(b,i.shape,i.dtype,w,m,"max");y=n.makeTensorInfo(m.outShape,i.dtype,L.values)}return y}const Zj={kernelName:Gl,backendName:"cpu",kernelFunc:Jj};function Qj(e){const{inputs:t,backend:n,attrs:s}=e,{dy:i,input:o,output:a}=t,c=o;Te([o,a],"maxPoolBackprop");const{filterSize:h,strides:p,pad:m,dimRoundingMode:y}=s,b=Mn(c.shape,h,p,1,m,y),w=n.data.get(c.dataId).values,L=wt(b.outShape,c.dtype,mC(w,c.shape,c.dtype,b).values),T=b.strideHeight,v=b.strideWidth,C=b.dilationHeight,O=b.dilationWidth,D=b.effectiveFilterHeight,k=b.effectiveFilterWidth,F=k-1-b.padInfo.left,B=D-1-b.padInfo.top,$=wt(c.shape,"float32"),Y=n.data.get(i.dataId).values,j=wt(i.shape,"float32",Y);for(let Z=0;Z<b.batchSize;++Z)for(let re=0;re<b.inChannels;++re)for(let de=0;de<b.inHeight;++de)for(let he=0;he<b.inWidth;++he){const ue=de-B,me=he-F;let ce=0;for(let ye=0;ye<D;ye+=C){const pe=(ue+ye)/T;if(pe<0||pe>=b.outHeight||Math.floor(pe)!==pe)continue;for(let Le=0;Le<k;Le+=O){const Se=(me+Le)/v;if(Se<0||Se>=b.outWidth||Math.floor(Se)!==Se)continue;const xe=D*k-1-L.get(Z,pe,Se,re),Oe=ye*k+Le,Ne=xe===Oe?1:0;if(Ne===0)continue;const De=j.get(Z,pe,Se,re);ce+=De*Ne}}$.set(ce,Z,de,he,re)}return n.makeTensorInfo($.shape,$.dtype,$.values)}const eK={kernelName:Wd,backendName:"cpu",kernelFunc:Qj};function tK(e,t,n,s,i){const o=Ke(t),a=ES(e,t,n,o,i,"max"),c=mC(e,t,n,i,!0,s);return[a.values,c.values]}const nK={kernelName:$d,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:s}=e,{filterSize:i,strides:o,pad:a,includeBatchInIndex:c}=t,h=n;Te(s,"MaxPoolWithArgmax");const p=h.data.get(s.dataId).values,m=Mn(s.shape,i,o,[1,1],a),[y,b]=tK(p,s.shape,s.dtype,c,m),w=h.write(y,m.outShape,s.dtype),L=h.write(b,m.outShape,s.dtype);return[{dataId:w,shape:m.outShape,dtype:s.dtype},{dataId:L,shape:m.outShape,dtype:"int32"}]}};function sK(e){const{inputs:t,backend:n,attrs:s}=e,{x:i}=t,{paddings:o,mode:a}=s;Te(i,"mirrorPad");const c=o.map((D,k)=>D[0]+i.shape[k]+D[1]),h=o.map(D=>D[0]),p=o.map((D,k)=>D[0]+i.shape[k]),m=a==="reflect"?0:1,y=n.data.get(i.dataId).values,b=i.shape.length,w=Ke(i.shape),L=M(c),T=c.length,v=Ke(c),C=bt(i.dtype,L);for(let D=0;D<L;D++){let k=Co(D,T,v);for(let B=0;B<T;B++)k[B]<h[B]?k[B]=h[B]*2-k[B]-m:k[B]>=p[B]&&(k[B]=(p[B]-1)*2-k[B]+m);k=k.map((B,$)=>B-h[$]);const F=Us(k,b,w);C[D]=y[F]}const O=n.write(C,c,i.dtype);return{dataId:O,shape:c,dtype:i.dtype}}const iK={kernelName:Yl,backendName:"cpu",kernelFunc:sK};const rK=Jp,oK={kernelName:Ud,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{boxes:s,scores:i}=e,{maxOutputSize:o,iouThreshold:a,scoreThreshold:c,padToMaxOutputSize:h}=n,p=t;Te(s,"NonMaxSuppressionPadded");const m=p.data.get(s.dataId).values,y=p.data.get(i.dataId).values,{selectedIndices:b,validOutputs:w}=rK(m,y,o,a,c,h);return[b,w]}};const aK=Zp,cK={kernelName:Bd,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{boxes:s,scores:i}=e,{maxOutputSize:o,iouThreshold:a,scoreThreshold:c,softNmsSigma:h}=n,p=t;Te(s,"NonMaxSuppressionWithScore");const m=p.data.get(s.dataId).values,y=p.data.get(i.dataId).values,b=o,w=a,L=c,T=h,{selectedIndices:v,selectedScores:C}=aK(m,y,b,w,L,T);return[v,C]}};function lK(e){const{inputs:t,backend:n,attrs:s}=e,{x:i}=t,{paddings:o,constantValue:a}=s;Te(i,"pad");const c=o.map((O,D)=>O[0]+i.shape[D]+O[1]),h=o.map(O=>O[0]),p=n.data.get(i.dataId).values,m=M(i.shape),y=i.shape.length,b=Ke(i.shape),w=M(c),L=c.length,T=Ke(c),v=bt(i.dtype,w);a!==0&&v.fill(a);for(let O=0;O<m;O++){const D=Co(O,y,b),k=D.map((B,$)=>B+h[$]),F=Us(k,L,T);v[F]=p[O]}const C=n.write(v,c,i.dtype);return{dataId:C,shape:c,dtype:i.dtype}}const bC={kernelName:Md,backendName:"cpu",kernelFunc:lK};const hK=xt(ql,e=>1/e),uK={kernelName:ql,backendName:"cpu",kernelFunc:hK};const dK={kernelName:jd,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{image:s}=e,{radians:i,fillValue:o,center:a}=t,c=n,h=bt(s.dtype,M(s.shape)),[p,m,y,b]=s.shape,[w,L]=gw(a,m,y),T=255,v=Math.sin(i),C=Math.cos(i),O=c.data.get(s.dataId).values;for(let k=0;k<p;k++){const F=k*y*m*b;for(let B=0;B<m;B++){const $=B*(y*b);for(let Y=0;Y<y;Y++){const j=Y*b;for(let Z=0;Z<b;Z++){const re=[p,B,Y,Z],de=re[2],he=re[1];let ue=(de-w)*C-(he-L)*v,me=(de-w)*v+(he-L)*C;ue=Math.round(ue+w),me=Math.round(me+L);let ce=o;if(typeof o!="number"&&(Z===3?ce=T:ce=o[Z]),ue>=0&&ue<y&&me>=0&&me<m){const pe=me*(y*b),Le=ue*b,Se=F+pe+Le+Z;ce=O[Se]}const ye=F+$+j+Z;h[ye]=ce}}}}const D=c.write(h,s.shape,s.dtype);return{dataId:D,shape:s.shape,dtype:s.dtype}}};const pK=xt(Jl,e=>{const t=Math.floor(e);return e-t<.5?Math.floor(e):e-t>.5?Math.ceil(e):t%2===0?t:t+1}),mK={kernelName:Jl,backendName:"cpu",kernelFunc:pK};const fK=em,gK=tm,yK=xt(Ql,e=>e>=0?gK*e:fK*(Math.exp(e)-1)),bK={kernelName:Ql,backendName:"cpu",kernelFunc:yK};const wK=xt(nh,e=>1/(1+Math.exp(-e))),LK={kernelName:nh,backendName:"cpu",kernelFunc:wK};const SK=xt(th,e=>e<0?-1:e>0?1:0),IK={kernelName:th,backendName:"cpu",kernelFunc:SK};const xK=xt($a,e=>Math.sin(e)),TK={kernelName:$a,backendName:"cpu",kernelFunc:xK};const AK=xt(eh,e=>Math.sinh(e)),vK={kernelName:eh,backendName:"cpu",kernelFunc:AK};const NK=11920928955078125e-23,wC=Math.log(NK)+2,CK=xt(sh,e=>{const t=e>-wC,n=e<wC,s=Math.exp(e);let i;return n?i=s:t?i=e:i=Math.log(1+s),i}),RK={kernelName:sh,backendName:"cpu",kernelFunc:CK};function LC(e){const{inputs:t,attrs:n,backend:s}=e,{x:i}=t,{perm:o}=n;Te(i,"transpose");const a=i.shape.length,c=new Array(a);for(let y=0;y<c.length;y++)c[y]=i.shape[o[y]];const h=s.data.get(i.dataId).values,p=RS(h,i.shape,i.dtype,o,c),m=s.write(p,c,i.dtype);return{dataId:m,shape:c,dtype:i.dtype}}const OK={kernelName:oh,backendName:"cpu",kernelFunc:LC};function EK(e){const{inputs:t,backend:n,attrs:s}=e,{x:i}=t,{blockShape:o,paddings:a}=s;Te([i],"spaceToBatchND");const c=M(o),h=[[0,0]];h.push(...a);for(let B=1+o.length;B<i.shape.length;++B)h.push([0,0]);const p=bC.kernelFunc({inputs:{x:i},backend:n,attrs:{paddings:h,constantValue:0}}),m=Gh(p.shape,o,c,!1),y=Yh(m.length,o.length,!1),b=Hh(p.shape,o,c,!1),w={x:p},L={shape:m},T=$i({inputs:w,backend:n,attrs:L}),v={x:T},C={perm:y},O=LC({inputs:v,backend:n,attrs:C}),D={x:O},k={shape:b},F=$i({inputs:D,backend:n,attrs:k});return n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(T),n.disposeIntermediateTensorInfo(O),F}const DK={kernelName:Gd,backendName:"cpu",kernelFunc:EK};const kK=xt(ih,e=>Math.sqrt(e)),FK={kernelName:ih,backendName:"cpu",kernelFunc:kK};const _K={kernelName:Yd,backendName:"cpu",kernelFunc:({inputs:e,backend:t})=>{const{x:n}=e,s=t;Te(n,"square");const i=s.data.get(n.dataId).values,o=new Float32Array(i.length);for(let c=0;c<i.length;++c){const h=i[c];o[c]=h*h}const a=s.write(o,n.shape,n.dtype);return{dataId:a,shape:n.shape,dtype:n.dtype}}};const WK=xt(ah,(e,t)=>{const n=t;return isNaN(e)?NaN:e>0?1:n.alpha}),$K={kernelName:ah,backendName:"cpu",kernelFunc:WK};const UK=xt(Ma,e=>Math.tan(e)),BK={kernelName:Ma,backendName:"cpu",kernelFunc:UK};const MK=xt(rh,e=>Math.tanh(e)),PK={kernelName:rh,backendName:"cpu",kernelFunc:MK};function zK(e){const{inputs:t,attrs:n,backend:s}=e,{axis:i}=n,{x:o}=t;Te(o,"unique");const a=s.data.get(o.dataId).values,{outputValues:c,outputShape:h,indices:p}=cC(a,i,o.shape,o.dtype);return[s.makeTensorInfo(h,o.dtype,c),s.makeTensorInfo([p.length],"int32",p)]}const VK={kernelName:Hd,backendName:"cpu",kernelFunc:zK};const GK=[x4,Bq,A4,N4,Yq,R4,E4,k4,_4,$4,B4,S4,P4,Vq,qq,V4,Mq,Y4,j4,X4,H4,ej,nj,Z4,ij,oj,aj,lj,uj,dj,mj,pj,DS,f4,Tj,Kq,Jq,Rj,Ej,kj,Qq,_j,$j,Pq,Bj,G4,Pj,Vj,Yj,t4,qj,Kj,Zj,eK,nK,Xj,iK,s4,oK,cK,r4,bC,y4,zq,uK,b4,w4,L4,dK,mK,a4,bK,LK,IK,TK,vK,c4,RK,DK,FK,_K,h4,$K,d4,BK,PK,OK,VK];for(const e of GK)Qd(e);const ao={},FS={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function zne(e){delete ao[e]}function YK(e,t){ao[e]=t}function Ui(e){if(!(e in ao)){const n=qK(e);if(n!==null)ao[e]=n;else return console.log("Could not get context for WebGL version",e),null}const t=ao[e];return t.isContextLost()?(delete ao[e],Ui(e)):(t.disable(t.DEPTH_TEST),t.disable(t.STENCIL_TEST),t.disable(t.BLEND),t.disable(t.DITHER),t.disable(t.POLYGON_OFFSET_FILL),t.disable(t.SAMPLE_COVERAGE),t.enable(t.SCISSOR_TEST),t.enable(t.CULL_FACE),t.cullFace(t.BACK),ao[e])}function HK(e){if(typeof OffscreenCanvas!="undefined"&&e===2)return new OffscreenCanvas(300,150);if(typeof document!="undefined")return document.createElement("canvas");throw new Error("Cannot create a canvas in this context")}function qK(e){if(e!==1&&e!==2)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");const t=HK(e);return t.addEventListener("webglcontextlost",n=>{n.preventDefault(),delete ao[e]},!1),e===1?t.getContext("webgl",FS)||t.getContext("experimental-webgl",FS):t.getContext("webgl2",FS)}var xu;(function(e){e[e.DENSE=0]="DENSE",e[e.SHARED_BATCH=1]="SHARED_BATCH"})(xu||(xu={}));var Os;(function(e){e[e.RENDER=0]="RENDER",e[e.UPLOAD=1]="UPLOAD",e[e.PIXELS=2]="PIXELS",e[e.DOWNLOAD=3]="DOWNLOAD"})(Os||(Os={}));var Rn;(function(e){e[e.UNPACKED_FLOAT16=0]="UNPACKED_FLOAT16",e[e.UNPACKED_FLOAT32=1]="UNPACKED_FLOAT32",e[e.PACKED_4X1_UNSIGNED_BYTE=2]="PACKED_4X1_UNSIGNED_BYTE",e[e.PACKED_2X2_FLOAT32=3]="PACKED_2X2_FLOAT32",e[e.PACKED_2X2_FLOAT16=4]="PACKED_2X2_FLOAT16"})(Rn||(Rn={}));function Tu(e,t){return[t,e]}function jK(e,t){return e*t}function Vne(e,t){return[t*4,e]}function Au(e){const t=M(e),n=Math.ceil(t/4);return Me(n)}function Gne(e,t){if(e%t!==0)throw new Error(`unpackedSize (${e}) must be a multiple of ${t}`);return e/t}function Yne(e,t,n){const s=e.length*n/4;if(t.length<s)throw new Error(`matrix length (${t.length}) must be >= ${s}`);let i=0;for(let o=0;o<e.length;o+=4)for(let a=0;a<n;a++)t[i++]=e[o+a]}function Ac(e,t){return[Math.max(1,Math.ceil(t/2)),Math.max(1,Math.ceil(e/2))]}function KK(e,t){const[n,s]=Ac(e,t);return n*s*4}function _S(e,t){const n=e;let s,i,o,a,c,h,p,m,y,b;return ae().getNumber("WEBGL_VERSION")===2?(s=n.R32F,i=n.R16F,o=n.RGBA16F,a=n.RGBA32F,c=n.RED,p=4,m=1,y=n.HALF_FLOAT,b=n.FLOAT):(s=e.RGBA,i=e.RGBA,o=e.RGBA,a=n.RGBA,c=e.RGBA,p=4,m=4,y=t!=null?t.HALF_FLOAT_OES:null,b=e.FLOAT),h=e.RGBA,{internalFormatFloat:s,internalFormatHalfFloat:i,internalFormatPackedHalfFloat:o,internalFormatPackedFloat:a,textureFormatFloat:c,downloadTextureFormat:h,downloadUnpackNumChannels:p,defaultNumChannels:m,textureTypeHalfFloat:y,textureTypeFloat:b}}function Ee(e,t){const n=t();return ae().getBool("DEBUG")&&XK(e),n}function XK(e){const t=e.getError();if(t!==e.NO_ERROR)throw new Error("WebGL Error: "+e5(e,t))}const JK=596e-10,ZK=65504;function QK(e){return!!(ae().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||e===0||JK<Math.abs(e)&&Math.abs(e)<ZK)}function e5(e,t){switch(t){case e.NO_ERROR:return"NO_ERROR";case e.INVALID_ENUM:return"INVALID_ENUM";case e.INVALID_VALUE:return"INVALID_VALUE";case e.INVALID_OPERATION:return"INVALID_OPERATION";case e.INVALID_FRAMEBUFFER_OPERATION:return"INVALID_FRAMEBUFFER_OPERATION";case e.OUT_OF_MEMORY:return"OUT_OF_MEMORY";case e.CONTEXT_LOST_WEBGL:return"CONTEXT_LOST_WEBGL";default:return`Unknown error code ${t}`}}function Gm(e,t){return mr(e,()=>e.getExtension(t),'Extension "'+t+'" not supported on this browser.')}function t5(e,t){const n=mr(e,()=>e.createShader(e.VERTEX_SHADER),"Unable to create vertex WebGLShader.");if(Ee(e,()=>e.shaderSource(n,t)),Ee(e,()=>e.compileShader(n)),e.getShaderParameter(n,e.COMPILE_STATUS)===!1)throw console.log(e.getShaderInfoLog(n)),new Error("Failed to compile vertex shader.");return n}function n5(e,t){const n=mr(e,()=>e.createShader(e.FRAGMENT_SHADER),"Unable to create fragment WebGLShader.");if(Ee(e,()=>e.shaderSource(n,t)),Ee(e,()=>e.compileShader(n)),e.getShaderParameter(n,e.COMPILE_STATUS)===!1)throw i5(t,e.getShaderInfoLog(n)),new Error("Failed to compile fragment shader.");return n}const s5=/ERROR: [0-9]+:([0-9]+):/g;function i5(e,t){const n=s5.exec(t);if(n==null){console.log(`Couldn't parse line number in error: ${t}`),console.log(e);return}const s=+n[1],i=e.split(`
`),o=i.length.toString().length+2,a=i.map((y,b)=>ct((b+1).toString(),o)+y);let c=0;for(let y=0;y<a.length;y++)c=Math.max(a[y].length,c);const h=a.slice(0,s-1),p=a.slice(s-1,s),m=a.slice(s);console.log(h.join(`
`)),console.log(t.split(`
`)[0]),console.log(`%c ${ct(p[0],c)}`,"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(m.join(`
`))}function r5(e){return mr(e,()=>e.createProgram(),"Unable to create WebGLProgram.")}function o5(e,t){if(Ee(e,()=>e.linkProgram(t)),e.getProgramParameter(t,e.LINK_STATUS)===!1)throw console.log(e.getProgramInfoLog(t)),new Error("Failed to link vertex and fragment shaders.")}function WS(e,t){if(Ee(e,()=>e.validateProgram(t)),e.getProgramParameter(t,e.VALIDATE_STATUS)===!1)throw console.log(e.getProgramInfoLog(t)),new Error("Shader program validation failed.")}function a5(e,t){const n=mr(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return Ee(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n)),Ee(e,()=>e.bufferData(e.ARRAY_BUFFER,t,e.STATIC_DRAW)),n}function c5(e,t){const n=mr(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return Ee(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,n)),Ee(e,()=>e.bufferData(e.ELEMENT_ARRAY_BUFFER,t,e.STATIC_DRAW)),n}function Hne(){return ae().getNumber("WEBGL_VERSION")===2?1:4}function l5(e){return mr(e,()=>e.createTexture(),"Unable to create WebGLTexture.")}function h5(e,t){const n=ae().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(e<=0||t<=0){const s=`[${e}x${t}]`;throw new Error("Requested texture size "+s+" is invalid.")}if(e>n||t>n){const s=`[${e}x${t}]`,i=`[${n}x${n}]`;throw new Error("Requested texture size "+s+" greater than WebGL maximum on this browser / GPU "+i+".")}}function u5(e){return mr(e,()=>e.createFramebuffer(),"Unable to create WebGLFramebuffer.")}function SC(e,t,n,s,i,o,a){const c=e.getAttribLocation(t,n);return c===-1?!1:(Ee(e,()=>e.bindBuffer(e.ARRAY_BUFFER,s)),Ee(e,()=>e.vertexAttribPointer(c,i,e.FLOAT,!1,o,a)),Ee(e,()=>e.enableVertexAttribArray(c)),!0)}function d5(e,t,n){xC(e,n),Ee(e,()=>e.activeTexture(e.TEXTURE0+n)),Ee(e,()=>e.bindTexture(e.TEXTURE_2D,t))}function qne(e,t){xC(e,t),Ee(e,()=>e.activeTexture(e.TEXTURE0+t)),Ee(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function p5(e,t,n){return mr(e,()=>e.getUniformLocation(t,n),'uniform "'+n+'" not present in program.')}function m5(e,t,n){return e.getUniformLocation(t,n)}function f5(e,t,n,s){Ee(e,()=>d5(e,t,s)),Ee(e,()=>e.uniform1i(n,s))}function jne(e){Ee(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,null)),Ee(e,()=>e.viewport(0,0,e.canvas.width,e.canvas.height)),Ee(e,()=>e.scissor(0,0,e.canvas.width,e.canvas.height))}function $S(e,t,n){Ee(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,n)),Ee(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0))}function IC(e,t){Ee(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,t)),Ee(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0))}function Ym(e){const t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+g5(e,t))}function g5(e,t){switch(t){case e.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case e.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case e.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return"FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case e.FRAMEBUFFER_UNSUPPORTED:return"FRAMEBUFFER_UNSUPPORTED";default:return`unknown error ${t}`}}function mr(e,t,n){const s=Ee(e,()=>t());if(s==null)throw new Error(n);return s}function xC(e,t){const n=e.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,s=t+e.TEXTURE0;if(s<e.TEXTURE0||s>n){const i=`[gl.TEXTURE0, gl.TEXTURE${n}]`;throw new Error(`textureUnit must be in ${i}.`)}}function vc(e,t=2){return M(e.slice(0,e.length-t))}function Nc(e){if(e.length===0)throw Error("Cannot get rows and columns of an empty shape array.");return[e.length>1?e[e.length-2]:1,e[e.length-1]]}function US(e){let t=[1,1,1];const n=e.length===0||e.length===1&&e[0]===1;return n||(t=[vc(e),...Nc(e)]),t}function y5(e,t=!1){let n=ae().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(t&&(n=n*2,e=e.map((i,o)=>o>=e.length-2?x(e[o]):e[o]),e.length===1&&(e=[2,e[0]])),e.length!==2){const i=hn(e);e=i.newShape}let s=M(e);if(e.length<=1&&s<=n)return[1,s];if(e.length===2&&e[0]<=n&&e[1]<=n)return e;if(e.length===3&&e[0]*e[1]<=n&&e[2]<=n)return[e[0]*e[1],e[2]];if(e.length===3&&e[0]<=n&&e[1]*e[2]<=n)return[e[0],e[1]*e[2]];if(e.length===4&&e[0]*e[1]*e[2]<=n&&e[3]<=n)return[e[0]*e[1]*e[2],e[3]];if(e.length===4&&e[0]<=n&&e[1]*e[2]*e[3]<=n)return[e[0],e[1]*e[2]*e[3]];if(t){const i=vc(e);let o=2,a=2;return e.length&&([o,a]=Nc(e)),s=i*(o/2)*(a/2),Me(s).map(c=>c*2)}return Me(s)}function Hm(e){return e%2===0}function qm(e,t){if(e=e.slice(-2),t=t.slice(-2),ie(e,t))return!0;if(!e.length||!t.length)return!0;if(e[0]===0||e[1]===0||t[0]===0||t[1]===0)return!0;if(e.length!==t.length){const n=e.slice(-1)[0],s=t.slice(-1)[0];if(n===s)return!0;if(Hm(n)&&Hm(s)&&(e[0]===1||t[0]===1))return!0}return e[1]===t[1]&&Hm(e[0])&&Hm(t[0])}let jm,Km;function b5(e){if(jm==null){const t=Ui(e);jm=t.getParameter(t.MAX_TEXTURE_SIZE)}return jm}function Kne(){jm=null}function Xne(){Km=null}function w5(e){if(Km==null){const t=Ui(e);Km=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,Km)}function L5(e){if(e===0)return 0;let t;const n=Ui(e);return Hs(n,"EXT_disjoint_timer_query_webgl2")&&e===2?t=2:Hs(n,"EXT_disjoint_timer_query")?t=1:t=0,t}function Hs(e,t){const n=e.getExtension(t);return n!=null}function TC(e){try{const t=Ui(e);if(t!=null)return!0}catch(t){return console.log("Error when getting WebGL context: ",t),!1}return!1}function S5(e){if(e===0)return!1;const t=Ui(e);if(e===1){if(!Hs(t,"OES_texture_float"))return!1}else if(!Hs(t,"EXT_color_buffer_float"))return!1;const n=BS(t);return n}function I5(e){if(e===0)return!1;const t=Ui(e);if(e===1){if(!Hs(t,"OES_texture_float"))return!1;if(!Hs(t,"WEBGL_color_buffer_float"))return!1}else{if(Hs(t,"EXT_color_buffer_float"))return BS(t);const s="EXT_color_buffer_half_float";if(Hs(t,s)){const i=t.getExtension(s);return x5(t,i)}return!1}const n=BS(t);return n}function BS(e){const t=_S(e),n=e.createTexture();e.bindTexture(e.TEXTURE_2D,n);const s=1,i=1;e.texImage2D(e.TEXTURE_2D,0,t.internalFormatFloat,s,i,0,t.textureFormatFloat,t.textureTypeFloat,null);const o=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,o),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,n,0);const a=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(n),e.deleteFramebuffer(o),a}function x5(e,t){const n=_S(e,t),s=e.createTexture();e.bindTexture(e.TEXTURE_2D,s);const i=1,o=1;e.texImage2D(e.TEXTURE_2D,0,n.internalFormatHalfFloat,i,o,0,n.textureFormatFloat,n.textureTypeHalfFloat,null);const a=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,a),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,s,0);const c=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(s),e.deleteFramebuffer(a),c}function T5(e){if(e!==2)return!1;const t=Ui(e),n=t.fenceSync!=null;return n}function vu(e,t){Array.isArray(e)||(e=[e]),e.forEach(n=>{n!=null&&A(n.dtype!=="complex64",()=>`${t} does not support complex64 tensors in the WebGL backend.`)})}const Ge=ae();Ge.registerFlag("HAS_WEBGL",()=>Ge.getNumber("WEBGL_VERSION")>0),Ge.registerFlag("WEBGL_VERSION",()=>TC(2)?2:TC(1)?1:0),Ge.registerFlag("WEBGL_CHECK_NUMERICAL_PROBLEMS",()=>!1),Ge.registerFlag("WEBGL_BUFFER_SUPPORTED",()=>Ge.get("WEBGL_VERSION")===2),Ge.registerFlag("WEBGL_CPU_FORWARD",()=>!0),Ge.registerFlag("WEBGL_FORCE_F16_TEXTURES",()=>!1),Ge.registerFlag("WEBGL_PACK",()=>Ge.getBool("HAS_WEBGL")),Ge.registerFlag("WEBGL_PACK_NORMALIZATION",()=>Ge.getBool("WEBGL_PACK")),Ge.registerFlag("WEBGL_PACK_CLIP",()=>Ge.getBool("WEBGL_PACK")),Ge.registerFlag("WEBGL_PACK_DEPTHWISECONV",()=>!1),Ge.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",()=>Ge.getBool("WEBGL_PACK")),Ge.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",()=>Ge.getBool("WEBGL_PACK")),Ge.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",()=>Ge.getBool("WEBGL_PACK")),Ge.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",()=>Ge.getBool("WEBGL_PACK")),Ge.registerFlag("WEBGL_PACK_REDUCE",()=>Ge.getBool("WEBGL_PACK")),Ge.registerFlag("WEBGL_LAZILY_UNPACK",()=>Ge.getBool("WEBGL_PACK")),Ge.registerFlag("WEBGL_CONV_IM2COL",()=>Ge.getBool("WEBGL_PACK")),Ge.registerFlag("WEBGL_MAX_TEXTURE_SIZE",()=>b5(Ge.getNumber("WEBGL_VERSION"))),Ge.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",()=>w5(Ge.getNumber("WEBGL_VERSION"))),Ge.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",()=>{const e=Ge.getNumber("WEBGL_VERSION");return e===0?0:L5(e)}),Ge.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",()=>Ge.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!UT()),Ge.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",()=>S5(Ge.getNumber("WEBGL_VERSION"))),Ge.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",()=>Ge.getBool("WEBGL_FORCE_F16_TEXTURES")?!1:Ge.getBool("WEBGL_RENDER_FLOAT32_CAPABLE")),Ge.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",()=>I5(Ge.getNumber("WEBGL_VERSION"))),Ge.registerFlag("WEBGL_FENCE_API_ENABLED",()=>T5(Ge.getNumber("WEBGL_VERSION"))),Ge.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",()=>{const e=Ge.getBool("WEBGL_RENDER_FLOAT32_ENABLED");return e?4:0}),Ge.registerFlag("WEBGL_DELETE_TEXTURE_THRESHOLD",()=>-1,e=>{if(e<0&&e!==-1)throw new Error(`WEBGL_DELETE_TEXTURE_THRESHOLD must be -1 (indicating never delete) or at least 0, but got ${e}.`)});const{simpleAbsImpl:A5,addImpl:v5,ceilImpl:N5,expImpl:C5,expm1Impl:R5,floorImpl:O5,logImpl:E5,maxImpl:D5,multiplyImpl:k5,rsqrtImpl:F5,sliceImpl:_5,subImpl:W5,transposeImpl:MS,uniqueImpl:$5}=p4;class U5{constructor(e,t){this.outputShape=[],this.outputShape=e,this.variableNames=t.map((i,o)=>`T${o}`);const n=[];this.variableNames.forEach(i=>{n.push(`float v${i} = get${i}AtOutCoords();`)});const s=this.variableNames.map(i=>`v${i}`).join(" + ");this.userCode=`
void main() {
${n.join(`
`)}
float result = ${s};
setOutput(result);
}
`}}class B5{constructor(e,t){this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.variableNames=t.map((i,o)=>`T${o}`);const n=[];this.variableNames.forEach(i=>{n.push(`vec4 v${i} = get${i}AtOutCoords();`)});const s=this.variableNames.map(i=>`v${i}`).join(" + ");this.userCode=`
void main() {
${n.join(`
`)}
vec4 result = ${s};
setOutput(result);
}
`}}class M5{constructor(e,t,n){this.variableNames=["A"];const{windowSize:s,batchSize:i,outSize:o}=e;n||this.variableNames.push("bestIndicesA"),this.outputShape=[i,o];const a=t==="max"?">":"<",c=n?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode=`
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
int inOffset = outIdx * ${s};
int bestIndex = inOffset;
float bestValue = getA(batch, bestIndex);
for (int i = 0; i < ${s}; i++) {
int inIdx = ${c};
float candidate = getA(batch, inIdx);
if (candidate ${a} bestValue) {
bestValue = candidate;
bestIndex = inIdx;
}
}
setOutput(float(bestIndex));
}
`}}function AC(e,t){return["x","y","z","w","u","v"].slice(0,t).map(n=>`${e}.${n}`)}function zn(e,t){return t===1?[e]:AC(e,t)}function P5(e,t){if(e===1)return"rc";let n="";for(let s=0;s<e;s++)n+=t[s],s<e-1&&(n+=",");return n}function Vn(){let e,t,n,s,i,o,a,c,h,p;return ae().getNumber("WEBGL_VERSION")===2?(e="#version 300 es",t="in",n="out",s="in",i="texture",o="outputColor",a="out vec4 outputColor;",c=`
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)
`,h="",p=`
#define round(value) newRound(value)
int newRound(float value) {
return int(floor(value + 0.5));
}
ivec4 newRound(vec4 value) {
return ivec4(floor(value + vec4(0.5)));
}
`):(e="",t="attribute",n="varying",s="varying",i="texture2D",o="gl_FragColor",a="",c=`
#define isnan(value) isnan_custom(value)
bool isnan_custom(float val) {
return (val > 0. || val < 1. || val == 0.) ? false : true;
}
bvec4 isnan_custom(vec4 val) {
return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w));
}
`,h=`
uniform float INFINITY;
bool isinf(float val) {
return abs(val) == INFINITY;
}
bvec4 isinf(vec4 val) {
return equal(abs(val), vec4(INFINITY));
}
`,p=`
int round(float value) {
return int(floor(value + 0.5));
}
ivec4 round(vec4 value) {
return ivec4(floor(value + vec4(0.5)));
}
`),{version:e,attribute:t,varyingVs:n,varyingFs:s,texture2D:i,output:o,defineOutput:a,defineSpecialNaN:c,defineSpecialInf:h,defineRound:p}}function na(e,t,n="index"){const s=Ke(t);return s.map((i,o)=>{const a=`int ${e[o]} = ${n} / ${i}`,c=o===s.length-1?`int ${e[o+1]} = ${n} - ${e[o]} * ${i}`:`index -= ${e[o]} * ${i}`;return`${a}; ${c};`}).join("")}function Xm(e){return e.length===1?`${e[0]}`:`vec${e.length}(${e.join(",")})`}function Jne(e,t){if(e.length!==t.length)throw new Error(`Vectors to be dotted must be of the same length -got ${e.length} and ${t.length}`);const n=[],s=Math.floor(e.length/4),i=e.length%4;for(let o=0;o<s;o++){const a=e.slice(o*4,o*4+4),c=t.slice(o*4,o*4+4);n.push(`${Xm(a)}, ${Xm(c)}`)}if(i!==0){let o=e.slice(s*4),a=t.slice(s*4);o.length===1&&(o=o.map(c=>`float(${c})`),a=a.map(c=>`float(${c})`)),n.push(`${Xm(o)}, ${Xm(a)}`)}return n.map((o,a)=>`dot(${o})`).join("+")}function PS(e){const t=Ke(e).map(n=>n.toString());return`
int getFlatIndex(ivec3 coords) {
return coords.x * ${t[0]} + coords.y * ${t[1]} + coords.z;
}
`}const vC=`
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:NC}=Nw;function z5(e,t,n,s){const i=[];e.forEach(L=>{const T=M(L.shapeInfo.logicalShape);L.shapeInfo.isUniform?i.push(`uniform float ${L.name}${T>1?`[${T}]`:""};`):(i.push(`uniform sampler2D ${L.name};`),i.push(`uniform int offset${L.name};`))});const o=i.join(`
`),a=e.map(L=>V5(L,t,s)).join(`
`),c=t.texShape,h=Vn(),p=H5(h);let m,y,b=K5(h);t.isPacked?(m=G5(t.logicalShape,c),y=j5(h)):(m=Y5(t.logicalShape,c),y=q5(h)),s&&(b+=Q5);const w=[b,p,y,o,m,a,n].join(`
`);return w}function Cc(e){const t=e.shapeInfo.logicalShape;switch(t.length){case 0:return u8(e);case 1:return p8(e);case 2:return f8(e);case 3:return y8(e);case 4:return w8(e);case 5:return L8(e);case 6:return S8(e);default:throw new Error(`${t.length}-D input sampling is not yet supported`)}}function CC(e){const t=e.shapeInfo.logicalShape;switch(t.length){case 0:return h8(e);case 1:return d8(e);case 2:return m8(e);case 3:return g8(e);default:return b8(e)}}function V5(e,t,n=!1){let s="";n?s+=CC(e):s+=Cc(e);const i=e.shapeInfo.logicalShape,o=t.logicalShape;return i.length<=o.length&&(n?s+=I8(e,t):s+=x8(e,t)),s}function G5(e,t){switch(e.length){case 0:return RC();case 1:return e8(e,t);case 2:return c8(e,t);case 3:return n8(e,t);default:return i8(e,t)}}function Y5(e,t){switch(e.length){case 0:return RC();case 1:return t8(e,t);case 2:return l8(e,t);case 3:return s8(e,t);case 4:return r8(e,t);case 5:return o8(e,t);case 6:return a8(e,t);default:throw new Error(`${e.length}-D output sampling is not yet supported`)}}function H5(e){return`
float sampleTexture(sampler2D textureSampler, vec2 uv) {
return ${e.texture2D}(textureSampler, uv).r;
}
`}function q5(e){return`
void setOutput(float val) {
${e.output} = vec4(val, 0, 0, 0);
}
`}function j5(e){return`
void setOutput(vec4 val) {
${e.output} = val;
}
`}function K5(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);
}
${X5}
${J5}
${Z5}
`;return t}const X5=`
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);
}
`,J5=`
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);
}
`,Z5=`
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);
}
`,Q5=`
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 RC(){return`
int getOutputCoords() {
return 0;
}
`}function e8(e,t){const n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];return n[0]===1?`
int getOutputCoords() {
return 2 * int(resultUV.x * ${n[1]}.0);
}
`:n[1]===1?`
int getOutputCoords() {
return 2 * int(resultUV.y * ${n[0]}.0);
}
`:`
int getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${n[0]}, ${n[1]}));
return 2 * (resTexRC.x * ${n[1]} + resTexRC.y);
}
`}function t8(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 n8(e,t){const n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],s=Math.ceil(e[2]/2),i=s*Math.ceil(e[1]/2);return`
ivec3 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${n[0]}, ${n[1]}));
int index = resTexRC.x * ${n[1]} + resTexRC.y;
int b = index / ${i};
index -= b * ${i};
int r = 2 * (index / ${s});
int c = imod(index, ${s}) * 2;
return ivec3(b, r, c);
}
`}function s8(e,t){const n=na(["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;
${n}
return ivec3(r, c, d);
}
`}function i8(e,t){const n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],s=Math.ceil(e[e.length-1]/2),i=s*Math.ceil(e[e.length-2]/2);let o=i,a="",c="b, r, c";for(let h=2;h<e.length-1;h++)o*=e[e.length-h-1],a=`
int b${h} = index / ${o};
index -= b${h} * ${o};
`+a,c=`b${h}, `+c;return`
ivec${e.length} getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${n[0]}, ${n[1]}));
int index = resTexRC.x * ${n[1]} + resTexRC.y;
${a}
int b = index / ${i};
index -= b * ${i};
int r = 2 * (index / ${s});
int c = imod(index, ${s}) * 2;
return ivec${e.length}(${c});
}
`}function r8(e,t){const n=na(["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;
${n}
return ivec4(r, c, d, d2);
}
`}function o8(e,t){const n=na(["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;
${n}
ivec5 outShape = ivec5(r, c, d, d2, d3);
return outShape;
}
`}function a8(e,t){const n=na(["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;
${n}
ivec6 result = ivec6(r, c, d, d2, d3, d4);
return result;
}
`}function c8(e,t){const n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(ie(e,t))return`
ivec2 getOutputCoords() {
return 2 * ivec2(resultUV.yx * vec2(${n[0]}, ${n[1]}));
}
`;const s=Math.ceil(e[1]/2);return`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${n[0]}, ${n[1]}));
int index = resTexRC.x * ${n[1]} + resTexRC.y;
int r = 2 * (index / ${s});
int c = imod(index, ${s}) * 2;
return ivec2(r, c);
}
`}function l8(e,t){return ie(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 sa(e){return`offset${e}`}function h8(e){const t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1),s=Vn();return`
vec4 ${n}() {
return ${s.texture2D}(${t}, halfCR);
}
`}function u8(e){const t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1);if(e.shapeInfo.isUniform)return`float ${n}() {return ${t};}`;const[s,i]=e.shapeInfo.texShape;if(s===1&&i===1)return`
float ${n}() {
return sampleTexture(${t}, halfCR);
}
`;const[o,a]=e.shapeInfo.texShape,c=sa(t);return`
float ${n}() {
vec2 uv = uvFromFlat(${o}, ${a}, ${c});
return sampleTexture(${t}, uv);
}
`}function d8(e){const t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1),s=e.shapeInfo.texShape,i=[Math.ceil(s[0]/2),Math.ceil(s[1]/2)],o=Vn();return`
vec4 ${n}(int index) {
vec2 uv = packedUVfrom1D(
${i[0]}, ${i[1]}, index);
return ${o.texture2D}(${t}, uv);
}
`}function p8(e){const t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1);if(e.shapeInfo.isUniform)return`
float ${n}(int index) {
${Rc(e)}
}
`;const s=e.shapeInfo.texShape,i=s[0],o=s[1];if(o===1&&i===1)return`
float ${n}(int index) {
return sampleTexture(${t}, halfCR);
}
`;const a=sa(t);return o===1?`
float ${n}(int index) {
vec2 uv = vec2(0.5, (float(index + ${a}) + 0.5) / ${i}.0);
return sampleTexture(${t}, uv);
}
`:i===1?`
float ${n}(int index) {
vec2 uv = vec2((float(index + ${a}) + 0.5) / ${o}.0, 0.5);
return sampleTexture(${t}, uv);
}
`:`
float ${n}(int index) {
vec2 uv = uvFromFlat(${i}, ${o}, index + ${a});
return sampleTexture(${t}, uv);
}
`}function m8(e){const t=e.shapeInfo.logicalShape,n=e.name,s="get"+n.charAt(0).toUpperCase()+n.slice(1),i=e.shapeInfo.texShape,o=i[0],a=i[1],c=Vn();if(i!=null&&ie(t,i))return`
vec4 ${s}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${a}.0, ${o}.0);
return ${c.texture2D}(${n}, uv);
}
`;const h=[Math.ceil(i[0]/2),Math.ceil(i[1]/2)],p=Math.ceil(t[1]/2);return`
vec4 ${s}(int row, int col) {
vec2 uv = packedUVfrom2D(${p}, ${h[0]}, ${h[1]}, row, col);
return ${c.texture2D}(${n}, uv);
}
`}function f8(e){const t=e.shapeInfo.logicalShape,n=e.name,s="get"+n.charAt(0).toUpperCase()+n.slice(1),i=e.shapeInfo.texShape;if(i!=null&&ie(t,i)){const y=i[0],b=i[1];return`
float ${s}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${b}.0, ${y}.0);
return sampleTexture(${n}, uv);
}
`}const{newShape:o,keptDims:a}=hn(t),c=o;if(c.length<t.length){const y=Oc(e,c),b=["row","col"];return`
${Cc(y)}
float ${s}(int row, int col) {
return ${s}(${Ec(b,a)});
}
`}if(e.shapeInfo.isUniform)return`
float ${s}(int row, int col) {
int index = round(dot(vec2(row, col), vec2(${t[1]}, 1)));
${Rc(e)}
}
`;const h=i[0],p=i[1],m=sa(n);return p===1?`
float ${s}(int row, int col) {
float index = dot(vec3(row, col, ${m}), vec3(${t[1]}, 1, 1));
vec2 uv = vec2(0.5, (index + 0.5) / ${h}.0);
return sampleTexture(${n}, uv);
}
`:h===1?`
float ${s}(int row, int col) {
float index = dot(vec3(row, col, ${m}), vec3(${t[1]}, 1, 1));
vec2 uv = vec2((index + 0.5) / ${p}.0, 0.5);
return sampleTexture(${n}, uv);
}
`:`
float ${s}(int row, int col) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${t[1]} + col + ${m};
vec2 uv = uvFromFlat(${h}, ${p}, index);
return sampleTexture(${n}, uv);
}
`}function g8(e){const t=e.shapeInfo.logicalShape,n=e.name,s="get"+n.charAt(0).toUpperCase()+n.slice(1),i=e.shapeInfo.texShape,o=[Math.ceil(i[0]/2),Math.ceil(i[1]/2)];if(t[0]===1){const y=t.slice(1),b=[1,2],w=Oc(e,y),L=["b","row","col"];return`
${CC(w)}
vec4 ${s}(int b, int row, int col) {
return ${s}(${Ec(L,b)});
}
`}const a=o[0],c=o[1],h=Math.ceil(t[2]/2),p=h*Math.ceil(t[1]/2),m=Vn();return`
vec4 ${s}(int b, int row, int col) {
vec2 uv = packedUVfrom3D(
${a}, ${c}, ${p}, ${h}, b, row, col);
return ${m.texture2D}(${n}, uv);
}
`}function y8(e){const t=e.shapeInfo.logicalShape,n=e.name,s="get"+n.charAt(0).toUpperCase()+n.slice(1),i=t[1]*t[2],o=t[2],{newShape:a,keptDims:c}=hn(t),h=a;if(h.length<t.length){const L=Oc(e,h),T=["row","col","depth"];return`
${Cc(L)}
float ${s}(int row, int col, int depth) {
return ${s}(${Ec(T,c)});
}
`}if(e.shapeInfo.isUniform)return`
float ${s}(int row, int col, int depth) {
int index = round(dot(vec3(row, col, depth),
vec3(${i}, ${o}, 1)));
${Rc(e)}
}
`;const p=e.shapeInfo.texShape,m=p[0],y=p[1],b=e.shapeInfo.flatOffset;if(y===i&&b==null)return`
float ${s}(int row, int col, int depth) {
float texR = float(row);
float texC = dot(vec2(col, depth), vec2(${o}, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${y}.0, ${m}.0);
return sampleTexture(${n}, uv);
}
`;if(y===o&&b==null)return`
float ${s}(int row, int col, int depth) {
float texR = dot(vec2(row, col), vec2(${t[1]}, 1));
float texC = float(depth);
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${y}.0, ${m}.0);
return sampleTexture(${n}, uv);
}
`;const w=sa(n);return`
float ${s}(int row, int col, int depth) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${i} + col * ${o} + depth + ${w};
vec2 uv = uvFromFlat(${m}, ${y}, index);
return sampleTexture(${n}, uv);
}
`}function b8(e){const t=e.shapeInfo.logicalShape,n=t.length,s=e.name,i="get"+s.charAt(0).toUpperCase()+s.slice(1),o=e.shapeInfo.texShape,a=[Math.ceil(o[0]/2),Math.ceil(o[1]/2)],c=a[0],h=a[1],p=Math.ceil(t[n-1]/2);let m=p*Math.ceil(t[n-2]/2),y="int b, int row, int col",b=`b * ${m} + (row / 2) * ${p} + (col / 2)`;for(let L=2;L<n-1;L++)y=`int b${L}, `+y,m*=t[n-L-1],b=`b${L} * ${m} + `+b;const w=Vn();return`
vec4 ${i}(${y}) {
int index = ${b};
int texR = index / ${h};
int texC = index - texR * ${h};
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${h}, ${c});
return ${w.texture2D}(${s}, uv);
}
`}function w8(e){const t=e.shapeInfo.logicalShape,n=e.name,s="get"+n.charAt(0).toUpperCase()+n.slice(1),i=t[3],o=t[2]*i,a=t[1]*o,{newShape:c,keptDims:h}=hn(t);if(c.length<t.length){const L=Oc(e,c),T=["row","col","depth","depth2"];return`
${Cc(L)}
float ${s}(int row, int col, int depth, int depth2) {
return ${s}(${Ec(T,h)});
}
`}if(e.shapeInfo.isUniform)return`
float ${s}(int row, int col, int depth, int depth2) {
int index = round(dot(vec4(row, col, depth, depth2),
vec4(${a}, ${o}, ${i}, 1)));
${Rc(e)}
}
`;const p=e.shapeInfo.flatOffset,m=e.shapeInfo.texShape,y=m[0],b=m[1];if(b===a&&p==null)return`
float ${s}(int row, int col, int depth, int depth2) {
float texR = float(row);
float texC =
dot(vec3(col, depth, depth2),
vec3(${o}, ${i}, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${b}.0, ${y}.0);
return sampleTexture(${n}, uv);
}
`;if(b===i&&p==null)return`
float ${s}(int row, int col, int depth, int depth2) {
float texR = dot(vec3(row, col, depth),
vec3(${t[1]*t[2]}, ${t[2]}, 1));
float texC = float(depth2);
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${b}.0, ${y}.0);
return sampleTexture(${n}, uv);
}
`;const w=sa(n);return`
float ${s}(int row, int col, int depth, int depth2) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${a} + col * ${o} +
depth * ${i} + depth2;
vec2 uv = uvFromFlat(${y}, ${b}, index + ${w});
return sampleTexture(${n}, uv);
}
`}function L8(e){const t=e.shapeInfo.logicalShape,n=e.name,s="get"+n.charAt(0).toUpperCase()+n.slice(1),i=t[4],o=t[3]*i,a=t[2]*o,c=t[1]*a,{newShape:h,keptDims:p}=hn(t);if(h.length<t.length){const T=Oc(e,h),v=["row","col","depth","depth2","depth3"];return`
${Cc(T)}
float ${s}(int row, int col, int depth, int depth2, int depth3) {
return ${s}(${Ec(v,p)});
}
`}if(e.shapeInfo.isUniform)return`
float ${s}(int row, int col, int depth, int depth2, int depth3) {
float index = dot(
vec4(row, col, depth, depth2),
vec4(${c}, ${a}, ${o}, ${i})) +
depth3;
${Rc(e)}
}
`;const m=e.shapeInfo.flatOffset,y=e.shapeInfo.texShape,b=y[0],w=y[1];if(w===c&&m==null)return`
float ${s}(int row, int col, int depth, int depth2, int depth3) {
int texR = row;
float texC = dot(vec4(col, depth, depth2, depth3),
vec4(${a}, ${o}, ${i}, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${w}.0, ${b}.0);
return sampleTexture(${n}, uv);
}
`;if(w===i&&m==null)return`
float ${s}(int row, int col, int depth, int depth2, int depth3) {
float texR = dot(
vec4(row, col, depth, depth2),
vec4(${t[1]*t[2]*t[3]},
${t[2]*t[3]}, ${t[3]}, 1));
int texC = depth3;
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${w}.0, ${b}.0);
return sampleTexture(${n}, uv);
}
`;const L=sa(n);return`
float ${s}(int row, int col, int depth, int depth2, int depth3) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${c} + col * ${a} + depth * ${o} +
depth2 * ${i} + depth3 + ${L};
vec2 uv = uvFromFlat(${b}, ${w}, index);
return sampleTexture(${n}, uv);
}
`}function S8(e){const t=e.shapeInfo.logicalShape,n=e.name,s="get"+n.charAt(0).toUpperCase()+n.slice(1),{newShape:i,keptDims:o}=hn(t);if(i.length<t.length){const v=Oc(e,i),C=["row","col","depth","depth2","depth3","depth4"];return`
${Cc(v)}
float ${s}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
return ${s}(${Ec(C,o)});
}
`}const a=t[5],c=t[4]*a,h=t[3]*c,p=t[2]*h,m=t[1]*p;if(e.shapeInfo.isUniform)return`
float ${s}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
int index = round(dot(
vec4(row, col, depth, depth2),
vec4(${m}, ${p}, ${h}, ${c})) +
dot(
vec2(depth3, depth4),
vec2(${a}, 1)));
${Rc(e)}
}
`;const y=e.shapeInfo.flatOffset,b=e.shapeInfo.texShape,w=b[0],L=b[1];if(L===m&&y==null)return`
float ${s}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
int texR = row;
float texC = dot(vec4(col, depth, depth2, depth3),
vec4(${p}, ${h}, ${c}, ${a})) +
float(depth4);
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${L}.0, ${w}.0);
return sampleTexture(${n}, uv);
}
`;if(L===a&&y==null)return`
float ${s}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
float texR = dot(vec4(row, col, depth, depth2),
vec4(${t[1]*t[2]*t[3]*t[4]},
${t[2]*t[3]*t[4]},
${t[3]*t[4]},
${t[4]})) + float(depth3);
int texC = depth4;
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${L}.0, ${w}.0);
return sampleTexture(${n}, uv);
}
`;const T=sa(n);return`
float ${s}(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 * ${m} + col * ${p} + depth * ${h} +
depth2 * ${c} + depth3 * ${a} + depth4 + ${T};
vec2 uv = uvFromFlat(${w}, ${L}, index);
return sampleTexture(${n}, uv);
}
`}function Rc(e){const t=e.name,n=M(e.shapeInfo.logicalShape);return n<2?`return ${t};`:`
for (int i = 0; i < ${n}; i++) {
if (i == index) {
return ${t}[i];
}
}
`}function I8(e,t){const n=e.name,s=n.charAt(0).toUpperCase()+n.slice(1),i="get"+s+"AtOutCoords",o=e.shapeInfo.logicalShape.length,a=t.logicalShape.length,c=NC(e.shapeInfo.logicalShape,t.logicalShape),h=Rt(a),p=a-o;let m;const y=["x","y","z","w","u","v"];o===0?m="":a<2&&c.length>=1?m="coords = 0;":m=c.map(O=>`coords.${y[O+p]} = 0;`).join(`
`);let b="";a<2&&o>0?b="coords":b=e.shapeInfo.logicalShape.map((O,D)=>`coords.${y[D+p]}`).join(", ");let w="return outputValue;";const L=M(e.shapeInfo.logicalShape),T=L===1,v=M(t.logicalShape),C=v===1;if(o===1&&!T&&!C)w=`
return vec4(outputValue.xy, outputValue.xy);
`;else if(T&&!C)a===1?w=`
return vec4(outputValue.x, outputValue.x, 0., 0.);
`:w=`
return vec4(outputValue.x);
`;else if(c.length){const O=o-2,D=o-1;c.indexOf(O)>-1&&c.indexOf(D)>-1?w="return vec4(outputValue.x);":c.indexOf(O)>-1?w="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":c.indexOf(D)>-1&&(w="return vec4(outputValue.xx, outputValue.zz);")}return`
vec4 ${i}() {
${h} coords = getOutputCoords();
${m}
vec4 outputValue = get${s}(${b});
${w}
}
`}function x8(e,t){const n=e.name,s=n.charAt(0).toUpperCase()+n.slice(1),i="get"+s+"AtOutCoords",o=t.texShape,a=e.shapeInfo.texShape,c=e.shapeInfo.logicalShape.length,h=t.logicalShape.length;if(!e.shapeInfo.isUniform&&c===h&&e.shapeInfo.flatOffset==null&&ie(a,o))return`
float ${i}() {
return sampleTexture(${n}, resultUV);
}
`;const p=Rt(h),m=NC(e.shapeInfo.logicalShape,t.logicalShape),y=h-c;let b;const w=["x","y","z","w","u","v"];c===0?b="":h<2&&m.length>=1?b="coords = 0;":b=m.map(T=>`coords.${w[T+y]} = 0;`).join(`
`);let L="";return h<2&&c>0?L="coords":L=e.shapeInfo.logicalShape.map((T,v)=>`coords.${w[v+y]}`).join(", "),`
float ${i}() {
${p} coords = getOutputCoords();
${b}
return get${s}(${L});
}
`}function Rt(e){if(e<=1)return"int";if(e===2)return"ivec2";if(e===3)return"ivec3";if(e===4)return"ivec4";if(e===5)return"ivec5";if(e===6)return"ivec6";throw Error(`GPU for rank ${e} is not yet supported`)}function Oc(e,t){const n=JSON.parse(JSON.stringify(e));return n.shapeInfo.logicalShape=t,n}function Ec(e,t){return t.map(n=>e[n]).join(", ")}class T8{constructor(e,t,n,s){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,A(e.length>2,()=>`Packed arg${n.charAt(0).toUpperCase()+n.slice(1)} supports only inputs with rank above 2.`);const i=e[e.length-1],o=Math.ceil(i/t);this.outputShape=e.slice(0,-1),o>1&&this.outputShape.push(o),s||this.variableNames.push("bestIndicesA");const a=this.outputShape,c=a.length,h=Rt(c),p=zn("coords",c);let m,y;if(o===1){y=c+1;const $=Rt(y);m=`
${$} sourceLocR = ${$}(${p.join()}, 0);
++${p[c-1]};
${$} sourceLocG = ${$}(${p.join()}, 0);
++${p[c-2]};
${$} sourceLocA = ${$}(${p.join()}, 0);
--${p[c-1]};
${$} sourceLocB = ${$}(${p.join()}, 0);
--${p[c-2]};`}else y=c,m=`
${h} sourceLocR = coords;
++${p[c-1]};
${h} sourceLocG = coords;
++${p[c-2]};
${h} sourceLocA = coords;
--${p[c-1]};
${h} sourceLocB = coords;
--${p[c-2]};`;const b=["x","y","z","w","u","v"].slice(0,y),w="."+b[y-1],L=b.map($=>"int "+$),T=zn("sourceLocR",y-1).concat("inIdx.r"),v=zn("sourceLocG",y-1).concat("inIdx.g"),C=zn("sourceLocB",y-1).concat("inIdx.b"),O=zn("sourceLocA",y-1).concat("inIdx.a"),D=n==="max"?"greaterThan":"lessThan",k=s?"":`
inIdx = round(vec4(getBestIndicesAChannel(${T.join()}),
getBestIndicesAChannel(${v.join()}),
getBestIndicesAChannel(${C.join()}),
getBestIndicesAChannel(${O.join()})));`,F=`vec4(
getAChannel(${T.join()}),
hasNextCol ? getAChannel(${v.join()}) : 0.,
hasNextRow ? getAChannel(${C.join()}) : 0.,
hasNextRow && hasNextCol ? getAChannel(${O.join()}) : 0.)`,B=s?"":`
float getBestIndicesAChannel(${L.join()}) {
return getChannel(getBestIndicesA(${b.join()}),
vec2(${b.slice(-2).join()}));
}`;this.userCode=`
float getAChannel(${L.join()}) {
return getChannel(getA(${b.join()}),
vec2(${b.slice(-2).join()}));
}
${B}
void main() {
${h} coords = getOutputCoords();
bool hasNextCol = ${p[c-1]} < ${a[c-1]-1};
bool hasNextRow = ${p[c-2]} < ${a[c-2]-1};
${m}
ivec4 srcIdx = ivec4(sourceLocR${w}, sourceLocG${w},
sourceLocB${w}, sourceLocA${w}) * ${t};
ivec4 inIdx = srcIdx;
vec4 bestIndex = vec4(inIdx);
vec4 bestValue = ${F};
for (int i = 0; i < ${t}; i++) {
inIdx = srcIdx;
${k}
vec4 candidate = ${F};
bvec4 nan = isnan(candidate);
bvec4 replace = bvec4(
vec4(${D}(candidate, bestValue)) * (vec4(1.0) - vec4(nan)));
bestValue = vec4(replace.x ? candidate.x : bestValue.x,
replace.y ? candidate.y : bestValue.y,
replace.z ? candidate.z : bestValue.z,
replace.w ? candidate.w : bestValue.w);
bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace));
srcIdx++;
}
setOutput(bestIndex);
}
`}}class A8{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;const t=e.filterHeight,n=e.filterWidth,s=e.strideHeight,i=e.strideWidth,o=e.dilationHeight,a=e.dilationWidth,c=e.effectiveFilterHeight,h=e.effectiveFilterWidth,p=c-1-e.padInfo.top,m=h-1-e.padInfo.left,y=1/(t*n);this.userCode=`
const ivec2 pads = ivec2(${p}, ${m});
const float avgMultiplier = float(${y});
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 dyRCCorner = coords.yz - pads;
int dyRCorner = dyRCCorner.x;
int dyCCorner = dyRCCorner.y;
// Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wR = 0; wR < ${c};
wR += ${o}) {
float dyR = float(dyRCorner + wR) / ${s}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
for (int wC = 0; wC < ${h};
wC+= ${a}) {
float dyC = float(dyCCorner + wC) / ${i}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
float dyValue = getDy(b, idyR, idyC, d);
dotProd += dyValue * avgMultiplier;
}
}
setOutput(dotProd);
}
`}}class v8{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;const t=e.filterDepth,n=e.filterHeight,s=e.filterWidth,i=e.strideDepth,o=e.strideHeight,a=e.strideWidth,c=e.dilationDepth,h=e.dilationHeight,p=e.dilationWidth,m=e.effectiveFilterDepth,y=e.effectiveFilterHeight,b=e.effectiveFilterWidth,w=m-1-e.padInfo.front,L=y-1-e.padInfo.top,T=b-1-e.padInfo.left,v=1/(t*n*s);this.userCode=`
const ivec3 pads = ivec3(${w}, ${L}, ${T});
const float avgMultiplier = float(${v});
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int ch = coords.u;
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
int dyDCorner = dyCorner.x;
int dyRCorner = dyCorner.y;
int dyCCorner = dyCorner.z;
// Convolve dy(?, ?, ?, d) with pos mask(:, :, :, ch) to get
// dx(xD, xR, xC, ch).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wD = 0; wD < ${m};
wD += ${c}) {
float dyD = float(dyDCorner + wD) / ${i}.0;
if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) {
continue;
}
int idyD = int(dyD);
for (int wR = 0; wR < ${y};
wR += ${h}) {
float dyR = float(dyRCorner + wR) / ${o}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
for (int wC = 0; wC < ${b};
wC += ${p}) {
float dyC = float(dyCCorner + wC) / ${a}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
float dyValue = getDy(batch, idyD, idyR, idyC, ch);
dotProd += dyValue * avgMultiplier;
}
}
}
setOutput(dotProd);
}
`}}const OC=`
if (isnan(a)) return a;
if (isnan(b)) return b;
`,N8=`
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;
}
`,C8=`
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);
`,Zne="return (a - b) * (a - b);",R8="return float(a == b);",O8="return float(a < b);",E8="return float(a <= b);",D8="return float(a > b);",k8="return float(a >= b);",F8="return float(a >= 1.0 && b >= 1.0);",_8="return float(a >= 1.0 || b >= 1.0);",W8=OC+`
return max(a, b);
`,$8=OC+`
return min(a, b);
`,U8=`if (b == 0.0) return NAN;
return mod(a, b);`,B8="return (b >= 1.0) ? a : a * (b + 1.0);",EC="return (a < 0.) ? b * a : a;";class $n{constructor(e,t,n){this.variableNames=["A","B"],this.outputShape=st(t,n),this.userCode=`
float binaryOperation(float a, float b) {
${e}
}
void main() {
float a = getAAtOutCoords();
float b = getBAtOutCoords();
setOutput(binaryOperation(a, b));
}
`}}const Jm=`
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;
`,M8=`
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);
`,P8=`
// 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));
`+Jm+`
return result;
`,DC=`
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
`,z8=`
vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));
return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));
`,V8=`
return vec4(equal(a, b));
`,Qne=`
return vec4(notEqual(a, b));
`,G8=`
return vec4(lessThan(a, b));
`,Y8=`
return vec4(lessThanEqual(a, b));
`,H8=`
return vec4(greaterThan(a, b));
`,q8=`
return vec4(greaterThanEqual(a, b));
`,j8=`
return vec4(
vec4(greaterThanEqual(a, vec4(1.0))) *
vec4(greaterThanEqual(b, vec4(1.0))));
`,K8=`
return min(
vec4(greaterThanEqual(a, vec4(1.0))) +
vec4(greaterThanEqual(b, vec4(1.0))),
vec4(1.0));
`,X8=`
vec4 result = vec4(max(a, b));
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
`+Jm+`
return result;
`,J8=`
vec4 result = vec4(min(a, b));
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
`+Jm+`
return result;
`,Z8=`
vec4 result = mod(a, b);
vec4 isNaN = vec4(equal(b, vec4(0.0)));
`+Jm+`
return result;
`;class fr{constructor(e,t,n,s=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=st(t,n);const i=this.outputShape.length;let o="";if(s)if(i===0||M(this.outputShape)===1)o=`
result.y = 0.;
result.z = 0.;
result.w = 0.;
`;else{const a=Rt(i);if(o=`
${a} coords = getOutputCoords();
`,i===1)o+=`
result.y = (coords + 1) >= ${this.outputShape[0]} ? 0. : result.y;
result.z = 0.;
result.w = 0.;
`;else{const c=zn("coords",i);o+=`
bool nextRowOutOfBounds =
(${c[i-2]} + 1) >= ${this.outputShape[i-2]};
bool nextColOutOfBounds =
(${c[i-1]} + 1) >= ${this.outputShape[i-1]};
result.y = nextColOutOfBounds ? 0. : result.y;
result.z = nextRowOutOfBounds ? 0. : result.z;
result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;
`}}this.userCode=`
vec4 binaryOperation(vec4 a, vec4 b) {
${e}
}
void main() {
vec4 a = getAAtOutCoords();
vec4 b = getBAtOutCoords();
vec4 result = binaryOperation(a, b);
${o}
setOutput(result);
}
`}}class Q8{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(n,s)=>{this.minLoc==null&&(this.minLoc=n.getUniformLocationNoThrow(s,"minVal"),this.maxLoc=n.getUniformLocationNoThrow(s,"maxVal")),n.gl.uniform1f(this.minLoc,e),n.gl.uniform1f(this.maxLoc,t)}}}class e6{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.userCode=`
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(n,s)=>{this.minLoc==null&&(this.minLoc=n.getUniformLocationNoThrow(s,"minVal"),this.maxLoc=n.getUniformLocationNoThrow(s,"maxVal")),n.gl.uniform1f(this.minLoc,e),n.gl.uniform1f(this.maxLoc,t)}}}class t6{constructor(e){this.variableNames=["real","imag"],this.outputShape=e,this.userCode=`
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 n6{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;const t=e.strideHeight,n=e.strideWidth,s=e.padInfo.top,i=e.padInfo.left,o=e.dataFormat==="channelsLast";this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int wR = coords.x;
int wC = coords.y;
int d1 = coords.z;
int d2 = coords.w;
// Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int b = 0; b < ${e.batchSize}; b++) {
for (int yR = 0; yR < ${e.outHeight}; yR++) {
int xR = wR + yR * ${t} - ${s};
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int yC = 0; yC < ${e.outWidth}; yC++) {
int xC = wC + yC * ${n} - ${i};
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
if (${o}) {
float dyValue = getDy(b, yR, yC, d2);
float xValue = getX(b, xR, xC, d1);
dotProd += (xValue * dyValue);
} else {
float dyValue = getDy(b, d2, yR, yC);
float xValue = getX(b, d1, xR, xC);
dotProd += (xValue * dyValue);
}
}
}
}
setOutput(dotProd);
}
`}}class s6{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterHeight,n=e.filterWidth,s=e.strideHeight,i=e.strideWidth,o=e.dataFormat==="channelsLast",a=t-1-e.padInfo.top,c=n-1-e.padInfo.left,h=o?1:2,p=o?2:3,m=o?3:1;this.userCode=`
const ivec2 pads = ivec2(${a}, ${c});
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d1 = coords[${m}];
ivec2 dyCorner = ivec2(coords[${h}], coords[${p}]) - 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) / ${s}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
int wRPerm = ${t} - 1 - wR;
for (int wC = 0; wC < ${n}; wC++) {
float dyC = float(dyCCorner + wC) / ${i}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
int wCPerm = ${n} - 1 - wC;
for (int d2 = 0; d2 < ${e.outChannels}; d2++) {
if (${o}) {
float xValue = getDy(batch, idyR, idyC, d2);
float wValue = getW(wRPerm, wCPerm, d1, d2);
dotProd += xValue * wValue;
} else {
float xValue = getDy(batch, d2, idyR, idyC);
float wValue = getW(wRPerm, wCPerm, d1, d2);
dotProd += xValue * wValue;
}
}
}
}
setOutput(dotProd);
}
`}}class i6{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;const t=e.strideDepth,n=e.strideHeight,s=e.strideWidth,i=e.padInfo.front,o=e.padInfo.top,a=e.padInfo.left;this.userCode=`
void main() {
ivec5 coords = getOutputCoords();
int wF = coords.x;
int wR = coords.y;
int wC = coords.z;
int d1 = coords.w;
int d2 = coords.u;
float dotProd = 0.0;
for (int b = 0; b < ${e.batchSize}; b++) {
for (int yF = 0; yF < ${e.outDepth}; yF++) {
int xF = wF + yF * ${t} - ${i};
if (xF < 0 || xF >= ${e.inDepth}) {
continue;
}
for (int yR = 0; yR < ${e.outHeight}; yR++) {
int xR = wR + yR * ${n} - ${o};
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int yC = 0; yC < ${e.outWidth}; yC++) {
int xC = wC + yC * ${s} - ${a};
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
float dyValue = getDy(b, yF, yR, yC, d2);
float xValue = getX(b, xF, xR, xC, d1);
dotProd += (xValue * dyValue);
}
}
}
}
setOutput(dotProd);
}
`}}class r6{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterDepth,n=e.filterHeight,s=e.filterWidth,i=e.strideDepth,o=e.strideHeight,a=e.strideWidth,c=t-1-e.padInfo.front,h=n-1-e.padInfo.top,p=s-1-e.padInfo.left;this.userCode=`
const ivec3 pads = ivec3(${c}, ${h}, ${p});
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int d1 = coords.u;
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
int dyFCorner = dyCorner.x;
int dyRCorner = dyCorner.y;
int dyCCorner = dyCorner.z;
float dotProd = 0.0;
for (int wF = 0; wF < ${t}; wF++) {
float dyF = float(dyFCorner + wF) / ${i}.0;
if (dyF < 0.0 || dyF >= ${e.outDepth}.0 || fract(dyF) > 0.0) {
continue;
}
int idyF = int(dyF);
int wFPerm = ${t} - 1 - wF;
for (int wR = 0; wR < ${n}; wR++) {
float dyR = float(dyRCorner + wR) / ${o}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
int wRPerm = ${n} - 1 - wR;
for (int wC = 0; wC < ${s}; wC++) {
float dyC = float(dyCCorner + wC) / ${a}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
int wCPerm = ${s} - 1 - wC;
for (int d2 = 0; d2 < ${e.outChannels}; d2++) {
float xValue = getDy(batch, idyF, idyR, idyC, d2);
float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);
dotProd += xValue * wValue;
}
}
}
}
setOutput(dotProd);
}
`}}class o6{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;const t=e.strideHeight,n=e.strideWidth,s=e.padInfo.top,i=e.padInfo.left,o=e.outChannels/e.inChannels;this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int wR = coords.x;
int wC = coords.y;
int d1 = coords.z;
int dm = coords.w;
int d2 = d1 * ${o} + dm;
float dotProd = 0.0;
// TO DO: Vec4 over the batch size
for (int b = 0; b < ${e.batchSize}; b++) {
for (int yR = 0; yR < ${e.outHeight}; yR++) {
int xR = wR + yR * ${t} - ${s};
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int yC = 0; yC < ${e.outWidth}; yC++) {
int xC = wC + yC * ${n} - ${i};
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
float dyValue = getDy(b, yR, yC, d2);
float xValue = getX(b, xR, xC, d1);
dotProd += (xValue * dyValue);
}
}
}
setOutput(dotProd);
}
`}}class a6{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterHeight,n=e.filterWidth,s=e.strideHeight,i=e.strideWidth,o=t-1-e.padInfo.top,a=n-1-e.padInfo.left,c=e.outChannels/e.inChannels;this.userCode=`
const ivec2 pads = ivec2(${o}, ${a});
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d1 = coords[3];
ivec2 dyCorner = coords.yz - pads;
int dyRCorner = dyCorner.x;
int dyCCorner = dyCorner.y;
float dotProd = 0.0;
for (int wR = 0; wR < ${t}; wR++) {
float dyR = float(dyRCorner + wR) / ${s}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
int wRPerm = ${t} - 1 - wR;
for (int wC = 0; wC < ${n}; wC++) {
float dyC = float(dyCCorner + wC) / ${i}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
int wCPerm = ${n} - 1 - wC;
// TO DO: Vec4 over the channelMul
for (int dm = 0; dm < ${c}; dm++) {
int d2 = d1 * ${c} + dm;
float xValue = getDy(batch, idyR, idyC, d2);
float wValue = getW(wRPerm, wCPerm, d1, dm);
dotProd += xValue * wValue;
}
}
}
setOutput(dotProd);
}
`}}class kC{constructor(e,t=!1,n=null,s=!1){this.variableNames=["x","W"],this.outputShape=e.outShape;const i=e.padInfo.top,o=e.padInfo.left,a=e.strideHeight,c=e.strideWidth,h=e.dilationHeight,p=e.dilationWidth,m=e.filterHeight,y=e.filterWidth,b=Math.floor(e.inChannels/4)*4,w=e.inChannels%4,L=e.dataFormat==="channelsLast",T=L?1:2,v=L?2:3,C=L?3:1;let O="",D="";n&&(s?O=`float activation(float a) {
float b = getPreluActivationWeightsAtOutCoords();
${n}
}`:O=`
float activation(float x) {
${n}
}
`,D="result = activation(result);");const k=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),s&&this.variableNames.push("preluActivationWeights"),this.userCode=`
${O}
const ivec2 strides = ivec2(${a}, ${c});
const ivec2 pads = ivec2(${i}, ${o});
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d2 = coords[${C}];
ivec2 xRCCorner =
ivec2(coords[${T}], coords[${v}]) * strides - pads;
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
// Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wR = 0; wR < ${m}; wR++) {
int xR = xRCorner + wR * ${h};
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int wC = 0; wC < ${y}; wC++) {
int xC = xCCorner + wC * ${p};
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
for (int d1 = 0; d1 < ${b}; d1 += 4) {
vec4 wValues = vec4(
getW(wR, wC, d1, d2),
getW(wR, wC, d1 + 1, d2),
getW(wR, wC, d1 + 2, d2),
getW(wR, wC, d1 + 3, d2)
);
if (${L}) {
vec4 xValues = vec4(
getX(batch, xR, xC, d1),
getX(batch, xR, xC, d1 + 1),
getX(batch, xR, xC, d1 + 2),
getX(batch, xR, xC, d1 + 3)
);
dotProd += dot(xValues, wValues);
} else {
vec4 xValues = vec4(
getX(batch, d1, xR, xC),
getX(batch, d1 + 1, xR, xC),
getX(batch, d1 + 2, xR, xC),
getX(batch, d1 + 3, xR, xC)
);
dotProd += dot(xValues, wValues);
}
}
if (${w===1}) {
if (${L}) {
dotProd +=
getX(batch, xR, xC, ${b}) *
getW(wR, wC, ${b}, d2);
} else {
dotProd +=
getX(batch, ${b}, xR, xC) *
getW(wR, wC, ${b}, d2);
}
} else if (${w===2}) {
vec2 wValues = vec2(
getW(wR, wC, ${b}, d2),
getW(wR, wC, ${b} + 1, d2)
);
if (${L}) {
vec2 xValues = vec2(
getX(batch, xR, xC, ${b}),
getX(batch, xR, xC, ${b} + 1)
);
dotProd += dot(xValues, wValues);
} else {
vec2 xValues = vec2(
getX(batch, ${b}, xR, xC),
getX(batch, ${b} + 1, xR, xC)
);
dotProd += dot(xValues, wValues);
}
} else if (${w===3}) {
vec3 wValues = vec3(
getW(wR, wC, ${b}, d2),
getW(wR, wC, ${b} + 1, d2),
getW(wR, wC, ${b} + 2, d2)
);
if (${L}) {
vec3 xValues = vec3(
getX(batch, xR, xC, ${b}),
getX(batch, xR, xC, ${b} + 1),
getX(batch, xR, xC, ${b} + 2)
);
dotProd += dot(xValues, wValues);
} else {
vec3 xValues = vec3(
getX(batch, ${b}, xR, xC),
getX(batch, ${b} + 1, xR, xC),
getX(batch, ${b} + 2, xR, xC)
);
dotProd += dot(xValues, wValues);
}
}
}
}
float result = dotProd;
${k}
${D}
setOutput(result);
}
`}}class c6{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;const t=e.padInfo.front,n=e.padInfo.top,s=e.padInfo.left,i=e.strideDepth,o=e.strideHeight,a=e.strideWidth,c=e.dilationDepth,h=e.dilationHeight,p=e.dilationWidth,m=e.filterDepth,y=e.filterHeight,b=e.filterWidth,w=Math.floor(e.inChannels/4)*4,L=e.inChannels%4;this.userCode=`
const ivec3 strides = ivec3(${i}, ${o}, ${a});
const ivec3 pads = ivec3(${t}, ${n}, ${s});
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int d2 = coords.u;
ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
int xFCorner = xFRCCorner.x;
int xRCorner = xFRCCorner.y;
int xCCorner = xFRCCorner.z;
// Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get
// y(yF, yR, yC, d2). ? = to be determined. : = across all
// values in that axis.
float dotProd = 0.0;
for (int wF = 0; wF < ${m}; wF++) {
int xF = xFCorner + wF * ${c};
if (xF < 0 || xF >= ${e.inDepth}) {
continue;
}
for (int wR = 0; wR < ${y}; wR++) {
int xR = xRCorner + wR * ${h};
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int wC = 0; wC < ${b}; wC++) {
int xC = xCCorner + wC * ${p};
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
for (int d1 = 0; d1 < ${w}; d1 += 4) {
vec4 xValues = vec4(
getX(batch, xF, xR, xC, d1),
getX(batch, xF, xR, xC, d1 + 1),
getX(batch, xF, xR, xC, d1 + 2),
getX(batch, xF, xR, xC, d1 + 3)
);
vec4 wValues = vec4(
getW(wF, wR, wC, d1, d2),
getW(wF, wR, wC, d1 + 1, d2),
getW(wF, wR, wC, d1 + 2, d2),
getW(wF, wR, wC, d1 + 3, d2)
);
dotProd += dot(xValues, wValues);
}
if (${L===1}) {
dotProd +=
getX(batch, xF, xR, xC, ${w}) *
getW(wF, wR, wC, ${w}, d2);
} else if (${L===2}) {
vec2 xValues = vec2(
getX(batch, xF, xR, xC, ${w}),
getX(batch, xF, xR, xC, ${w} + 1)
);
vec2 wValues = vec2(
getW(wF, wR, wC, ${w}, d2),
getW(wF, wR, wC, ${w} + 1, d2)
);
dotProd += dot(xValues, wValues);
} else if (${L===3}) {
vec3 xValues = vec3(
getX(batch, xF, xR, xC, ${w}),
getX(batch, xF, xR, xC, ${w} + 1),
getX(batch, xF, xR, xC, ${w} + 2)
);
vec3 wValues = vec3(
getW(wF, wR, wC, ${w}, d2),
getW(wF, wR, wC, ${w} + 1, d2),
getW(wF, wR, wC, ${w} + 2, d2)
);
dotProd += dot(xValues, wValues);
}
}
}
}
setOutput(dotProd);
}
`}}class FC{constructor(e,t=!1,n=null,s=!1){this.variableNames=["x","W"],this.outputShape=e.outShape;const i=e.inHeight,o=e.inWidth,a=e.padInfo.top,c=e.padInfo.left,h=e.strideHeight,p=e.strideWidth,m=e.dilationHeight,y=e.dilationWidth,b=e.filterHeight,w=e.filterWidth,L=e.outChannels/e.inChannels;let T="",v="";n&&(s?T=`float activation(float a) {
float b = getPreluActivationWeightsAtOutCoords();
${n}
}`:T=`
float activation(float x) {
${n}
}
`,v="result = activation(result);");const C=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),s&&this.variableNames.push("preluActivationWeights"),this.userCode=`
${T}
const ivec2 strides = ivec2(${h}, ${p});
const ivec2 pads = ivec2(${a}, ${c});
void main() {
ivec4 coords = getOutputCoords();
int batch = coords.x;
ivec2 xRCCorner = coords.yz * strides - pads;
int d2 = coords.w;
int d1 = d2 / ${L};
int q = d2 - d1 * ${L};
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
// Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
// TO DO(dsmilkov): Flatten the two for loops and vec4 the operations.
for (int wR = 0; wR < ${b}; wR++) {
int xR = xRCorner + wR * ${m};
if (xR < 0 || xR >= ${i}) {
continue;
}
for (int wC = 0; wC < ${w}; wC++) {
int xC = xCCorner + wC * ${y};
if (xC < 0 || xC >= ${o}) {
continue;
}
float xVal = getX(batch, xR, xC, d1);
float wVal = getW(wR, wC, d1, q);
dotProd += xVal * wVal;
}
}
float result = dotProd;
${C}
${v}
setOutput(result);
}
`}}class _C{constructor(e,t=!1,n=null,s=!1){this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e.outShape;const i=e.inHeight,o=e.inWidth,a=e.padInfo.top,c=e.padInfo.left,h=e.strideHeight,p=e.strideWidth,m=e.dilationHeight,y=e.dilationWidth,b=e.filterHeight,w=e.filterWidth,L=w;let T="int xR; int xC; int xCOffset;";for(let D=0;D<b;D++)for(let k=0;k<w;k++)T+=`
vec4 xTexelR${D}C${k*2} = vec4(0.);
vec4 wR${D}C${k} = vec4(0.);
vec4 xR${D}C${k} = vec4(0.);`;for(let D=0;D<b;D++)for(let k=0;k<L;k++){const F=k*2;if(T+=`
xR = xRCorner + ${D*m};
xC = xCCorner + ${F*y};
`,p===1){if(F<w&&(c%2===1?T+=`
xCOffset = xC + 1;
if(xR >= 0 && xR < ${i} && xCOffset >= 0 && xCOffset < ${o}) {
xTexelR${D}C${F} = getX(batch, xR, xCOffset, d1);
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if(xCOffset + 1 >= ${o}) {
xTexelR${D}C${F}.zw = vec2(0.);
}
} else {
xTexelR${D}C${F} = vec4(0.);
}
xCOffset = xC + 1 - 2;
if(xR >= 0 && xR < ${i} && xCOffset >= 0 && xCOffset < ${o}) {
vec4 previous = getX(batch, xR, xCOffset, d1);
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if(xCOffset + 1 >= ${o}) {
previous.zw = vec2(0.);
}
xR${D}C${F} = vec4(previous.zw, xTexelR${D}C${F}.xy);
} else {
xR${D}C${F} = vec4(0, 0, xTexelR${D}C${F}.xy);
}
`:T+=`
if(xR >= 0 && xR < ${i} && xC >= 0 && xC < ${o}) {
xTexelR${D}C${F} = getX(batch, xR, xC, d1);
} else {
xTexelR${D}C${F} = vec4(0.);
}
xR${D}C${F} = xTexelR${D}C${F};
`,F+1<w)){const B=c%2===0?x(y):y;y%2===0&&c%2===1||y%2!==0&&c%2!==1?(T+=`
xCOffset = xC + ${c%2} + ${B};
if(xR >= 0 && xR < ${i} &&
xCOffset >= 0 && xCOffset < ${o}) {
xTexelR${D}C${F+2} = getX(batch, xR, xCOffset, d1);
}
`,y>1&&(T+=`
xCOffset -= 2;
if(xR >= 0 && xR < ${i} &&
xCOffset >= 0 && xCOffset < ${o}) {
xTexelR${D}C${F} = getX(batch, xR, xCOffset, d1);
} else {
xTexelR${D}C${F} = vec4(0.);
}
`),T+=`
xR${D}C${F+1} = vec4(
xTexelR${D}C${F}.zw, xTexelR${D}C${F+2}.xy);
`):T+=`
xCOffset = xC + ${B};
if(xR >= 0 && xR < ${i} &&
xCOffset >= 0 && xCOffset < ${o}) {
xTexelR${D}C${F+2} = getX(batch, xR, xCOffset, d1);
}
xR${D}C${F+1} = xTexelR${D}C${F+2};
`}}else F<w&&(T+=`
if(xR >= 0 && xR < ${i}) {
`,c%2===1?(T+=`
xCOffset = xC + 1 - ${p};
if(xCOffset >= 0 && xCOffset < ${o}) {
xTexelR${D}C${F} = getX(batch, xR, xCOffset, d1);
} else {
xTexelR${D}C${F} = vec4(0.);
}
if(xC + 1 >= 0 && xC + 1 < ${o}) {
xTexelR${D}C${F+2} = getX(batch, xR, xC + 1, d1);
} else {
xTexelR${D}C${F+2} = vec4(0.);
}
xR${D}C${F} = vec4(
xTexelR${D}C${F}.zw, xTexelR${D}C${F+2}.zw);
`,F+1<w&&(T+=`
vec4 final = vec4(0.);
xCOffset = xC + 1 + ${p};
if(xCOffset >= 0 && xCOffset < ${o}) {
final = getX(batch, xR, xCOffset, d1);
}
xR${D}C${F+1} = vec4(xTexelR${D}C${F+2}.xy, final.xy);
`)):(T+=`
if(xC >= 0 && xC < ${o}) {
xTexelR${D}C${F} = getX(batch, xR, xC, d1);
} else {
xTexelR${D}C${F} = vec4(0.);
}
xCOffset = xC + ${p};
if(xCOffset >= 0 && xCOffset < ${o}) {
xTexelR${D}C${F+2} = getX(batch, xR, xCOffset, d1);
} else {
xTexelR${D}C${F+2} = vec4(0.);
}
xR${D}C${F} = vec4(
xTexelR${D}C${F}.xy, xTexelR${D}C${F+2}.xy);
`,F+1<w&&(T+=`
xR${D}C${F+1} = vec4(
xTexelR${D}C${F}.zw, xTexelR${D}C${F+2}.zw);
`)),T+="}");F<w&&(T+=`
vec4 wTexelR${D}C${F} = getW(${D}, ${F}, d1, q);
wR${D}C${F} = vec4(wTexelR${D}C${F}.xz, wTexelR${D}C${F}.xz);
`,F+1<w&&(T+=`
vec4 wTexelR${D}C${F+1} = getW(${D}, ${F+1}, d1, q);
wR${D}C${F+1} =
vec4(wTexelR${D}C${F+1}.xz, wTexelR${D}C${F+1}.xz);`))}for(let D=0;D<b;D++)for(let k=0;k<w;k++)T+=`dotProd += xR${D}C${k} * wR${D}C${k};`;let v="",C="";n&&(s?v=`vec4 activation(vec4 a) {
vec4 b = getPreluActivationWeightsAtOutCoords();
${n}
}`:v=`vec4 activation(vec4 x) {
${n}
}`,C="result = activation(result);");const O=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),s&&this.variableNames.push("preluActivationWeights"),this.userCode=`
${v}
const ivec2 strides = ivec2(${h}, ${p});
const ivec2 pads = ivec2(${a}, ${c});
void main() {
ivec4 coords = getOutputCoords();
int batch = coords.x;
ivec2 xRCCorner = coords.yz * strides - pads;
int d2 = coords.w;
int d1 = d2;
int q = 0;
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
vec4 dotProd = vec4(0.);
${T}
vec4 result = dotProd;
${O}
${C}
setOutput(result);
}
`}}class l6{constructor(e,t,n,s,i){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];const[o,a,c,h]=e,[p]=t,[m,y]=n;this.outputShape=[p,m,y,h];const b=s==="bilinear"?1:0,[w,L]=[`${a-1}.0`,`${c-1}.0`],[T,v,C]=m>1?[`${(a-1)/(m-1)}`,"(y2-y1) * height_ratio",`y1*${w} + float(y)*(height_scale)`]:["0.0","0.0",`0.5 * (y1+y2) * ${w}`],[O,D,k]=y>1?[`${(c-1)/(y-1)}`,"(x2-x1) * width_ratio",`x1*${L} + float(x)*(width_scale)`]:["0.0","0.0",`0.5 * (x1+x2) * ${L}`];this.userCode=`
const float height_ratio = float(${T});
const float width_ratio = float(${O});
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int y = coords[1];
int x = coords[2];
int d = coords[3];
// get box vals
float y1 = getBoxes(b,0);
float x1 = getBoxes(b,1);
float y2 = getBoxes(b,2);
float x2 = getBoxes(b,3);
// get image in batch index
int bInd = round(getBoxInd(b));
if(bInd < 0 || bInd >= ${o}) {
return;
}
float height_scale = ${v};
float width_scale = ${D};
float in_y = ${C};
if( in_y < 0.0 || in_y > ${w} ) {
setOutput(float(${i}));
return;
}
float in_x = ${k};
if( in_x < 0.0 || in_x > ${L} ) {
setOutput(float(${i}));
return;
}
vec2 sourceFracIndexCR = vec2(in_x,in_y);
if(${b} == 1) {
// Compute the four integer indices.
ivec2 sourceFloorCR = ivec2(sourceFracIndexCR);
ivec2 sourceCeilCR = ivec2(ceil(sourceFracIndexCR));
float topLeft = getImage(b, sourceFloorCR.y, sourceFloorCR.x, d);
float bottomLeft = getImage(b, sourceCeilCR.y, sourceFloorCR.x, d);
float topRight = getImage(b, sourceFloorCR.y, sourceCeilCR.x, d);
float bottomRight = getImage(b, sourceCeilCR.y, sourceCeilCR.x, d);
vec2 fracCR = sourceFracIndexCR - vec2(sourceFloorCR);
float top = topLeft + (topRight - topLeft) * fracCR.x;
float bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x;
float newValue = top + (bottom - top) * fracCR.y;
setOutput(newValue);
} else {
// Compute the coordinators of nearest neighbor point.
ivec2 sourceNearestCR = ivec2(floor(
sourceFracIndexCR + vec2(0.5,0.5)));
float newValue = getImage(b, sourceNearestCR.y, sourceNearestCR.x, d);
setOutput(newValue);
}
}
`}}class WC{constructor(e,t,n){this.variableNames=["x"],this.outputShape=e;const s=e.length,i=t?"0.0":`getX(${$C(s,"coords")})`,o=e[e.length-1];let a="",c="";t?(a=n?`end != ${o-1}`:"end != 0",c=n?"end + 1":"end - 1"):(a=n?`end + pow2 < ${o}`:"end >= pow2",c=n?"end + pow2":"end - pow2"),this.userCode=`
uniform float index;
void main() {
${Rt(s)} coords = getOutputCoords();
int end = ${UC(s,"coords")};
float val = ${i};
int pow2 = int(pow(2.0, index));
if (${a}) {
int idx = ${c};
${UC(s,"coords")} = idx;
val += getX(${$C(s,"coords")});
}
setOutput(val);
}
`}getCustomSetupFunc(e){return(t,n)=>{this.index==null&&(this.index=t.getUniformLocation(n,"index")),t.gl.uniform1f(this.index,e)}}}function $C(e,t){if(e===1)return`${t}`;if(e===2)return`${t}.x, ${t}.y`;if(e===3)return`${t}.x, ${t}.y, ${t}.z`;if(e===4)return`${t}.x, ${t}.y, ${t}.z, ${t}.w`;throw Error(`Cumulative sum for rank ${e} is not yet supported`)}function UC(e,t){if(e===1)return`${t}`;if(e===2)return`${t}.y`;if(e===3)return`${t}.z`;if(e===4)return`${t}.w`;throw Error(`Cumulative sum for rank ${e} is not yet supported`)}class h6{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=xu.DENSE;const t=Au(e),n=Vn();this.outputShape=e,this.userCode=`
ivec3 outCoordsFromFlatIndex(int index) {
${na(["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);
}
${n.output} = result;
}
`}}class u6{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=xu.DENSE;const t=Au(e),n=Vn();this.outputShape=e,this.userCode=`
ivec3 outCoordsFromFlatIndex(int index) {
${na(["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));
}
${n.output} = result;
}
`}}class d6{constructor(e,t,n){this.variableNames=["x"],this.outputShape=[],this.outputShape=e,this.blockSize=t,this.dataFormat=n,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 p6{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 m6{constructor(e){this.variableNames=["A"],this.outTexUsage=Os.DOWNLOAD;const t=Vn();this.outputShape=e,this.userCode=`
${vC}
void main() {
float x = getAAtOutCoords();
${t.output} = encode_float(x);
}
`}}class f6{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=Os.DOWNLOAD;const t=Vn();this.outputShape=e,this.userCode=`
${vC}
void main() {
ivec3 coords = getOutputCoords();
float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));
${t.output} = encode_float(x);
}
`}}class g6{constructor(e,t,n=!1){this.variableNames=["A"];const s=Vn(),[i,o]=t;this.outputShape=e;let a="result";n&&(a="floor(result * 255. + 0.5)"),this.userCode=`
${PS(e)}
void main() {
ivec3 coords = getOutputCoords();
int flatIndex = getFlatIndex(coords);
int offset = imod(flatIndex, 4);
flatIndex = idiv(flatIndex, 4, 1.);
int r = flatIndex / ${o};
int c = imod(flatIndex, ${o});
vec2 uv = (vec2(c, r) + halfCR) / vec2(${o}.0, ${i}.0);
vec4 values = ${s.texture2D}(A, uv);
float result;
if(offset == 0) {
result = values[0];
} else if(offset == 1) {
result = values[1];
} else if(offset == 2) {
result = values[2];
} else {
result = values[3];
}
${s.output} = vec4(${a}, 0., 0., 0.);
}
`}}class y6{constructor(e,t,n=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;const s=Vn(),[i,o]=t;this.outputShape=e;let a="",c="result";n&&(c="floor(result * 255. + 0.5)");for(let h=0;h<=1;h++)for(let p=0;p<=1;p++){const m=h*2+p;a+=`
localCoords = coords;
if(localCoords[2] + ${p} < ${e[2]}) {
localCoords[2] += ${p};
if(localCoords[1] + ${h} < ${e[1]}) {
localCoords[1] += ${h};
flatIndex = getFlatIndex(localCoords);
offset = imod(flatIndex, 4);
flatIndex = idiv(flatIndex, 4, 1.);
r = flatIndex / ${o};
c = imod(flatIndex, ${o});
uv = (vec2(c, r) + halfCR) / vec2(${o}.0, ${i}.0);
values = ${s.texture2D}(A, uv);
if(offset == 0) {
result[${m}] = values[0];
} else if(offset == 1) {
result[${m}] = values[1];
} else if(offset == 2) {
result[${m}] = values[2];
} else {
result[${m}] = values[3];
}
}
}
`}this.userCode=`
${PS(e)}
void main() {
ivec3 coords = getOutputCoords();
vec4 result = vec4(0.);
int flatIndex, r, c, offset;
ivec3 localCoords;
vec2 uv;
vec4 values;
${a}
${s.output} = ${c};
}
`}}class b6{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,n)=>{this.valueLoc==null&&(this.valueLoc=t.getUniformLocationNoThrow(n,"value")),t.gl.uniform1f(this.valueLoc,e)}}}class w6{constructor(e,t,n){this.variableNames=["A","indices"];const s=e.slice();s[n]=t,this.outputShape=s,this.rank=s.length;const i=Rt(this.rank),o=L6(e,n);this.userCode=`
void main() {
${i} resRC = getOutputCoords();
setOutput(getA(${o}));
}
`}}function L6(e,t){const n=e.length;if(n>4)throw Error(`Gather for rank ${n} is not yet supported`);if(n===1)return"int(getIndices(resRC))";const s=["resRC.x","resRC.y","resRC.z","resRC.w"],i=[];for(let o=0;o<e.length;o++)o===t?i.push(`int(getIndices(${s[o]}))`):i.push(`${s[o]}`);return i.join()}class S6{constructor(e,t,n){this.sliceDim=e,this.strides=t,this.variableNames=["x","indices"],this.outputShape=n;const s=Rt(t.length),i=Rt(n.length),o=this.sliceDim>1?"strides[j]":"strides";this.userCode=`
${s} strides = ${s}(${this.strides});
void main() {
${i} coords = getOutputCoords();
int flattenIndex = 0;
for (int j = 0; j < ${this.sliceDim}; j++) {
int index = round(getIndices(coords[0], j));
flattenIndex += index * ${o};
}
setOutput(getX(flattenIndex, coords[1]));
}
`}}function I6(e){const t=Vn(),n=`${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 t5(e,n)}function x6(e){const t=new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]);return a5(e,t)}function T6(e){const t=new Uint16Array([0,1,2,2,1,3]);return c5(e,t)}function Nu(e,t,n,s,i,o){h5(t,n);const a=l5(e),c=e.TEXTURE_2D;return Ee(e,()=>e.bindTexture(c,a)),Ee(e,()=>e.texParameteri(c,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE)),Ee(e,()=>e.texParameteri(c,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)),Ee(e,()=>e.texParameteri(c,e.TEXTURE_MIN_FILTER,e.NEAREST)),Ee(e,()=>e.texParameteri(c,e.TEXTURE_MAG_FILTER,e.NEAREST)),Ee(e,()=>e.texImage2D(c,0,s,t,n,0,i,o,null)),Ee(e,()=>e.bindTexture(e.TEXTURE_2D,null)),a}function BC(e){return e.internalFormatFloat}function A6(e,t,n,s){const[i,o]=Tu(t,n);return Nu(e,i,o,BC(s),s.textureFormatFloat,e.FLOAT)}function MC(e){return e.internalFormatHalfFloat}function v6(e,t,n,s){const[i,o]=Tu(t,n);return Nu(e,i,o,MC(s),s.textureFormatFloat,s.textureTypeHalfFloat)}function PC(e){return e.downloadTextureFormat}function N6(e,t,n,s){const[i,o]=Tu(t,n);return Nu(e,i,o,PC(s),e.RGBA,e.UNSIGNED_BYTE)}function zC(e){return e.internalFormatPackedFloat}function C6(e,t,n,s){const[i,o]=Ac(t,n);return Nu(e,i,o,zC(s),e.RGBA,e.FLOAT)}function VC(e){return e.internalFormatPackedHalfFloat}function R6(e,t,n,s){const[i,o]=Ac(t,n);return Nu(e,i,o,VC(s),e.RGBA,s.textureTypeHalfFloat)}function O6(e,t,n){const s=0,i=3*4,o=3*4+2*4;Ee(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n));const a=SC(e,t,"clipSpacePos",n,3,o,s);return a&&SC(e,t,"uv",n,2,o,i)}function E6(e,t,n,s,i,o){Ee(e,()=>e.bindTexture(e.TEXTURE_2D,t));let a,c,h;i instanceof Uint8Array?(a=new Uint8Array(n*s*4),c=e.UNSIGNED_BYTE,h=e.RGBA):(a=new Float32Array(n*s*4),c=e.FLOAT,h=o.internalFormatPackedFloat),a.set(i),Ee(e,()=>e.texImage2D(e.TEXTURE_2D,0,h,n,s,0,e.RGBA,c,a)),Ee(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function D6(e,t,n){Ee(e,()=>e.bindTexture(e.TEXTURE_2D,t)),n.data instanceof Uint8Array?Ee(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,n.width,n.height,0,e.RGBA,e.UNSIGNED_BYTE,n.data)):Ee(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,n)),Ee(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function k6(e,t,n,s){const i=e.createBuffer();Ee(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,i));const o=4,a=4,c=o*a*t*n;return Ee(e,()=>e.bufferData(e.PIXEL_PACK_BUFFER,c,e.STREAM_READ)),Ee(e,()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,0)),Ee(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,null)),i}function F6(e,t,n){const s=e,i=new Float32Array(n);return s.bindBuffer(s.PIXEL_PACK_BUFFER,t),s.getBufferSubData(s.PIXEL_PACK_BUFFER,0,i),s.bindBuffer(s.PIXEL_PACK_BUFFER,null),i}function _6(e,t,n,s){const[i,o]=Tu(t,n),a=4,c=new Uint8Array(jK(t*n,a));return Ee(e,()=>e.readPixels(0,0,i,o,s.downloadTextureFormat,e.UNSIGNED_BYTE,c)),new Float32Array(c.buffer)}function W6(e,t,n,s,i,o,a,c){const h=e,p=new Float32Array(KK(o,a));return h.bindBuffer(h.PIXEL_PACK_BUFFER,t),h.getBufferSubData(h.PIXEL_PACK_BUFFER,0,p),h.bindBuffer(h.PIXEL_PACK_BUFFER,null),p}function $6(e,t,n){const s=new Float32Array(t*n*4);return Ee(e,()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,s)),s}class U6{constructor(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];const t=ae().getNumber("WEBGL_VERSION");e!=null?(this.gl=e,YK(t,e)):this.gl=Ui(t);let n="WEBGL_color_buffer_float";const s="EXT_color_buffer_half_float";if(ae().getNumber("WEBGL_VERSION")===1){const i="OES_texture_float",o="OES_texture_half_float";if(this.textureFloatExtension=Gm(this.gl,i),Hs(this.gl,o))this.textureHalfFloatExtension=Gm(this.gl,o);else if(ae().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support half float textures, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.");if(this.colorBufferFloatExtension=this.gl.getExtension(n),Hs(this.gl,s))this.colorBufferHalfFloatExtension=Gm(this.gl,s);else if(ae().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support color renderable half floats, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.")}else if(n="EXT_color_buffer_float",Hs(this.gl,n))this.colorBufferFloatExtension=this.gl.getExtension(n);else if(Hs(this.gl,s))this.colorBufferHalfFloatExtension=this.gl.getExtension(s);else throw new Error("GL context does not support color renderable floats");this.vertexBuffer=x6(this.gl),this.indexBuffer=T6(this.gl),this.framebuffer=u5(this.gl),this.textureConfig=_S(this.gl,this.textureHalfFloatExtension)}get debug(){return ae().getBool("DEBUG")}dispose(){if(this.disposed)return;this.program!=null&&console.warn("Disposing a GPGPUContext that still has a bound WebGLProgram. This is probably a resource leak, delete the program with GPGPUContext.deleteProgram before disposing."),this.outputTexture!=null&&console.warn("Disposing a GPGPUContext that still has a bound output matrix texture. This is probably a resource leak, delete the output matrix texture with GPGPUContext.deleteMatrixTexture before disposing.");const e=this.gl;Ee(e,()=>e.finish()),Ee(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,null)),Ee(e,()=>e.deleteFramebuffer(this.framebuffer)),Ee(e,()=>e.bindBuffer(e.ARRAY_BUFFER,null)),Ee(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)),Ee(e,()=>e.deleteBuffer(this.indexBuffer)),this.disposed=!0}createFloat32MatrixTexture(e,t){return this.throwIfDisposed(),A6(this.gl,e,t,this.textureConfig)}createFloat16MatrixTexture(e,t){return this.throwIfDisposed(),v6(this.gl,e,t,this.textureConfig)}createUnsignedBytesMatrixTexture(e,t){return this.throwIfDisposed(),N6(this.gl,e,t,this.textureConfig)}uploadPixelDataToTexture(e,t){this.throwIfDisposed(),D6(this.gl,e,t)}uploadDenseMatrixToTexture(e,t,n,s){this.throwIfDisposed(),E6(this.gl,e,t,n,s,this.textureConfig)}createFloat16PackedMatrixTexture(e,t){return this.throwIfDisposed(),R6(this.gl,e,t,this.textureConfig)}createPackedMatrixTexture(e,t){return this.throwIfDisposed(),C6(this.gl,e,t,this.textureConfig)}deleteMatrixTexture(e){this.throwIfDisposed(),this.outputTexture===e&&(IC(this.gl,this.framebuffer),this.outputTexture=null),Ee(this.gl,()=>this.gl.deleteTexture(e))}downloadByteEncodedFloatMatrixFromOutputTexture(e,t,n){return this.downloadMatrixDriver(e,()=>_6(this.gl,t,n,this.textureConfig))}downloadPackedMatrixFromBuffer(e,t,n,s,i,o){return W6(this.gl,e,t,n,s,i,o,this.textureConfig)}downloadFloat32MatrixFromBuffer(e,t){return F6(this.gl,e,t)}createBufferFromTexture(e,t,n){this.bindTextureToFrameBuffer(e);const s=k6(this.gl,t,n,this.textureConfig);return this.unbindTextureToFrameBuffer(),s}createAndWaitForFence(){const e=this.createFence(this.gl);return this.pollFence(e)}createFence(e){let t,n;if(ae().getBool("WEBGL_FENCE_API_ENABLED")){const s=e,i=s.fenceSync(s.SYNC_GPU_COMMANDS_COMPLETE,0);e.flush(),n=()=>{const o=s.clientWaitSync(i,0,0);return o===s.ALREADY_SIGNALED||o===s.CONDITION_SATISFIED},t=i}else ae().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(t=this.beginQuery(),this.endQuery(),n=()=>this.isQueryAvailable(t,ae().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))):n=()=>!0;return{query:t,isFencePassed:n}}downloadMatrixFromPackedTexture(e,t,n){return this.downloadMatrixDriver(e,()=>$6(this.gl,t,n))}createProgram(e){this.throwIfDisposed();const t=this.gl,n=n5(t,e),s=I6(t),i=r5(t);return Ee(t,()=>t.attachShader(i,s)),Ee(t,()=>t.attachShader(i,n)),o5(t,i),this.debug&&WS(t,i),this.vertexAttrsAreBound||(this.setProgram(i),this.vertexAttrsAreBound=O6(t,this.program,this.vertexBuffer)),i}deleteProgram(e){this.throwIfDisposed(),e===this.program&&(this.program=null),e!=null&&Ee(this.gl,()=>this.gl.deleteProgram(e))}setProgram(e){this.throwIfDisposed(),this.program=e,this.program!=null&&this.debug&&WS(this.gl,this.program),Ee(this.gl,()=>this.gl.useProgram(e))}getUniformLocation(e,t,n=!0){return this.throwIfDisposed(),n?p5(this.gl,e,t):m5(this.gl,e,t)}getAttributeLocation(e,t){return this.throwIfDisposed(),Ee(this.gl,()=>this.gl.getAttribLocation(e,t))}getUniformLocationNoThrow(e,t){return this.throwIfDisposed(),this.gl.getUniformLocation(e,t)}setInputMatrixTexture(e,t,n){this.throwIfDisposed(),this.throwIfNoProgram(),f5(this.gl,e,t,n)}setOutputMatrixTexture(e,t,n){this.setOutputMatrixTextureDriver(e,n,t)}setOutputPackedMatrixTexture(e,t,n){this.throwIfDisposed();const[s,i]=Ac(t,n);this.setOutputMatrixTextureDriver(e,s,i)}setOutputMatrixWriteRegion(e,t,n,s){this.setOutputMatrixWriteRegionDriver(n,e,s,t)}setOutputPackedMatrixWriteRegion(e,t,n,s){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")}debugValidate(){this.program!=null&&WS(this.gl,this.program),Ym(this.gl)}executeProgram(){this.throwIfDisposed(),this.throwIfNoProgram();const e=this.gl;this.debug&&this.debugValidate(),Ee(e,()=>e.drawElements(e.TRIANGLES,6,e.UNSIGNED_SHORT,0))}blockUntilAllProgramsCompleted(){this.throwIfDisposed(),Ee(this.gl,()=>this.gl.finish())}getQueryTimerExtension(){return this.disjointQueryTimerExtension==null&&(this.disjointQueryTimerExtension=Gm(this.gl,ae().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2?"EXT_disjoint_timer_query_webgl2":"EXT_disjoint_timer_query")),this.disjointQueryTimerExtension}getQueryTimerExtensionWebGL2(){return this.getQueryTimerExtension()}getQueryTimerExtensionWebGL1(){return this.getQueryTimerExtension()}beginQuery(){if(ae().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2){const n=this.gl,s=this.getQueryTimerExtensionWebGL2(),i=n.createQuery();return n.beginQuery(s.TIME_ELAPSED_EXT,i),i}const e=this.getQueryTimerExtensionWebGL1(),t=e.createQueryEXT();return e.beginQueryEXT(e.TIME_ELAPSED_EXT,t),t}endQuery(){if(ae().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2){const t=this.gl,n=this.getQueryTimerExtensionWebGL2();t.endQuery(n.TIME_ELAPSED_EXT);return}const e=this.getQueryTimerExtensionWebGL1();e.endQueryEXT(e.TIME_ELAPSED_EXT)}async waitForQueryAndGetTime(e){return await $t(()=>this.disposed||this.isQueryAvailable(e,ae().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))),this.getQueryTime(e,ae().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}getQueryTime(e,t){if(t===0)return null;if(t===2){const n=this.gl,s=n.getQueryParameter(e,n.QUERY_RESULT);return s/1e6}else{const n=this.getQueryTimerExtensionWebGL1(),s=n.getQueryObjectEXT(e,n.QUERY_RESULT_EXT);return s/1e6}}isQueryAvailable(e,t){if(t===0)return!0;if(t===2){const n=this.gl,s=this.getQueryTimerExtensionWebGL2(),i=n.getQueryParameter(e,n.QUERY_RESULT_AVAILABLE);return this.disjoint==null&&(this.disjoint=this.gl.getParameter(s.GPU_DISJOINT_EXT)),i&&!this.disjoint}else{const n=this.getQueryTimerExtensionWebGL1(),s=n.getQueryObjectEXT(e,n.QUERY_RESULT_AVAILABLE_EXT);return this.disjoint==null&&(this.disjoint=this.gl.getParameter(n.GPU_DISJOINT_EXT)),s&&!this.disjoint}}pollFence(e){return new Promise(t=>{this.addItemToPoll(()=>e.isFencePassed(),()=>t())})}pollItems(){const e=B6(this.itemsToPoll.map(t=>t.isDoneFn));for(let t=0;t<=e;++t){const{resolveFn:n}=this.itemsToPoll[t];n()}this.itemsToPoll=this.itemsToPoll.slice(e+1)}addItemToPoll(e,t){if(this.itemsToPoll.push({isDoneFn:e,resolveFn:t}),this.itemsToPoll.length>1)return;$t(()=>(this.pollItems(),this.itemsToPoll.length===0))}bindTextureToFrameBuffer(e){this.throwIfDisposed(),$S(this.gl,e,this.framebuffer),this.debug&&Ym(this.gl)}unbindTextureToFrameBuffer(){this.outputTexture!=null?($S(this.gl,this.outputTexture,this.framebuffer),this.debug&&Ym(this.gl)):IC(this.gl,this.framebuffer)}downloadMatrixDriver(e,t){this.bindTextureToFrameBuffer(e);const n=t();return this.unbindTextureToFrameBuffer(),n}setOutputMatrixTextureDriver(e,t,n){this.throwIfDisposed();const s=this.gl;$S(s,e,this.framebuffer),this.debug&&Ym(s),this.outputTexture=e,Ee(s,()=>s.viewport(0,0,t,n)),Ee(s,()=>s.scissor(0,0,t,n))}setOutputMatrixWriteRegionDriver(e,t,n,s){this.throwIfDisposed(),Ee(this.gl,()=>this.gl.scissor(e,t,n,s))}throwIfDisposed(){if(this.disposed)throw new Error("Attempted to use disposed GPGPUContext.")}throwIfNoProgram(){if(this.program==null)throw new Error("No GPU program is currently set.")}}function B6(e){let t=0;for(;t<e.length;++t){const n=e[t]();if(!n)break}return t-1}function M6(e,t,n,s){const i=t.userCode,o=n.map((w,L)=>{const T={logicalShape:w.shape,texShape:w.isUniform?null:w.texData.texShape,isUniform:w.isUniform,isPacked:w.isUniform?!1:w.texData.isPacked,flatOffset:null};return w.texData!=null&&w.texData.slice!=null&&w.texData.slice.flatOffset>0&&(T.flatOffset=w.texData.slice.flatOffset),{name:t.variableNames[L],shapeInfo:T}}),a=o.map(w=>w.shapeInfo),c={logicalShape:s.shape,texShape:s.texData.texShape,isUniform:!1,isPacked:s.texData.isPacked,flatOffset:null},h=z5(o,c,i,t.packedInputs),p=e.createProgram(h);let m=null;const y=e.getUniformLocation(p,"NAN",!1);ae().getNumber("WEBGL_VERSION")===1&&(m=e.getUniformLocation(p,"INFINITY",!1));const b={};for(let w=0;w<t.variableNames.length;w++){const L=t.variableNames[w],T=!1;b[L]=e.getUniformLocation(p,L,T),b[`offset${L}`]=e.getUniformLocation(p,`offset${L}`,T)}return{program:t,source:h,webGLProgram:p,uniformLocations:b,inShapeInfos:a,outShapeInfo:c,infLoc:m,nanLoc:y}}function GC(e,t){if(e.length!==t.length)throw Error(`Binary was compiled with ${e.length} inputs, but was executed with ${t.length} inputs`);e.forEach((n,s)=>{const i=n.logicalShape,o=t[s],a=o.shape;if(!ie(i,a))throw Error(`Binary was compiled with different shapes than the current args. Shapes ${i} and ${a} must match`);if(n.isUniform&&o.isUniform)return;const c=n.texShape,h=o.isUniform?null:o.texData.texShape;if(!ie(c,h))throw Error(`Binary was compiled with different texture shapes than the current args. Shape ${c} and ${h} must match`)})}function P6(e,t,n,s,i){GC(t.inShapeInfos,n),GC([t.outShapeInfo],[s]);const o=s.texData.texture,a=s.texData.texShape;s.texData.isPacked?e.setOutputPackedMatrixTexture(o,a[0],a[1]):e.setOutputMatrixTexture(o,a[0],a[1]),e.setProgram(t.webGLProgram),ae().getNumber("WEBGL_VERSION")===1&&(t.infLoc!==null&&e.gl.uniform1f(t.infLoc,Infinity)),t.nanLoc!==null&&e.gl.uniform1f(t.nanLoc,NaN),n.forEach((c,h)=>{const p=t.program.variableNames[h],m=t.uniformLocations[p],y=t.uniformLocations[`offset${p}`];if(m==null)return;if(c.isUniform){if(M(c.shape)<2)e.gl.uniform1f(m,c.uniformValues[0]);else{let b=c.uniformValues;b instanceof Float32Array||(b=new Float32Array(b)),e.gl.uniform1fv(m,b)}return}c.texData.slice!=null&&y!=null&&e.gl.uniform1i(y,c.texData.slice.flatOffset),e.setInputMatrixTexture(c.texData.texture,m,h)}),i!=null&&i(e,t.webGLProgram),e.executeProgram()}function z6(e,t,n){let s="";t.concat(n).forEach(a=>{const c=a.texData!=null&&a.texData.slice!=null&&a.texData.slice.flatOffset>0,h=a.isUniform?"uniform":a.texData.texShape;s+=`${a.shape}_${h}_${c}`});const i=e.userCode;let o=e.constructor.name;return o+="_"+s+"_"+i,o}class V6{constructor(e,t,n){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e;const{filterWidth:s,inChannels:i,strideWidth:o,strideHeight:a,padInfo:c,outWidth:h,dilationWidth:p,dilationHeight:m,dataFormat:y}=n,{left:b,top:w}=c,L=i*s,T=Vn(),v=y==="channelsLast",C=v?0:1,O=v?1:2;let D="";for(let k=0;k<=1;k++)for(let F=0;F<=1;F++)D+=`
blockIndex = rc.y + ${F};
pos = rc.x + ${k};
if(blockIndex < ${e[1]} && pos < ${e[0]}) {
offsetY = int(blockIndex / (${h})) * ${a} - ${w};
d0 = offsetY + ${m} * (pos / ${L});
if(d0 < ${t[C]} && d0 >= 0) {
offsetX = int(mod(float(blockIndex), ${h}.) * ${o}. - ${b}.);
d1 = offsetX + ${p} * (int(mod(float(pos), ${L}.) / ${i}.));
if(d1 < ${t[O]} && d1 >= 0) {
ch = int(mod(float(pos), ${i}.));
if (${v}) {
innerDims = vec2(d1, ch);
result[${k*2+F}] = getChannel(
getA(d0, int(innerDims.x),
int(innerDims.y)), innerDims);
} else {
innerDims = vec2(d0, d1);
result[${k*2+F}] = 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;
${D}
${T.output} = result;
}
`}}class G6{constructor(e,t,n,s,i){this.variableNames=["x"],this.outputShape=[];const o=t,a=e[3]-1;this.outputShape=e;let c;const h=`float(${n}) + float(${s}) * sum`;i===.5?c=`inversesqrt(${h})`:i===1?c=`1.0/(${h})`:c=`exp(log(${h}) * float(-${i}));`,this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int r = coords[1];
int c = coords[2];
int d = coords[3];
float x = getX(b, r, c, d);
float sum = 0.0;
for (int j = -${o}; j <= ${o}; j++) {
int idx = d + j;
if (idx >= 0 && idx <= ${a}) {
float z = getX(b, r, c, idx);
sum += z * z;
}
}
float val = x * ${c};
setOutput(val);
}
`}}class Y6{constructor(e,t,n,s,i){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=e,this.depth=e[3],this.depthRadius=t,this.bias=n,this.alpha=s,this.beta=i,this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int r = coords[1];
int c = coords[2];
float result = 0.0;
for (int d = 0; d < ${this.depth}; ++d) {
int depthBegin = int(max(0.0, float(d - ${t})));
int depthEnd = int(min(float(${this.depth}),
float(d + ${t} + 1)));
const int MIN_DEPTH_BEGIN = 0;
const int MAX_DEPTH_END = ${this.depth};
float norm = 0.0;
for (int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k) {
if (k < depthBegin){
continue;
}
else if (k >= depthBegin && k < depthEnd) {
norm += getInputImage(b, r, c, k) * getInputImage(b, r, c, k);
}
else {
break;
}
}
norm = float(${s}) * norm + float(${n});
for(int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k){
if (k < depthBegin){
continue;
}
else if (k >= depthBegin && k < depthEnd){
float dyi = -2.0 * float(${s})
* float(${i})
* getInputImage(b ,r ,c, k) * getOutputImage(b, r, c, d)
/ norm;
if (k == d) {
dyi += pow(norm, -1.0 * ${i});
}
if (k == coords[3]) {
dyi *= getDy(b, r, c, d);
result += dyi;
}
}
else {
break;
}
}
}
setOutput(result);
}
`}}class H6{constructor(e,t,n,s,i){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;const o=t,a=e[3]-1;this.outputShape=e;let c;const h=`float(${n}) + float(${s}) * sum`;i===.5?c=`inversesqrt(${h})`:i===1?c=`1.0/(${h})`:c=`exp(log(${h}) * float(-${i}));`,this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int b = coords.x;
int r = coords.y;
int c = coords.z;
int d = coords.w;
bool hasNextCol = d < ${this.outputShape[3]};
bool hasNextRow = c < ${this.outputShape[2]};
vec4 sum = vec4(0.);
vec4 xFragAtOutputCoords = getX(b, r, c, d);
vec4 xAtOutputCoords = vec4(
getChannel(xFragAtOutputCoords, vec2(c, d)),
hasNextCol ?
getChannel(xFragAtOutputCoords, vec2(c, d + 1)) : 0.0,
hasNextRow ?
getChannel(xFragAtOutputCoords , vec2(c + 1, d)) : 0.0,
(hasNextRow && hasNextCol) ?
getChannel(xFragAtOutputCoords, vec2(c + 1, d + 1)) : 0.0
);
int firstChannel = d - ${o};
vec2 cache = vec2(0.);
if(firstChannel >= 0){
vec4 firstChannelFrag = getX(b, r, c, firstChannel);
cache.x = getChannel(firstChannelFrag, vec2(c, firstChannel));
if(hasNextRow){
cache.y = getChannel(firstChannelFrag, vec2(c + 1, firstChannel));
}
}
ivec2 depth = ivec2(d, d + 1);
for (int j = - ${o}; j <= ${o}; j++) {
ivec2 idx = depth + j;
bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));
bvec2 belowUpperBound = lessThanEqual(idx, ivec2(${a}));
bool depthInRange = aboveLowerBound.x && belowUpperBound.x;
bool depthPlusOneInRange = aboveLowerBound.y && belowUpperBound.y;
if(depthInRange || depthPlusOneInRange){
vec4 z = vec4(0.);
vec4 xFragAtCurrentDepth;
z.xz = cache.xy;
if(depthPlusOneInRange && hasNextCol){
xFragAtCurrentDepth = idx.y != d ?
getX(b, r, c, idx.y) : xFragAtOutputCoords;
z.y = getChannel(xFragAtCurrentDepth, vec2(c, idx.y));
if(hasNextRow){
z.w = getChannel(xFragAtCurrentDepth, vec2(c + 1, idx.y));
}
}
cache.xy = z.yw;
sum += z * z;
}
}
vec4 result = xAtOutputCoords * ${c};
setOutput(result);
}
`}}class q6{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;const t=e.strideHeight,n=e.strideWidth,s=e.dilationHeight,i=e.effectiveFilterHeight,o=e.effectiveFilterWidth,a=i-1-e.padInfo.top,c=o-1-e.padInfo.left,h=i*o-1;this.userCode=`
const ivec2 pads = ivec2(${a}, ${c});
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 dyRCCorner = coords.yz - pads;
int dyRCorner = dyRCCorner.x;
int dyCCorner = dyRCCorner.y;
// Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wR = 0; wR < ${i};
wR += ${s}) {
float dyR = float(dyRCorner + wR) / ${t}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
for (int wC = 0; wC < ${o}; wC++) {
float dyC = float(dyCCorner + wC) / ${n}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
float dyValue = getDy(b, idyR, idyC, d);
int maxPosValue = ${h} - int(getMaxPos(b, idyR, idyC, d));
// Get the current value, check it against the value from the
// position matrix.
int curPosValue = wR * ${o} + wC;
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
dotProd += dyValue * mask;
}
}
setOutput(dotProd);
}
`}}class j6{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;const t=e.strideDepth,n=e.strideHeight,s=e.strideWidth,i=e.dilationDepth,o=e.dilationHeight,a=e.dilationWidth,c=e.effectiveFilterDepth,h=e.effectiveFilterHeight,p=e.effectiveFilterWidth,m=c-1-e.padInfo.front,y=h-1-e.padInfo.top,b=p-1-e.padInfo.left,w=c*h*p-1;this.userCode=`
const ivec3 pads = ivec3(${m}, ${y}, ${b});
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int ch = coords.u;
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
int dyDCorner = dyCorner.x;
int dyRCorner = dyCorner.y;
int dyCCorner = dyCorner.z;
// Convolve dy(?, ?, ?, ch) with pos mask(:, :, :, d) to get
// dx(xD, xR, xC, ch).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wD = 0; wD < ${c};
wD += ${i}) {
float dyD = float(dyDCorner + wD) / ${t}.0;
if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) {
continue;
}
int idyD = int(dyD);
for (int wR = 0; wR < ${h};
wR += ${o}) {
float dyR = float(dyRCorner + wR) / ${n}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
for (int wC = 0; wC < ${p};
wC += ${a}) {
float dyC = float(dyCCorner + wC) / ${s}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
float dyValue = getDy(batch, idyD, idyR, idyC, ch);
int maxPosValue = ${w} -
int(getMaxPos(batch, idyD, idyR, idyC, ch));
// Get the current value, check it against the value from the
// position matrix.
int curPosValue =
wD * ${h} * ${p} +
wR * ${p} + wC;
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
dotProd += dyValue * mask;
}
}
}
setOutput(dotProd);
}
`}}class zS{constructor(e,t,n,s=!1,i=!1,o=!1,a=null,c=!1){this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=n;const h=s?e[1]:e[2],p=Math.ceil(h/2),m=s?"i * 2, rc.y":"rc.y, i * 2",y=i?"rc.z, i * 2":"i * 2, rc.z",b=s?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],w=i?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"];let L="",T="";a&&(c?L=`vec4 activation(vec4 a) {
vec4 b = getPreluActivationWeightsAtOutCoords();
${a}
}`:L=`vec4 activation(vec4 x) {
${a}
}`,T="result = activation(result);");const v=o?"result += getBiasAtOutCoords();":"";o&&this.variableNames.push("bias"),c&&this.variableNames.push("preluActivationWeights");let C="rc.x",O="rc.x";e[0]<t[0]?C=`int(min(float(rc.x), ${e[0]-1}.))`:t[0]<e[0]&&(O=`int(min(float(rc.x), ${t[0]-1}.))`),this.userCode=`
${L}
const float sharedDimension = ${p}.0;
vec4 dot2x2ARowBCol(ivec3 rc) {
vec4 result = vec4(0);
for (int i = 0; i < ${p}; i++) {
int batchA = ${C};
int batchB = ${O};
vec4 a = getMatrixA(batchA, ${m});
vec4 b = getMatrixB(batchB, ${y});
// These swizzled products need to be separately added.
// See: https://github.com/tensorflow/tfjs/issues/1735
result += (${b[0]} * ${w[0]});
result += (${b[1]} * ${w[1]});
}
return result;
}
void main() {
ivec3 rc = getOutputCoords();
vec4 result = dot2x2ARowBCol(rc);
${v}
${T}
setOutput(result);
}
`}}class K6{constructor(e,t,n){this.variableNames=["probs"],this.outputShape=[e,n],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,n)=>{this.seedLoc==null&&(this.seedLoc=t.getUniformLocation(n,"seed")),t.gl.uniform1f(this.seedLoc,e)}}}class X6{constructor(e,t,n,s){this.variableNames=["indices"],this.outputShape=[e,t],this.userCode=`
void main() {
ivec2 coords = getOutputCoords();
int index = round(getIndices(coords.x));
setOutput(mix(float(${s}), float(${n}),
float(index == coords.y)));
}
`}}class J6{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outputShape=e;const t=e.length;if(t===0)this.userCode=`
void main() {
setOutput(vec4(getA(), 0., 0., 0.));
}
`;else{const n=zn("rc",t),s=Rt(t),i=Q6(t,e,n),o=e7(t,e[e.length-1],e[e.length-2],n),a=t7(e,n);this.userCode=`
void main() {
${s} rc = getOutputCoords();
if(${i}) {
setOutput(vec4(0));
} else {
${o}
setOutput(vec4(${a}));
}
}
`}}}function Z6(e,t){const n=[];for(let s=0;s<=1;s++)for(let i=0;i<=1;i++){let o=`${s===0?"r":"rp1"}, ${i===0?"c":"cp1"}`;for(let a=2;a<e;a++)o=`${t[t.length-1-a]},`+o;n.push(o)}return n}function Q6(e,t,n){if(e===1)return`rc > ${t[0]}`;let s="";for(let i=e-2;i<e;i++)s+=`${n[i]} >= ${t[i]}`,i<e-1&&(s+="||");return s}function e7(e,t,n,s){if(e===1)return"";const i=s.slice(-2);return`
int r = ${i[0]};
int c = ${i[1]};
int rp1 = r + 1;
int cp1 = c + 1;
bool cEdge = cp1 >= ${t};
bool rEdge = rp1 >= ${n};
`}function t7(e,t){const n=e.length,s=Z6(n,t);return n===1?`getA(rc),
rc + 1 >= ${e[0]} ? 0. : getA(rc + 1),
0, 0`:`getA(${s[0]}),
cEdge ? 0. : getA(${s[1]}),
rEdge ? 0. : getA(${s[2]}),
rEdge || cEdge ? 0. : getA(${s[3]})`}class n7{constructor(e,t,n){this.variableNames=["x"],this.outputShape=t.map((h,p)=>h[0]+e[p]+h[1]);const s=e.length,i=Rt(s),o=t.map(h=>h[0]).join(","),a=t.map((h,p)=>h[0]+e[p]).join(","),c=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,s);if(s===1){this.userCode=`
int start = ${o};
int end = ${a};
void main() {
int outC = getOutputCoords();
if (outC < start || outC >= end) {
setOutput(float(${n}));
} else {
setOutput(getX(outC - start));
}
}
`;return}this.userCode=`
${i} start = ${i}(${o});
${i} end = ${i}(${a});
void main() {
${i} outC = getOutputCoords();
if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {
setOutput(float(${n}));
} else {
${i} coords = outC - start;
setOutput(getX(${c}));
}
}
`}}class s7{constructor(e,t,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.map((L,T)=>L[0]+e[T]+L[1]);const s=e.length,i=Rt(s),o=t.map(L=>L[0]).join(","),a=t.map((L,T)=>L[0]+e[T]).join(","),c=zn("rc",s),h=zn("source",s),p=`${c[s-1]} < ${this.outputShape[s-1]}`,m=s===1?"source":`vec2(${h.slice(-2).join()})`,y=[`${i} rc = outputLoc;`,`${c[s-1]} += 1;
if(${p}) {
`,s===1?"":`}
rc = outputLoc;
${c[s-2]} += 1;
if(${c[s-2]} < ${this.outputShape[s-2]}) {`,s===1?"":` ${c[s-1]} += 1;
if(${p}) {`],b=s===1?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))";let w="";for(let L=0,T=s===1?2:4;L<T;L++)w+=`
${y[L]}
if (${b}) {
result[${L}] = float(${n});
} else {
${i} source = rc - start;
result[${L}] = getChannel(getX(${h.join()}), ${m});
}
`;w+=s===1?"} ":"}}",this.userCode=`
const ${i} start = ${i}(${o});
const ${i} end = ${i}(${a});
void main() {
${i} outputLoc = getOutputCoords();
vec4 result = vec4(0.);
${w}
setOutput(result);
}
`}}class Cu{constructor(e,t,n,s=!1,i=!1){if(this.variableNames=["x"],t==="avg"&&n)throw new Error("Cannot compute positions for average pool.");const o=e.filterWidth,a=e.strideHeight,c=e.strideWidth,h=e.dilationHeight,p=e.dilationWidth,m=e.effectiveFilterHeight,y=e.effectiveFilterWidth,b=e.padInfo.top,w=e.padInfo.left;this.outputShape=e.outShape;const L=t==="avg",T=`((batch * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + d`,v=`(xR * ${e.inWidth} + xC) * ${e.inChannels} + d`;let C="0.0";if(L||(C="-1.0 / 1e-20"),n){const $=">=";this.userCode=`
const ivec2 strides = ivec2(${a}, ${c});
const ivec2 pads = ivec2(${b}, ${w});
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d = coords[3];
ivec2 xRCCorner = coords.yz * strides - pads;
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
// max/min x(?, ?, d) to get y(yR, yC, d).
// ? = to be determined
float minMaxValue = 0.0;
float minMaxValueFound = 0.0;
int minMaxPosition = 0;
float avgValue = 0.0;
for (int wR = 0; wR < ${m};
wR += ${h}) {
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int wC = 0; wC < ${y};
wC += ${p}) {
int xC = xCCorner + wC;
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
float value = getX(batch, xR, xC, d);
// If a min / max value has already been found, use it. If not,
// use the current value.
float currMinMaxValue = mix(
value, minMaxValue, minMaxValueFound);
if (value ${$} currMinMaxValue) {
minMaxValue = value;
minMaxValueFound = 1.0;
minMaxPosition = ${s?i?T:v:`wR * ${y} + wC`};
}
}
}
setOutput(float(minMaxPosition));
}
`;return}const O="max";let D=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(D="avgValue / count");const k=Math.floor(o/4)*4,F=o%4,B=`
if (${L}) {
avgValue += dot(values, ones);
} else {
minMaxValue = ${O}(values, minMaxValue);
}
`;this.userCode=`
const ivec2 strides = ivec2(${a}, ${c});
const ivec2 pads = ivec2(${b}, ${w});
const float initializationValue = ${C};
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(${C});
float avgValue = 0.0;
count = 0.0;
for (int wR = 0; wR < ${m};
wR += ${h}) {
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int wC = 0; wC < ${k}; wC += 4) {
int xC = xCCorner + wC * ${p};
vec4 values = vec4(
getValue(batch, xR, xC, d),
getValue(batch, xR, xC + ${p}, d),
getValue(batch, xR, xC + 2 * ${p}, d),
getValue(batch, xR, xC + 3 * ${p}, d)
);
${B}
}
int xC = xCCorner + ${k};
if (${F===1}) {
vec4 values = vec4(
getValue(batch, xR, xC, d),
initializationValue,
initializationValue,
initializationValue
);
${B}
} else if (${F===2}) {
vec4 values = vec4(
getValue(batch, xR, xC, d),
getValue(batch, xR, xC + ${p}, d),
initializationValue,
initializationValue
);
${B}
} else if (${F===3}) {
vec4 values = vec4(
getValue(batch, xR, xC, d),
getValue(batch, xR, xC + ${p}, d),
getValue(batch, xR, xC + 2 * ${p}, d),
initializationValue
);
${B}
}
}
setOutput(${D});
}
`}}class VS{constructor(e,t,n,s=!1,i=!1){if(this.variableNames=["x"],t==="avg"&&n)throw new Error("Cannot compute positions for average pool.");const o=e.filterWidth,a=e.strideDepth,c=e.strideHeight,h=e.strideWidth,p=e.dilationDepth,m=e.dilationHeight,y=e.dilationWidth,b=e.effectiveFilterDepth,w=e.effectiveFilterHeight,L=e.effectiveFilterWidth,T=e.padInfo.front,v=e.padInfo.top,C=e.padInfo.left;this.outputShape=e.outShape;const O=t==="avg";let D="0.0";if(O||(D="-1.0 / 1e-20"),n){const j=">=";this.userCode=`
const ivec3 strides =
ivec3(${a}, ${c}, ${h});
const ivec3 pads = ivec3(${T}, ${v}, ${C});
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int ch = coords.u;
ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
int xDCorner = xCorner.x;
int xRCorner = xCorner.y;
int xCCorner = xCorner.z;
// max/min x(?, ?, ?, ch) to get y(yD, yR, yC, ch).
// ? = to be determined
float minMaxValue = 0.0;
float minMaxValueFound = 0.0;
int minMaxPosition = 0;
for (int wD = 0; wD < ${b};
wD += ${p}) {
int xD = xDCorner + wD;
if (xD < 0 || xD >= ${e.inDepth}) {
continue;
}
for (int wR = 0; wR < ${w};
wR += ${m}) {
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int wC = 0; wC < ${L};
wC += ${y}) {
int xC = xCCorner + wC;
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
float value = getX(batch, xD, xR, xC, ch);
// If a min / max value has already been found, use it. If not,
// use the current value.
float currMinMaxValue = mix(
value, minMaxValue, minMaxValueFound);
if (value ${j} currMinMaxValue) {
minMaxValue = value;
minMaxValueFound = 1.0;
minMaxPosition = ${s?i?`(((batch * ${e.inDepth} + xD) * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch`:`((xD * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch`:`wD * ${w} * ${L} +
wR * ${L} + wC`};
}
}
}
}
setOutput(float(minMaxPosition));
}
`;return}const k="max";let F=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(F="avgValue / count");const B=Math.floor(o/4)*4,$=o%4,Y=`
if (${O}) {
avgValue += dot(values, ones);
} else {
minMaxValue = ${k}(values, minMaxValue);
}
`;this.userCode=`
const ivec3 strides =
ivec3(${a}, ${c}, ${h});
const ivec3 pads = ivec3(${T}, ${v}, ${C});
const float initializationValue = ${D};
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
float count = 0.0;
float getValue(int batch, int xD, int xR, int xC, int ch) {
if (xC < 0 || xC >= ${e.inWidth}) {
return initializationValue;
}
count += 1.0;
return getX(batch, xD, xR, xC, ch);
}
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int ch = coords.u;
ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
int xDCorner = xCorner.x;
int xRCorner = xCorner.y;
int xCCorner = xCorner.z;
// max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch).
// ? = to be determined
vec4 minMaxValue = vec4(${D});
float avgValue = 0.0;
count = 0.0;
for (int wD = 0; wD < ${b};
wD += ${p}) {
int xD = xDCorner + wD;
if (xD < 0 || xD >= ${e.inDepth}) {
continue;
}
for (int wR = 0; wR < ${w};
wR += ${m}) {
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int wC = 0; wC < ${B}; wC += 4) {
int xC = xCCorner + wC * ${y};
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
getValue(batch, xD, xR, xC + ${y}, ch),
getValue(batch, xD, xR, xC + 2 * ${y}, ch),
getValue(batch, xD, xR, xC + 3 * ${y}, ch)
);
${Y}
}
int xC = xCCorner + ${B};
if (${$===1}) {
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
initializationValue,
initializationValue,
initializationValue
);
${Y}
} else if (${$===2}) {
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
getValue(batch, xD, xR, xC + ${y}, ch),
initializationValue,
initializationValue
);
${Y}
} else if (${$===3}) {
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
getValue(batch, xD, xR, xC + ${y}, ch),
getValue(batch, xD, xR, xC + 2 * ${y}, ch),
initializationValue
);
${Y}
}
}
setOutput(${F});
}
}
`}}class YC{constructor(e,t){this.variableNames=["x"];const{windowSize:n,batchSize:s,inSize:i,outSize:o}=e;this.outputShape=[s,o];let a="0.0",c="";t==="prod"?a="1.0":t==="min"?(a="1.0 / 1e-20",c="min"):t==="max"&&(a="-1.0 / 1e-20",c="max");let h=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="sum"?h="sumValue":t==="prod"?h="prodValue":t==="all"?h="allValue":t==="any"&&(h="anyValue");const p=Math.floor(n/4)*4,m=n%4;let y=`
if (${t==="sum"}) {
sumValue += dot(values, ones);
} else if (${t==="prod"}) {
vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);
prodValue *= tmp[0] * tmp[1];
} else {
minMaxValue = ${c}(values, minMaxValue);
}
`,b="vec4";t==="all"?(a="1.0",y=`
bool reducedAllValue = all(values);
float floatedReducedAllValue = float(reducedAllValue);
allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);
`,b="bvec4"):t==="any"&&(a="0.0",y=`
bool reducedAnyValue = any(values);
float floatedReducedAnyValue = float(reducedAnyValue);
anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);
`,b="bvec4");let w="";i%n>0&&(w=`
if (inIdx < 0 || inIdx >= ${i}) {
return initializationValue;
}
`),this.userCode=`
const float initializationValue = ${a};
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
float getValue(int batch, int inIdx) {
${w}
return getX(batch, inIdx);
}
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
int inOffset = outIdx * ${n};
vec4 minMaxValue = vec4(${a});
float prodValue = 1.0;
float sumValue = 0.0;
float allValue = 1.0;
float anyValue = 0.0;
for (int i = 0; i < ${p}; i += 4) {
int inIdx = inOffset + i;
${b} values = ${b}(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
getValue(batch, inIdx + 3)
);
${y}
}
int inIdx = inOffset + ${p};
if (${m===1}) {
${b} values = ${b}(
getValue(batch, inIdx),
initializationValue,
initializationValue,
initializationValue
);
${y}
} else if (${m===2}) {
${b} values = ${b}(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
initializationValue,
initializationValue
);
${y}
} else if (${m===3}) {
${b} values = ${b}(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
initializationValue
);
${y}
}
setOutput(${h});
}
`}}class HC{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e;let n="";for(let s=0;s<4;s++){let i="thisRC = rc;";s%2===1&&(i+="thisRC.z += 1;"),s>1&&(i+="thisRC.y += 1;"),n+=`
${i}
${s>0?"if(thisRC.y < rows && thisRC.z < cols){":""}
int flatIndex = getFlatIndex(thisRC);
ivec3 inputRC = inputCoordsFromReshapedOutCoords(flatIndex);
vec2 inputRCInnerDims = vec2(float(inputRC.y),float(inputRC.z));
result[${s}] =
getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);
${s>0?"}":""}
`}this.userCode=`
${i7(t)}
${PS(e)}
void main() {
ivec3 rc = getOutputCoords();
vec4 result = vec4(0.);
ivec3 thisRC;
int rows = ${e[1]};
int cols = ${e[2]};
${n}
setOutput(result);
}
`}}function i7(e){const t=na(["r","c","d"],e);return`
ivec3 inputCoordsFromReshapedOutCoords(int index) {
${t}
return ivec3(r, c, d);
}
`}class r7{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t.shape;const[,s,i]=t.shape,[,o,a]=e.shape,c=[n&&o>1?s-1:s,n&&a>1?i-1:i],h=[n&&o>1?o-1:o,n&&a>1?a-1:a],p=c[0]/h[0],m=c[1]/h[1],y=1/p,b=1/m,w=Math.ceil(y)*2+2,L=Math.ceil(b)*2+2;this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
int r = coords[1];
int c = coords[2];
float accumulator = 0.0;
const float heightScale = float(${p});
const float widthScale = float(${m});
const float invHeightScale = float(${y});
const float invWidthScale = float(${b});
const int winHeight = int(${w});
const int winWidth = int(${L});
// Compute bounds for where in dy we will look
float startRLerp = floor(float(r) * invHeightScale);
int startDyR = int(startRLerp - float(winHeight / 2));
float startCLerp = floor(float(c) * invWidthScale);
int startDyC = int(startCLerp - float(winWidth / 2));
// Loop over dy
for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {
int dyR = dyROffset + startDyR;
// Guard against the window exceeding the bounds of dy
if (dyR < 0 || dyR >= ${o}) {
continue;
}
for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {
int dyC = dyCOffset + startDyC;
// Guard against the window exceeding the bounds of dy
if (dyC < 0 || dyC >= ${a}) {
continue;
}
float dxR = float(dyR) * heightScale;
int topDxRIndex = int(floor(dxR));
int bottomDxRIndex = int(min(ceil(dxR), ${s-1}.0));
float dxRLerp = dxR - float(topDxRIndex);
float inverseDxRLerp = 1.0 - dxRLerp;
float dxC = float(dyC) * widthScale;
int leftDxCIndex = int(floor(dxC));
int rightDxCIndex = int(min(ceil(dxC), ${i-1}.0));
float dxCLerp = dxC - float(leftDxCIndex);
float inverseDxCLerp = 1.0 - dxCLerp;
if (r == topDxRIndex && c == leftDxCIndex) {
// topLeft
accumulator +=
getDy(b, dyR, dyC, d) * inverseDxRLerp * inverseDxCLerp;
}
if (r == topDxRIndex && c == rightDxCIndex) {
// topRight
accumulator += getDy(b, dyR, dyC, d) * inverseDxRLerp * dxCLerp;
}
if (r == bottomDxRIndex && c == leftDxCIndex) {
// bottomLeft
accumulator += getDy(b, dyR, dyC, d) * dxRLerp * inverseDxCLerp;
}
if (r == bottomDxRIndex && c == rightDxCIndex) {
// bottomRight
accumulator += getDy(b, dyR, dyC, d) * dxRLerp * dxCLerp;
}
}
}
// End loop over dy
setOutput(accumulator);
}
`}}class o7{constructor(e,t,n,s){this.variableNames=["A"],this.outputShape=[];const[i,o,a,c]=e;this.outputShape=[i,t,n,c];const h=[s&&t>1?o-1:o,s&&n>1?a-1:a],p=[s&&t>1?t-1:t,s&&n>1?n-1:n];this.userCode=`
const vec2 effectiveInputOverOutputRatioRC = vec2(
${h[0]/p[0]},
${h[1]/p[1]});
const vec2 inputShapeRC = vec2(${o}.0, ${a}.0);
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 yRC = coords.yz;
// Fractional source index.
vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;
// Compute the four integer indices.
ivec2 sourceFloorRC = ivec2(sourceFracIndexRC);
ivec2 sourceCeilRC = ivec2(
min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));
float topLeft = getA(b, sourceFloorRC.x, sourceFloorRC.y, d);
float bottomLeft = getA(b, sourceCeilRC.x, sourceFloorRC.y, d);
float topRight = getA(b, sourceFloorRC.x, sourceCeilRC.y, d);
float bottomRight = getA(b, sourceCeilRC.x, sourceCeilRC.y, d);
vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC);
float top = topLeft + (topRight - topLeft) * fracRC.y;
float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;
float newValue = top + (bottom - top) * fracRC.x;
setOutput(newValue);
}
`}}class a7{constructor(e,t,n,s){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];const[i,o,a,c]=e;this.outputShape=[i,t,n,c];const h=[s&&t>1?o-1:o,s&&n>1?a-1:a],p=[s&&t>1?t-1:t,s&&n>1?n-1:n];this.userCode=`
const vec3 effectiveInputOverOutputRatioRC = vec3(
${h[0]/p[0]},
${h[1]/p[1]},
${h[1]/p[1]});
const vec3 inputShapeRC = vec3(${o}.0, ${a}.0,
${a}.0);
float getAValue(int b, int r, int c, int d) {
return getChannel(getA(b, r, c, d), vec2(c, d));
}
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
// Calculate values for next column in yRC.z.
ivec3 yRC = coords.yzz + ivec3(0, 0, 1);
// Fractional source index.
vec3 sourceFracIndexRC = vec3(yRC) * effectiveInputOverOutputRatioRC;
// Compute the four integer indices.
ivec3 sourceFloorRC = ivec3(sourceFracIndexRC);
ivec3 sourceCeilRC = ivec3(
min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));
// Should we calculate next column and row elements in 2x2 packed cell.
bool hasNextCol = d < ${c-1};
bool hasNextRow = coords.z < ${n-1};
// In parallel, construct four corners for all four components in
// packed 2x2 cell.
vec4 topLeft = vec4(
getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d),
hasNextCol ? getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d + 1)
: 0.0,
hasNextRow ? getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d)
: 0.0,
(hasNextRow && hasNextCol) ?
getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d + 1) : 0.0);
vec4 bottomLeft = vec4(
getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d),
hasNextCol ? getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d + 1)
: 0.0,
hasNextRow ? getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d)
: 0.0,
(hasNextRow && hasNextCol) ?
getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d + 1) : 0.0);
vec4 topRight = vec4(
getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d),
hasNextCol ? getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d + 1)
: 0.0,
hasNextRow ? getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d)
: 0.0,
(hasNextRow && hasNextCol) ?
getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d + 1) : 0.0);
vec4 bottomRight = vec4(
getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d),
hasNextCol ? getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d + 1)
: 0.0,
hasNextRow ? getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d)
: 0.0,
(hasNextRow && hasNextCol) ?
getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d + 1) : 0.0);
vec3 fracRC = sourceFracIndexRC - vec3(sourceFloorRC);
vec4 top = mix(topLeft, topRight, fracRC.yyzz);
vec4 bottom = mix(bottomLeft, bottomRight, fracRC.yyzz);
vec4 newValue = mix(top, bottom, fracRC.x);
setOutput(newValue);
}
`}}class c7{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t.shape;const[,s,i]=t.shape,[,o,a]=e.shape,c=[n&&o>1?s-1:s,n&&a>1?i-1:i],h=[n&&o>1?o-1:o,n&&a>1?a-1:a],p=c[0]/h[0],m=c[1]/h[1],y=1/p,b=1/m,w=Math.ceil(y)*2+2,L=Math.ceil(b)*2+2;this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
int r = coords[1];
int c = coords[2];
float accumulator = 0.0;
const float heightScale = float(${p});
const float widthScale = float(${m});
const float invHeightScale = float(${y});
const float invWidthScale = float(${b});
const int winHeight = int(${w});
const int winWidth = int(${L});
// Compute bounds for where in dy we will look
float startRLerp = floor(float(r) * invHeightScale);
int startDyR = int(floor(startRLerp - float(winHeight / 2)));
float startCLerp = floor(float(c) * invWidthScale);
int startDyC = int(floor(startCLerp - float(winWidth / 2)));
// Loop over dy
for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {
int dyR = dyROffset + startDyR;
// Guard against the window exceeding the bounds of dy
if (dyR < 0 || dyR >= ${o}) {
continue;
}
for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {
int dyC = dyCOffset + startDyC;
// Guard against the window exceeding the bounds of dy
if (dyC < 0 || dyC >= ${a}) {
continue;
}
float sourceFracRow =
float(${c[0]}) *
(float(dyR) / float(${h[0]}));
float sourceFracCol =
float(${c[1]}) *
(float(dyC) / float(${h[1]}));
int sourceNearestRow = int(min(
float(int(${s}) - 1),
${n} ? float(round(sourceFracRow)) :
float(floor(sourceFracRow))));
int sourceNearestCol = int(min(
float(int(${i}) - 1),
${n} ? float(round(sourceFracCol)) :
float(floor(sourceFracCol))));
if (r == sourceNearestRow && c == sourceNearestCol) {
accumulator += getDy(b, dyR, dyC, d);
}
}
}
// End loop over dy
setOutput(accumulator);
}
`}}class l7{constructor(e,t,n,s){this.variableNames=["A"],this.outputShape=[];const[i,o,a,c]=e;this.outputShape=[i,t,n,c];const h=[s&&t>1?o-1:o,s&&n>1?a-1:a],p=[s&&t>1?t-1:t,s&&n>1?n-1:n],m=s?"0.5":"0.0";this.userCode=`
const vec2 effectiveInputOverOutputRatioRC = vec2(
${h[0]/p[0]},
${h[1]/p[1]});
const vec2 inputShapeRC = vec2(${o}.0, ${a}.0);
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 yRC = coords.yz;
// Fractional source index.
vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;
// Compute the coordinators of nearest neighbor point.
ivec2 sourceNearestRC = ivec2(
min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${m})));
float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);
setOutput(newValue);
}
`}}class h7{constructor(e,t){this.variableNames=["x"];const n=e.length;if(n>4)throw new Error(`WebGL backend: Reverse of rank-${n} tensor is not yet supported`);if(this.outputShape=e,n===1){this.userCode=`
void main() {
int coord = getOutputCoords();
setOutput(getX(${e[0]} - coord - 1));
}
`;return}const s=a=>t.indexOf(a)!==-1&&e[a]!==1?`${e[a]} - coords[${a}] - 1`:`coords[${a}]`,i=e.map((a,c)=>s(c)).join(","),o=Rt(n);this.userCode=`
void main() {
${o} coords = getOutputCoords();
setOutput(getX(${i}));
}
`}}class u7{constructor(e,t){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;const n=e.length;if(n>4)throw new Error(`WebGL backend: Reverse of rank-${n} tensor is not yet supported`);this.outputShape=e;const s=zn("rc",n),i=`${s[n-1]} + 1 < ${this.outputShape[n-1]}`,o=`${s[n-2]} + 1 < ${this.outputShape[n-2]}`,a=Rt(n);n===1?this.userCode=`
void main(){
int rc = getOutputCoords();
vec4 result = vec4(0.);
result.r = getChannel(getX(${e[0]} - rc - 1),
${e[0]} - rc - 1);
if(${i}){
result.g = getChannel(getX(${e[0]} - (rc + 1) - 1),
${e[0]} - (rc + 1) - 1);
}
setOutput(result);
}
`:this.userCode=`
void main() {
${a} rc = getOutputCoords();
vec4 result = vec4(0.);
result.r = ${c(s.slice())};
if(${i}){
result.g = ${h(s.slice())};
}
if(${o}) {
result.b = ${p(s.slice())};
if(${i}) {
result.a = ${m(s.slice())};
}
}
setOutput(result);
}
`;function c(w){return y(w)}function h(w){return w[n-1]="("+w[n-1]+" + 1)",y(w)}function p(w){return w[n-2]="("+w[n-2]+" + 1)",y(w)}function m(w){return w[n-1]="("+w[n-1]+" + 1)",w[n-2]="("+w[n-2]+" + 1)",y(w)}function y(w){const L=e.map((C,O)=>b(O,w)),T=L.join(","),v=L.slice(-2).join(",");return`getChannel(getX(${T}), vec2(${v}))`}function b(w,L){return t.indexOf(w)!==-1&&e[w]!==1?`${e[w]} - ${L[w]} - 1`:`${L[w]}`}}}class qC{constructor(e,t,n,s,i,o,a=!0){this.variableNames=["updates","indices","defaultValue"],this.outputShape=o;const c=Rt(i.length),h=Rt(o.length);let p="";n===1?p="i":n===2&&(p="i, j");const m=`getIndices(${p})`;let y="";s===1?y="i":s===2&&(y="i, coords[1]");const b=`getUpdates(${y})`,w=t>1?"strides[j]":"strides";this.userCode=`
${c} strides = ${c}(${i});
void main() {
${h} 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(${m});
flattenedIndex += index * ${w};
}
if (flattenedIndex == coords[0]) {
sum += ${b};
found = true;
}
}
setOutput(mix(getDefaultValue(), sum, float(found)));
}
`}}class d7{constructor(e,t){this.variableNames=["x","segmentIds"];const n=e.windowSize,s=e.batchSize,i=e.inSize,o=e.numSegments,a=o*Math.ceil(i/n);this.outputShape=[s,a];const c="0.0",h="sumValue",p=Math.floor(n/4)*4,m=n%4,y=`
sumValue += dot(values, segFilter);
`;let b="";i%n>0&&(b=`
if (inIdx < 0 || inIdx >= ${i}) {
return initializationValue;
}
`);let w="";i%n>0&&(w=`
if (inIdx < 0 || inIdx >= ${i}) {
return -1.0;
}
`),this.userCode=`
const float initializationValue = ${c};
float getValue(int batch, int inIdx) {
${b}
return getX(batch, inIdx);
}
float getSegmentIdAtIndex(int inIdx) {
${w}
return getSegmentIds(inIdx);
}
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
int inOffset = int(floor(float(outIdx) / float(
${o})) * float(${n}));
int currentSeg = int(mod(float(outIdx), float(${o})));
float sumValue = 0.0;
for (int i = 0; i < ${p}; i += 4) {
int inIdx = inOffset + i;
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
getValue(batch, inIdx + 3)
);
vec4 segFilter = vec4(
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 3)) == currentSeg ? 1 : 0
);
${y}
}
int inIdx = inOffset + ${p};
if (${m===1}) {
vec4 values = vec4(
getValue(batch, inIdx),
initializationValue,
initializationValue,
initializationValue
);
int inIdxSeg = int(getSegmentIdAtIndex(inIdx));
vec4 segFilter = vec4(
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
0,
0,
0
);
${y}
} else if (${m===2}) {
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
initializationValue,
initializationValue
);
vec4 segFilter = vec4(
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
0,
0
);
${y}
} else if (${m===3}) {
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
initializationValue
);
vec4 segFilter = vec4(
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,
0
);
${y}
}
setOutput(${h});
}
`}}class p7{constructor(e,t,n){this.variableNames=["c","a","b"],this.outputShape=t;let s,i;if(n>4)throw Error(`Where for rank ${n} is not yet supported`);if(n===1)i="resRC",s="resRC";else{const a=["resRC.x","resRC.y","resRC.z","resRC.w"],c=[],h=[];for(let p=0;p<t.length;p++)h.push(`${a[p]}`),p<e&&c.push(`${a[p]}`);s=c.join(),i=h.join()}const o=Rt(n);this.userCode=`
void main() {
${o} resRC = getOutputCoords();
float cVal = getC(${s});
if (cVal >= 1.0) {
setOutput(getA(${i}));
} else {
setOutput(getB(${i}));
}
}
`}}class m7{constructor(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;const t=Rt(this.rank),n=`uniform int start[${this.rank}];`,s=f7(this.rank);let i;const o=e.map((a,c)=>`sourceLoc.${GS[c]} = start[${c}] + coords.${GS[c]};`);i=`
${t} sourceLoc;
${t} coords = getOutputCoords();
${o.join(`
`)}
`,this.userCode=`
${n}
void main() {
${i}
setOutput(getSource(${s}));
}
`}getCustomSetupFunc(e){if(e.length!==this.rank)throw Error(`The rank (${this.rank}) of the program must match the length of start (${e.length})`);return(t,n)=>{if(this.startLoc==null&&(this.startLoc=t.getUniformLocationNoThrow(n,"start"),this.startLoc==null))return;t.gl.uniform1iv(this.startLoc,e)}}}const GS=["x","y","z","w","u","v"];function f7(e){if(e===1)return"sourceLoc";if(e<=6)return GS.slice(0,e).map(t=>"sourceLoc."+t).join(",");throw Error(`Slicing for rank ${e} is not yet supported`)}class g7{constructor(e){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.rank=e.length;const t=Rt(this.rank),n=zn("coords",this.rank),s=zn("sourceLoc",this.rank),i=this.rank===1?"sourceLoc":`vec2(${s.slice(-2).join()})`,o=`getChannel(getSource(${s.join()}), ${i})`,a=`
result.x = ${o};
if (++${n[this.rank-1]} < ${e[this.rank-1]}) {
++${s[this.rank-1]};
result.y = ${o};
--${s[this.rank-1]};
}
`,c=this.rank===1?"":`
--${n[this.rank-1]};
if (++${n[this.rank-2]} < ${e[this.rank-2]}) {
++${s[this.rank-2]};
result.z = ${o};
if (++${n[this.rank-1]} < ${e[this.rank-1]}) {
++${s[this.rank-1]};
result.w = ${o};
}
}
`,h=this.rank<=4?`sourceLoc = coords +
${t}(${e.map((p,m)=>`start[${m}]`).join()});`:e.map((p,m)=>`${s[m]} = ${n[m]} + start[${m}];`).join(`
`);this.userCode=`
uniform int start[${this.rank}];
void main() {
${t} coords = getOutputCoords();
${t} sourceLoc;
${h}
vec4 result = vec4(0.);
${a}
${c}
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,n)=>{if(this.startLoc==null&&(this.startLoc=t.getUniformLocationNoThrow(n,"start"),this.startLoc==null))return;t.gl.uniform1iv(this.startLoc,e)}}}class y7{constructor(e,t,n){this.variableNames=["x"],this.outputShape=n;const s=n.length,i=Rt(n.length),o=Rt(n.length);let a="";if(s===1)a="coords * strides + begin";else{let c=0;a=n.map((h,p)=>(c++,n.length===1?`coords * strides[${p}] + begin[${p}]`:`coords[${c-1}] * strides[${p}] + begin[${p}]`)).join(",")}this.userCode=`
${i} begin = ${i}(${e});
${i} strides = ${i}(${t});
void main() {
${o} coords = getOutputCoords();
setOutput(getX(${a}));
}
`}}class b7{constructor(e){this.gpgpu=e,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0,this.freeTextures={},this.logEnabled=!1,this.usedTextures={}}acquireTexture(e,t,n){const s=KC(t,n),i=XC(e,s,n);i in this.freeTextures||(this.freeTextures[i]=[]),i in this.usedTextures||(this.usedTextures[i]=[]);const o=jC(e,s,this.gpgpu.gl,this.gpgpu.textureConfig,n);if(this.freeTextures[i].length>0){this.numFreeTextures--,this.numUsedTextures++,this._numBytesFree-=o,this.log();const c=this.freeTextures[i].shift();return this.usedTextures[i].push(c),c}let a;return s===Rn.PACKED_2X2_FLOAT32?a=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):s===Rn.PACKED_2X2_FLOAT16?a=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):s===Rn.UNPACKED_FLOAT32?a=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):s===Rn.UNPACKED_FLOAT16?a=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):s===Rn.PACKED_4X1_UNSIGNED_BYTE&&(a=this.gpgpu.createUnsignedBytesMatrixTexture(e[0],e[1])),this.usedTextures[i].push(a),this.numUsedTextures++,this._numBytesAllocated+=o,this.log(),a}releaseTexture(e,t,n,s){if(this.freeTextures==null)return;const i=KC(n,s),o=XC(t,i,s);o in this.freeTextures||(this.freeTextures[o]=[]);const a=jC(t,i,this.gpgpu.gl,this.gpgpu.textureConfig,s),c=ae().get("WEBGL_DELETE_TEXTURE_THRESHOLD");c!==-1&&this._numBytesAllocated>c?(this.gpgpu.deleteMatrixTexture(e),this._numBytesAllocated-=a):(this.freeTextures[o].push(e),this.numFreeTextures++,this._numBytesFree+=a),this.numUsedTextures--;const h=this.usedTextures[o],p=h.indexOf(e);if(p<0)throw new Error("Cannot release a texture that was never provided by this texture manager");h.splice(p,1),this.log()}log(){if(!this.logEnabled)return;const e=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",`${this.numFreeTextures} / ${this.numUsedTextures}`,`(${e})`);const t=this._numBytesFree/this._numBytesAllocated;console.log(`Bytes allocated: ${this._numBytesAllocated}`),console.log(`Bytes unused: ${this._numBytesFree} (${Math.round(100*t)}%)`)}get numBytesAllocated(){return this._numBytesAllocated}get numBytesFree(){return this._numBytesFree}getNumUsedTextures(){return this.numUsedTextures}getNumFreeTextures(){return this.numFreeTextures}dispose(){if(this.freeTextures==null)return;for(const e in this.freeTextures)this.freeTextures[e].forEach(t=>{this.gpgpu.deleteMatrixTexture(t)});for(const e in this.usedTextures)this.usedTextures[e].forEach(t=>{this.gpgpu.deleteMatrixTexture(t)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0}}function w7(e,t){const n=e;if(t===n.R32F)return 4;if(t===n.R16F)return 2;if(t===n.RGBA32F)return 16;if(t===e.RGBA)return 16;if(t===n.RGBA16F)return 8;throw new Error(`Unknown internal format ${t}`)}function jC(e,t,n,s,i){const o=L7(t,s);let a;if(i){const[h,p]=Ac(e[0],e[1]);a=h*p}else{const[h,p]=Tu(e[0],e[1]);a=h*p}const c=w7(n,o);return a*c}function L7(e,t){switch(e){case Rn.PACKED_2X2_FLOAT32:return zC(t);case Rn.PACKED_2X2_FLOAT16:return VC(t);case Rn.UNPACKED_FLOAT32:return BC(t);case Rn.UNPACKED_FLOAT16:return MC(t);case Rn.PACKED_4X1_UNSIGNED_BYTE:return PC(t);default:throw new Error(`Unknown physical texture type ${e}`)}}function S7(e){return ae().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?Rn.PACKED_2X2_FLOAT32:Rn.UNPACKED_FLOAT32:e?Rn.PACKED_2X2_FLOAT16:Rn.UNPACKED_FLOAT16}function KC(e,t){if(e===Os.UPLOAD)return Rn.PACKED_2X2_FLOAT32;if(e===Os.RENDER||e==null)return S7(t);if(e===Os.DOWNLOAD||e===Os.PIXELS)return Rn.PACKED_4X1_UNSIGNED_BYTE;throw new Error(`Unknown logical texture type ${e}`)}function XC(e,t,n){return`${e[0]}_${e[1]}_${t}_${n}`}class I7{constructor(e,t){this.variableNames=["A"];const n=new Array(e.length);for(let o=0;o<n.length;o++)n[o]=e[o]*t[o];this.outputShape=n,this.rank=n.length;const s=Rt(this.rank),i=x7(e);this.userCode=`
void main() {
${s} resRC = getOutputCoords();
setOutput(getA(${i}));
}
`}}function x7(e){const t=e.length;if(t>5)throw Error(`Tile for rank ${t} is not yet supported`);if(t===1)return`imod(resRC, ${e[0]})`;const n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],s=[];for(let i=0;i<e.length;i++)s.push(`imod(${n[i]}, ${e[i]})`);return s.join()}class it{constructor(e,t){this.variableNames=["A"],this.outputShape=e,this.userCode=`
float unaryOperation(float x) {
${t}
}
void main() {
float x = getAAtOutCoords();
float y = unaryOperation(x);
setOutput(y);
}
`}}const gr="if (isnan(x)) return x;",T7="return x;",JC="return abs(x);",ZC=gr+`
return (x < 0.0) ? 0.0 : x;
`,QC=gr+`
return (x < 0.0) ? 0.0 : min(6.0, x);
`,e2="return (x >= 0.0) ? x : (exp(x) - 1.0);",A7=`
// Stable and Attracting Fixed Point (0, 1) for Normalized Weights.
// see: https://arxiv.org/abs/1706.02515
float scaleAlpha = ${em};
float scale = ${tm};
return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);
`;function v7(e=0){return gr+`
return x > 0.0 ? 1.0 : float(${e});
`}const t2="return -x;",n2="return ceil(x);",s2="return floor(x);",N7=`
if (isnan(x)) { return 0.0; }
return sign(x);
`,C7="return float(isnan(x));",R7="return float(isinf(x));",O7="return float(!isnan(x) && !isinf(x));",E7=`
// 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;
}
}
`,i2="return exp(x);",r2="return exp(x) - 1.0;",D7=`if (x < 0.0) return NAN;
return log(x);`,k7="return log(1.0 + x);",F7="return sqrt(x);",_7="return inversesqrt(x);",W7="return 1.0 / (1.0 + exp(-1.0 * x));",$7=`
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;
`,U7=gr+`
if (abs(x) > 1.) {
return NAN;
}
return asin(x);
`,B7=gr+`
if (abs(x) > 1.) {
return NAN;
}
return acos(x);
`,M7=gr+`
return atan(x);
`,P7=`
float e2x = exp(x);
return (e2x - 1.0 / e2x) / 2.0;
`,z7=`
float e2x = exp(-x);
return (e2x + 1.0 / e2x) / 2.0;
`,V7=`
float e2x = exp(-2.0 * abs(x));
return sign(x) * (1.0 - e2x) / (1.0 + e2x);
`,G7=gr+"return log(x + sqrt(x * x + 1.0));",Y7=gr+`
if (x < 1.0) return NAN;
return log(x + sqrt(x * x - 1.0));`,H7=gr+`
if ((x < -1.0) || (x > 1.0)) return NAN;
return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,q7=`
// Error function is calculated approximately with elementary function.
// See "Handbook of Mathematical Functions with Formulas,
// Graphs, and Mathematical Tables", Abramowitz and Stegun.
float p = ${ww};
float a1 = ${Lw};
float a2 = ${Sw};
float a3 = ${Iw};
float a4 = ${xw};
float a5 = ${Tw};
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));
`,j7="return 1.0 / x;",K7="return float(!(x >= 1.0));",Zm="return x;";const X7="return x;",J7=`
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;
`,o2=`
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;
`,a2=`
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;
`,c2=`
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 Ru{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 Z7{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e;const t=e.length,n=zn("rc",t),s=Rt(t),i=P5(t,n),o=n.slice(-2),a=t<=1?"rc":`vec2(${o.join(",")})`;this.userCode=`
void main() {
${s} rc = getOutputCoords();
vec4 packedInput = getA(${i});
setOutput(getChannel(packedInput, ${a}));
}
`}}const{segment_util:l2}=Nw,Q7=Cw,eX=Rw,tX=Ow,nX=Vp,sX=1e-7,iX=1e-4,Qm={};function rX(e){return e in Qm||(Qm[e]={}),Qm[e]}function ef(e,t=!1){if(e==="linear")return t?X7:T7;if(e==="relu")return t?o2:ZC;if(e==="elu")return t?c2:e2;if(e==="relu6")return t?a2:QC;if(e==="prelu")return t?DC:EC;throw new Error(`Activation ${e} has not been implemented for the WebGL backend.`)}const oX=128,aX=600;function cX(){return ae().global.screen==null?1024:ae().global.screen.height*ae().global.screen.width*window.devicePixelRatio*aX/1024/1024}const h2=1e3;class lX extends f{constructor(e){super();if(this.pendingRead=new WeakMap,this.pendingDisposal=new WeakSet,this.dataRefCount=new WeakMap,this.numBytesInGPU=0,this.uploadWaitMs=0,this.downloadWaitMs=0,this.warnedAboutMemory=!1,this.warnedAboutCPUBackend=!1,this.pendingDeletes=0,this.disposed=!1,!ae().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");if(e==null){const t=Ui(ae().getNumber("WEBGL_VERSION"));this.binaryCache=rX(ae().getNumber("WEBGL_VERSION")),this.gpgpu=new U6(t),this.canvas=t.canvas,this.gpgpuCreatedLocally=!0}else this.gpgpu=e,this.binaryCache={},this.gpgpuCreatedLocally=!1,this.canvas=e.gl.canvas;this.textureManager=new b7(this.gpgpu),this.numMBBeforeWarning=cX(),this.texData=new d(this,tr())}numDataIds(){return this.texData.numDataIds()+(this.cpuBackend?this.cpuBackend.numDataIds():0)-this.pendingDeletes}write(e,t,n){if((ae().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||ae().getBool("DEBUG"))&&this.checkNumericalProblems(e),n==="complex64"&&e!=null)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");const s={};return this.texData.set(s,{shape:t,dtype:n,values:e,usage:Os.UPLOAD,refCount:1,complexParentRefCount:0}),s}incRef(e){const t=this.texData.get(e);t.refCount++}decRef(e){if(this.texData.has(e)){const t=this.texData.get(e);t.refCount--}}move(e,t,n,s){if(ae().getBool("DEBUG")&&this.checkNumericalProblems(t),s==="complex64")throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(e,{shape:n,dtype:s,values:t,usage:Os.UPLOAD,refCount:1,complexParentRefCount:0})}disposeIntermediateTensorInfo(e){const t=e.dataId;if(this.texData.has(t)){const n=this.texData.get(t);n.refCount--,n.refCount<1&&this.disposeData(t)}}readSync(e){const t=this.texData.get(e),{values:n,dtype:s,complexTensorInfos:i,slice:o,shape:a,isPacked:c}=t;if(o!=null){let y;c?y=new Ru(a,Zm):y=new it(a,Zm);const b=this.runWebGLProgram(y,[{dataId:e,shape:a,dtype:s}],s),w=this.readSync(b.dataId);return this.disposeIntermediateTensorInfo(b),w}if(n!=null)return this.convertAndCacheOnCPU(e);if(s==="string")return n;const h=this.activeTimers!=null;let p;h&&(p=Jn());let m;if(s==="complex64"){const y=this.readSync(i.real.dataId),b=this.readSync(i.imag.dataId);m=ar(y,b)}else m=this.getValuesFromTexture(e);return h&&(this.downloadWaitMs+=Jn()-p),this.convertAndCacheOnCPU(e,m)}async read(e){if(this.pendingRead.has(e)){const w=this.pendingRead.get(e);return new Promise(L=>w.push(L))}const t=this.texData.get(e),{values:n,shape:s,slice:i,dtype:o,complexTensorInfos:a,isPacked:c}=t;if(i!=null){let w;c?w=new Ru(s,Zm):w=new it(s,Zm);const L=this.runWebGLProgram(w,[{dataId:e,shape:s,dtype:o}],o),T=this.read(L.dataId);return this.disposeIntermediateTensorInfo(L),T}if(n!=null)return this.convertAndCacheOnCPU(e);if(!ae().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&ae().getNumber("WEBGL_VERSION")===2)throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");let h=null,p;if(o!=="complex64"&&ae().get("WEBGL_BUFFER_SUPPORTED")){p=this.decode(e);const w=this.texData.get(p.dataId);h=this.gpgpu.createBufferFromTexture(w.texture,...Au(s))}this.pendingRead.set(e,[]),o!=="complex64"&&await this.gpgpu.createAndWaitForFence();let m;if(o==="complex64"){const w=await Promise.all([this.read(a.real.dataId),this.read(a.imag.dataId)]),L=w[0],T=w[1];m=ar(L,T)}else if(h==null)m=this.getValuesFromTexture(e);else{const w=M(s);m=this.gpgpu.downloadFloat32MatrixFromBuffer(h,w)}p!=null&&this.disposeIntermediateTensorInfo(p);const y=this.convertAndCacheOnCPU(e,m),b=this.pendingRead.get(e);return this.pendingRead.delete(e),b.forEach(w=>w(y)),this.pendingDisposal.has(e)&&(this.pendingDisposal.delete(e),this.disposeData(e),this.pendingDeletes--),y}checkNumericalProblems(e){if(e==null)return;for(let t=0;t<e.length;t++){const n=e[t];if(!QK(n))throw ae().getBool("WEBGL_RENDER_FLOAT32_CAPABLE")?Error(`The value ${n} cannot be represented with your current settings. Consider enabling float32 rendering: 'tf.env().set('WEBGL_RENDER_FLOAT32_ENABLED', true);'`):Error(`The value ${n} cannot be represented on this device.`)}}getValuesFromTexture(e){const{shape:t,dtype:n,isPacked:s}=this.texData.get(e),i=M(t);if(ae().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")){const y=this.decode(e),b=this.texData.get(y.dataId),w=this.gpgpu.downloadMatrixFromPackedTexture(b.texture,...Au(t)).subarray(0,i);return this.disposeIntermediateTensorInfo(y),w}const o=ae().getBool("WEBGL_PACK")&&s===!0,a=o?US(t):t,c=o?new f6(a):new m6(a),h=this.runWebGLProgram(c,[{shape:a,dtype:n,dataId:e}],"float32"),p=this.texData.get(h.dataId),m=this.gpgpu.downloadByteEncodedFloatMatrixFromOutputTexture(p.texture,p.texShape[0],p.texShape[1]).subarray(0,i);return this.disposeIntermediateTensorInfo(h),m}async time(e){const t=this.activeTimers,n=[];let s=!1;this.programTimersStack==null?(this.programTimersStack=n,s=!0):this.activeTimers.push(n),this.activeTimers=n,e();const i=Q(this.activeTimers.map(c=>c.query)).filter(c=>c!=null),o=Q(this.activeTimers.map(c=>c.name)).filter(c=>c!=null);this.activeTimers=t,s&&(this.programTimersStack=null);const a={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null};if(ae().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0){const c=await Promise.all(i);a.kernelMs=N(c),a.getExtraProfileInfo=()=>c.map((h,p)=>({name:o[p],ms:h})).map(h=>`${h.name}: ${h.ms}`).join(", ")}else a.kernelMs={error:"WebGL query timers are not supported in this environment."};return this.uploadWaitMs=0,this.downloadWaitMs=0,a}memory(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU,numBytesInGPUAllocated:this.textureManager.numBytesAllocated,numBytesInGPUFree:this.textureManager.numBytesFree}}startTimer(){return ae().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:Jn(),endMs:null}}endTimer(e){return ae().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),e):(e.endMs=Jn(),e)}async getQueryTime(e){if(ae().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0)return this.gpgpu.waitForQueryAndGetTime(e);const t=e;return t.endMs-t.startMs}disposeData(e){if(this.pendingDisposal.has(e))return;if(this.pendingRead.has(e)){this.pendingDisposal.add(e),this.pendingDeletes++;return}if(!this.texData.has(e))return;if(this.texData.get(e).complexParentRefCount>0){this.texData.get(e).refCount--;return}this.releaseGPUData(e);const{complexTensorInfos:t}=this.texData.get(e);t!=null&&(this.texData.get(t.real.dataId).complexParentRefCount--,this.disposeIntermediateTensorInfo(t.real),this.texData.get(t.imag.dataId).complexParentRefCount--,this.disposeIntermediateTensorInfo(t.imag)),this.texData.delete(e)}releaseGPUData(e){const{texture:t,dtype:n,texShape:s,usage:i,isPacked:o,slice:a}=this.texData.get(e),c=a&&a.origDataId||e,h=this.dataRefCount.get(c);h>1?this.dataRefCount.set(c,h-1):(this.dataRefCount.delete(c),t!=null&&(this.numBytesInGPU-=this.computeBytes(s,n),this.textureManager.releaseTexture(t,s,i,o)));const p=this.texData.get(e);p.texture=null,p.texShape=null,p.isPacked=!1,p.slice=null}getTexture(e){return this.uploadToGPU(e),this.texData.get(e).texture}getDataInfo(e){return this.texData.get(e)}getCPUBackend(){return ae().getBool("WEBGL_CPU_FORWARD")?(this.cpuBackend==null&&(this.cpuBackend=tr().findBackend("cpu")),this.cpuBackend):null}shouldExecuteOnCPU(e,t=oX){const n=this.getCPUBackend();return!this.warnedAboutCPUBackend&&n==null&&(console.warn("Your application contains ops that are small enough to be executed on the CPU backend, however the CPU backend cannot be found. Consider importing the CPU backend (@tensorflow/tfjs-backend-cpu) for better performance."),this.warnedAboutCPUBackend=!0),n!=null&&e.every(s=>this.texData.get(s.dataId).texture==null&&M(s.shape)<t)}getGPGPUContext(){return this.gpgpu}slice(e,t,n){if(this.shouldExecuteOnCPU([e])){const o=_5(this.texData.get(e.dataId).values,t,n,e.shape,e.dtype);return this.makeOutput(n,e.dtype,o)}if(M(n)===0)return sn([],n,e.dtype);const{isPacked:s}=this.texData.get(e.dataId),i=wb(e.shape,t,n);if(s||!i){const o=ae().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new g7(n):new m7(n),a=o.getCustomSetupFunc(t);return this.compileAndRun(o,[e],null,a)}return this.uploadToGPU(e.dataId),this.shallowSlice(e,t,n)}shallowSlice(e,t,n){const s=this.texData.get(e.dataId),i=this.makeOutput(n,e.dtype),o=this.texData.get(i.dataId);Object.assign(o,s),o.shape=n,o.dtype=e.dtype;let a=Lb(t,e.strides);s.slice&&(a+=s.slice.flatOffset),o.slice={flatOffset:a,origDataId:s.slice&&s.slice.origDataId||e.dataId};const c=this.dataRefCount.get(o.slice.origDataId)||1;return this.dataRefCount.set(o.slice.origDataId,c+1),i}stridedSlice(e,t,n,s){const i=this.tryRunOnCpuOrThrow([e],()=>this.cpuBackend.stridedSlice(e,t,n,s));if(i)return i;const o=dp(t,n,s);if(o.some(c=>c===0))return sn([],o);const a=new y7(t,s,o);return this.compileAndRun(a,[e])}reverse(e,t){const n=ae().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new u7(e.shape,t):new h7(e.shape,t);return this.compileAndRun(n,[e])}neg(e){const t=this.tryRunOnCpuOrThrow([e],()=>this.cpuBackend.neg(e));if(t)return t;if(ae().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,t2,e.dtype);const n=new it(e.shape,t2);return this.compileAndRun(n,[e])}batchMatMul(e,t,n,s){const i=n?e.shape[2]:e.shape[1],o=s?t.shape[1]:t.shape[2],a=n?e.shape[1]:e.shape[2],c=Math.max(e.shape[0],t.shape[0]);if((i===1||o===1)&&a>h2){n&&(e=Ye(e,[0,2,1])),s&&(t=Ye(t,[0,2,1]));const m=o===1?e:e.as3D(c,a,1),y=o===1?2:1,b=o===1?t.as3D(c,1,a):t,w=X(m,b);return w.sum(y,!0)}const h=Bn(e.dtype,t.dtype),p=new zS(e.shape,t.shape,[c,i,o],n,s);return this.compileAndRun(p,[e,t],h)}fusedBatchMatMul({a:e,b:t,transposeA:n,transposeB:s,bias:i,activation:o,preluActivationWeights:a}){const c=n?e.shape[2]:e.shape[1],h=s?t.shape[1]:t.shape[2],p=Math.max(e.shape[0],t.shape[0]),m=Bn(e.dtype,t.dtype),y=i!=null,b=a!=null,w=o?ef(o,!0):null,L=new zS(e.shape,t.shape,[p,c,h],n,s,y,w,b),T=[e,t];return i&&T.push(i),a&&T.push(a),this.compileAndRun(L,T,m)}localResponseNormalization4D(e,t,n,s,i){const o=ae().getBool("WEBGL_PACK_NORMALIZATION")?new H6(e.shape,t,n,s,i):new G6(e.shape,t,n,s,i);return this.compileAndRun(o,[e])}LRNGrad(e,t,n,s,i,o,a){const c=new Y6(t.shape,s,i,o,a);return this.compileAndRun(c,[t,n,e])}tile(e,t){if(e.dtype==="string"){const s=this.readSync(e.dataId),i=s.map(a=>lh(a)),o=wt(e.shape,e.dtype,i);return eX(o,t)}const n=new I7(e.shape,t);return this.compileAndRun(n,[e])}pad(e,t,n){const s=ae().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new s7(e.shape,t,n):new n7(e.shape,t,n);return this.compileAndRun(s,[e])}gather(e,t,n){const s=this.tryRunOnCpuOrThrow([e,t],()=>this.cpuBackend.gather(e,t,n));if(s)return s;const i=new w6(e.shape,t.size,n);return this.compileAndRun(i,[e,t])}batchToSpaceND(e,t,n){A(e.rank<=4,()=>"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet");const s=t.reduce((p,m)=>p*m),i=Gh(e.shape,t,s),o=Yh(i.length,t.length),a=Hh(e.shape,t,s),c=yw(n,t.length),h=bw(a,n,t.length);return Ye(e.reshape(i),o).reshape(a).slice(c,h)}spaceToBatchND(e,t,n){A(e.rank<=4,()=>"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet");const s=t.reduce((m,y)=>m*y),i=[[0,0]];i.push(...n);for(let m=1+t.length;m<e.shape.length;++m)i.push([0,0]);const o=e.pad(i),a=Gh(o.shape,t,s,!1),c=Yh(a.length,t.length,!1),h=Hh(o.shape,t,s,!1),p=Ye(o.reshape(a),c);return K(p,h)}reduce(e,t,n){const s=e.shape[0],i=e.shape[1],o=Ah(i),a=Math.ceil(i/o),c={windowSize:o,inSize:i,batchSize:s,outSize:a},h=new YC(c,t),p=this.compileAndRun(h,[e],n);return p.shape[1]===1?p:this.reduce(p,t,n)}argReduce(e,t,n=null){let s=e.shape[0],i=e.shape[1];n!=null&&(s=n.shape[0],i=n.shape[1]);const o=Ah(i),a={windowSize:o,inSize:i,batchSize:s,outSize:Math.ceil(i/o)},c=new M5(a,t,n==null),h=[e];n!=null&&h.push(n);const p=this.compileAndRun(c,h,"int32");return p.shape[1]===1?p:this.argReduce(e,t,p)}argReducePacked(e,t,n=null){const s=n!=null?n.shape:e.shape,i=s[s.length-1],o=Ah(i),a=new T8(s,o,t,n==null),c=n==null?[e]:[e,n],h=this.compileAndRun(a,c,"int32");return h.rank===e.rank?this.argReducePacked(e,t,h):h}sum(e,t){Zn("sum",t,e.rank);const[n,s]=vn(e.shape,t),i=M(s),o=e.as2D(-1,i),a=np(e.dtype);return this.reduce(o,"sum",a).reshape(n)}prod(e,t){const n=this.tryRunOnCpuOrThrow([e],()=>this.cpuBackend.prod(e,t));if(n)return n;const[s,i]=vn(e.shape,t),o=M(i),a=e.as2D(-1,o),c=np(e.dtype);return this.reduce(a,"prod",c).reshape(s)}unsortedSegmentSum(e,t,n){let s=0;const i=Qn([s],e.rank);let o=e;i!=null&&(o=Ye(e,i),s=hs(1,e.rank)[0]);const a=l2.computeOutShape(o.shape,s,n),c=M([o.shape[s]]),h=o.as2D(-1,c),p=np(e.dtype);let m=this.segOpCompute(h,"unsortedSegmentSum",t,p,n).reshape(a);return i!=null&&(m=Ye(m,yh(i))),m}segOpCompute(e,t,n,s,i){const o=e.shape[0],a=e.shape[1],c=l2.segOpComputeOptimalWindowSize(a,i),h={windowSize:c,inSize:a,batchSize:o,numSegments:i},p=new d7(h,t),m=this.compileAndRun(p,[e,n],s);return m.shape[1]===i?m:(n=Dh(0,i).tile([a/c]),this.segOpCompute(m,t,n,s,i))}argMinMaxReduce(e,t,n){const s=[t];if(Zn("arg"+n.charAt(0).toUpperCase()+n.slice(1),s,e.rank),!ae().getBool("WEBGL_PACK_REDUCE")||e.rank<=2){const[i,o]=vn(e.shape,s),a=M(o),c=e.as2D(-1,a);return this.argReduce(c,n).reshape(i)}return this.argReducePacked(e,n)}argMin(e,t){return this.argMinMaxReduce(e,t,"min")}argMax(e,t){return this.argMinMaxReduce(e,t,"max")}cumsum(e,t,n,s){if(t!==e.rank-1)throw new Error(`WebGL cumsum shader expects an inner-most axis=${e.rank-1} but got axis=${t}`);const i=e.shape[t];let o=e;for(let a=0;a<=Math.ceil(Math.log2(i))-1;a++){const c=new WC(e.shape,!1,s),h=c.getCustomSetupFunc(a),p=o;o=this.compileAndRun(c,[o],o.dtype,h),p.dispose()}if(n){const a=new WC(e.shape,n,s),c=o;o=this.compileAndRun(a,[o]),c.dispose()}return o}equal(e,t){if(ae().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,V8,"bool");const n=new $n(R8,e.shape,t.shape);return this.compileAndRun(n,[e,t],"bool")}less(e,t){const n=this.tryRunOnCpuOrThrow([e,t],()=>this.cpuBackend.less(e,t));if(n)return n;if(ae().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,G8,"bool");const s=new $n(O8,e.shape,t.shape);return this.compileAndRun(s,[e,t],"bool")}lessEqual(e,t){if(ae().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,Y8,"bool");const n=new $n(E8,e.shape,t.shape);return this.compileAndRun(n,[e,t],"bool")}greater(e,t){const n=this.tryRunOnCpuOrThrow([e,t],()=>this.cpuBackend.greater(e,t));if(n)return n;if(ae().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,H8,"bool");const s=new $n(D8,e.shape,t.shape);return this.compileAndRun(s,[e,t],"bool")}greaterEqual(e,t){if(ae().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,q8,"bool");const n=new $n(k8,e.shape,t.shape);return this.compileAndRun(n,[e,t],"bool")}logicalNot(e){const t=new it(e.shape,K7);return this.compileAndRun(t,[e])}logicalAnd(e,t){if(ae().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,j8,"bool");const n=new $n(F8,e.shape,t.shape);return this.compileAndRun(n,[e,t],"bool")}logicalOr(e,t){if(ae().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,K8,"bool");const n=new $n(_8,e.shape,t.shape);return this.compileAndRun(n,[e,t],"bool")}select(e,t,n){const s=new p7(e.rank,t.shape,t.rank);return this.compileAndRun(s,[e,t,n],Bn(t.dtype,n.dtype))}where(e){hc("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");const t=e.dataSync();return nX(e.shape,t)}topk(e,t,n){const s=e.dataSync();return tX(s,e.shape,e.dtype,t,n)}min(e,t){Zn("min",t,e.rank);const[n,s]=vn(e.shape,t),i=M(s),o=e.as2D(-1,i);return this.reduce(o,"min",o.dtype).reshape(n)}minimum(e,t){const n=this.tryRunOnCpuOrThrow([e,t],()=>this.cpuBackend.minimum(e,t));if(n)return n;const s=ae().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new fr(J8,e.shape,t.shape):new $n($8,e.shape,t.shape);return this.compileAndRun(s,[e,t])}mod(e,t){const n=ae().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new fr(Z8,e.shape,t.shape):new $n(U8,e.shape,t.shape);return this.compileAndRun(n,[e,t])}maximum(e,t){const n=this.tryRunOnCpuOrThrow([e,t],()=>this.cpuBackend.maximum(e,t));if(n)return n;const s=ae().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new fr(X8,e.shape,t.shape):new $n(W8,e.shape,t.shape);return this.compileAndRun(s,[e,t])}all(e,t){Zn("all",t,e.rank);const[n,s]=vn(e.shape,t),i=M(s),o=e.as2D(-1,i);return this.reduce(o,"all",o.dtype).reshape(n)}any(e,t){Zn("any",t,e.rank);const[n,s]=vn(e.shape,t),i=M(s),o=e.as2D(-1,i);return this.reduce(o,"any",o.dtype).reshape(n)}floorDiv(e,t){const n=N8,s="int32";if(ae().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,M8,s);const i=new $n(n,e.shape,t.shape);return this.compileAndRun(i,[e,t],s)}packedUnaryOp(e,t,n){const s=new Ru(e.shape,t);return this.compileAndRun(s,[e],n)}packedBinaryOp(e,t,n,s,i=!1){const o=new fr(n,e.shape,t.shape,i);return this.compileAndRun(o,[e,t],s)}makeComplexComponentTensorInfo(e,t){return{dataId:t.dataId,dtype:t.dtype,shape:e.shape}}addN(e){if(e.length===1)return e[0];if(e.length>ae().get("WEBGL_MAX_TEXTURES_IN_SHADER")){const o=Math.floor(e.length/2),a=this.addN(e.slice(0,o)),c=this.addN(e.slice(o));return this.addN([a,c])}const t=e.map(o=>o.dtype).reduce((o,a)=>Bn(o,a)),n=e.map(o=>o.shape),s=ae().getBool("WEBGL_PACK"),i=s?new B5(e[0].shape,n):new U5(e[0].shape,n);return this.compileAndRun(i,e,t)}pow(e,t){const n=ae().getBool("WEBGL_PACK_BINARY_OPERATIONS"),s=n?new fr(P8,e.shape,t.shape):new $n(C8,e.shape,t.shape),i=Bn(e.dtype,t.dtype);return this.compileAndRun(s,[e,t],i)}ceil(e){if(this.shouldExecuteOnCPU([e])){const n=N5(this.texData.get(e.dataId).values,e.dtype);return this.makeOutput(e.shape,e.dtype,n)}if(ae().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,n2,e.dtype);const t=new it(e.shape,n2);return this.compileAndRun(t,[e])}floor(e){if(this.shouldExecuteOnCPU([e])){const n=O5(this.texData.get(e.dataId).values,e.dtype);return this.makeOutput(e.shape,e.dtype,n)}if(ae().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,s2,e.dtype);const t=new it(e.shape,s2);return this.compileAndRun(t,[e])}sign(e){const t=new it(e.shape,N7);return this.compileAndRun(t,[e])}isNaN(e){const t=new it(e.shape,C7);return this.compileAndRun(t,[e],"bool")}isInf(e){const t=new it(e.shape,R7);return this.compileAndRun(t,[e],"bool")}isFinite(e){const t=new it(e.shape,O7);return this.compileAndRun(t,[e],"bool")}round(e){const t=new it(e.shape,E7);return this.compileAndRun(t,[e])}exp(e){if(this.shouldExecuteOnCPU([e])){const n=C5(this.texData.get(e.dataId).values,e.dtype);return this.makeOutput(e.shape,e.dtype,n)}if(ae().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,i2,e.dtype);const t=new it(e.shape,i2);return this.compileAndRun(t,[e])}expm1(e){if(this.shouldExecuteOnCPU([e])){const n=R5(this.texData.get(e.dataId).values,e.dtype);return this.makeOutput(e.shape,e.dtype,n)}if(ae().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,r2,e.dtype);const t=new it(e.shape,r2);return this.compileAndRun(t,[e])}softmax(e,t){const n=je([t],e.shape),s=ns(e,n),i=Nn(s.shape,n),o=Re(e,s.reshape(i)),a=this.exp(o),c=this.sum(a,n).reshape(i);return We(a,c)}log(e){if(this.shouldExecuteOnCPU([e])){const n=E5(this.texData.get(e.dataId).values,e.dtype);return this.makeOutput(e.shape,e.dtype,n)}if(ae().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,J7,e.dtype);const t=new it(e.shape,D7);return this.compileAndRun(t,[e])}log1p(e){const t=new it(e.shape,k7);return this.compileAndRun(t,[e])}sqrt(e){const t=new it(e.shape,F7);return this.compileAndRun(t,[e])}rsqrt(e){if(this.shouldExecuteOnCPU([e])){const n=F5(this.texData.get(e.dataId).values,e.dtype);return this.makeOutput(e.shape,e.dtype,n)}const t=new it(e.shape,_7);return this.compileAndRun(t,[e])}reciprocal(e){const t=new it(e.shape,j7);return this.compileAndRun(t,[e])}relu(e){let t;return ae().getBool("WEBGL_PACK")?t=new Ru(e.shape,o2):t=new it(e.shape,ZC),this.compileAndRun(t,[e])}relu6(e){let t;return ae().getBool("WEBGL_PACK")?t=new Ru(e.shape,a2):t=new it(e.shape,QC),this.compileAndRun(t,[e])}prelu(e,t){const n=ae().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new fr(DC,e.shape,t.shape):new $n(EC,e.shape,t.shape);return this.compileAndRun(n,[e,t])}elu(e){if(ae().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,c2,e.dtype);const t=new it(e.shape,e2);return this.compileAndRun(t,[e])}eluDer(e,t){const n=ae().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new fr(z8,e.shape,t.shape):new $n(B8,e.shape,t.shape);return this.compileAndRun(n,[e,t])}selu(e){const t=new it(e.shape,A7);return this.compileAndRun(t,[e])}clip(e,t,n){let s;ae().getBool("WEBGL_PACK_CLIP")?s=new e6(e.shape):s=new Q8(e.shape);const i=s.getCustomSetupFunc(t,n);return this.compileAndRun(s,[e],null,i)}abs(e){if(this.shouldExecuteOnCPU([e])&&e.dtype!=="complex64"){const n=A5(this.texData.get(e.dataId).values);return this.makeOutput(e.shape,e.dtype,n)}if(ae().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,JC,e.dtype);const t=new it(e.shape,JC);return this.compileAndRun(t,[e])}complexAbs(e){const t=this.texData.get(e.dataId),n=new t6(e.shape),s=[this.makeComplexComponentTensorInfo(e,t.complexTensorInfos.real),this.makeComplexComponentTensorInfo(e,t.complexTensorInfos.imag)];return this.compileAndRun(n,s)}sigmoid(e){const t=new it(e.shape,W7);return this.compileAndRun(t,[e])}softplus(e){const t=new it(e.shape,$7);return this.compileAndRun(t,[e])}asin(e){const t=new it(e.shape,U7);return this.compileAndRun(t,[e])}acos(e){const t=new it(e.shape,B7);return this.compileAndRun(t,[e])}atan(e){const t=new it(e.shape,M7);return this.compileAndRun(t,[e])}sinh(e){const t=new it(e.shape,P7);return this.compileAndRun(t,[e])}cosh(e){const t=new it(e.shape,z7);return this.compileAndRun(t,[e])}tanh(e){const t=new it(e.shape,V7);return this.compileAndRun(t,[e])}asinh(e){const t=new it(e.shape,G7);return this.compileAndRun(t,[e])}acosh(e){const t=new it(e.shape,Y7);return this.compileAndRun(t,[e])}atanh(e){const t=new it(e.shape,H7);return this.compileAndRun(t,[e])}erf(e){const t=new it(e.shape,q7);return this.compileAndRun(t,[e])}step(e,t){const n=new it(e.shape,v7(t));return this.compileAndRun(n,[e])}conv2dByMatMul(e,t,n,s,i,o){const a=e.shape,c=this.texData.get(e.dataId),h=n.inChannels,p=a[0]*a[1]*a[2],m=n.outChannels,y=n.dataFormat==="channelsLast",b=!1,w=!1,L=(p===1||m===1)&&h>h2,T=a[2]%2!==0&&!!c.isPacked;if(L||!ae().getBool("WEBGL_LAZILY_UNPACK")||!ae().getBool("WEBGL_PACK_BINARY_OPERATIONS")||!T){const B=y?a[0]*a[1]*a[2]:a[0]*a[2]*a[3],$=K(e,[1,B,n.inChannels]),Y=K(t,[1,n.inChannels,n.outChannels]),j=this.fusedBatchMatMul({a:$,b:Y,transposeA:b,transposeB:w,bias:s,activation:i,preluActivationWeights:o});return K(j,n.outShape)}const v=y?a[0]*a[1]*(a[2]+1):a[0]*a[2]*(a[3]+1),C={dataId:e.dataId,shape:[1,v,n.inChannels],dtype:e.dtype},O=c.shape;c.shape=c.shape.slice(),c.shape[c.shape.length-2]++,A(qm(c.shape,C.shape),()=>`packed reshape ${c.shape} to ${C.shape} isn't free`);const D=K(t,[1,n.inChannels,n.outChannels]),k=this.fusedBatchMatMul({a:C,b:D,transposeA:b,transposeB:w,bias:s,activation:i,preluActivationWeights:o}),F=this.texData.get(k.dataId);return A(F.isPacked,()=>"batchMatMul result is expected to be packed"),c.shape=O,F.shape=n.outShape,tr().makeTensorFromDataId(k.dataId,n.outShape,k.dtype)}conv2dWithIm2Row(e,t,n,s,i,o){const{filterWidth:a,filterHeight:c,inChannels:h,outWidth:p,outHeight:m,dataFormat:y}=n,b=y==="channelsLast",w=a*c*h,L=m*p,T=[w,L],v=!0,C=!1,O=e.squeeze([0]),D=t.reshape([1,w,-1]),k=new V6(T,O.shape,n),F=this.compileAndRun(k,[O]).reshape([1,T[0],T[1]]),B=s!=null,$=o!=null,Y=i?ef(i,!0):null,j=new zS(F.shape,D.shape,[1,L,n.outChannels],v,C,B,Y,$),Z=[F,D];s&&Z.push(s),$&&Z.push(o);const re=this.compileAndRun(j,Z);return b?re.reshape([1,m,p,n.outChannels]):re.reshape([1,n.outChannels,m,p])}fusedConv2d({input:e,filter:t,convInfo:n,bias:s,activation:i,preluActivationWeights:o}){if(n.filterHeight===1&&n.filterWidth===1&&n.dilationHeight===1&&n.dilationWidth===1&&n.strideHeight===1&&n.strideWidth===1&&(n.padInfo.type==="SAME"||n.padInfo.type==="VALID"))return this.conv2dByMatMul(e,t,n,s,i,o);if(ae().getBool("WEBGL_CONV_IM2COL")&&e.shape[0]===1)return this.conv2dWithIm2Row(e,t,n,s,i,o);const a=s!=null,c=o!=null,h=i?ef(i,!1):null,p=new kC(n,a,h,c),m=[e,t];return s&&m.push(s),o&&m.push(o),this.compileAndRun(p,m)}conv2d(e,t,n){if(n.filterHeight===1&&n.filterWidth===1&&n.dilationHeight===1&&n.dilationWidth===1&&n.strideHeight===1&&n.strideWidth===1&&(n.padInfo.type==="SAME"||n.padInfo.type==="VALID"))return this.conv2dByMatMul(e,t,n);if(ae().getBool("WEBGL_CONV_IM2COL")&&e.shape[0]===1)return this.conv2dWithIm2Row(e,t,n);const s=new kC(n);return this.compileAndRun(s,[e,t])}conv2dDerInput(e,t,n){const s=new s6(n);return this.compileAndRun(s,[e,t])}conv2dDerFilter(e,t,n){const s=new n6(n);return this.compileAndRun(s,[e,t])}fusedDepthwiseConv2D({input:e,filter:t,convInfo:n,bias:s,activation:i,preluActivationWeights:o}){const a=ae().getBool("WEBGL_PACK_DEPTHWISECONV")&&n.strideWidth<=2&&n.outChannels/n.inChannels===1,c=i?ef(i,a):null,h=[e,t],p=s!=null,m=o!=null;p&&h.push(s),m&&h.push(o);let y;return a?(y=new _C(n,p,c,m),this.compileAndRun(y,h)):(y=new FC(n,p,c,m),this.compileAndRun(y,h))}depthwiseConv2D(e,t,n){let s;return ae().getBool("WEBGL_PACK_DEPTHWISECONV")&&n.strideWidth<=2&&n.outChannels/n.inChannels===1?(s=new _C(n),this.compileAndRun(s,[e,t])):(s=new FC(n),this.compileAndRun(s,[e,t]))}depthwiseConv2DDerInput(e,t,n){const s=new a6(n);return this.compileAndRun(s,[e,t])}depthwiseConv2DDerFilter(e,t,n){const s=new o6(n);return this.compileAndRun(s,[e,t])}conv3d(e,t,n){const s=new c6(n);return this.compileAndRun(s,[e,t])}conv3dDerInput(e,t,n){const s=new r6(n);return this.compileAndRun(s,[e,t])}conv3dDerFilter(e,t,n){const s=new i6(n);return this.compileAndRun(s,[e,t])}unstack(e,t){const n=e.shape[t],s=new Array(e.rank-1);let i=0;for(let h=0;h<e.rank;h++)h!==t&&(s[i++]=e.shape[h]);const o=new Array(e.rank).fill(0),a=e.shape.slice();a[t]=1;const c=new Array(n);for(let h=0;h<c.length;h++)o[t]=h,c[h]=this.slice(e,o,a).reshape(s);return c}avgPool3d(e,t){const n=new VS(t,"avg",!1);return this.compileAndRun(n,[e],"float32")}avgPool3dBackprop(e,t,n){const s=new v8(n);return this.compileAndRun(s,[e],t.dtype)}maxPool3d(e,t){const n=new VS(t,"max",!1);return this.compileAndRun(n,[e],"float32")}maxPool3dBackprop(e,t,n,s){const i=!0,o=new VS(s,"max",i),a=this.compileAndRun(o,[t]),c=new j6(s),h=this.compileAndRun(c,[e,a],t.dtype);return a.dispose(),h}resizeBilinear(e,t,n,s){const i=ae().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new a7(e.shape,t,n,s):new o7(e.shape,t,n,s);return this.compileAndRun(i,[e],"float32")}resizeBilinearBackprop(e,t,n){const s=new r7(e,t,n);return this.compileAndRun(s,[e])}resizeNearestNeighbor(e,t,n,s){const i=new l7(e.shape,t,n,s);return this.compileAndRun(i,[e])}resizeNearestNeighborBackprop(e,t,n){const s=new c7(e,t,n);return this.compileAndRun(s,[e])}multinomial(e,t,n,s){const i=t?e:Yo(e),o=i.shape[0],a=i.shape[1],c=new K6(o,a,n),h=c.getCustomSetupFunc(s);return this.compileAndRun(c,[i],"int32",h)}oneHot(e,t,n,s){const i=new X6(e.size,t,n,s);return this.compileAndRun(i,[e])}diag(e){const t=new p6(e.size);return this.compileAndRun(t,[e])}cropAndResize(e,t,n,s,i,o){const a=new l6(e.shape,t.shape,s,i,o);return this.compileAndRun(a,[e,t,n],"float32")}depthToSpace(e,t,n){A(t>1,()=>`blockSize should be > 1 for depthToSpace, but was: ${t}`);const s=e.shape[0],i=n==="NHWC"?e.shape[1]:e.shape[2],o=n==="NHWC"?e.shape[2]:e.shape[3],a=n==="NHWC"?e.shape[3]:e.shape[1],c=i*t,h=o*t,p=a/(t*t),m=n==="NHWC"?[s,c,h,p]:[s,p,c,h],y=new d6(m,t,n);return this.compileAndRun(y,[e])}split(e,t,n){return Q7(e,t,n)}scatterND(e,t,n){const{sliceRank:s,numUpdates:i,sliceSize:o,strides:a,outputSize:c}=qa(t,e,n),h=[c/o,o],p=e.reshape([i,s]),m=t.reshape([i,o]);if(c===0)return Av(sn([]),n);const y=Ce(0),b=new qC(i,s,p.rank,m.rank,a,h),w=this.compileAndRun(b,[m,p,y]);return w.reshape(n)}sparseToDense(e,t,n,s){const{sliceRank:i,numUpdates:o,strides:a,outputSize:c}=qa(t,e,n),h=!1,p=new qC(o,i,e.rank,t.rank,a,[c,1],h),m=this.compileAndRun(p,[t,e,s]);return m.reshape(n)}gatherND(e,t){const n=t.shape,s=n[n.length-1],[i,o,a,c]=hp(e,t),h=t.reshape([o,s]),p=e.reshape([e.size/a,a]),m=new S6(s,c,[o,a]),y=this.compileAndRun(m,[p,h]);return y.reshape(i)}fill(e,t,n){if(n=n||Ea(t),n==="string"){const s=Is(n,M(e));return s.fill(t),tr().makeTensor(s,e,n,this)}else{const s=new b6(e,t),i=s.getCustomSetupFunc(t);return this.compileAndRun(s,[],n,i)}}onesLike(e){if(e.dtype==="string")throw new Error("onesLike is not supported under string dtype");return this.fill(e.shape,1,e.dtype)}zerosLike(e){return this.fill(e.shape,e.dtype==="string"?"":0,e.dtype)}linspace(e,t,n){return vw(e,t,n)}makeTensorInfo(e,t,n){const s=this.write(n,e,t);return this.texData.get(s).usage=null,{dataId:s,shape:e,dtype:t}}makeOutput(e,t,n){const{dataId:s}=this.makeTensorInfo(e,t,n);return tr().makeTensorFromDataId(s,e,t,this)}unpackTensor(e){const t=new Z7(e.shape);return this.runWebGLProgram(t,[e],e.dtype)}packTensor(e){const t=new J6(e.shape),n=!0;return this.runWebGLProgram(t,[e],e.dtype,null,n)}packedReshape(e,t){const n=[vc(e.shape),...Nc(e.shape)],s={dtype:e.dtype,shape:n,dataId:e.dataId},i=[vc(t),...Nc(t)],o=new HC(i,n),a=!0,c=this.runWebGLProgram(o,[s],e.dtype,null,a);return{dataId:c.dataId,shape:t,dtype:c.dtype}}decode(e){const t=this.texData.get(e),{isPacked:n,shape:s,dtype:i}=t,o=US(s);let a;n?a=new u6(o):a=new h6(o);const c=!0,h=this.runWebGLProgram(a,[{shape:o,dtype:i,dataId:e}],i,null,c);return{dtype:i,shape:s,dataId:h.dataId}}runWebGLProgram(e,t,n,s,i=!1){const o=this.makeTensorInfo(e.outputShape,n),a=this.texData.get(o.dataId);if(e.packedOutput&&(a.isPacked=!0),e.outPackingScheme===xu.DENSE){const L=Au(e.outputShape);a.texShape=L.map(T=>T*2)}if(e.outTexUsage!=null&&(a.usage=e.outTexUsage),M(o.shape)===0)return a.values=bt(o.dtype,0),o;const c=[],h=t.map(L=>{if(L.dtype==="complex64")throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");let T=this.texData.get(L.dataId);if(T.texture==null){if(!e.packedInputs&&M(L.shape)<=ae().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:L.shape,texData:null,isUniform:!0,uniformValues:T.values};e.packedInputs&&(T.isPacked=!0,T.shape=L.shape)}else if(!!T.isPacked!==!!e.packedInputs)L=T.isPacked?this.unpackTensor(L):this.packTensor(L),c.push(L),T=this.texData.get(L.dataId);else if(T.isPacked&&!qm(T.shape,L.shape)){const v=L,C=L.shape;L.shape=T.shape,L=this.packedReshape(L,C),c.push(L),T=this.texData.get(L.dataId),v.shape=C}return this.uploadToGPU(L.dataId),{shape:L.shape,texData:T,isUniform:!1}});this.uploadToGPU(o.dataId);const p={shape:o.shape,texData:a,isUniform:!1},m=z6(e,h,p),y=this.getAndSaveBinary(m,()=>M6(this.gpgpu,e,h,p)),b=this.activeTimers!=null;let w;if(b&&(w=this.startTimer()),P6(this.gpgpu,y,h,p,s),c.forEach(L=>this.disposeIntermediateTensorInfo(L)),b&&(w=this.endTimer(w),this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(w)})),!ae().getBool("WEBGL_LAZILY_UNPACK")&&a.isPacked&&i===!1){const L=this.unpackTensor(o);return this.disposeIntermediateTensorInfo(o),L}return o}compileAndRun(e,t,n,s,i=!1){n=n||t[0].dtype;const o=this.runWebGLProgram(e,t,n,s,i);return tr().makeTensorFromDataId(o.dataId,o.shape,o.dtype)}getAndSaveBinary(e,t){return e in this.binaryCache||(this.binaryCache[e]=t()),this.binaryCache[e]}getTextureManager(){return this.textureManager}dispose(){if(this.disposed)return;if(!ae().getBool("IS_TEST")){const e=Object.keys(this.binaryCache);e.forEach(t=>{this.gpgpu.deleteProgram(this.binaryCache[t].webGLProgram),delete this.binaryCache[t]})}this.textureManager.dispose(),this.canvas!=null&&typeof HTMLCanvasElement!="undefined"&&this.canvas instanceof HTMLCanvasElement?this.canvas.remove():this.canvas=null,this.gpgpuCreatedLocally&&(this.gpgpu.program=null,this.gpgpu.dispose()),this.disposed=!0}floatPrecision(){return this.floatPrecisionValue==null&&(this.floatPrecisionValue=ee(()=>{if(!ae().get("WEBGL_RENDER_FLOAT32_ENABLED")){const e=ae().getBool("DEBUG");ae().set("DEBUG",!1);const t=this.abs(Ce(1e-8)).dataSync()[0];if(ae().set("DEBUG",e),t>0)return 32}return 16})),this.floatPrecisionValue}epsilon(){return this.floatPrecision()===32?sX:iX}uploadToGPU(e){const t=this.texData.get(e),{shape:n,dtype:s,values:i,texture:o,usage:a,isPacked:c}=t;if(o!=null)return;const h=this.activeTimers!=null;let p;h&&(p=Jn());let m=t.texShape;if(m==null&&(m=y5(n,c),t.texShape=m),i!=null){const y=US(n);let b,w=m[1],L=m[0];const T=i instanceof Uint8Array;c?([w,L]=Ac(m[0],m[1]),b=new y6(y,[L,w],T)):b=new g6(y,[L,w],T);const v=this.makeTensorInfo([L,w],s);T?this.texData.get(v.dataId).usage=Os.PIXELS:this.texData.get(v.dataId).usage=Os.UPLOAD,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(v.dataId),w,L,i);const C=!0,O=this.runWebGLProgram(b,[v],s,null,C),D=this.texData.get(O.dataId);t.texture=D.texture,t.texShape=D.texShape,t.isPacked=D.isPacked,t.usage=D.usage,this.disposeIntermediateTensorInfo(v),this.texData.delete(O.dataId),t.values=null,h&&(this.uploadWaitMs+=Jn()-p)}else{const y=this.acquireTexture(m,a,s,c);t.texture=y}}convertAndCacheOnCPU(e,t){const n=this.texData.get(e),{dtype:s}=n;return this.releaseGPUData(e),t!=null&&(n.values=hX(t,s)),n.values}acquireTexture(e,t,n,s){if(this.numBytesInGPU+=this.computeBytes(e,n),!this.warnedAboutMemory&&this.numBytesInGPU>this.numMBBeforeWarning*1024*1024){const i=(this.numBytesInGPU/1024/1024).toFixed(2);this.warnedAboutMemory=!0,console.warn(`High memory usage in GPU: ${i} MB, most likely due to a memory leak`)}return this.textureManager.acquireTexture(e,t,s)}computeBytes(e,t){return e[0]*e[1]*iy(t)}tryRunOnCpuOrThrow(e,t){if(this.shouldExecuteOnCPU(e))try{return t()}catch(n){if(ae().getBool("IS_TEST"))throw new Error("CPU forwarding failed")}return null}}function hX(e,t){if(t==="float32"||t==="complex64")return e;if(t==="int32"||t==="bool"){const n=t==="int32"?new Int32Array(e.length):new Uint8Array(e.length);for(let s=0;s<n.length;++s)n[s]=Math.round(e[s]);return n}else throw new Error(`Unknown dtype ${t}`)}const uX="2.7.0";function dX(){ae().set("WEBGL_FORCE_F16_TEXTURES",!0)}sb()&&Tb("webgl",()=>new lX,2);const ese={forceHalfFloat:dX};function yr(e){const{inputs:t,backend:n}=e,{x:s}=t;return n.incRef(s.dataId),{dataId:s.dataId,shape:s.shape,dtype:s.dtype}}const pX={kernelName:$l,backendName:"webgl",kernelFunc:yr};function Dc(e){const{inputs:t,backend:n}=e,{real:s,imag:i}=t,o=n.makeTensorInfo(s.shape,"complex64"),a=n.texData.get(o.dataId),c=yr({inputs:{x:s},backend:n}),h=n.texData.get(c.dataId);h.complexParentRefCount++;const p=yr({inputs:{x:i},backend:n}),m=n.texData.get(p.dataId);return m.complexParentRefCount++,a.complexTensorInfos={real:c,imag:p},o}const mX={kernelName:xd,backendName:"webgl",kernelFunc:Dc};const u2="if (isnan(x)) return x;",fX=`
if (isnan(a)) return a;
if (isnan(b)) return b;
`,gX=`
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 tf(e){return({inputs:t,backend:n})=>{const{x:s}=t,i=n,o=new it(s.shape,e);return i.runWebGLProgram(o,[s],s.dtype)}}function kc({opSnippet:e,packedOpSnippet:t,checkOutOfBounds:n=!1,supportsComplex:s=!1,cpuKernelImpl:i,dtype:o}){return({inputs:a,backend:c})=>{const{a:h,b:p}=a,m=c;if(s&&h.dtype==="complex64"){const L=m.texData.get(h.dataId),T=m.texData.get(p.dataId),[v,C]=[[L.complexTensorInfos.real,T.complexTensorInfos.real],[L.complexTensorInfos.imag,T.complexTensorInfos.imag]].map(D=>{const[k,F]=D,B={dataId:k.dataId,dtype:k.dtype,shape:h.shape},$={dataId:F.dataId,dtype:F.dtype,shape:p.shape},Y=new $n(e,h.shape,p.shape);return m.runWebGLProgram(Y,[B,$],Bn(k.dtype,F.dtype))}),O=Dc({inputs:{real:v,imag:C},backend:m});return m.disposeIntermediateTensorInfo(v),m.disposeIntermediateTensorInfo(C),O}const y=o||Bn(h.dtype,p.dtype);if(m.shouldExecuteOnCPU([h,p])&&i!=null){const L=m.texData.get(h.dataId),T=m.texData.get(p.dataId),[v,C]=i(h.shape,p.shape,L.values,T.values,y),O=m.makeTensorInfo(C,y),D=m.texData.get(O.dataId);return D.values=v,O}const b=ae().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&t!=null;let w;return b?w=new fr(t,h.shape,p.shape,n):w=new $n(e,h.shape,p.shape),m.runWebGLProgram(w,[h,p],y)}}const d2="return a + b;",yX=kc({opSnippet:d2,packedOpSnippet:d2,supportsComplex:!0,cpuKernelImpl:v5}),bX={kernelName:Oo,backendName:"webgl",kernelFunc:yX};const wX=fX+`
return atan(a, b);
`,LX=`
vec4 result = atan(a, b);
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
`+gX+`
return result;
`,SX=kc({opSnippet:wX,packedOpSnippet:LX}),IX={kernelName:Ld,backendName:"webgl",kernelFunc:SX};function xX(e){const{inputs:t,backend:n,attrs:s}=e,{x:i}=t;vu(i,"avgPool");const{filterSize:o,strides:a,pad:c,dimRoundingMode:h}=s,p=1;A(cn(a,p),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${p}'`);const m=Mn(i.shape,o,a,p,c,h);if(m.filterWidth===1&&m.filterHeight===1&&ie(m.inShape,m.outShape))return yr({inputs:{x:i},backend:n});const y=new Cu(m,"avg",!1);return n.runWebGLProgram(y,[i],"float32")}const TX={kernelName:vl,backendName:"webgl",kernelFunc:xX};function AX(e){const{inputs:t,backend:n,attrs:s}=e,{dy:i,input:o}=t,a=o;vu([i,o],"avgPoolBackprop");const{filterSize:c,strides:h,pad:p}=s,m=Mn(a.shape,c,h,1,p),y=new A8(m);return n.runWebGLProgram(y,[i],a.dtype)}const vX={kernelName:Sd,backendName:"webgl",kernelFunc:AX};class NX{constructor(e,t,n,s,i,o){this.outputShape=[],this.variableNames=["x","mean","variance"],st(e,t),st(e,n);let a="0.0";s!=null&&(st(e,s),this.variableNames.push("offset"),a="getOffsetAtOutCoords()");let c="1.0";i!=null&&(st(e,i),this.variableNames.push("scale"),c="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`
void main() {
float x = getXAtOutCoords();
float mean = getMeanAtOutCoords();
float variance = getVarianceAtOutCoords();
float offset = ${a};
float scale = ${c};
float inv = scale * inversesqrt(variance + float(${o}));
setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));
}
`}}class CX{constructor(e,t,n,s,i,o){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],st(e,t),st(e,n);let a="vec4(0.0)";s!=null&&(st(e,s),this.variableNames.push("offset"),a="getOffsetAtOutCoords()");let c="vec4(1.0)";i!=null&&(st(e,i),this.variableNames.push("scale"),c="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`
void main() {
vec4 offset = ${a};
vec4 scale = ${c};
vec4 x = getXAtOutCoords();
vec4 mean = getMeanAtOutCoords();
vec4 variance = getVarianceAtOutCoords();
vec4 inv = scale * inversesqrt(variance + vec4(${o}));
setOutput((x - mean) * inv + offset);
}
`}}const RX=({inputs:e,backend:t,attrs:n})=>{const{x:s,mean:i,variance:o,offset:a,scale:c}=e;A(i.shape.length===o.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),A(a==null||i.shape.length===a.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),A(c==null||i.shape.length===c.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let{varianceEpsilon:h}=n;h==null&&(h=.001);const p=[s,i,o];let m=null;a!=null&&(m=a.shape,p.push(a));let y=null;c!=null&&(y=c.shape,p.push(c));const b=ae().getBool("WEBGL_PACK_NORMALIZATION")?new CX(s.shape,i.shape,o.shape,m,y,h):new NX(s.shape,i.shape,o.shape,m,y,h),w=t.runWebGLProgram(b,p,p[0].dtype);return w},OX={kernelName:Wl,backendName:"webgl",kernelFunc:RX};const EX="return float(a != b);",p2=kc({opSnippet:EX,dtype:"bool"}),DX={kernelName:Hl,backendName:"webgl",kernelFunc:p2};function YS(e){const{inputs:t,backend:n}=e,{input:s}=t,i=n.texData.get(s.dataId);return yr({inputs:{x:i.complexTensorInfos.real},backend:n})}const kX={kernelName:zd,backendName:"webgl",kernelFunc:YS};const FX="return float(int(x));";function _X(e,t){const n=new it(e.shape,FX),s=t.runWebGLProgram(n,[e],"int32");return{dataId:s.dataId,shape:s.shape,dtype:s.dtype}}function HS(e){const{inputs:t,backend:n,attrs:s}=e,{x:i}=t,{dtype:o}=s;if(o==="complex64"){if(i.dtype==="complex64")return yr({inputs:{x:i},backend:n});const a=pt(i.shape),c=HS({inputs:{x:i},backend:n,attrs:{dtype:"float32"}}),h=Dc({inputs:{real:c,imag:a},backend:n});return a.dispose(),n.disposeIntermediateTensorInfo(c),h}if(i.dtype==="complex64"){const a=YS({inputs:{input:i},backend:n}),c=HS({inputs:{x:a},backend:n,attrs:{dtype:o}});return n.disposeIntermediateTensorInfo(a),c}if(!Oa(i.dtype,o)){const a=yr({inputs:{x:i},backend:n});return{dataId:a.dataId,shape:a.shape,dtype:o}}if(o==="int32")return _X(i,n);if(o==="bool"){const a=n.makeTensorInfo([],"bool",bt("bool",1)),c={a:i,b:a},h=p2({inputs:c,backend:n});return n.disposeIntermediateTensorInfo(a),h}throw new Error(`Error in Cast: failed to cast ${i.dtype} to ${o}`)}const WX={kernelName:ka,backendName:"webgl",kernelFunc:HS};class $X{constructor(e){this.outputShape=[],this.outputShape=nr(e,1),this.variableNames=e.map((o,a)=>`T${a}`);const t=new Array(e.length-1);t[0]=e[0][1];for(let o=1;o<t.length;o++)t[o]=t[o-1]+e[o][1];const n=[`if (yC < ${t[0]}) setOutput(getT0(yR, yC));`];for(let o=1;o<t.length;o++){const a=t[o-1];n.push(`else if (yC < ${t[o]}) setOutput(getT${o}(yR, yC-${a}));`)}const s=t.length,i=t[t.length-1];n.push(`else setOutput(getT${s}(yR, yC-${i}));`),this.userCode=`
void main() {
ivec2 coords = getOutputCoords();
int yR = coords.x;
int yC = coords.y;
${n.join(`
`)}
}
`}}class UX{constructor(e,t){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=nr(e,t);const n=this.outputShape,s=n.length,i=Rt(s),o=zn("coords",s),a=["x","y","z","w","u","v"].slice(0,s);this.variableNames=e.map((L,T)=>`T${T}`);const c=new Array(e.length-1);c[0]=e[0][t];for(let L=1;L<c.length;L++)c[L]=c[L-1]+e[L][t];const h=a[t],p=a.slice(-2),m=a.join();let y=`if (${h} < ${c[0]}) {
return getChannel(
getT0(${m}), vec2(${p.join()}));
}`;for(let L=1;L<c.length;L++){const T=c[L-1];y+=`
if (${h} < ${c[L]} && ${h} >= ${c[L-1]}) {
return getChannel(
getT${L}(${nf(a,h,T)}),
vec2(${nf(p,h,T)}));
}`}const b=c.length,w=c[c.length-1];y+=`
return getChannel(
getT${b}(${nf(a,h,w)}),
vec2(${nf(p,h,w)}));`,this.userCode=`
float getValue(${a.map(L=>"int "+L)}) {
${y}
}
void main() {
${i} coords = getOutputCoords();
vec4 result = vec4(getValue(${o}), 0., 0., 0.);
${o[s-1]} = ${o[s-1]} + 1;
if (${o[s-1]} < ${n[s-1]}) {
result.g = getValue(${o});
}
${o[s-2]} = ${o[s-2]} + 1;
if (${o[s-2]} < ${n[s-2]}) {
result.a = getValue(${o});
}
${o[s-1]} = ${o[s-1]} - 1;
if (${o[s-2]} < ${n[s-2]} &&
${o[s-1]} < ${n[s-1]}) {
result.b = getValue(${o});
}
setOutput(result);
}
`}}function nf(e,t,n){const s=e.indexOf(t),i=e.map((o,a)=>a===s?`${o} - ${n}`:o);return i.join()}function m2(e){const{inputs:t,backend:n}=e,{input:s}=t,i=n.texData.get(s.dataId);return yr({inputs:{x:i.complexTensorInfos.imag},backend:n})}const BX={kernelName:Fd,backendName:"webgl",kernelFunc:m2};function MX(e,t,n){const s=[vc(e.shape),...Nc(e.shape)],i={dtype:e.dtype,shape:s,dataId:e.dataId},o=[vc(t),...Nc(t)],a=new HC(o,s),c=!0,h=n.runWebGLProgram(a,[i],e.dtype,null,c);return{dataId:h.dataId,shape:t,dtype:h.dtype}}function br(e){const{inputs:t,backend:n,attrs:s}=e,{x:i}=t,{shape:o}=s,a=n,c=M(i.shape),h=Vt(o,c),p=M(h);A(c===p,()=>`The new shape (${h}) has ${p} elements and the old shape (${i.shape}) has ${c} elements. The new shape and old shape must have the same number of elements.`);const m=a.texData.get(i.dataId);return m.isPacked&&!qm(i.shape,h)&&!(m.texture!==null&&qm(m.shape,h))?MX(i,h,a):(a.incRef(i.dataId),{dataId:i.dataId,shape:h,dtype:i.dtype})}const PX={kernelName:Kl,backendName:"webgl",kernelFunc:br};function Fc(e,t,n){const s=e[0].dtype;if(s==="complex64"){const p=e.map(L=>YS({inputs:{input:L},backend:n})),m=e.map(L=>m2({inputs:{input:L},backend:n})),y=Fc(p,t,n),b=Fc(m,t,n),w=Dc({inputs:{real:y,imag:b},backend:n});return p.forEach(L=>n.disposeIntermediateTensorInfo(L)),m.forEach(L=>n.disposeIntermediateTensorInfo(L)),n.disposeIntermediateTensorInfo(y),n.disposeIntermediateTensorInfo(b),w}if(e.length>ae().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){const p=Math.floor(e.length/2),m=Fc(e.slice(0,p),t,n),y=Fc(e.slice(p),t,n),b=Fc([m,y],t,n);return n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(y),b}if(ae().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&e[0].shape.length>1){const p=new UX(e.map(m=>m.shape),t);return n.runWebGLProgram(p,e,s)}const i=nr(e.map(p=>p.shape),t),o=e.map(p=>br({inputs:{x:p},attrs:{shape:[-1,M(p.shape.slice(t))]},backend:n})),a=new $X(o.map(p=>p.shape)),c=n.runWebGLProgram(a,o,s);o.forEach(p=>n.disposeIntermediateTensorInfo(p));const h=br({inputs:{x:c},attrs:{shape:i},backend:n});return n.disposeIntermediateTensorInfo(c),h}function zX(e){const{inputs:t,backend:n,attrs:s}=e,{axis:i}=s,o=je(i,t[0].shape)[0],a=nr(t.map(p=>p.shape),o);if(M(a)===0)return n.makeTensorInfo(a,t[0].dtype,[]);const c=t.filter(p=>M(p.shape)>0);if(c.length===1)return c[0];const h=c.map(p=>p.shape);return Lp(h,o),Fc(c,o,n)}const VX={kernelName:Rl,backendName:"webgl",kernelFunc:zX};const GX=u2+`
return cos(x);
`,YX=tf(GX),HX={kernelName:Fa,backendName:"webgl",kernelFunc:YX};const qX=`
if (a == b) {
return 1.0;
};
return a / b;`,jX=`
// 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;
`,KX=kc({opSnippet:qX,packedOpSnippet:jX,checkOutOfBounds:!0}),XX={kernelName:_a,backendName:"webgl",kernelFunc:KX};class f2{constructor(e,t,n){this.variableNames=["real","imag"];const s=t[1];this.outputShape=t;const i=n?`2.0 * ${Math.PI}`:`-2.0 * ${Math.PI}`,o=n?`${s}.0`:"1.0";let a;if(e==="real")a="return real * expR - imag * expI;";else if(e==="imag")a="return real * expI + imag * expR;";else throw new Error(`FFT component must be either "real" or "imag", got ${e}.`);this.userCode=`
const float exponentMultiplier = ${i};
float unaryOpComplex(float real, float expR, float imag, float expI) {
${a}
}
float mulMatDFT(int batch, int index) {
float indexRatio = float(index) / float(${s});
float exponentMultiplierTimesIndexRatio =
exponentMultiplier * indexRatio;
float result = 0.0;
for (int i = 0; i < ${s}; i++) {
// x = (-2|2 * PI / N) * index * i;
float x = exponentMultiplierTimesIndexRatio * float(i);
float expR = cos(x);
float expI = sin(x);
float real = getReal(batch, i);
float imag = getImag(batch, i);
result +=
unaryOpComplex(real, expR, imag, expI) / ${o};
}
return result;
}
void main() {
ivec2 coords = getOutputCoords();
setOutput(mulMatDFT(coords[0], coords[1]));
}
`}}function g2(e,t,n){const s=n.texData.get(e.dataId),i=M(e.shape),o=e.shape[e.shape.length-1],a=i/o,c=br({inputs:{x:e},backend:n,attrs:{shape:[a,o]}}),h=c.shape,p=new f2("real",h,t),m=new f2("imag",h,t),y=[{dataId:s.complexTensorInfos.real.dataId,dtype:s.complexTensorInfos.real.dtype,shape:h},{dataId:s.complexTensorInfos.imag.dataId,dtype:s.complexTensorInfos.imag.dtype,shape:h}],b=n.runWebGLProgram(p,y,"float32"),w=n.runWebGLProgram(m,y,"float32"),L=Dc({inputs:{real:b,imag:w},backend:n});n.disposeIntermediateTensorInfo(b),n.disposeIntermediateTensorInfo(w);const T=br({inputs:{x:L},backend:n,attrs:{shape:e.shape}});return n.disposeIntermediateTensorInfo(T),T}function JX(e){const{inputs:t,backend:n}=e,{input:s}=t;return g2(s,!1,n)}const ZX={kernelName:Ed,backendName:"webgl",kernelFunc:JX};class QX{constructor(e){this.variableNames=["Image"],this.outputShape=[];const t=e[2];this.outputShape=e,this.userCode=`
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 eJ={kernelName:Dd,backendName:"webgl",kernelFunc:({inputs:e,backend:t})=>{const{image:n}=e,s=t,i=new QX(n.shape),o=s.runWebGLProgram(i,[n],n.dtype);return o}};class tJ{constructor(e){this.variableNames=["A"];const t=Vn(),[n,s]=e;this.outputShape=e,this.userCode=`
void main() {
ivec3 coords = getOutputCoords();
int texR = coords[0];
int texC = coords[1];
int depth = coords[2];
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${s}.0, ${n}.0);
vec4 values = ${t.texture2D}(A, uv);
float value;
if (depth == 0) {
value = values.r;
} else if (depth == 1) {
value = values.g;
} else if (depth == 2) {
value = values.b;
} else if (depth == 3) {
value = values.a;
}
setOutput(floor(value * 255.0 + 0.5));
}
`}}class nJ{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;const t=Vn(),[n,s]=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(${s}.0, ${n}.0);
vec4 values = ${t.texture2D}(A, uv);
float value;
if (depth == 0) {
value = values.r;
} else if (depth == 1) {
value = values.g;
} else if (depth == 2) {
value = values.b;
} else if (depth == 3) {
value = values.a;
}
result[row * 2 + col] = floor(value * 255.0 + 0.5);
}
}
${t.output} = result;
}
`}}const sJ={kernelName:qd,backendName:"webgl",kernelFunc:iJ};let _c;function iJ(e){const{inputs:t,backend:n,attrs:s}=e;let{pixels:i}=t;const{numChannels:o}=s,a=typeof HTMLVideoElement!="undefined"&&i instanceof HTMLVideoElement,c=typeof HTMLImageElement!="undefined"&&i instanceof HTMLImageElement,[h,p]=a?[i.videoWidth,i.videoHeight]:[i.width,i.height],m=[p,h],y=[p,h,o];(c||a)&&(_c==null&&(_c=document.createElement("canvas").getContext("2d")),_c.canvas.width=h,_c.canvas.height=p,_c.drawImage(i,0,0,h,p),i=_c.canvas);const b=n.makeTensorInfo(m,"int32");n.texData.get(b.dataId).usage=Os.PIXELS,n.gpgpu.uploadPixelDataToTexture(n.getTexture(b.dataId),i);const w=ae().getBool("WEBGL_PACK")?new nJ(y):new tJ(y),L=n.runWebGLProgram(w,[b],"int32");return n.disposeData(b.dataId),L}function rJ(e){const{inputs:t,backend:n}=e,{input:s}=t;return g2(s,!0,n)}const oJ={kernelName:kd,backendName:"webgl",kernelFunc:rJ};class y2{constructor(e,t){this.variableNames=["x"];const{windowSize:n,batchSize:s,inSize:i,outSize:o}=e;this.outputShape=[s,o];const a=Math.floor(n/4)*4,c=n%4;let h="sumValue += dot(values, ones);";if(t!=null){const m=1/t;h=`sumValue += dot(values * ${we(m)?m.toPrecision(2):m}, ones);`}let p="";i%n>0&&(p=`
if (inIdx < 0 || inIdx >= ${i}) {
return 0.0;
}
`),this.userCode=`
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
float getValue(int batch, int inIdx) {
${p}
return getX(batch, inIdx);
}
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
int inOffset = outIdx * ${n};
float sumValue = 0.0;
for (int i = 0; i < ${a}; i += 4) {
int inIdx = inOffset + i;
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
getValue(batch, inIdx + 3)
);
${h}
}
int inIdx = inOffset + ${a};
if (${c===1}) {
vec4 values = vec4(getValue(batch, inIdx), 0.0, 0.0, 0.0);
${h}
} else if (${c===2}) {
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1), 0.0, 0.0);
${h}
} else if (${c===3}) {
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2), 0.0);
${h}
}
setOutput(sumValue);
}
`}}function aJ(e){const t=[];for(;t.length===0||t[t.length-1].outSize!==1;){const n=t.length?t[t.length-1].outSize:e[1],s=Ah(n);t.push({inSize:n,windowSize:s,outSize:Math.ceil(n/s)})}return t}function b2(e,t,n,s){const i=aJ(e.shape);let o=e;for(let a=0;a<i.length;a++){const{inSize:c,windowSize:h,outSize:p}=i[a];let m,y;n==="mean"?m=a===0?new y2({windowSize:h,inSize:c,batchSize:e.shape[0],outSize:p},c):new y2({windowSize:h,inSize:c,batchSize:e.shape[0],outSize:p}):m=new YC({windowSize:h,inSize:c,batchSize:e.shape[0],outSize:p},n),y=o,o=s.runWebGLProgram(m,[o],t),y.dataId!==e.dataId&&s.disposeIntermediateTensorInfo(y)}return o}function cJ(e,t,n,s){const i=M(t),o=M(e.shape),a=o/i,c=br({inputs:{x:e},attrs:{shape:[a,i]},backend:s}),h=b2(c,e.dtype,"max",s),p=br({inputs:{x:h},attrs:{shape:n},backend:s});return s.disposeIntermediateTensorInfo(c),s.disposeIntermediateTensorInfo(h),p}class lJ{constructor(e,t){this.variableNames=["A"];const n=new Array(e.length);for(let o=0;o<n.length;o++)n[o]=e[t[o]];this.outputShape=n,this.rank=n.length;const s=Rt(this.rank),i=hJ(t);this.userCode=`
void main() {
${s} resRC = getOutputCoords();
setOutput(getA(${i}));
}
`}}function hJ(e){const t=e.length;if(t>6)throw Error(`Transpose for rank ${t} is not yet supported`);const n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],s=new Array(t);for(let i=0;i<e.length;i++)s[e[i]]=n[i];return s.join()}class uJ{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0;const n=new Array(e.length);for(let p=0;p<n.length;p++)n[p]=e[t[p]];if(this.outputShape=n,this.rank=n.length,this.rank>6)throw Error(`Packed transpose for rank ${this.rank} is not yet supported.`);const s=Rt(this.rank),i=AC("rc",this.rank),o=new Array(this.rank);for(let p=0;p<t.length;p++)o[t[p]]=i[p];const a=`vec2(${o.slice(-2).join()})`,c=`++${i[this.rank-1]} < ${n[this.rank-1]}`,h=`getChannel(getA(${o.join()}), ${a})`;this.userCode=`
void main() {
${s} rc = getOutputCoords();
vec4 result = vec4(0.);
result[0] = ${h};
if(${c}) {
result[1] = ${h};
}
--${i[this.rank-1]};
if(++${i[this.rank-2]} < ${n[this.rank-2]}) {
result[2] = ${h};
if(${c}) {
result[3] = ${h};
}
}
setOutput(result);
}
`}}function qS(e,t,n){const s=ae().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new uJ(e.shape,t):new lJ(e.shape,t);return n.runWebGLProgram(s,[e],e.dtype)}const dJ={kernelName:Vl,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:s}=e,{reductionIndices:i,keepDims:o}=t,a=n,c=s.shape.length,h=je(i,s.shape);let p=h;const m=Qn(p,c),y=m!=null,b=a.shouldExecuteOnCPU([s]);let w=s;if(y){if(b){const O=a.texData.get(w.dataId),D=O.values,k=new Array(c);for(let $=0;$<k.length;$++)k[$]=s.shape[m[$]];const F=MS(D,s.shape,s.dtype,m,k);w=a.makeTensorInfo(k,s.dtype);const B=a.texData.get(w.dataId);B.values=F}else w=qS(s,m,a);p=hs(p.length,c)}Zn("max",p,c);const[L,T]=vn(w.shape,p);let v=L;o&&(v=Nn(L,h));let C;if(b){const O=a.texData.get(w.dataId),D=O.values,k=D5(D,M(T),v,s.dtype);C=a.makeTensorInfo(v,s.dtype);const F=a.texData.get(C.dataId);F.values=k}else C=cJ(w,T,v,a);return y&&a.disposeIntermediateTensorInfo(w),C}};function pJ(e){const{inputs:t,backend:n,attrs:s}=e,{x:i}=t;vu(i,"maxPool");const{filterSize:o,strides:a,pad:c,dimRoundingMode:h}=s,p=1;A(cn(a,p),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${p}'`);const m=Mn(i.shape,o,a,p,c,h);if(m.filterWidth===1&&m.filterHeight===1&&ie(m.inShape,m.outShape))return yr({inputs:{x:i},backend:n});const y=new Cu(m,"max",!1);return n.runWebGLProgram(y,[i],i.dtype)}const mJ={kernelName:Gl,backendName:"webgl",kernelFunc:pJ};function fJ(e){const{inputs:t,backend:n,attrs:s}=e,{dy:i,input:o,output:a}=t,c=o;vu([o,a],"maxPoolBackprop");const{filterSize:h,strides:p,pad:m,dimRoundingMode:y}=s,b=Mn(c.shape,h,p,1,m,y),w=!0,L=new Cu(b,"max",w),T=n.runWebGLProgram(L,[c],c.dtype),v=new q6(b),C=n.runWebGLProgram(v,[i,T],c.dtype);return n.disposeIntermediateTensorInfo(T),C}const gJ={kernelName:Wd,backendName:"webgl",kernelFunc:fJ};function yJ(e,t,n,s){let i=new Cu(n,"max",!1);const o=s.runWebGLProgram(i,[e],"float32");i=new Cu(n,"max",!0,!0,t);const a=s.runWebGLProgram(i,[e],"float32");return[o,a]}const bJ={kernelName:$d,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:s}=e,{filterSize:i,strides:o,pad:a,includeBatchInIndex:c}=t,h=n;A(s.shape.length===4,()=>`Error in maxPool: input must be rank 4 but got rank ${s.shape.length}.`);const p=[1,1];A(cn(o,p),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${o} and dilations '${p}'`);const m=Mn(s.shape,i,o,p,a),[y,b]=yJ(s,c,m,h);return[y,b]}};function wJ(e,t,n,s){const i=M(t),o=M(e.shape),a=o/i,c=br({inputs:{x:e},attrs:{shape:[a,i]},backend:s}),h=b2(c,"float32","mean",s),p=br({inputs:{x:h},attrs:{shape:n},backend:s});return s.disposeIntermediateTensorInfo(c),s.disposeIntermediateTensorInfo(h),p}const LJ={kernelName:Ry,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:s}=e,{keepDims:i,axis:o}=t,a=n,c=s.shape.length,h=je(o,s.shape);let p=h;const m=Qn(p,c),y=m!=null,b=a.shouldExecuteOnCPU([s]),w=[];let L=s;if(y){if(b){const D=a.texData.get(L.dataId),k=D.values,F=new Array(c);for(let Y=0;Y<F.length;Y++)F[Y]=s.shape[m[Y]];const B=MS(k,s.shape,s.dtype,m,F);L=a.makeTensorInfo(F,s.dtype);const $=a.texData.get(L.dataId);$.values=B}else L=qS(s,m,a);w.push(L),p=hs(p.length,c)}Zn("sum",p,c);const[T,v]=vn(L.shape,p);let C=T;i&&(C=Nn(T,h));const O=wJ(L,v,C,a);for(const D of w)a.disposeIntermediateTensorInfo(D);return O}};class SJ{constructor(e,t,n){this.variableNames=["x"],this.outputShape=t.map((p,m)=>p[0]+e[m]+p[1]);const s=e.length,i=Rt(s),o=t.map(p=>p[0]).join(","),a=t.map((p,m)=>p[0]+e[m]).join(","),c=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,s),h=n==="reflect"?0:1;if(s===1){this.userCode=`
int start = ${o};
int end = ${a};
void main() {
int outC = getOutputCoords();
if (outC < start) {
outC = start * 2 - outC - ${h};
} else if(outC >= end) {
outC = (end - 1) * 2 - outC + ${h};
}
setOutput(getX(outC - start));
}
`;return}this.userCode=`
${i} start = ${i}(${o});
${i} end = ${i}(${a});
void main() {
${i} outC = getOutputCoords();
for (int i = 0; i < ${s}; i++) {
if (outC[i] < start[i]) {
outC[i] = start[i] * 2 - outC[i] - ${h};
} else if(outC[i] >= end[i]) {
outC[i] = (end[i] - 1) * 2 - outC[i] + ${h};
}
}
${i} coords = outC - start;
setOutput(getX(${c}));
}
`}}class IJ{constructor(e,t,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.map((w,L)=>w[0]+e[L]+w[1]);const s=e.length,i=Rt(s),o=t.map(w=>w[0]).join(","),a=t.map((w,L)=>w[0]+e[L]).join(","),c=zn("rc",s),h=zn("source",s),p=`${c[s-1]} < ${this.outputShape[s-1]}`,m=s===1?"source":`vec2(${h.slice(-2).join()})`,y=n==="reflect"?0:1;let b="";if(s===1){const w=`
${i} source = rc;
if (source < start) {
source = start * 2 - source - ${y};
} else if (source >= end) {
source = (end - 1) * 2 - source + ${y};
}
source -= start;
`;b=`
${i} rc = outputLoc;
${w}
result[0] = getChannel(getX(${h.join()}), ${m});
${c[s-1]} += 1;
if(${p}) {
${w}
result[1] = getChannel(getX(${h.join()}), ${m});
}
`}else{const w=`
${i} source = rc;
${i} lt = ${i}(lessThan(source, start));
${i} gte = ${i}(greaterThanEqual(source, end));
${i} orig = 1 - (lt + gte);
source = orig * source +
lt * (start * 2 - source - ${y}) +
gte * ((end - 1) * 2 - source + ${y});
source -= start;
`;b=`
${i} rc = outputLoc;
${w}
result[0] = getChannel(getX(${h.join()}), ${m});
${c[s-1]} += 1;
if(${p}) {
${w}
result[1] = getChannel(getX(${h.join()}), ${m});
}
rc = outputLoc;
${c[s-2]} += 1;
if(${c[s-2]} < ${this.outputShape[s-2]}) {
${w}
result[2] = getChannel(getX(${h.join()}), ${m});
${c[s-1]} += 1;
if(${p}) {
${w}
result[3] = getChannel(getX(${h.join()}), ${m});
}
}
`}this.userCode=`
const ${i} start = ${i}(${o});
const ${i} end = ${i}(${a});
void main() {
${i} outputLoc = getOutputCoords();
vec4 result = vec4(0.);
${b}
setOutput(result);
}
`}}const xJ=({inputs:e,backend:t,attrs:n})=>{const{x:s}=e,{paddings:i,mode:o}=n,a=ae().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new IJ(s.shape,i,o):new SJ(s.shape,i,o),c=t.runWebGLProgram(a,[s],s.dtype);return c},TJ={kernelName:Yl,backendName:"webgl",kernelFunc:xJ};const w2={REAL:"return areal * breal - aimag * bimag;",IMAG:"return areal * bimag + aimag * breal;"};class L2{constructor(e,t,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=st(t,n),this.userCode=`
float binaryOpComplex(
float areal, float aimag, float breal, float bimag) {
${e}
}
void main() {
float areal = getARealAtOutCoords();
float aimag = getAImagAtOutCoords();
float breal = getBRealAtOutCoords();
float bimag = getBImagAtOutCoords();
setOutput(binaryOpComplex(areal, aimag, breal, bimag));
}
`}}const S2="return a * b;";function AJ(e){const{inputs:t,backend:n}=e,{a:s,b:i}=t,o=Bn(s.dtype,i.dtype);if(s.dtype==="complex64"){const c=n.texData.get(s.dataId),h=n.texData.get(i.dataId),p=new L2(w2.REAL,s.shape,i.shape),m=new L2(w2.IMAG,s.shape,i.shape),y=[{dataId:c.complexTensorInfos.real.dataId,dtype:c.complexTensorInfos.real.dtype,shape:s.shape},{dataId:c.complexTensorInfos.imag.dataId,dtype:c.complexTensorInfos.imag.dtype,shape:s.shape},{dataId:h.complexTensorInfos.real.dataId,dtype:h.complexTensorInfos.real.dtype,shape:i.shape},{dataId:h.complexTensorInfos.imag.dataId,dtype:h.complexTensorInfos.imag.dtype,shape:i.shape}],b=n.runWebGLProgram(p,y,"float32"),w=n.runWebGLProgram(m,y,"float32"),L=Dc({inputs:{real:b,imag:w},backend:n});return n.disposeIntermediateTensorInfo(b),n.disposeIntermediateTensorInfo(w),L}if(n.shouldExecuteOnCPU([s,i])){const c=n.texData.get(s.dataId),h=n.texData.get(i.dataId),[p,m]=k5(s.shape,i.shape,c.values,h.values,o),y=n.makeTensorInfo(m,o),b=n.texData.get(y.dataId);return b.values=p,y}let a;return ae().getBool("WEBGL_PACK_BINARY_OPERATIONS")?a=new fr(S2,s.shape,i.shape):a=new $n(S2,s.shape,i.shape),n.runWebGLProgram(a,[s,i],o)}const vJ={kernelName:Wa,backendName:"webgl",kernelFunc:AJ};const NJ={kernelName:Fy,backendName:"webgl",kernelFunc:({inputs:e,backend:t,attrs:n})=>{hc("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{boxes:s,scores:i}=e,{maxOutputSize:o,iouThreshold:a,scoreThreshold:c}=n,h=t,p=h.readSync(s.dataId),m=h.readSync(i.dataId),y=o,b=a,w=c;return Xp(p,m,y,b,w)}};const CJ=Jp,RJ={kernelName:Ud,backendName:"webgl",kernelFunc:({inputs:e,backend:t,attrs:n})=>{hc("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{boxes:s,scores:i}=e,{maxOutputSize:o,iouThreshold:a,scoreThreshold:c,padToMaxOutputSize:h}=n,p=t,m=p.readSync(s.dataId),y=p.readSync(i.dataId),{selectedIndices:b,validOutputs:w}=CJ(m,y,o,a,c,h);return[b,w]}};const OJ=Zp,EJ={kernelName:Bd,backendName:"webgl",kernelFunc:({inputs:e,backend:t,attrs:n})=>{hc("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{boxes:s,scores:i}=e,{maxOutputSize:o,iouThreshold:a,scoreThreshold:c,softNmsSigma:h}=n,p=t,m=p.readSync(s.dataId),y=p.readSync(i.dataId),b=o,w=a,L=c,T=h,{selectedIndices:v,selectedScores:C}=OJ(m,y,b,w,L,T);return[v,C]}};class DJ{constructor(e,t,n,s){this.variableNames=["Image"],this.outputShape=[];const i=e[1],o=e[2],a=Math.sin(t).toFixed(3),c=Math.cos(t).toFixed(3);this.outputShape=e;const[h,p]=gw(s,i,o),m=h.toFixed(3),y=p.toFixed(3);let b="";typeof n=="number"?b=`float outputValue = ${n.toFixed(2)};`:b=`
vec3 fill = vec3(${n.join(",")});
float outputValue = fill[coords[3]];`,this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int x = coords[2];
int y = coords[1];
float coordXFloat = (float(x) - ${m}) * ${c} - (float(y) - ${y}) * ${a};
float coordYFloat = (float(x) - ${m}) * ${a} + (float(y) - ${y}) * ${c};
int coordX = int(round(coordXFloat + ${m}));
int coordY = int(round(coordYFloat + ${y}));
${b}
if(coordX >= 0 && coordX < ${o} && coordY >= 0 && coordY < ${i}) {
outputValue = getImage(coords[0], coordY, coordX, coords[3]);
}
setOutput(outputValue);
}
`}}const kJ={kernelName:jd,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{image:s}=e,{radians:i,fillValue:o,center:a}=t,c=n,h=new DJ(s.shape,i,o,a),p=c.runWebGLProgram(h,[s],s.dtype);return p}};const FJ=u2+`
return sin(x);
`,_J=tf(FJ),WJ={kernelName:$a,backendName:"webgl",kernelFunc:_J};const $J="return x * x;",UJ=tf($J),BJ={kernelName:Yd,backendName:"webgl",kernelFunc:UJ};const I2="return (a - b) * (a - b);",MJ=kc({opSnippet:I2,packedOpSnippet:I2}),PJ={kernelName:Ua,backendName:"webgl",kernelFunc:MJ};const x2="return a - b;",zJ=kc({opSnippet:x2,packedOpSnippet:x2,supportsComplex:!0,cpuKernelImpl:W5}),VJ={kernelName:Ba,backendName:"webgl",kernelFunc:zJ};const GJ="return tan(x);",YJ=tf(GJ),HJ={kernelName:Ma,backendName:"webgl",kernelFunc:YJ};const qJ={kernelName:oh,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:s}=e,{perm:i}=t,o=n,a=s.shape.length,c=new Array(a);for(let p=0;p<c.length;p++)c[p]=s.shape[i[p]];let h;if(o.shouldExecuteOnCPU([s])){const p=o.texData.get(s.dataId),m=p.values,y=MS(m,s.shape,s.dtype,i,c);h=o.makeTensorInfo(c,s.dtype);const b=o.texData.get(h.dataId);b.values=y}else h=qS(s,i,o);return h}};function jJ(e){const{inputs:t,attrs:n,backend:s}=e,{axis:i}=n,{x:o}=t;vu(o,"unique"),console.warn("WARNING: ","UI might be locked temporarily as data is being downloaded");const a=s.readSync(o.dataId),{outputValues:c,outputShape:h,indices:p}=$5(a,i,o.shape,o.dtype);return[s.makeTensorInfo(h,o.dtype,c),s.makeTensorInfo([p.length],"int32",p)]}const KJ={kernelName:Hd,backendName:"webgl",kernelFunc:jJ};const XJ=[bX,IX,TX,vX,OX,WX,mX,VX,HX,XX,ZX,eJ,sJ,pX,oJ,BX,dJ,mJ,gJ,bJ,LJ,TJ,vJ,NJ,RJ,EJ,DX,kX,PX,kJ,WJ,BJ,VJ,PJ,HJ,qJ,KJ];for(const e of XJ)Qd(e);const JJ="2.7.0";const ZJ={"tfjs-core":gA,"tfjs-backend-cpu":m4,"tfjs-backend-webgl":uX,"tfjs-data":Y0,"tfjs-layers":Nm,"tfjs-converter":x0,tfjs:JJ};r.Abs=wd,r.Acos=Ll,r.Acosh=Sl,r.AdadeltaOptimizer=Uh,r.AdagradOptimizer=Bh,r.AdamOptimizer=Mh,r.AdamaxOptimizer=Ph,r.Add=Oo,r.AddN=ly,r.All=sT,r.Any=iT,r.ArgMax=hy,r.ArgMin=uy,r.Asin=Il,r.Asinh=xl,r.Atan=Tl,r.Atan2=Ld,r.Atanh=Al,r.AvgPool=vl,r.AvgPool3D=dy,r.AvgPool3DBackprop=rT,r.AvgPoolBackprop=Sd,r.BatchMatMul=Id,r.BatchToSpaceND=py,r.BroadcastTo=my,r.Callback=c0,r.CallbackList=nN,r.Cast=ka,r.Ceil=Nl,r.ClipByValue=Cl,r.Complex=xd,r.Concat=Rl,r.Conv2D=Td,r.Conv2DBackpropFilter=fy,r.Conv2DBackpropInput=Ad,r.Conv3D=vd,r.Conv3DBackpropFilterV2=gy,r.Conv3DBackpropInputV2=yy,r.Cos=Fa,r.Cosh=Ol,r.CropAndResize=oT,r.Cumsum=by,r.CustomCallback=iN,r.DataStorage=d,r.DepthToSpace=aT,r.DepthwiseConv2dNative=Nd,r.DepthwiseConv2dNativeBackpropFilter=wy,r.DepthwiseConv2dNativeBackpropInput=Ly,r.Diag=cT,r.Dilation2D=Cd,r.Dilation2DBackpropFilter=Od,r.Dilation2DBackpropInput=Rd,r.Div=_a,r.EarlyStopping=h0,r.Elu=El,r.EluGrad=lT,r.Environment=eT,r.Equal=hT,r.Erf=Dl,r.Exp=kl,r.Expm1=Fl,r.FFT=Ed,r.Fill=Sy,r.FlipLeftRight=Dd,r.Floor=_l,r.FloorDiv=Iy,r.FromPixels=qd,r.FusedBatchNorm=Wl,r.FusedConv2D=Xd,r.FusedDepthwiseConv2D=Jd,r.GatherNd=uT,r.GatherV2=xy,r.GraphModel=I0,r.Greater=dT,r.GreaterEqual=Ty,r.History=sN,r.IFFT=kd,r.Identity=$l,r.Imag=Fd,r.InputSpec=Sn,r.IsFinite=Ul,r.IsInf=Bl,r.IsNan=Ml,r.KernelBackend=f,r.LRN=vy,r.LRNBackprop=bT,r.LayerVariable=ai,r.LayersModel=ur,r.Less=pT,r.LessEqual=mT,r.LinSpace=fT,r.Log=Pl,r.Log1p=zl,r.LogSoftmax=Ay,r.LogicalAnd=gT,r.LogicalNot=_d,r.LogicalOr=yT,r.Max=Vl,r.MaxPool=Gl,r.MaxPool3D=Cy,r.MaxPool3DBackprop=wT,r.MaxPoolBackprop=Wd,r.MaxPoolWithArgmax=$d,r.Maximum=Ny,r.Mean=Ry,r.Min=Oy,r.Minimum=Ey,r.MirrorPad=Yl,r.Mod=Dy,r.MomentumOptimizer=zh,r.Multiply=Wa,r.Negate=ky,r.NonMaxSuppressionV3=Fy,r.NonMaxSuppressionV4=Ud,r.NonMaxSuppressionV5=Bd,r.NotEqual=Hl,r.OP_SCOPE_SUFFIX=PT,r.OneHot=Wy,r.OnesLike=_y,r.Optimizer=or,r.PadV2=Md,r.Pool=Rk,r.Pow=$y,r.Prelu=Pd,r.Prod=LT,r.RMSPropOptimizer=Vh,r.RNN=Wi,r.Range=ST,r.Real=zd,r.Reciprocal=ql,r.Relu=jl,r.Relu6=Xl,r.Reshape=Kl,r.ResizeBilinear=By,r.ResizeBilinearGrad=xT,r.ResizeNearestNeighbor=Uy,r.ResizeNearestNeighborGrad=IT,r.Reverse=My,r.RotateWithOffset=jd,r.Round=Jl,r.Rsqrt=Zl,r.SGDOptimizer=lc,r.ScatterNd=TT,r.SelectV2=Py,r.Selu=Ql,r.Sequential=yc,r.Sigmoid=nh,r.Sign=th,r.Sin=$a,r.Sinh=eh,r.Slice=Vd,r.Softmax=Gy,r.Softplus=sh,r.SpaceToBatchND=Gd,r.SparseToDense=AT,r.SplitV=Vy,r.Sqrt=ih,r.Square=Yd,r.SquaredDifference=Ua,r.Step=ah,r.StridedSlice=vT,r.Sub=Ba,r.Sum=zy,r.SymbolicTensor=ci,r.Tan=Ma,r.Tanh=rh,r.Tensor=te,r.TensorBuffer=an,r.Tile=Yy,r.TopK=NT,r.Transpose=oh,r.Unique=Hd,r.Unpack=Hy,r.UnsortedSegmentSum=qy,r.Variable=ph,r.ZerosLike=jy,r._FusedMatMul=Kd,r.abs=pn,r.acos=Ab,r.acosh=vb,r.add=be,r.addN=wA,r.addStrict=KA,r.all=yp,r.any=bh,r.argMax=wh,r.argMin=Cb,r.asin=Rb,r.asinh=Ob,r.atan=Eb,r.atan2=Db,r.atanh=kb,r.avgPool=Sh,r.avgPool3d=Wb,r.backend=bA,r.backend_util=Nw,r.basicLSTMCell=j_,r.batchNorm=Uo,r.batchNorm2d=SA,r.batchNorm3d=IA,r.batchNorm4d=xA,r.batchToSpaceND=Ih,r.booleanMaskAsync=oB,r.broadcastTo=xh,r.browser=JF,r.buffer=wt,r.callbacks=OY,r.cast=ve,r.ceil=$b,r.clipByValue=es,r.clone=Pr,r.complex=er,r.concat=Yt,r.concat1d=TA,r.concat2d=AA,r.concat3d=vA,r.concat4d=NA,r.constraints=t3,r.conv1d=Ip,r.conv2d=sr,r.conv2dTranspose=xp,r.conv3d=Bb,r.conv3dTranspose=fW,r.copyRegisteredKernels=Dk,r.cos=Th,r.cosh=Tp,r.cosineWindow=dw,r.cumsum=Ap,r.customGrad=Oi,r.data=Eq,r.deprecationWarn=dn,r.depthToSpace=Mb,r.depthwiseConv2d=Bo,r.deregisterOp=DY,r.device_util=Jk,r.diag=IW,r.dilation2d=Pb,r.disableDeprecationWarnings=h_,r.dispose=qe,r.disposeVariables=u_,r.div=We,r.divNoNan=zb,r.divStrict=XA,r.dot=RA,r.dropout=av,r.elu=Xa,r.enableDebugMode=l_,r.enableProdMode=c_,r.enclosingPowerOfTwo=cv,r.engine=tr,r.env=ae,r.equal=ei,r.equalStrict=VA,r.erf=Vb,r.exp=As,r.expandDims=ts,r.expm1=Gb,r.eye=vp,r.fft=Fh,r.fill=Ja,r.findBackend=y_,r.findBackendFactory=b_,r.floor=Za,r.floorDiv=gp,r.fused=BB,r.gather=Qa,r.gatherND=ov,r.gather_util=ZF,r.getBackend=f_,r.getGradient=Xy,r.getKernel=Ky,r.getKernelsForBackend=Zd,r.grad=e$,r.grads=t$,r.greater=vs,r.greaterEqual=ir,r.greaterEqualStrict=GA,r.greaterStrict=YA,r.ifft=rc,r.imag=vh,r.image=Xr,r.inTopKAsync=DB,r.initializers=$3,r.input=CN,r.io=PF,r.irfft=Pp,r.isFinite=EA,r.isInf=DA,r.isNaN=kA,r.keep=wn,r.kernel_impls=KM,r.layers=aY,r.leakyRelu=Np,r.less=Nh,r.lessEqual=Hr,r.lessEqualStrict=HA,r.lessStrict=qA,r.linalg=bv,r.linspace=FA,r.loadGraphModel=KH,r.loadLayersModel=BV,r.localResponseNormalization=Hb,r.log=us,r.log1p=Cp,r.logSigmoid=_A,r.logSoftmax=Op,r.logSumExp=jb,r.logicalAnd=Ps,r.logicalNot=Ch,r.logicalOr=Ep,r.logicalXor=WA,r.losses=YM,r.matMul=lt,r.math=jF,r.max=ns,r.maxPool=Rh,r.maxPool3d=Kb,r.maxPoolWithArgmax=$A,r.maximum=Ms,r.maximumStrict=JA,r.mean=qt,r.memory=fp,r.metrics=xY,r.min=tc,r.minimum=Po,r.minimumStrict=ZA,r.mirrorPad=Xb,r.mod=Dp,r.modStrict=QA,r.model=$V,r.models=TY,r.moments=kp,r.movingAverage=TB,r.mul=X,r.mulStrict=ev,r.multiRNNCell=N$,r.multinomial=UA,r.neg=Ht,r.nextFrame=Qp,r.norm=Gp,r.notEqual=qr,r.notEqualStrict=jA,r.oneHot=_o,r.ones=ti,r.onesLike=Wn,r.op=z,r.outerProduct=k$,r.pad=Ei,r.pad1d=W$,r.pad2d=U$,r.pad3d=M$,r.pad4d=z$,r.pool=BA,r.pow=ni,r.powStrict=tv,r.prelu=Eh,r.print=XT,r.prod=Fp,r.profile=d_,r.rand=J$,r.randomGamma=uU,r.randomNormal=Qb,r.randomUniform=Go,r.range=Dh,r.ready=m_,r.real=nc,r.reciprocal=ew,r.registerBackend=Tb,r.registerCallbackConstructor=MV,r.registerGradient=CT,r.registerKernel=Qd,r.registerOp=EY,r.regularizers=CY,r.relu=Di,r.relu6=tw,r.removeBackend=g_,r.reshape=K,r.reverse=Ns,r.reverse1d=wU,r.reverse2d=SU,r.reverse3d=xU,r.reverse4d=AU,r.rfft=_h,r.round=nw,r.rsqrt=_p,r.scalar=Ce,r.scatterND=rv,r.scatter_util=QF,r.selu=Wp,r.separableConv2d=sw,r.sequential=UV,r.serialization=e_,r.setBackend=yA,r.setPlatform=w_,r.setdiff1dAsync=MA,r.sigmoid=Ri,r.sign=iw,r.signal=GM,r.sin=$p,r.sinh=Up,r.slice=nt,r.slice1d=Bp,r.slice2d=rw,r.slice3d=Mp,r.slice4d=kh,r.slice_util=mA,r.softmax=Yo,r.softplus=ec,r.spaceToBatchND=Oh,r.sparseToDense=uw,r.spectral=VM,r.split=ps,r.sqrt=Cn,r.square=At,r.squaredDifference=Wh,r.squaredDifferenceStrict=nv,r.squeeze=jr,r.stack=ss,r.step=oc,r.stridedSlice=ow,r.sub=Re,r.subStrict=sv,r.sum=$e,r.sumOutType=np,r.tan=aw,r.tanh=Ka,r.tensor=sn,r.tensor1d=ds,r.tensor2d=Kr,r.tensor3d=sA,r.tensor4d=ac,r.tensor5d=JU,r.tensor6d=ZU,r.tensor_util=qk,r.test_util=a_,r.tidy=ee,r.tile=Yr,r.time=p_,r.topk=cw,r.train=qo,r.transpose=Ye,r.truncatedNormal=$h,r.unique=zp,r.unregisterGradient=Ek,r.unregisterKernel=Ok,r.unsortedSegmentSum=lw,r.unstack=si,r.upcastType=Bn,r.util=Fk,r.valueAndGrad=n$,r.valueAndGrads=s$,r.variable=zA,r.variableGrads=qb,r.version=ZJ,r.version_converter=x0,r.version_core=gA,r.version_layers=Nm,r.where=Pn,r.whereAsync=hw,r.zeros=pt,r.zerosLike=tt,Object.defineProperty(r,"__esModule",{value:!0})})});var $2=XS((y9,W2)=>{$c(y9,{isNodejs:()=>b9});function b9(){return typeof global=="object"&&!0&&typeof W2!="undefined"&&typeof process!="undefined"&&!!process.version}});function xr(r,l,u=!1){if(r.beginPath(),l.slice(1).forEach(({x:d,y:f},g)=>{const I=l[g];r.moveTo(I.x,I.y),r.lineTo(d,f)}),u){const d=l[l.length-1],f=l[0];if(!d||!f)return;r.moveTo(d.x,d.y),r.lineTo(f.x,f.y)}r.stroke()}class ys{constructor(r,l){if(!gi(r)||!gi(l))throw new Error(`Dimensions.constructor - expected width and height to be valid numbers, instead have ${JSON.stringify({width:r,height:l})}`);this._width=r,this._height=l}get width(){return this._width}get height(){return this._height}reverse(){return new ys(1/this.width,1/this.height)}}const oI={};$c(oI,{computeReshapedDimensions:()=>lI,getCenterPoint:()=>ca,isDimensions:()=>hf,isEven:()=>lf,isFloat:()=>cI,isTensor:()=>oa,isTensor1D:()=>w9,isTensor2D:()=>aI,isTensor3D:()=>Tr,isTensor4D:()=>Ds,isValidNumber:()=>gi,isValidProbablitiy:()=>Mc,range:()=>Pi,round:()=>aa});const U2=He(Ze());function oa(r,l){return r instanceof U2.Tensor&&r.shape.length===l}function w9(r){return oa(r,1)}function aI(r){return oa(r,2)}function Tr(r){return oa(r,3)}function Ds(r){return oa(r,4)}function cI(r){return r%1!==0}function lf(r){return r%2===0}function aa(r,l=2){const u=Math.pow(10,l);return Math.floor(r*u)/u}function hf(r){return r&&r.width&&r.height}function lI({width:r,height:l},u){const d=u/Math.max(l,r);return new ys(Math.round(r*d),Math.round(l*d))}function ca(r){return r.reduce((l,u)=>l.add(u),new Qe(0,0)).div(new Qe(r.length,r.length))}function Pi(r,l,u){return Array(r).fill(0).map((d,f)=>l+f*u)}function gi(r){return!!r&&r!==Infinity&&r!==-Infinity&&!isNaN(r)||r===0}function Mc(r){return gi(r)&&0<=r&&r<=1}class Qe{constructor(r,l){this._x=r,this._y=l}get x(){return this._x}get y(){return this._y}add(r){return new Qe(this.x+r.x,this.y+r.y)}sub(r){return new Qe(this.x-r.x,this.y-r.y)}mul(r){return new Qe(this.x*r.x,this.y*r.y)}div(r){return new Qe(this.x/r.x,this.y/r.y)}abs(){return new Qe(Math.abs(this.x),Math.abs(this.y))}magnitude(){return Math.sqrt(Math.pow(this.x,2)+Math.pow(this.y,2))}floor(){return new Qe(Math.floor(this.x),Math.floor(this.y))}}class _t{static isRect(r){return!!r&&[r.x,r.y,r.width,r.height].every(gi)}static assertIsValidBox(r,l,u=!1){if(!_t.isRect(r))throw new Error(`${l} - invalid box: ${JSON.stringify(r)}, expected object with properties x, y, width, height`);if(!u&&(r.width<0||r.height<0))throw new Error(`${l} - width (${r.width}) and height (${r.height}) must be positive numbers`)}constructor(r,l=!0){const u=r||{},d=[u.left,u.top,u.right,u.bottom].every(gi),f=[u.x,u.y,u.width,u.height].every(gi);if(!f&&!d)throw new Error(`Box.constructor - expected box to be IBoundingBox | IRect, instead have ${JSON.stringify(u)}`);const[g,I,S,x]=f?[u.x,u.y,u.width,u.height]:[u.left,u.top,u.right-u.left,u.bottom-u.top];_t.assertIsValidBox({x:g,y:I,width:S,height:x},"Box.constructor",l),this._x=g,this._y=I,this._width=S,this._height=x}get x(){return this._x}get y(){return this._y}get width(){return this._width}get height(){return this._height}get left(){return this.x}get top(){return this.y}get right(){return this.x+this.width}get bottom(){return this.y+this.height}get area(){return this.width*this.height}get topLeft(){return new Qe(this.left,this.top)}get topRight(){return new Qe(this.right,this.top)}get bottomLeft(){return new Qe(this.left,this.bottom)}get bottomRight(){return new Qe(this.right,this.bottom)}round(){const[r,l,u,d]=[this.x,this.y,this.width,this.height].map(f=>Math.round(f));return new _t({x:r,y:l,width:u,height:d})}floor(){const[r,l,u,d]=[this.x,this.y,this.width,this.height].map(f=>Math.floor(f));return new _t({x:r,y:l,width:u,height:d})}toSquare(){let{x:r,y:l,width:u,height:d}=this;const f=Math.abs(u-d);return u<d&&(r-=f/2,u+=f),d<u&&(l-=f/2,d+=f),new _t({x:r,y:l,width:u,height:d})}rescale(r){const l=hf(r)?r.width:r,u=hf(r)?r.height:r;return new _t({x:this.x*l,y:this.y*u,width:this.width*l,height:this.height*u})}pad(r,l){let[u,d,f,g]=[this.x-r/2,this.y-l/2,this.width+r,this.height+l];return new _t({x:u,y:d,width:f,height:g})}clipAtImageBorders(r,l){const{x:u,y:d,right:f,bottom:g}=this,I=Math.max(u,0),S=Math.max(d,0),x=f-I,N=g-S,E=Math.min(x,r-I),_=Math.min(N,l-S);return new _t({x:I,y:S,width:E,height:_}).floor()}shift(r,l){const{width:u,height:d}=this,f=this.x+r,g=this.y+l;return new _t({x:f,y:g,width:u,height:d})}padAtBorders(r,l){const u=this.width+1,d=this.height+1;let f=1,g=1,I=u,S=d,x=this.left,N=this.top,E=this.right,_=this.bottom;return E>l&&(I=-E+l+u,E=l),_>r&&(S=-_+r+d,_=r),x<1&&(S=2-x,x=1),N<1&&(S=2-N,N=1),{dy:g,edy:S,dx:f,edx:I,y:N,ey:_,x,ex:E,w:u,h:d}}calibrate(r){return new _t({left:this.left+r.left*this.width,top:this.top+r.top*this.height,right:this.right+r.right*this.width,bottom:this.bottom+r.bottom*this.height}).toSquare().round()}}class Fu extends _t{constructor(r,l,u,d,f=!1){super({left:r,top:l,right:u,bottom:d},f)}}class Pc{constructor(r,l,u,d,f){this._imageDims=new ys(f.width,f.height),this._score=r,this._classScore=l,this._className=u,this._box=new _t(d).rescale(this._imageDims)}get score(){return this._score}get classScore(){return this._classScore}get className(){return this._className}get box(){return this._box}get imageDims(){return this._imageDims}get imageWidth(){return this.imageDims.width}get imageHeight(){return this.imageDims.height}get relativeBox(){return new _t(this._box).rescale(this.imageDims.reverse())}forSize(r,l){return new Pc(this.score,this.classScore,this.className,this.relativeBox,{width:r,height:l})}}class Jt extends Pc{constructor(r,l,u){super(r,r,"",l,u)}forSize(r,l){const{score:u,relativeBox:d,imageDims:f}=super.forSize(r,l);return new Jt(u,d,f)}}function hI(r,l,u=!0){const d=Math.max(0,Math.min(r.right,l.right)-Math.max(r.left,l.left)),f=Math.max(0,Math.min(r.bottom,l.bottom)-Math.max(r.top,l.top)),g=d*f;return u?g/(r.area+l.area-g):g/Math.min(r.area,l.area)}function uI(r){const l=r.map(S=>S.x),u=r.map(S=>S.y),d=l.reduce((S,x)=>x<S?x:S,Infinity),f=u.reduce((S,x)=>x<S?x:S,Infinity),g=l.reduce((S,x)=>S<x?x:S,0),I=u.reduce((S,x)=>S<x?x:S,0);return new Fu(d,f,g,I)}function dI(r,l,u,d=!0){let f=l.map((I,S)=>({score:I,boxIndex:S})).sort((I,S)=>I.score-S.score).map(I=>I.boxIndex);const g=[];for(;f.length>0;){const I=f.pop();g.push(I);const S=f,x=[];for(let N=0;N<S.length;N++){const E=S[N],_=r[I],A=r[E];x.push(hI(_,A,d))}f=f.filter((N,E)=>x[E]<=u)}return g}const zi=He(Ze());function yi(r,l){return zi.tidy(()=>{const[u,d,f]=l,g=zi.fill([...r.shape.slice(0,3),1],u,"float32"),I=zi.fill([...r.shape.slice(0,3),1],d,"float32"),S=zi.fill([...r.shape.slice(0,3),1],f,"float32"),x=zi.concat([g,I,S],3);return zi.sub(r,x)})}const fo=He(Ze());function pI(r,l=!1){return fo.tidy(()=>{const[u,d]=r.shape.slice(1);if(u===d)return r;const f=Math.abs(u-d),g=Math.round(f*(l?.5:1)),I=u>d?2:1,S=A=>{const U=r.shape.slice();return U[I]=A,fo.fill(U,0,"float32")},x=S(g),N=f-x.shape[I],E=l&&N?S(N):null,_=[E,r,x].filter(A=>!!A).map(A=>fo.cast(A,"float32"));return fo.concat(_,I)})}function L9(r){const l=r.slice();for(let u=l.length-1;u>0;u--){const d=Math.floor(Math.random()*(u+1)),f=l[u];l[u]=l[d],l[d]=f}return l}function _u(r){return 1/(1+Math.exp(-r))}function S9(r){return Math.log(r/(1-r))}class Wu extends _t{constructor(r,l,u,d,f=!1){super({x:r,y:l,width:u,height:d},f)}}const I9=.5,x9=.43,T9=.45;class js{constructor(r,l,u=new Qe(0,0)){const{width:d,height:f}=l;this._imgDims=new ys(d,f),this._shift=u,this._positions=r.map(g=>g.mul(new Qe(d,f)).add(u))}get shift(){return new Qe(this._shift.x,this._shift.y)}get imageWidth(){return this._imgDims.width}get imageHeight(){return this._imgDims.height}get positions(){return this._positions}get relativePositions(){return this._positions.map(r=>r.sub(this._shift).div(new Qe(this.imageWidth,this.imageHeight)))}forSize(r,l){return new this.constructor(this.relativePositions,{width:r,height:l})}shiftBy(r,l){return new this.constructor(this.relativePositions,this._imgDims,new Qe(r,l))}shiftByPoint(r){return this.shiftBy(r.x,r.y)}align(r,l={}){if(r){const f=r instanceof Jt?r.box.floor():new _t(r);return this.shiftBy(f.x,f.y).align(null,l)}const{useDlibAlignment:u,minBoxPadding:d}=Object.assign({},{useDlibAlignment:!1,minBoxPadding:.2},l);return u?this.alignDlib():this.alignMinBbox(d)}alignDlib(){const r=this.getRefPointsForAlignment(),[l,u,d]=r,f=E=>d.sub(E).magnitude(),g=(f(l)+f(u))/2,I=Math.floor(g/T9),S=ca(r),x=Math.floor(Math.max(0,S.x-I9*I)),N=Math.floor(Math.max(0,S.y-x9*I));return new Wu(x,N,Math.min(I,this.imageWidth+x),Math.min(I,this.imageHeight+N))}alignMinBbox(r){const l=uI(this.positions);return l.pad(l.width*r,l.height*r)}getRefPointsForAlignment(){throw new Error("getRefPointsForAlignment not implemented by base class")}}class A9 extends js{getRefPointsForAlignment(){const r=this.positions;return[r[0],r[1],ca([r[3],r[4]])]}}class $u extends js{getJawOutline(){return this.positions.slice(0,17)}getLeftEyeBrow(){return this.positions.slice(17,22)}getRightEyeBrow(){return this.positions.slice(22,27)}getNose(){return this.positions.slice(27,36)}getLeftEye(){return this.positions.slice(36,42)}getRightEye(){return this.positions.slice(42,48)}getMouth(){return this.positions.slice(48,68)}getRefPointsForAlignment(){return[this.getLeftEye(),this.getRightEye(),this.getMouth()].map(ca)}}class uf{constructor(r,l){this._label=r,this._distance=l}get label(){return this._label}get distance(){return this._distance}toString(r=!0){return`${this.label}${r?` (${aa(this.distance)})`:""}`}}class df extends _t{static assertIsValidLabeledBox(r,l){if(_t.assertIsValidBox(r,l),!gi(r.label))throw new Error(`${l} - expected property label (${r.label}) to be a number`)}constructor(r,l){super(r);this._label=l}get label(){return this._label}}class la{constructor(r,l){if(!(typeof r=="string"))throw new Error("LabeledFaceDescriptors - constructor expected label to be a string");if(!Array.isArray(l)||l.some(u=>!(u instanceof Float32Array)))throw new Error("LabeledFaceDescriptors - constructor expected descriptors to be an array of Float32Array");this._label=r,this._descriptors=l}get label(){return this._label}get descriptors(){return this._descriptors}toJSON(){return{label:this.label,descriptors:this.descriptors.map(r=>Array.from(r))}}static fromJSON(r){const l=r.descriptors.map(u=>new Float32Array(u));return new la(r.label,l)}}class v9 extends df{static assertIsValidPredictedBox(r,l){if(df.assertIsValidLabeledBox(r,l),!Mc(r.score)||!Mc(r.classScore))throw new Error(`${l} - expected properties score (${r.score}) and (${r.classScore}) to be a number between [0, 1]`)}constructor(r,l,u,d){super(r,l);this._score=u,this._classScore=d}get score(){return this._score}get classScore(){return this._classScore}}function Vi(r){return r.detection instanceof Jt}function ha(r,l){const u={detection:l};return Object.assign({},r,u)}function mI(){const r=window.fetch||function(){throw new Error("fetch - missing fetch implementation for browser environment")},l=function(){throw new Error("readFile - filesystem not available for browser environment")};return{Canvas:HTMLCanvasElement,CanvasRenderingContext2D,Image:HTMLImageElement,ImageData,Video:HTMLVideoElement,createCanvasElement:()=>document.createElement("canvas"),createImageElement:()=>document.createElement("img"),fetch:r,readFile:l}}function pf(r){let l="";if(!r)try{r=require("fs")}catch(d){l=d.toString()}const u=r?function(d){return new Promise((f,g)=>{r.readFile(d,function(I,S){return I?g(I):f(S)})})}:function(){throw new Error(`readFile - failed to require fs in nodejs environment with error: ${l}`)};return{readFile:u}}function fI(){const r=global.Canvas||global.HTMLCanvasElement,l=global.Image||global.HTMLImageElement,u=function(){if(r)return new r;throw new Error("createCanvasElement - missing Canvas implementation for nodejs environment")},d=function(){if(l)return new l;throw new Error("createImageElement - missing Image implementation for nodejs environment")},f=global.fetch||function(){throw new Error("fetch - missing fetch implementation for nodejs environment")},g=pf();return{Canvas:r||class{},CanvasRenderingContext2D:global.CanvasRenderingContext2D||class{},Image:l||class{},ImageData:global.ImageData||class{},Video:global.HTMLVideoElement||class{},createCanvasElement:u,createImageElement:d,fetch:f,...g}}function gI(){return typeof window=="object"&&typeof document!="undefined"&&typeof HTMLImageElement!="undefined"&&typeof HTMLCanvasElement!="undefined"&&typeof HTMLVideoElement!="undefined"&&typeof ImageData!="undefined"&&typeof CanvasRenderingContext2D!="undefined"}const yI=He($2());let xn;function N9(){if(!xn)throw new Error("getEnv - environment is not defined, check isNodejs() and isBrowser()");return xn}function bI(r){xn=r}function wI(){if(gI())return bI(mI());if(yI.isNodejs())return bI(fI())}function C9(r){if(xn||wI(),!xn)throw new Error("monkeyPatch - environment is not defined, check isNodejs() and isBrowser()");const{Canvas:l=xn.Canvas,Image:u=xn.Image}=r;xn.Canvas=l,xn.Image=u,xn.createCanvasElement=r.createCanvasElement||(()=>new l),xn.createImageElement=r.createImageElement||(()=>new u),xn.ImageData=r.ImageData||xn.ImageData,xn.Video=r.Video||xn.Video,xn.fetch=r.fetch||xn.fetch,xn.readFile=r.readFile||xn.readFile}const St={getEnv:N9,setEnv:bI,initialize:wI,createBrowserEnv:mI,createFileSystem:pf,createNodejsEnv:fI,monkeyPatch:C9,isBrowser:gI,isNodejs:yI.isNodejs};wI();function ua(r){return!St.isNodejs()&&typeof r=="string"?document.getElementById(r):r}function as(r){const{Canvas:l,CanvasRenderingContext2D:u}=St.getEnv();if(r instanceof u)return r;const d=ua(r);if(!(d instanceof l))throw new Error("resolveContext2d - expected canvas to be of instance of Canvas");const f=d.getContext("2d");if(!f)throw new Error("resolveContext2d - canvas 2d context is null");return f}var Gi;(function(r){r.TOP_LEFT="TOP_LEFT",r.TOP_RIGHT="TOP_RIGHT",r.BOTTOM_LEFT="BOTTOM_LEFT",r.BOTTOM_RIGHT="BOTTOM_RIGHT"})(Gi||(Gi={}));class mf{constructor(r={}){const{anchorPosition:l,backgroundColor:u,fontColor:d,fontSize:f,fontStyle:g,padding:I}=r;this.anchorPosition=l||Gi.TOP_LEFT,this.backgroundColor=u||"rgba(0, 0, 0, 0.5)",this.fontColor=d||"rgba(255, 255, 255, 1)",this.fontSize=f||14,this.fontStyle=g||"Georgia",this.padding=I||4}}class zc{constructor(r,l,u={}){this.text=typeof r=="string"?[r]:r instanceof zc?r.text:r,this.anchor=l,this.options=new mf(u)}measureWidth(r){const{padding:l}=this.options;return this.text.map(u=>r.measureText(u).width).reduce((u,d)=>u<d?d:u,0)+2*l}measureHeight(){const{fontSize:r,padding:l}=this.options;return this.text.length*r+2*l}getUpperLeft(r,l){const{anchorPosition:u}=this.options,d=u===Gi.BOTTOM_RIGHT||u===Gi.TOP_RIGHT,f=u===Gi.BOTTOM_LEFT||u===Gi.BOTTOM_RIGHT,g=this.measureWidth(r),I=this.measureHeight(),S=d?this.anchor.x-g:this.anchor.x,x=f?this.anchor.y-I:this.anchor.y;if(l){const{width:N,height:E}=l,_=Math.max(Math.min(S,N-g),0),A=Math.max(Math.min(x,E-I),0);return{x:_,y:A}}return{x:S,y:x}}draw(r){const l=ua(r),u=as(l),{backgroundColor:d,fontColor:f,fontSize:g,fontStyle:I,padding:S}=this.options;u.font=`${g}px ${I}`;const x=this.measureWidth(u),N=this.measureHeight();u.fillStyle=d;const E=this.getUpperLeft(u,l);u.fillRect(E.x,E.y,x,N),u.fillStyle=f,this.text.forEach((_,A)=>{const U=S+E.x,ne=S+E.y+(A+1)*g;u.fillText(_,U,ne)})}}class B2{constructor(r={}){const{boxColor:l,lineWidth:u,label:d,drawLabelOptions:f}=r;this.boxColor=l||"rgba(0, 0, 255, 1)",this.lineWidth=u||2,this.label=d;const g={anchorPosition:Gi.BOTTOM_LEFT,backgroundColor:this.boxColor};this.drawLabelOptions=new mf(Object.assign({},g,f))}}class LI{constructor(r,l={}){this.box=new _t(r),this.options=new B2(l)}draw(r){const l=as(r),{boxColor:u,lineWidth:d}=this.options,{x:f,y:g,width:I,height:S}=this.box;l.strokeStyle=u,l.lineWidth=d,l.strokeRect(f,g,I,S);const{label:x}=this.options;x&&new zc([x],{x:f-d/2,y:g},this.options.drawLabelOptions).draw(r)}}function R9(r,l){const u=Array.isArray(l)?l:[l];u.forEach(d=>{const f=d instanceof Jt?d.score:Vi(d)?d.detection.score:void 0,g=d instanceof Jt?d.box:Vi(d)?d.detection.box:new _t(d),I=f?`${aa(f)}`:void 0;new LI(g,{label:I}).draw(r)})}function Uu(r){const{Image:l,Video:u}=St.getEnv();return r instanceof l&&r.complete||r instanceof u&&r.readyState>=3}function SI(r){return new Promise((l,u)=>{if(r instanceof St.getEnv().Canvas||Uu(r))return l(null);function d(g){if(!g.currentTarget)return;g.currentTarget.removeEventListener("load",d),g.currentTarget.removeEventListener("error",f),l(g)}function f(g){if(!g.currentTarget)return;g.currentTarget.removeEventListener("load",d),g.currentTarget.removeEventListener("error",f),u(g)}r.addEventListener("load",d),r.addEventListener("error",f)})}function II(r){return new Promise((l,u)=>{if(!(r instanceof Blob))return u("bufferToImage - expected buf to be of type: Blob");const d=new FileReader;d.onload=()=>{if(typeof d.result!="string")return u("bufferToImage - expected reader.result to be a string, in onload");const f=St.getEnv().createImageElement();f.onload=()=>l(f),f.onerror=u,f.src=d.result},d.onerror=u,d.readAsDataURL(r)})}function da(r){const{Image:l,Video:u}=St.getEnv();return r instanceof l?new ys(r.naturalWidth,r.naturalHeight):r instanceof u?new ys(r.videoWidth,r.videoHeight):new ys(r.width,r.height)}function Vc({width:r,height:l}){const{createCanvasElement:u}=St.getEnv(),d=u();return d.width=r,d.height=l,d}function Bu(r,l){const{ImageData:u}=St.getEnv();if(!(r instanceof u)&&!Uu(r))throw new Error("createCanvasFromMedia - media has not finished loading yet");const{width:d,height:f}=l||da(r),g=Vc({width:d,height:f});return r instanceof u?as(g).putImageData(r,0,0):as(g).drawImage(r,0,0,d,f),g}const ff=He(Ze());async function xI(r,l){const u=l||St.getEnv().createCanvasElement(),[d,f,g]=r.shape.slice(Ds(r)?1:0),I=ff.tidy(()=>r.as3D(d,f,g).toInt());return await ff.browser.toPixels(I,u),I.dispose(),u}function gf(r){const{Image:l,Canvas:u,Video:d}=St.getEnv();return r instanceof l||r instanceof u||r instanceof d}const O9=1e-7,E9=1e-4;class M2{time(r){return se("time")}read(r){return se("read")}readSync(r){return se("readSync")}numDataIds(){return se("numDataIds")}disposeData(r){return se("disposeData")}write(r,l,u){return se("write")}move(r,l,u,d){return se("move")}memory(){return se("memory")}floatPrecision(){return se("floatPrecision")}epsilon(){return this.floatPrecision()===32?O9:E9}batchMatMul(r,l,u,d){return se("batchMatMul")}fusedBatchMatMul({a:r,b:l,transposeA:u,transposeB:d,bias:f,activation:g,preluActivationWeights:I}){return se("fusedBatchMatMul")}slice(r,l,u){return se("slice")}stridedSlice(r,l,u,d){return se("stridedSlice")}unstack(r,l){return se("unstack")}reverse(r,l){return se("reverse")}concat(r,l){return se("concat")}neg(r){return se("neg")}add(r,l){return se("add")}addN(r){return se("addN")}subtract(r,l){return se("subtract")}multiply(r,l){return se("multiply")}realDivide(r,l){return se("realDivide")}floorDiv(r,l){return se("floorDiv")}sum(r,l){return se("sum")}prod(r,l){return se("prod")}unsortedSegmentSum(r,l,u){return se("unsortedSegmentSum")}argMin(r,l){return se("argMin")}argMax(r,l){return se("argMax")}equal(r,l){return se("equal")}notEqual(r,l){return se("notEqual")}less(r,l){return se("less")}lessEqual(r,l){return se("lessEqual")}greater(r,l){return se("greater")}greaterEqual(r,l){return se("greaterEqual")}logicalNot(r){return se("logicalNot")}logicalAnd(r,l){return se("logicalAnd")}logicalOr(r,l){return se("logicalOr")}where(r){return se("where")}select(r,l,u){return se("select")}topk(r,l,u){return se("topk")}min(r,l){return se("min")}minimum(r,l){return se("minimum")}mod(r,l){return se("mod")}max(r,l){return se("max")}maximum(r,l){return se("maximum")}all(r,l){return se("all")}any(r,l){return se("any")}squaredDifference(r,l){return se("squaredDifference")}ceil(r){return se("ceil")}floor(r){return se("floor")}round(r){return se("round")}sign(r){return se("sign")}isNaN(r){return se("isNaN")}isInf(r){return se("isInf")}isFinite(r){return se("isFinite")}pow(r,l){return se("pow")}exp(r){return se("exp")}expm1(r){return se("expm1")}softmax(r,l){return se("softmax")}log(r){return se("log")}log1p(r){return se("log1p")}sqrt(r){return se("sqrt")}rsqrt(r){return se("rsqrt")}square(r){return se("square")}reciprocal(r){return se("reciprocal")}relu(r){return se("relu")}relu6(r){return se("relu6")}prelu(r,l){return se("prelu")}elu(r){return se("elu")}eluDer(r,l){return se("eluDer")}selu(r){return se("selu")}int(r){return se("int")}clip(r,l,u){return se("clip")}abs(r){return se("abs")}complexAbs(r){return se("complexAbs")}sigmoid(r){return se("sigmoid")}softplus(r){return se("softplus")}sin(r){return se("sin")}cos(r){return se("cos")}tan(r){return se("tan")}asin(r){return se("asin")}acos(r){return se("acos")}atan(r){return se("atan")}atan2(r,l){return se("atan2")}sinh(r){return se("sinh")}cosh(r){return se("cosh")}tanh(r){return se("tanh")}asinh(r){return se("asinh")}acosh(r){return se("acosh")}atanh(r){return se("atanh")}erf(r){return se("erf")}step(r,l){return se("step")}fusedConv2d({input:r,filter:l,convInfo:u,bias:d,activation:f,preluActivationWeights:g}){return se("fusedConv2d")}conv2d(r,l,u){return se("conv2d")}conv2dDerInput(r,l,u){return se("conv2dDerInput")}conv2dDerFilter(r,l,u){return se("conv2dDerFilter")}fusedDepthwiseConv2D({input:r,filter:l,convInfo:u,bias:d,activation:f,preluActivationWeights:g}){return se("fusedDepthwiseConv2D")}depthwiseConv2D(r,l,u){return se("depthwiseConv2D")}depthwiseConv2DDerInput(r,l,u){return se("depthwiseConv2DDerInput")}depthwiseConv2DDerFilter(r,l,u){return se("depthwiseConv2DDerFilter")}conv3d(r,l,u){return se("conv3d")}conv3dDerInput(r,l,u){return se("conv3dDerInput")}conv3dDerFilter(r,l,u){return se("conv3dDerFilter")}maxPool(r,l){return se("maxPool")}maxPoolBackprop(r,l,u,d){return se("maxPoolBackprop")}avgPool(r,l){return se("avgPool")}avgPoolBackprop(r,l,u){return se("avgPoolBackprop")}avgPool3d(r,l){return se("avgPool3d")}avgPool3dBackprop(r,l,u){return se("avgPool3dBackprop")}maxPool3d(r,l){return se("maxPool3d")}maxPool3dBackprop(r,l,u,d){return se("maxPool3dBackprop")}reshape(r,l){return se("reshape")}cast(r,l){return se("cast")}tile(r,l){return se("tile")}pad(r,l,u){return se("pad")}transpose(r,l){return se("transpose")}gather(r,l,u){return se("gather")}gatherND(r,l){return se("gatherND")}scatterND(r,l,u){return se("scatterND")}batchToSpaceND(r,l,u){return se("batchToSpaceND")}spaceToBatchND(r,l,u){return se("spaceToBatchND")}resizeBilinear(r,l,u,d){return se("resizeBilinear")}resizeBilinearBackprop(r,l,u){return se("resizeBilinearBackprop")}resizeNearestNeighbor(r,l,u,d){return se("resizeNearestNeighbor")}resizeNearestNeighborBackprop(r,l,u){return se("resizeNearestNeighborBackprop")}batchNorm(r,l,u,d,f,g){return se("batchNorm")}localResponseNormalization4D(r,l,u,d,f){return se("localResponseNormalization4D")}LRNGrad(r,l,u,d,f,g,I){return se("LRNGrad")}multinomial(r,l,u,d){return se("multinomial")}oneHot(r,l,u,d){return se("oneHot")}cumsum(r,l,u,d){return se("cumsum")}nonMaxSuppression(r,l,u,d,f){return se("nonMaxSuppression")}fft(r){return se("fft")}ifft(r){return se("ifft")}complex(r,l){return se("complex")}real(r){return se("real")}imag(r){return se("imag")}cropAndResize(r,l,u,d,f,g){return se("cropAndResize")}depthToSpace(r,l,u){return se("depthToSpace")}split(r,l,u){return se("split")}sparseToDense(r,l,u,d){return se("sparseToDense")}diag(r){return se("diag")}fill(r,l,u){return se("fill")}onesLike(r){return se("onesLike")}zerosLike(r){return se("zerosLike")}linspace(r,l,u){return se("linspace")}dispose(){return se("dispose")}}function se(r){throw new Error(`'${r}' not yet implemented or not found in the registry. This kernel may not be supported by the tfjs backend you have chosen`)}function J(r,l){if(!r)throw new Error(typeof l=="string"?l:l())}function tn(r,l,u=""){J(Mu(r,l),()=>u+` Shapes ${r} and ${l} must match`)}function Gc(r){J(r!=null,()=>"The input to the tensor constructor must be a non-null value.")}function pa(r,l=[],u=!1){if(l==null&&(l=[]),Array.isArray(r)||ks(r)&&!u)for(let d=0;d<r.length;++d)pa(r[d],l,u);else l.push(r);return l}function Zt(r){if(r.length===0)return 1;let l=r[0];for(let u=1;u<r.length;u++)l*=r[u];return l}function Mu(r,l){if(r===l)return!0;if(r==null||l==null)return!1;if(r.length!==l.length)return!1;for(let u=0;u<r.length;u++)if(r[u]!==l[u])return!1;return!0}function nn(r){return r%1===0}function Yc(r,l){return l<=r.length?r:r+" ".repeat(l-r.length)}function P2(r,l){let u=1,d=-1;for(let g=0;g<r.length;++g)if(r[g]>=0)u*=r[g];else if(r[g]===-1){if(d!==-1)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${d} and dim ${g}`);d=g}else if(r[g]<0)throw Error(`Shapes can not be < 0. Found ${r[g]} at dim ${g}`);if(d===-1){if(l>0&&l!==u)throw Error(`Size(${l}) must match the product of shape ${r}`);return r}if(u===0)throw Error(`Cannot infer the missing size in [${r}] when there are 0 elements`);if(l%u!==0)throw Error(`The implicit shape can't be a fractional number. Got ${l} / ${u}`);const f=r.slice();return f[d]=l/u,f}function ft(r,l){const u=l.length;return r=r==null?l.map((d,f)=>f):[].concat(r),J(r.every(d=>d>=-u&&d<u),()=>`All values in axis param must be in range [-${u}, ${u}) but got axis ${r}`),J(r.every(d=>nn(d)),()=>`All values in axis param must be integers but got axis ${r}`),r.map(d=>d<0?u+d:d)}function z2(r,l){const u=[],d=[],f=l!=null&&Array.isArray(l)&&l.length===0,g=l==null||f?null:ft(l,r).sort();let I=0;for(let S=0;S<r.length;++S){if(g!=null){if(g[I]===S&&r[S]!==1)throw new Error(`Can't squeeze axis ${S} since its dim '${r[S]}' is not 1`);(g[I]==null||g[I]>S)&&r[S]===1&&(u.push(r[S]),d.push(S)),g[I]<=S&&I++}r[S]!==1&&(u.push(r[S]),d.push(S))}return{newShape:u,keptDims:d}}function V2(r,l){let u=null;if(r==null||r==="float32")u=new Float32Array(l);else if(r==="int32")u=new Int32Array(l);else if(r==="bool")u=new Uint8Array(l);else if(r==="string")u=new Array(l);else throw new Error(`Unknown data type ${r}`);return u}function G2(r,l){for(let u=0;u<r.length;u++){const d=r[u];if(isNaN(d)||!isFinite(d))throw Error(`A tensor of type ${l} being uploaded contains ${d}.`)}}function Y2(r){return r==="bool"||r==="complex64"||r==="float32"||r==="int32"||r==="string"}function ks(r){return r instanceof Float32Array||r instanceof Int32Array||r instanceof Uint8Array}function H2(r){if(r==="float32"||r==="int32")return 4;if(r==="complex64")return 8;if(r==="bool")return 1;throw new Error(`Unknown dtype ${r}`)}function q2(r){if(r==null)return 0;let l=0;return r.forEach(u=>l+=u.length),l}function Pu(r){return typeof r=="string"||r instanceof String}function D9(r){return typeof r=="boolean"}function k9(r){return typeof r=="number"}function zu(r){return Array.isArray(r)?zu(r[0]):r instanceof Float32Array?"float32":r instanceof Int32Array||r instanceof Uint8Array?"int32":k9(r)?"float32":Pu(r)?"string":D9(r)?"bool":"float32"}function TI(r){return!!(r&&r.constructor&&r.call&&r.apply)}function Vu(r){const l=r.length;if(l<2)return[];const u=new Array(l-1);u[l-2]=r[l-1];for(let d=l-3;d>=0;--d)u[d]=u[d+1]*r[d+1];return u}function j2(r,l,u){const d=new Array;if(l.length===1){const f=l[0];for(let g=0;g<f;g++)d[g]=u[r+g]}else{const f=l[0],g=l.slice(1),I=g.reduce((S,x)=>S*x);for(let S=0;S<f;S++)d[S]=j2(r+S*I,g,u)}return d}function AI(r,l){if(r.length===0)return l[0];const u=r.reduce((d,f)=>d*f);if(u===0)return[];if(u!==l.length)throw new Error(`[${r}] does not match the input size ${l.length}.`);return j2(0,r,l)}function yf(r,l){const u=ma(r,l);for(let d=0;d<u.length;d++)u[d]=1;return u}function ma(r,l){if(l==null||l==="float32"||l==="complex64")return new Float32Array(r);if(l==="int32")return new Int32Array(r);if(l==="bool")return new Uint8Array(r);throw new Error(`Unknown data type ${l}`)}function bf(r){r.forEach(l=>{J(Number.isInteger(l)&&l>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${r}].`)})}function wf(r){return r&&r.then&&typeof r.then=="function"}const K2="tfjsflags";class X2{constructor(r){this.global=r,this.flags={},this.flagRegistry={},this.urlFlags={},this.populateURLFlags()}setPlatform(r,l){this.platform!=null&&console.warn(`Platform ${this.platformName} has already been set. Overwriting the platform with ${l}.`),this.platformName=r,this.platform=l}registerFlag(r,l,u){if(this.flagRegistry[r]={evaluationFn:l,setHook:u},this.urlFlags[r]!=null){const d=this.urlFlags[r];console.warn(`Setting feature override from URL ${r}: ${d}.`),this.set(r,d)}}async getAsync(r){return r in this.flags?this.flags[r]:(this.flags[r]=await this.evaluateFlag(r),this.flags[r])}get(r){if(r in this.flags)return this.flags[r];const l=this.evaluateFlag(r);if(wf(l))throw new Error(`Flag ${r} cannot be synchronously evaluated. Please use getAsync() instead.`);return this.flags[r]=l,this.flags[r]}getNumber(r){return this.get(r)}getBool(r){return this.get(r)}getFlags(){return this.flags}get features(){return this.flags}set(r,l){if(this.flagRegistry[r]==null)throw new Error(`Cannot set flag ${r} as it has not been registered.`);this.flags[r]=l,this.flagRegistry[r].setHook!=null&&this.flagRegistry[r].setHook(l)}evaluateFlag(r){if(this.flagRegistry[r]==null)throw new Error(`Cannot evaluate flag '${r}': no evaluation function found.`);return this.flagRegistry[r].evaluationFn()}setFlags(r){this.flags=Object.assign({},r)}reset(){this.flags={},this.urlFlags={},this.populateURLFlags()}populateURLFlags(){if(typeof this.global=="undefined"||typeof this.global.location=="undefined"||typeof this.global.location.search=="undefined")return;const r=F9(this.global.location.search);if(K2 in r){const l=r[K2].split(",");l.forEach(u=>{const[d,f]=u.split(":");this.urlFlags[d]=_9(d,f)})}}}function F9(r){const l={};return r.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(u,...d)=>(W9(l,d[0],d[1]),d.join("="))),l}function W9(r,l,u){r[decodeURIComponent(l)]=decodeURIComponent(u||"")}function _9(r,l){if(l=l.toLowerCase(),l==="true"||l==="false")return l==="true";if(`${+l}`===l)return+l;throw new Error(`Could not parse value flag value ${l} for flag ${r}.`)}function Fs(){return J2}let J2=null;function Z2(r){J2=r}let vI;function NI(){if(vI==null){let r;if(typeof window!="undefined")r=window;else if(typeof global!="undefined")r=global;else if(typeof process!="undefined")r=process;else if(typeof self!="undefined")r=self;else throw new Error("Could not find a global object");vI=r}return vI}function $9(){const r=NI();return r._tfGlobals==null&&(r._tfGlobals=new Map),r._tfGlobals}function CI(r,l){const u=$9();if(u.has(r))return u.get(r);{const d=l();return u.set(r,d),u.get(r)}}const Lf="Abs",Q2="Acos",eR="Acosh",Hc="Add",tR="AddN",nR="ArgMax",sR="ArgMin",iR="Asin",rR="Asinh",oR="Atan",aR="Atanh",cR="Atan2",lR="AvgPool",hR="AvgPoolBackprop",uR="AvgPool3D",dR="AvgPool3DBackprop",Sf="BatchMatMul",If="BatchToSpaceND",xf="BroadcastTo",qc="Cast",pR="Ceil",mR="ClipByValue",fR="Complex",Tf="Concat",Af="Conv2D",gR="Conv2DBackpropFilter",vf="Conv2DBackpropInput",yR="Conv3D",bR="Conv3DBackpropFilterV2",wR="Conv3DBackpropInputV2",Nf="Cos",Cf="Cosh",Rf="Cumsum",LR="CropAndResize",SR="DepthwiseConv2dNative",IR="DepthwiseConv2dNativeBackpropFilter",xR="DepthwiseConv2dNativeBackpropInput",TR="Dilation2D",AR="Dilation2DBackpropInput",vR="Dilation2DBackpropFilter",Of="Div",NR="Elu",CR="EluGrad",RR="Erf",OR="Equal",Ef="Exp",ER="Expm1",DR="FFT",kR="Fill",FR="FlipLeftRight",Df="Floor",kf="FloorDiv",_R="FusedBatchNorm",Ff="GatherV2",WR="Greater",_f="GreaterEqual",Wf="Identity",$R="IFFT",UR="Imag",BR="IsFinite",MR="IsInf",PR="IsNan",zR="Less",VR="LessEqual",$f="Log",Uf="Log1p",GR="LogicalAnd",YR="LogicalNot",HR="LogSoftmax",qR="LRN",jR="LRNBackprop",Bf="Max",Mf="Maximum",KR="MaxPool",XR="MaxPoolBackprop",JR="MaxPool3D",ZR="MaxPool3DBackprop",QR="Mean",Pf="Min",zf="Minimum",eO="MirrorPad",tO="Mod",Vf="Multiply",Gf="Negate",nO="NotEqual",sO="NonMaxSuppressionV3",iO="NonMaxSuppressionV4",rO="NonMaxSuppressionV5",oO="OnesLike",aO="OneHot",Yf="PadV2",Hf="Pow",cO="Prelu",lO="Range",hO="Real",uO="Reciprocal",qf="Relu",jf="Reshape",Kf="ResizeNearestNeighbor",dO="ResizeNearestNeighborGrad",Xf="ResizeBilinear",pO="ResizeBilinearGrad",mO="Relu6",Jf="Reverse",fO="Round",Zf="Rsqrt",Qf="SelectV2",gO="Selu",eg="Slice",tg="Sin",ng="Sinh",yO="Sign",sg="Sigmoid",bO="Softplus",ig="Sqrt",rg="Sum",og="SpaceToBatchND",ag="SplitV",wO="Softmax",cg="SquaredDifference",LO="Square",lg="Sub",SO="Tan",IO="Tanh",hg="Tile",ug="Transpose",dg="Unpack",pg="UnsortedSegmentSum",mg="ZerosLike",fg="Step",RI="FromPixels",xO="RotateWithOffset";const TO=CI("kernelRegistry",()=>new Map),OI=CI("gradRegistry",()=>new Map);function gg(r,l){const u=U9(r,l);return TO.get(u)}function EI(r){return OI.get(r)}function DI(r){const l=TO.entries(),u=[];for(;;){const{done:d,value:f}=l.next();if(d)break;const[g,I]=f,[S]=g.split("_");S===r&&u.push(I)}return u}function AO(r){const{kernelName:l}=r;OI.has(l)&&(Fs().getBool("DEBUG")&&console.warn(`Overriding the gradient for '${l}'`)),OI.set(l,r)}function U9(r,l){return`${l}_${r}`}function B9(r,l){return r instanceof Float32Array&&l==="float32"||r instanceof Int32Array&&l==="int32"||r instanceof Uint8Array&&l==="bool"}function yg(r,l){if(l==="string")throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(r)&&(r=pa(r)),Fs().getBool("DEBUG")&&G2(r,l),B9(r,l))return r;if(l==null||l==="float32"||l==="complex64")return new Float32Array(r);if(l==="int32")return new Int32Array(r);if(l==="bool"){const u=new Uint8Array(r.length);for(let d=0;d<u.length;++d)Math.round(r[d])!==0&&(u[d]=1);return u}else throw new Error(`Unknown data type ${l}`)}function kI(){return Fs().platform.now()}function vO(r,l="utf-8"){return l=l||"utf-8",Fs().platform.encode(r,l)}function FI(r,l="utf-8"){return l=l||"utf-8",Fs().platform.decode(r,l)}class NO{constructor(r,l){this.backendTimer=r,this.logger=l,l==null&&(this.logger=new P9)}profileKernel(r,l,u){let d;const f=()=>{d=u()},g=this.backendTimer.time(f);for(let S=0;S<d.length;S++){const x=d[S];x.data().then(N=>{M9(N,x.dtype,r)})}const I={kernelName:r,outputs:d,inputs:l,timeMs:g.then(S=>S.kernelMs),extraInfo:g.then(S=>S.getExtraProfileInfo!=null?S.getExtraProfileInfo():"")};return I}logKernelProfile(r){const{kernelName:l,outputs:u,timeMs:d,inputs:f,extraInfo:g}=r;u.forEach(I=>{Promise.all([I.data(),d,g]).then(S=>{this.logger.logKernelProfile(l,I,S[0],S[1],f,S[2])})})}}function M9(r,l,u){if(l!=="float32")return!1;for(let d=0;d<r.length;d++){const f=r[d];if(isNaN(f)||!isFinite(f))return console.warn(`Found ${f} in the result of '${u}'`),!0}return!1}class P9{logKernelProfile(r,l,u,d,f,g){const I=typeof d=="number"?Yc(`${d}ms`,9):d.error,S=Yc(r,25),x=l.rank,N=l.size,E=Yc(l.shape.toString(),14);let _="";for(const A in f){const U=f[A];if(U!=null){const ne=U.shape||l.shape,Q=ne.length;_+=`${A}: ${Q}D ${Q>0?ne:""} `}}console.log(`%c${S} %c${I} %c${x}D ${E} %c${N} %c${_} %c${g}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}}function CO(r,l,u){const d={},f={};for(let x=0;x<l.length;x++)d[l[x].id]=!0;for(let x=0;x<r.length;x++){const N=r[x],E=N.inputs;for(const _ in E){const A=E[_];let U=!1;for(let ne=0;ne<l.length;ne++)if(d[A.id]){N.outputs.forEach(Q=>d[Q.id]=!0),U=!0,f[N.id]=!0;break}if(U)break}}const g={};g[u.id]=!0;const I={};for(let x=r.length-1;x>=0;x--){const N=r[x],E=N.inputs;for(let _=0;_<N.outputs.length;_++)if(g[N.outputs[_].id]){for(const A in E)g[E[A].id]=!0,I[N.id]=!0;break}}const S=[];for(let x=0;x<r.length;x++){const N=r[x];if(f[N.id]&&I[N.id]){const E={};for(const A in N.inputs){const U=N.inputs[A];d[U.id]&&(E[A]=U)}const _=Object.assign({},N);_.inputs=E,_.outputs=N.outputs,S.push(_)}}return S}function RO(r,l,u,d){for(let f=l.length-1;f>=0;f--){const g=l[f],I=[];if(g.outputs.forEach(x=>{const N=r[x.id];N!=null?I.push(N):I.push(null)}),g.gradient==null)throw new Error(`Cannot compute gradient: gradient function not found for ${g.kernelName}.`);const S=g.gradient(I);for(const x in g.inputs){if(!(x in S))throw new Error(`Cannot backprop through input ${x}. Available gradients found: ${Object.keys(S)}.`);const N=u(()=>S[x]());if(N.dtype!=="float32")throw new Error(`Error in gradient for op ${g.kernelName}. The gradient of input ${x} must have 'float32' dtype, but has '${N.dtype}'`);const E=g.inputs[x];if(!Mu(N.shape,E.shape))throw new Error(`Error in gradient for op ${g.kernelName}. The gradient of input '${x}' has shape '${N.shape}', which does not match the shape of the input '${E.shape}'`);if(r[E.id]==null)r[E.id]=N;else{const _=r[E.id];r[E.id]=d(_,N),_.dispose()}}}}const OO=20,Gu=3,_I=7;function EO(r,l,u,d){const f=Vu(l),g=z9(r,l,u,f),I=l.length,S=bg(r,l,u,f,g),x=["Tensor"];return d&&(x.push(` dtype: ${u}`),x.push(` rank: ${I}`),x.push(` shape: [${l}]`),x.push(" values:")),x.push(S.map(N=>" "+N).join(`
`)),x.join(`
`)}function z9(r,l,u,d){const f=Zt(l),g=d[d.length-1],I=new Array(g).fill(0),S=l.length,x=u==="complex64"?Hu(r):r;if(S>1)for(let N=0;N<f/g;N++){const E=N*g;for(let _=0;_<g;_++)I[_]=Math.max(I[_],Yu(x[E+_],0,u).length)}return I}function Yu(r,l,u){let d;return Array.isArray(r)?d=`${parseFloat(r[0].toFixed(_I))} + ${parseFloat(r[1].toFixed(_I))}j`:Pu(r)?d=`'${r}'`:u==="bool"?d=DO(r):d=parseFloat(r.toFixed(_I)).toString(),Yc(d,l)}function DO(r){return r===0?"false":"true"}function bg(r,l,u,d,f,g=!0){const I=u==="complex64"?2:1,S=l[0],x=l.length;if(x===0){if(u==="complex64"){const Q=Hu(r);return[Yu(Q[0],0,u)]}return u==="bool"?[DO(r[0])]:[r[0].toString()]}if(x===1){if(S>OO){const M=Gu*I;let fe=Array.from(r.slice(0,M)),ie=Array.from(r.slice((S-Gu)*I,S*I));return u==="complex64"&&(fe=Hu(fe),ie=Hu(ie)),["["+fe.map((we,Ae)=>Yu(we,f[Ae],u)).join(", ")+", ..., "+ie.map((we,Ae)=>Yu(we,f[S-Gu+Ae],u)).join(", ")+"]"]}const Q=u==="complex64"?Hu(r):Array.from(r);return["["+Q.map((M,fe)=>Yu(M,f[fe],u)).join(", ")+"]"]}const N=l.slice(1),E=d.slice(1),_=d[0]*I,A=[];if(S>OO){for(let Q=0;Q<Gu;Q++){const M=Q*_,fe=M+_;A.push(...bg(r.slice(M,fe),N,u,E,f,!1))}A.push("...");for(let Q=S-Gu;Q<S;Q++){const M=Q*_,fe=M+_;A.push(...bg(r.slice(M,fe),N,u,E,f,Q===S-1))}}else for(let Q=0;Q<S;Q++){const M=Q*_,fe=M+_;A.push(...bg(r.slice(M,fe),N,u,E,f,Q===S-1))}const U=x===2?",":"";A[0]="["+A[0]+U;for(let Q=1;Q<A.length-1;Q++)A[Q]=" "+A[Q]+U;let ne=`,
`;for(let Q=2;Q<x;Q++)ne+=`
`;return A[A.length-1]=" "+A[A.length-1]+"]"+(g?"":ne),A}function Hu(r){const l=[];for(let u=0;u<r.length;u+=2)l.push([r[u],r[u+1]]);return l}class kO{constructor(r,l,u){if(this.dtype=l,this.shape=r.slice(),this.size=Zt(r),u!=null){const d=u.length;J(d===this.size,()=>`Length of values '${d}' does not match the size inferred by the shape '${this.size}'.`)}if(l==="complex64")throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=u||V2(l,this.size),this.strides=Vu(r)}set(r,...l){l.length===0&&(l=[0]),J(l.length===this.rank,()=>`The number of provided coordinates (${l.length}) must match the rank (${this.rank})`);const u=this.locToIndex(l);this.values[u]=r}get(...r){r.length===0&&(r=[0]);let l=0;for(const d of r){if(d<0||d>=this.shape[l]){const f=`Requested out of range element at ${r}. Buffer shape=${this.shape}`;throw new Error(f)}l++}let u=r[r.length-1];for(let d=0;d<r.length-1;++d)u+=this.strides[d]*r[d];return this.values[u]}locToIndex(r){if(this.rank===0)return 0;if(this.rank===1)return r[0];let l=r[r.length-1];for(let u=0;u<r.length-1;++u)l+=this.strides[u]*r[u];return l}indexToLoc(r){if(this.rank===0)return[];if(this.rank===1)return[r];const l=new Array(this.shape.length);for(let u=0;u<l.length-1;++u)l[u]=Math.floor(r/this.strides[u]),r-=l[u]*this.strides[u];return l[l.length-1]=r,l}get rank(){return this.shape.length}toTensor(){return Yi().makeTensor(this.values,this.shape,this.dtype)}}let Yi=null,jc=null,V9=null;function FO(r){Yi=r}function _O(r){jc=r}function WO(r){V9=r}class kn{constructor(r,l,u,d){this.kept=!1,this.isDisposedInternal=!1,this.shape=r.slice(),this.dtype=l||"float32",this.size=Zt(r),this.strides=Vu(r),this.dataId=u,this.id=d,this.rankType=this.rank<5?this.rank.toString():"higher"}get rank(){return this.shape.length}async buffer(){const r=await this.data();return jc.buffer(this.shape,this.dtype,r)}bufferSync(){return jc.buffer(this.shape,this.dtype,this.dataSync())}async array(){const r=await this.data();return AI(this.shape,r)}arraySync(){return AI(this.shape,this.dataSync())}async data(){this.throwIfDisposed();const r=Yi().read(this.dataId);if(this.dtype==="string"){const l=await r;try{return l.map(u=>FI(u))}catch(u){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}}return r}dataSync(){this.throwIfDisposed();const r=Yi().readSync(this.dataId);if(this.dtype==="string")try{return r.map(l=>FI(l))}catch(l){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}return r}async bytes(){this.throwIfDisposed();const r=await Yi().read(this.dataId);return this.dtype==="string"?r:new Uint8Array(r.buffer)}dispose(){if(this.isDisposed)return;Yi().disposeTensor(this),this.isDisposedInternal=!0}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(r=!1){return jc.print(this,r)}clone(){return this.throwIfDisposed(),jc.clone(this)}toString(r=!1){const l=this.dataSync();return EO(l,this.shape,this.dtype,r)}cast(r){return this.throwIfDisposed(),jc.cast(this,r)}variable(r=!0,l,u){return this.throwIfDisposed(),Yi().makeVariable(this,r,l,u)}}Object.defineProperty(kn,Symbol.hasInstance,{value:r=>!!r&&r.data!=null&&r.dataSync!=null&&r.throwIfDisposed!=null});class wg extends kn{constructor(r,l,u,d){super(r.shape,r.dtype,r.dataId,d);this.trainable=l,this.name=u}assign(r){if(r.dtype!==this.dtype)throw new Error(`dtype of the new value (${r.dtype}) and previous value (${this.dtype}) must match`);if(!Mu(r.shape,this.shape))throw new Error(`shape of the new value (${r.shape}) and previous value (${this.shape}) must match`);Yi().disposeTensor(this),this.dataId=r.dataId,Yi().incRef(this,null)}dispose(){Yi().disposeVariable(this),this.isDisposedInternal=!0}}Object.defineProperty(wg,Symbol.hasInstance,{value:r=>r instanceof kn&&r.assign!=null&&r.assign instanceof Function});var $O;(function(r){r.R0="R0",r.R1="R1",r.R2="R2",r.R3="R3",r.R4="R4",r.R5="R5",r.R6="R6"})($O||($O={}));var WI;(function(r){r.float32="float32",r.int32="int32",r.bool="int32",r.complex64="complex64"})(WI||(WI={}));var $I;(function(r){r.float32="float32",r.int32="int32",r.bool="bool",r.complex64="complex64"})($I||($I={}));var UI;(function(r){r.float32="float32",r.int32="float32",r.bool="float32",r.complex64="complex64"})(UI||(UI={}));var BI;(function(r){r.float32="complex64",r.int32="complex64",r.bool="complex64",r.complex64="complex64"})(BI||(BI={}));const G9={float32:UI,int32:WI,bool:$I,complex64:BI};function UO(r,l){if(r==="string"||l==="string"){if(r==="string"&&l==="string")return"string";throw new Error(`Can not upcast ${r} with ${l}`)}return G9[r][l]}function Lt(r,l){if(r.dtype===l.dtype)return[r,l];const u=UO(r.dtype,l.dtype);return[r.cast(u),l.cast(u)]}function Lg(r){const l=[],u=new Set;return BO(r,l,u),l}function BO(r,l,u){if(r==null)return;if(r instanceof kn){l.push(r);return}if(!Y9(r))return;const d=r;for(const f in d){const g=d[f];u.has(g)||(u.add(g),BO(g,l,u))}}function Y9(r){return Array.isArray(r)||typeof r=="object"}class MO{constructor(){this.registeredVariables={},this.nextTapeNodeId=0,this.numBytes=0,this.numTensors=0,this.numStringTensors=0,this.numDataBuffers=0,this.gradientDepth=0,this.kernelDepth=0,this.scopeStack=[],this.numDataMovesStack=[],this.nextScopeId=0,this.tensorInfo=new WeakMap,this.profiling=!1,this.activeProfile={newBytes:0,newTensors:0,peakBytes:0,kernels:[],result:null}}dispose(){for(const r in this.registeredVariables)this.registeredVariables[r].dispose()}}class qu{constructor(r){this.ENV=r,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new MO}async ready(){if(this.pendingBackendInit!=null)return this.pendingBackendInit.then(()=>{});if(this.backendInstance!=null)return;const r=this.getSortedBackends();for(let l=0;l<r.length;l++){const u=r[l],d=await this.initializeBackend(u).success;if(d){await this.setBackend(u);return}}throw new Error("Could not initialize any backends, all backend initializations failed.")}get backend(){if(this.pendingBackendInit!=null)throw new Error(`Backend '${this.backendName}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);if(this.backendInstance==null){const{name:r,asyncInit:l}=this.initializeBackendsAndReturnBest();if(l)throw new Error(`The highest priority backend '${r}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);this.setBackend(r)}return this.backendInstance}backendNames(){return Object.keys(this.registryFactory)}findBackend(r){if(!(r in this.registry))if(r in this.registryFactory){const{asyncInit:l}=this.initializeBackend(r);if(l)return null}else return null;return this.registry[r]}findBackendFactory(r){return r in this.registryFactory?this.registryFactory[r].factory:null}registerBackend(r,l,u=1){return r in this.registryFactory?(console.warn(`${r} backend was already registered. Reusing existing backend factory.`),!1):(this.registryFactory[r]={factory:l,priority:u},!0)}async setBackend(r){if(this.registryFactory[r]==null)throw new Error(`Backend name '${r}' not found in registry`);if(this.backendName=r,this.registry[r]==null){this.backendInstance=null;const{success:l,asyncInit:u}=this.initializeBackend(r),d=u?await l:l;if(!d)return!1}return this.backendInstance=this.registry[r],this.setupRegisteredKernels(),this.profiler=new NO(this.backendInstance),!0}setupRegisteredKernels(){const r=DI(this.backendName);r.forEach(l=>{l.setupFunc!=null&&l.setupFunc(this.backendInstance)})}disposeRegisteredKernels(r){const l=DI(r);l.forEach(u=>{u.disposeFunc!=null&&u.disposeFunc(this.registry[r])})}initializeBackend(r){const l=this.registryFactory[r];if(l==null)throw new Error(`Cannot initialize backend ${r}, no registration found.`);try{const u=l.factory();if(u&&!(u instanceof M2)&&typeof u.then=="function"){const d=++this.pendingBackendInitId,f=u.then(g=>d<this.pendingBackendInitId?!1:(this.registry[r]=g,this.pendingBackendInit=null,!0)).catch(g=>(d<this.pendingBackendInitId||(this.pendingBackendInit=null,console.warn(`Initialization of backend ${r} failed`),console.warn(g.stack||g.message)),!1));return this.pendingBackendInit=f,{success:f,asyncInit:!0}}else return this.registry[r]=u,{success:!0,asyncInit:!1}}catch(u){return console.warn(`Initialization of backend ${r} failed`),console.warn(u.stack||u.message),{success:!1,asyncInit:!1}}}removeBackend(r){if(!(r in this.registryFactory))throw new Error(`${r} backend not found in registry`);this.backendName===r&&this.pendingBackendInit!=null&&this.pendingBackendInitId++,r in this.registry&&(this.disposeRegisteredKernels(r),this.registry[r].dispose(),delete this.registry[r]),delete this.registryFactory[r],this.backendName===r&&(this.pendingBackendInit=null,this.backendName=null,this.backendInstance=null)}getSortedBackends(){if(Object.keys(this.registryFactory).length===0)throw new Error("No backend found in registry.");return Object.keys(this.registryFactory).sort((r,l)=>this.registryFactory[l].priority-this.registryFactory[r].priority)}initializeBackendsAndReturnBest(){const r=this.getSortedBackends();for(let l=0;l<r.length;l++){const u=r[l],{success:d,asyncInit:f}=this.initializeBackend(u);if(f||d)return{name:u,asyncInit:f}}throw new Error("Could not initialize any backends, all backend initializations failed.")}moveData(r,l){const u=this.state.tensorInfo.get(l),d=u.backend,f=this.readSync(l);d.disposeData(l),u.backend=r,r.move(l,f,u.shape,u.dtype),this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack[this.state.numDataMovesStack.length-1]++}tidy(r,l){let u=null;if(l==null){if(typeof r!="function")throw new Error("Please provide a function to tidy()");l=r}else{if(typeof r!="string"&&!(r instanceof String))throw new Error("When calling with two arguments, the first argument to tidy() must be a string");if(typeof l!="function")throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");u=r}let d;return this.scopedRun(()=>this.startScope(u),()=>this.endScope(d),()=>(d=l(),d instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),d))}scopedRun(r,l,u){r();try{const d=u();return l(),d}catch(d){throw l(),d}}nextTensorId(){return qu.nextTensorId++}nextVariableId(){return qu.nextVariableId++}clone(r){const l=this.makeTensorFromDataId(r.dataId,r.shape,r.dtype),u={x:r},d=g=>({x:()=>{const I="float32",S={x:g},x={dtype:I};return H.runKernelFunc(N=>N.cast(g,I),S,null,qc,x)}}),f=[];return this.addTapeNode(this.state.activeScope.name,u,[l],d,f,{}),l}runKernel(r,l,u,d,f){const g=null,I=null;return this.runKernelFunc(g,l,I,r,u,d,f)}shouldCheckForMemLeaks(){return this.ENV.getBool("IS_TEST")}checkKernelForMemLeak(r,l,u){const d=this.backend.numDataIds();let f=0;u.forEach(S=>{f+=S.dtype==="complex64"?3:1});const g=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],I=d-l-f-g;if(I>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${I} data ids) after running '${r}'`)}runKernelFunc(r,l,u,d,f,g,I){let S,x=[];const N=this.isTapeOn();d==null&&(d=this.state.activeScope!=null?this.state.activeScope.name:"");const E=this.state.numBytes,_=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);let A;const U=gg(d,this.backendName);let ne;if(U!=null)A=()=>{const M=this.backend.numDataIds();ne=U.kernelFunc({inputs:l,attrs:f,backend:this.backend});const fe=Array.isArray(ne)?ne:[ne];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(d,M,fe);const ie=fe.map(({dataId:we,shape:Ae,dtype:Me})=>this.makeTensorFromDataId(we,Ae,Me));if(N){let we=this.getTensorsForGradient(d,l,ie);if(we==null){I==null&&(I=[]);const Ae=ie.filter((Me,et)=>I[et]);we=(g||[]).slice().concat(Ae)}x=this.saveTensorsForBackwardMode(we)}return ie};else{const M=fe=>{if(!N)return;x=fe.map(ie=>this.keep(this.clone(ie)))};A=()=>{const fe=this.backend.numDataIds();ne=this.tidy(()=>r(this.backend,M));const ie=Array.isArray(ne)?ne:[ne];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(d,fe,ie),ie}}let Q;return this.scopedRun(()=>this.state.kernelDepth++,()=>this.state.kernelDepth--,()=>{!this.ENV.getBool("DEBUG")&&!this.state.profiling?S=A():(Q=this.profiler.profileKernel(d,l,()=>A()),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(Q),S=Q.outputs)}),N&&this.addTapeNode(d,l,S,u,x,f),this.state.profiling&&this.state.activeProfile.kernels.push({name:d,bytesAdded:this.state.numBytes-E,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-_,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(l).map(M=>l[M]!=null?l[M].shape:null),outputShapes:S.map(M=>M.shape),kernelTimeMs:Q.timeMs,extraInfo:Q.extraInfo}),Array.isArray(ne)?S:S[0]}saveTensorsForBackwardMode(r){const l=r.map(u=>this.keep(this.clone(u)));return l}getTensorsForGradient(r,l,u){const d=EI(r);if(d!=null){const f=d.inputsToSave||[],g=d.outputsToSave||[];let I;d.saveAllInputs?(J(Array.isArray(l),()=>"saveAllInputs is true, expected inputs to be an array."),I=Object.keys(l).map(x=>l[x])):I=f.map(x=>l[x]);const S=u.filter((x,N)=>g[N]);return I.concat(S)}return null}makeTensor(r,l,u,d){if(r==null)throw new Error("Values passed to engine.makeTensor() are null");u=u||"float32",d=d||this.backend;let f=r;u==="string"&&Pu(r[0])&&(f=r.map(S=>vO(S)));const g=d.write(f,l,u),I=new kn(l,u,g,this.nextTensorId());if(this.incRef(I,d),u==="string"){const S=this.state.tensorInfo.get(g),x=q2(f);this.state.numBytes+=x-S.bytes,S.bytes=x}return I}makeTensorFromDataId(r,l,u,d){u=u||"float32";const f=new kn(l,u,r,this.nextTensorId());return this.incRef(f,d),f}makeVariable(r,l=!0,u,d){u=u||this.nextVariableId().toString(),d!=null&&d!==r.dtype&&(r=r.cast(d));const f=new wg(r,l,u,this.nextTensorId());if(this.state.registeredVariables[f.name]!=null)throw new Error(`Variable with name ${f.name} was already registered`);return this.state.registeredVariables[f.name]=f,this.incRef(f,this.backend),f}incRef(r,l){const u=this.state.tensorInfo.has(r.dataId)?this.state.tensorInfo.get(r.dataId).refCount:0;if(this.state.numTensors++,r.dtype==="string"&&this.state.numStringTensors++,u===0){this.state.numDataBuffers++;let d=0;r.dtype!=="complex64"&&r.dtype!=="string"&&(d=r.size*H2(r.dtype)),this.state.tensorInfo.set(r.dataId,{backend:l||this.backend,dtype:r.dtype,shape:r.shape,bytes:d,refCount:0}),this.state.numBytes+=d}this.state.tensorInfo.get(r.dataId).refCount++,r instanceof wg||this.track(r)}disposeTensor(r){if(!this.state.tensorInfo.has(r.dataId))return;this.state.numTensors--,r.dtype==="string"&&this.state.numStringTensors--;const l=this.state.tensorInfo.get(r.dataId),u=l.refCount;u<=1?(r.dtype!=="complex64"&&(this.state.numBytes-=l.bytes),this.state.numDataBuffers--,l.backend.disposeData(r.dataId),this.state.tensorInfo.delete(r.dataId)):this.state.tensorInfo.get(r.dataId).refCount--}disposeVariables(){for(const r in this.state.registeredVariables){const l=this.state.registeredVariables[r];this.disposeVariable(l)}}disposeVariable(r){this.disposeTensor(r),this.state.registeredVariables[r.name]!=null&&delete this.state.registeredVariables[r.name]}memory(){const r=this.backend.memory();return r.numTensors=this.state.numTensors,r.numDataBuffers=this.state.numDataBuffers,r.numBytes=this.state.numBytes,this.state.numStringTensors>0&&(r.unreliable=!0,r.reasons==null&&(r.reasons=[]),r.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),r}async profile(r){this.state.profiling=!0;const l=this.state.numBytes,u=this.state.numTensors;this.state.activeProfile.kernels=[],this.state.activeProfile.result=await r(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max(...this.state.activeProfile.kernels.map(d=>d.totalBytesSnapshot)),this.state.activeProfile.newBytes=this.state.numBytes-l,this.state.activeProfile.newTensors=this.state.numTensors-u;for(const d of this.state.activeProfile.kernels)d.kernelTimeMs=await d.kernelTimeMs,d.extraInfo=await d.extraInfo;return this.state.activeProfile}isTapeOn(){return this.state.gradientDepth>0&&this.state.kernelDepth===0}addTapeNode(r,l,u,d,f,g){const I={id:this.state.nextTapeNodeId++,kernelName:r,inputs:l,outputs:u,saved:f},S=EI(r);S!=null&&(d=S.gradFunc),d!=null&&(I.gradient=x=>(x=x.map((N,E)=>{if(N==null){const _=u[E],A=ma(_.size,_.dtype);return this.makeTensor(A,_.shape,_.dtype)}return N}),d(x.length>1?x:x[0],f,g))),this.state.activeTape.push(I)}keep(r){return r.kept=!0,r}startTape(){this.state.gradientDepth===0&&(this.state.activeTape=[]),this.state.gradientDepth++}endTape(){this.state.gradientDepth--}startScope(r){const l={track:[],name:"unnamed scope",id:this.state.nextScopeId++};r&&(l.name=r),this.state.scopeStack.push(l),this.state.activeScope=l}endScope(r){const l=Lg(r),u=new Set(l.map(f=>f.id));for(let f=0;f<this.state.activeScope.track.length;f++){const g=this.state.activeScope.track[f];!g.kept&&!u.has(g.id)&&g.dispose()}const d=this.state.scopeStack.pop();this.state.activeScope=this.state.scopeStack.length===0?null:this.state.scopeStack[this.state.scopeStack.length-1],l.forEach(f=>{!f.kept&&f.scopeId===d.id&&this.track(f)})}gradients(r,l,u,d=!1){if(J(l.length>0,()=>"gradients() received an empty list of xs."),u!=null&&u.dtype!=="float32")throw new Error(`dy must have 'float32' dtype, but has '${u.dtype}'`);const f=this.scopedRun(()=>this.startTape(),()=>this.endTape(),()=>this.tidy("forward",r));J(f instanceof kn,()=>"The result y returned by f() must be a tensor.");const g=CO(this.state.activeTape,l,f);if(!d&&g.length===0&&l.length>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.");return this.tidy("backward",()=>{const I={};I[f.id]=u==null?H9(f.shape):u,RO(I,g,x=>this.tidy(x),q9);const S=l.map(x=>I[x.id]);return this.state.gradientDepth===0&&(this.state.activeTape.forEach(x=>{for(const N of x.saved)N.dispose()}),this.state.activeTape=null),{value:f,grads:S}})}customGrad(r){return J(TI(r),()=>"The f passed in customGrad(f) must be a function."),(...l)=>{J(l.every(f=>f instanceof kn),()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors");let u;const d={};return l.forEach((f,g)=>{d[g]=f}),this.runKernelFunc((f,g)=>(u=r(...l,g),J(u.value instanceof kn,()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),J(TI(u.gradFunc),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."),u.value),d,(f,g)=>{const I=u.gradFunc(f,g),S=Array.isArray(I)?I:[I];J(S.length===l.length,()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns the same number of tensors as inputs passed to f(...)."),J(S.every(N=>N instanceof kn),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors.");const x={};return S.forEach((N,E)=>{x[E]=()=>N}),x})}}readSync(r){const l=this.state.tensorInfo.get(r);return l.backend.readSync(r)}read(r){const l=this.state.tensorInfo.get(r);return l.backend.read(r)}async time(r){const l=kI(),u=await this.backend.time(r);return u.wallMs=kI()-l,u}track(r){return this.state.activeScope!=null&&(r.scopeId=this.state.activeScope.id,this.state.activeScope.track.push(r)),r}get registeredVariables(){return this.state.registeredVariables}reset(){this.pendingBackendInitId++,this.state.dispose(),this.ENV.reset(),this.state=new MO;for(const r in this.registry)this.disposeRegisteredKernels(r),this.registry[r].dispose(),delete this.registry[r];this.backendName=null,this.backendInstance=null,this.pendingBackendInit=null}}qu.nextTensorId=0;qu.nextVariableId=0;function H9(r){const l=yf(Zt(r),"float32");return H.makeTensor(l,r,"float32")}function MI(){const r=NI();if(r._tfengine==null){const l=new X2(r);r._tfengine=new qu(l)}return Z2(r._tfengine.ENV),FO(()=>r._tfengine),r._tfengine}const H=MI();function q9(r,l){const u={a:r,b:l};return H.runKernelFunc((d,f)=>{const g=d.add(r,l);return f([r,l]),g},u,null,Hc)}function PO(){return typeof window!="undefined"&&window.document!=null||typeof WorkerGlobalScope!="undefined"}const Ar=Fs();Ar.registerFlag("DEBUG",()=>!1,r=>{r&&console.warn("Debugging mode is ON. The output of every math call will be downloaded to CPU and checked for NaNs. This significantly impacts performance.")});Ar.registerFlag("IS_BROWSER",()=>PO());Ar.registerFlag("IS_NODE",()=>typeof process!="undefined"&&typeof process.versions!="undefined"&&typeof process.versions.node!="undefined");Ar.registerFlag("IS_CHROME",()=>typeof navigator!="undefined"&&navigator!=null&&navigator.userAgent!=null&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor));Ar.registerFlag("PROD",()=>!1);Ar.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",()=>Ar.getBool("DEBUG"));Ar.registerFlag("DEPRECATION_WARNINGS_ENABLED",()=>!0);Ar.registerFlag("IS_TEST",()=>!1);function vr(r,l){let u=r;if(ks(r))return l==="string"?[]:[r.length];if(!Array.isArray(r))return[];const d=[];for(;Array.isArray(u)||ks(u)&&l!=="string";)d.push(u.length),u=u[0];return Array.isArray(r)&&Fs().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&zO(r,d,[]),d}function zO(r,l,u){if(u=u||[],!Array.isArray(r)&&!ks(r)){J(l.length===0,()=>`Element arr[${u.join("][")}] is a primitive, but should be an array/TypedArray of ${l[0]} elements`);return}J(l.length>0,()=>`Element arr[${u.join("][")}] should be a primitive, but is an array of ${r.length} elements`),J(r.length===l[0],()=>`Element arr[${u.join("][")}] should have ${l[0]} elements, but has ${r.length} elements`);const d=l.slice(1);for(let f=0;f<r.length;++f)zO(r[f],d,u.concat(f))}function VO(r,l,u,d){if(r==null)return;if(r!=="numeric"&&r!==l||r==="numeric"&&l==="string")throw new Error(`Argument '${u}' passed to '${d}' must be ${r} tensor, but got ${l} tensor`)}function P(r,l,u,d="numeric"){if(r instanceof kn)return VO(d,r.dtype,l,u),r;let f=zu(r);if(f!=="string"&&["bool","int32","float32"].indexOf(d)>=0&&(f=d),VO(d,f,l,u),r==null||!ks(r)&&!Array.isArray(r)&&typeof r!="number"&&typeof r!="boolean"&&typeof r!="string"){const x=r==null?"null":r.constructor.name;throw new Error(`Argument '${l}' passed to '${u}' must be a Tensor or TensorLike, but got '${x}'`)}const g=vr(r,f);!ks(r)&&!Array.isArray(r)&&(r=[r]);const I=!0,S=f!=="string"?yg(r,f):pa(r,[],I);return H.makeTensor(S,g,f)}function Sg(r,l,u,d="numeric"){if(!Array.isArray(r))throw new Error(`Argument ${l} passed to ${u} must be a \`Tensor[]\` or \`TensorLike[]\``);const f=r;return f.map((g,I)=>P(g,`${l}[${I}]`,u),d)}const GO="__op";function V(r){const l=Object.keys(r);if(l.length!==1)throw new Error(`Please provide an object with a single key (operation name) mapping to a function. Got an object with ${l.length} keys.`);let u=l[0];const d=r[u];u.endsWith("_")&&(u=u.substring(0,u.length-1)),u=u+GO;const f=(...g)=>{H.startScope(u);try{const I=d(...g);return wf(I)&&console.error("Cannot return a Promise inside of tidy."),H.endScope(I),I}catch(I){throw H.endScope(null),I}};return Object.defineProperty(f,"name",{value:u,configurable:!0}),f}function j9(r,l){const u=P(r,"real","complex"),d=P(l,"imag","complex");tn(u.shape,d.shape,`real and imag shapes, ${u.shape} and ${d.shape}, must match in call to tf.complex().`);const f=I=>I.complex(u,d),g={real:u,imag:d};return H.runKernelFunc(f,g,null,fR)}const Hi=V({complex_:j9});function qi(r,l,u,d){if(d==null&&(d=zu(r)),d==="complex64")throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!ks(r)&&!Array.isArray(r)&&typeof r!="number"&&typeof r!="boolean"&&typeof r!="string")throw new Error("values passed to tensor(values) must be a number/boolean/string or an array of numbers/booleans/strings, or a TypedArray");if(l!=null){bf(l);const f=Zt(l),g=Zt(u);J(f===g,()=>`Based on the provided shape, [${l}], the tensor should have ${f} values but has ${g}`);for(let I=0;I<u.length;++I){const S=u[I],x=I===u.length-1?S!==Zt(l.slice(I)):!0;J(u[I]===l[I]||!x,()=>`Error creating a new Tensor. Inferred shape (${u}) does not match the provided shape (${l}). `)}}return!ks(r)&&!Array.isArray(r)&&(r=[r]),l=l||u,r=d!=="string"?yg(r,d):pa(r,[],!0),H.makeTensor(r,l,d)}function PI(r,l,u){const d=vr(r,u);return qi(r,l,d,u)}function ju(r,l="float32",u){return l=l||"float32",bf(r),new kO(r,l,u)}function K9(r,l){const u=P(r,"x","cast");if(!Y2(l))throw new Error(`Failed to cast to unknown dtype ${l}`);if(l==="string"&&u.dtype!=="string"||l!=="string"&&u.dtype==="string")throw new Error("Only strings can be casted to strings");const d={x:u},f={dtype:l};return H.runKernelFunc(g=>g.cast(u,l),d,null,qc,f)}const Ie=V({cast_:K9});function X9(r){const l=P(r,"x","clone",null),u=()=>H.makeTensorFromDataId(l.dataId,l.shape,l.dtype),d={x:l};return H.runKernelFunc(u,d,null,Wf)}const bi=V({clone_:X9});function zI(r,l=!1){console.log(r.toString(l))}MI();const J9={buffer:ju,cast:Ie,clone:bi,print:zI};_O(J9);function Z9(r,l){const u=P(r,"x","reshape",null),d={x:u},f={shape:l},g=(I,S)=>(l=P2(l,u.size),J(u.size===Zt(l),()=>"new shape and old shape must have the same number of elements."),S([u]),I.reshape(u,l));return H.runKernelFunc(g,d,null,jf,f)}const oe=V({reshape_:Z9});function Q9(r,l,u=!1,d=!1){let f=P(r,"a","matMul"),g=P(l,"b","matMul");[f,g]=Lt(f,g);const I=(N,E)=>{E([f,g]);const _=u?f.shape[f.rank-2]:f.shape[f.rank-1],A=d?g.shape[g.rank-1]:g.shape[g.rank-2],U=u?f.shape[f.rank-1]:f.shape[f.rank-2],ne=d?g.shape[g.rank-2]:g.shape[g.rank-1],Q=f.shape.slice(0,-2),M=g.shape.slice(0,-2),fe=Zt(Q),ie=Zt(M),we=fe===ie||fe===1||ie===1;J(f.rank>=2&&g.rank>=2&&we,()=>`Error in matMul: the input batch dimensions must either be the same or at least one input batch dimension must be 1. Got input batch dimensions of (${Q}) and (${M}).`),J(_===A,()=>`Error in matMul: inner shapes (${_}) and (${A}) of Tensors with shapes ${f.shape} and ${g.shape} and transposeA=${u} and transposeB=${d} must match.`);const Ae=fe>ie?Q:M,Me=Ae.concat([U,ne]),et=u?oe(f,[fe,_,U]):oe(f,[fe,U,_]),ct=d?oe(g,[ie,ne,A]):oe(g,[ie,A,ne]),$t=N.batchMatMul(et,ct,u,d);return oe($t,Me)},S={a:f,b:g},x={transposeA:u,transposeB:d};return H.runKernelFunc(I,S,null,Sf,x)}const bn=V({matMul_:Q9});function eZ(r,l){const u=P(r,"x","transpose");if(l==null&&(l=u.shape.map((g,I)=>I).reverse()),J(u.rank===l.length,()=>`Error in transpose: rank of input ${u.rank} must match length of perm ${l}.`),l.forEach(g=>{J(g>=0&&g<u.rank,()=>`All entries in 'perm' must be between 0 and ${u.rank-1} but got ${l}`)}),u.rank<=1)return u.clone();const d={x:u},f={perm:l};return H.runKernelFunc(g=>g.transpose(u,l),d,null,ug,f)}const Tn=V({transpose_:eZ});function VI(r,l,u){if(Gc(r),l!=null&&l.length!==3)throw new Error("tensor3d() requires shape to have three numbers");const d=vr(r,u);if(d.length!==3&&d.length!==1)throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");if(d.length===1&&l==null)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return qi(r,l,d,u)}const GI={};$c(GI,{fromPixels:()=>sZ,toPixels:()=>nZ});let Kc;function tZ(r,l=3){if(l>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");if(r==null)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");let u=!1,d=!1,f=!1,g=!1,I=!1;if(r.data instanceof Uint8Array)u=!0;else if(typeof ImageData!="undefined"&&r instanceof ImageData)d=!0;else if(typeof HTMLVideoElement!="undefined"&&r instanceof HTMLVideoElement)f=!0;else if(typeof HTMLImageElement!="undefined"&&r instanceof HTMLImageElement)g=!0;else if(r.getContext!=null)I=!0;else throw new Error(`pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData in browser, or OffscreenCanvas, ImageData in webworker or {data: Uint32Array, width: number, height: number}, but was ${r.constructor.name}`);if(f){const U=2;if(f&&r.readyState<U)throw new Error("The video element has not loaded data yet. Please wait for `loadeddata` event on the <video> element.")}const S=gg(RI,H.backendName);if(S!=null){const U={pixels:r},ne={numChannels:l};return H.runKernel(RI,U,ne)}const[x,N]=f?[r.videoWidth,r.videoHeight]:[r.width,r.height];let E;I?E=r.getContext("2d").getImageData(0,0,x,N).data:d||u?E=r.data:(g||f)&&(Kc==null&&(Kc=document.createElement("canvas").getContext("2d")),Kc.canvas.width=x,Kc.canvas.height=N,Kc.drawImage(r,0,0,x,N),E=Kc.getImageData(0,0,x,N).data);let _;if(l===4)_=new Int32Array(E);else{const U=x*N;_=new Int32Array(U*l);for(let ne=0;ne<U;ne++)for(let Q=0;Q<l;++Q)_[ne*l+Q]=E[ne*4+Q]}const A=[N,x,l];return VI(_,A,"int32")}async function nZ(r,l){let u=P(r,"img","toPixels");if(!(r instanceof kn)){const N=u;u=Ie(N,"int32"),N.dispose()}if(u.rank!==2&&u.rank!==3)throw new Error(`toPixels only supports rank 2 or 3 tensors, got rank ${u.rank}.`);const[d,f]=u.shape.slice(0,2),g=u.rank===2?1:u.shape[2];if(g>4||g===2)throw new Error(`toPixels only supports depth of size 1, 3 or 4 but got ${g}`);if(u.dtype!=="float32"&&u.dtype!=="int32")throw new Error(`Unsupported type for toPixels: ${u.dtype}. Please use float32 or int32 tensors.`);const I=await u.data(),S=u.dtype==="float32"?255:1,x=new Uint8ClampedArray(f*d*4);for(let N=0;N<d*f;++N){const E=[0,0,0,255];for(let A=0;A<g;A++){const U=I[N*g+A];if(u.dtype==="float32"){if(U<0||U>1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${U}.`)}else if(u.dtype==="int32"&&(U<0||U>255))throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${U}.`);g===1?(E[0]=U*S,E[1]=U*S,E[2]=U*S):E[A]=U*S}const _=N*4;x[_+0]=Math.round(E[0]),x[_+1]=Math.round(E[1]),x[_+2]=Math.round(E[2]),x[_+3]=Math.round(E[3])}if(l!=null){l.width=f,l.height=d;const N=l.getContext("2d"),E=new ImageData(x,f,d);N.putImageData(E,0,0)}return u!==r&&u.dispose(),x}const sZ=V({fromPixels_:tZ});function YO(r,l,u){const d=r.shape.length;J(d===l.length,()=>`Error in slice${d}D: Length of begin ${l} must match the rank of the array (${d}).`),J(d===u.length,()=>`Error in slice${d}D: Length of size ${u} must match the rank of the array (${d}).`);for(let f=0;f<d;++f)J(l[f]+u[f]<=r.shape[f],()=>`Error in slice${d}D: begin[${f}] + size[${f}] (${l[f]+u[f]}) would overflow input.shape[${f}] (${r.shape[f]})`)}function Ig(r,l,u){let d;const f=r.shape.length;typeof l=="number"?d=[l,...new Array(f-1).fill(0)]:l.length<f?d=l.concat(new Array(f-l.length).fill(0)):d=l.slice(),d.forEach(I=>{J(I!==-1,()=>"slice() does not support negative begin indexing.")});let g;return u==null?g=new Array(f).fill(-1):typeof u=="number"?g=[u,...new Array(f-1).fill(-1)]:u.length<f?g=u.concat(new Array(f-u.length).fill(-1)):g=u,g=g.map((I,S)=>I>=0?I:(J(I===-1,()=>`Negative size values should be exactly -1 but got ${I} for the slice() size at index ${S}.`),r.shape[S]-d[S])),[d,g]}function iZ(r){Fs().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(r+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}WO(iZ);function HO(r,l){return H.tidy(r,l)}function qO(r){const l=Lg(r);l.forEach(u=>u.dispose())}function rZ(r,l){let u=P(r,"a","add"),d=P(l,"b","add");[u,d]=Lt(u,d);const f=(I,S)=>{const x=I.add(u,d);return S([u,d]),x},g={a:u,b:d};return H.runKernelFunc(f,g,null,Hc)}const vt=V({add_:rZ});function oZ(r,l){let u=P(r,"a","floorDiv"),d=P(l,"b","floorDiv");[u,d]=Lt(u,d);const f=(I,S)=>{const x=I.floorDiv(u,d);return S([u,d]),x},g={a:u,b:d};return H.runKernelFunc(f,g,null,kf)}const YI=V({floorDiv_:oZ});function aZ(r,l){let u=P(r,"a","div"),d=P(l,"b","div");if([u,d]=Lt(u,d),u.dtype==="int32"&&d.dtype==="int32")return YI(u,d);const f=(S,x)=>{const N=S.realDivide(u,d);return x([u,d]),N},g={a:u,b:d},I={};return H.runKernelFunc(f,g,null,Of,I)}const Pe=V({div_:aZ});function cZ(r,l){let u=P(r,"a","mul"),d=P(l,"b","mul");[u,d]=Lt(u,d);const f=(I,S)=>{const x=I.multiply(u,d);return S([u,d]),x},g={a:u,b:d};return H.runKernelFunc(f,g,null,Vf)}const le=V({mul_:cZ});function lZ(r){const l=P(r,"x","abs"),u={x:l};return H.runKernelFunc((d,f)=>(f([l]),l.dtype==="complex64"?d.complexAbs(l):d.abs(l)),u,null,Lf)}const Yn=V({abs_:lZ});function hZ(r,l){for(let u=0;u<r.length;++u)if(r[r.length-u-1]!==l-1-u)return!1;return!0}function uZ(r,l,u){const d=r.length+l.length,f=[];let g=0,I=0;for(let S=0;S<d;S++)u.indexOf(S)===-1?f.push(r[g++]):f.push(l[I++]);return f}function jO(r,l){const u=[],d=r.length;for(let g=0;g<d;g++)l.indexOf(g)===-1&&u.push(r[g]);const f=l.map(g=>r[g]);return[u,f]}function cs(r,l){const u=l.map(d=>1);return uZ(r,u,l)}function ji(r,l){if(hZ(r,l))return null;const u=[];for(let d=0;d<l;++d)r.indexOf(d)===-1&&u.push(d);return r.forEach(d=>u.push(d)),u}function Xc(r){return r.map((l,u)=>[u,l]).sort((l,u)=>l[1]-u[1]).map(l=>l[0])}function go(r,l){const u=[];for(let d=l-r;d<l;++d)u.push(d);return u}function Tg(r,l,u,d,f,g,I="channelsLast"){const[S,x]=xg(l);let N;if(I==="channelsLast")N=[S,x,r[3],r[3]];else if(I==="channelsFirst")N=[S,x,r[1],r[1]];else throw new Error(`Unknown dataFormat ${I}`);return wi(r,N,u,d,f,g,!1,I)}function Ag(r,l,u,d,f,g,I="NDHWC"){const[S,x,N]=HI(l);let E,_;if(I==="NDHWC")_="channelsLast",E=[S,x,N,r[4],r[4]];else if(I==="NCDHW")_="channelsFirst",E=[S,x,N,r[1],r[1]];else throw new Error(`Unknown dataFormat ${I}`);return Ku(r,E,u,d,f,!1,_,g)}function wi(r,l,u,d,f,g,I=!1,S="channelsLast"){let[x,N,E,_]=[-1,-1,-1,-1];if(S==="channelsLast")[x,N,E,_]=r;else if(S==="channelsFirst")[x,_,N,E]=r;else throw new Error(`Unknown dataFormat ${S}`);const[A,U,,ne]=l,[Q,M]=xg(u),[fe,ie]=xg(d),we=Jc(A,fe),Ae=Jc(U,ie),{padInfo:Me,outHeight:et,outWidth:ct}=dZ(f,N,E,Q,M,we,Ae,g,S),$t=I?ne*_:ne;let Vt;return S==="channelsFirst"?Vt=[x,$t,et,ct]:S==="channelsLast"&&(Vt=[x,et,ct,$t]),{batchSize:x,dataFormat:S,inHeight:N,inWidth:E,inChannels:_,outHeight:et,outWidth:ct,outChannels:$t,padInfo:Me,strideHeight:Q,strideWidth:M,filterHeight:A,filterWidth:U,effectiveFilterHeight:we,effectiveFilterWidth:Ae,dilationHeight:fe,dilationWidth:ie,inShape:r,outShape:Vt,filterShape:l}}function Ku(r,l,u,d,f,g=!1,I="channelsLast",S){let[x,N,E,_,A]=[-1,-1,-1,-1,-1];if(I==="channelsLast")[x,N,E,_,A]=r;else if(I==="channelsFirst")[x,A,N,E,_]=r;else throw new Error(`Unknown dataFormat ${I}`);const[U,ne,Q,,M]=l,[fe,ie,we]=HI(u),[Ae,Me,et]=HI(d),ct=Jc(U,Ae),$t=Jc(ne,Me),Vt=Jc(Q,et),{padInfo:je,outDepth:hn,outHeight:bt,outWidth:Is}=pZ(f,N,E,_,fe,ie,we,ct,$t,Vt,S),_r=g?M*A:M;let Wr;return I==="channelsFirst"?Wr=[x,_r,hn,bt,Is]:I==="channelsLast"&&(Wr=[x,hn,bt,Is,_r]),{batchSize:x,dataFormat:I,inDepth:N,inHeight:E,inWidth:_,inChannels:A,outDepth:hn,outHeight:bt,outWidth:Is,outChannels:_r,padInfo:je,strideDepth:fe,strideHeight:ie,strideWidth:we,filterDepth:U,filterHeight:ne,filterWidth:Q,effectiveFilterDepth:ct,effectiveFilterHeight:$t,effectiveFilterWidth:Vt,dilationDepth:Ae,dilationHeight:Me,dilationWidth:et,inShape:r,outShape:Wr,filterShape:l}}function mZ(r,l,u,d,f){d==null&&(d=KO(r,l,u));const g=r[0],I=r[1],S=fa((g-l+2*d)/u+1,f);J(nn(S),()=>`The output # of rows (${S}) must be an integer. Change the stride and/or zero pad parameters`);const x=fa((I-l+2*d)/u+1,f);return J(nn(x),()=>`The output # of columns (${x}) must be an integer. Change the stride and/or zero pad parameters`),[S,x]}function fZ(r,l,u,d,f,g){f==null&&(f=KO(r,l,d));const I=r[0],S=r[1],x=r[2],N=fa((I-l+2*f)/d+1,g);J(nn(N),()=>`The output # of depths (${N}) must be an integer. Change the stride and/or zero pad parameters`);const E=fa((S-l+2*f)/d+1,g);J(nn(E),()=>`The output # of rows (${E}) must be an integer. Change the stride and/or zero pad parameters`);const _=fa((x-l+2*f)/d+1,g);return J(nn(_),()=>`The output # of columns (${_}) must be an integer. Change the stride and/or zero pad parameters`),[N,E,_,u]}function KO(r,l,u,d=1){const f=Jc(l,d);return Math.floor((r[0]*(u-1)-u+f)/2)}function xg(r){return typeof r=="number"?[r,r,r]:r.length===2?[r[0],r[1],1]:r}function HI(r){return typeof r=="number"?[r,r,r]:r}function Jc(r,l){return l<=1?r:r+(r-1)*(l-1)}function dZ(r,l,u,d,f,g,I,S,x){let N,E,_;if(typeof r=="number"){const A=r===0?"VALID":"NUMBER";N={top:r,bottom:r,left:r,right:r,type:A};const U=mZ([l,u],g,d,r,S);E=U[0],_=U[1]}else if(r==="same"){E=Math.ceil(l/d),_=Math.ceil(u/f);const A=Math.max(0,(E-1)*d+g-l),U=Math.max(0,(_-1)*f+I-u),ne=Math.floor(A/2),Q=A-ne,M=Math.floor(U/2),fe=U-M;N={top:ne,bottom:Q,left:M,right:fe,type:"SAME"}}else if(r==="valid")N={top:0,bottom:0,left:0,right:0,type:"VALID"},E=Math.ceil((l-g+1)/d),_=Math.ceil((u-I+1)/f);else if(typeof r=="object"){const A=x==="channelsLast"?r[1][0]:r[2][0],U=x==="channelsLast"?r[1][1]:r[2][1],ne=x==="channelsLast"?r[2][0]:r[3][0],Q=x==="channelsLast"?r[2][1]:r[3][1],M=A===0&&U===0&&ne===0&&Q===0?"VALID":"EXPLICIT";N={top:A,bottom:U,left:ne,right:Q,type:M},E=fa((l-g+A+U)/d+1,S),_=fa((u-I+ne+Q)/f+1,S)}else throw Error(`Unknown padding parameter: ${r}`);return{padInfo:N,outHeight:E,outWidth:_}}function pZ(r,l,u,d,f,g,I,S,x,N,E){let _,A,U,ne;if(typeof r=="number"){const Q=r===0?"VALID":"NUMBER";_={top:r,bottom:r,left:r,right:r,front:r,back:r,type:Q};const M=fZ([l,u,d,1],S,1,f,r,E);A=M[0],U=M[1],ne=M[2]}else if(r==="same"){A=Math.ceil(l/f),U=Math.ceil(u/g),ne=Math.ceil(d/I);const Q=(A-1)*f+S-l,M=(U-1)*g+x-u,fe=(ne-1)*I+N-d,ie=Math.floor(Q/2),we=Q-ie,Ae=Math.floor(M/2),Me=M-Ae,et=Math.floor(fe/2),ct=fe-et;_={top:Ae,bottom:Me,left:et,right:ct,front:ie,back:we,type:"SAME"}}else if(r==="valid")_={top:0,bottom:0,left:0,right:0,front:0,back:0,type:"VALID"},A=Math.ceil((l-S+1)/f),U=Math.ceil((u-x+1)/g),ne=Math.ceil((d-N+1)/I);else throw Error(`Unknown padding parameter: ${r}`);return{padInfo:_,outDepth:A,outHeight:U,outWidth:ne}}function fa(r,l){if(!l)return r;switch(l){case"round":return Math.round(r);case"ceil":return Math.ceil(r);case"floor":return Math.floor(r);default:throw new Error(`Unknown roundingMode ${l}`)}}function yo(r){const[l,u,d]=xg(r);return l===1&&u===1&&d===1}function bo(r,l){return yo(r)||yo(l)}function Zc(r){if(r==="NHWC")return"channelsLast";if(r==="NCHW")return"channelsFirst";throw new Error(`Unknown dataFormat ${r}`)}function XO(r,l){const u=r[0].length;r.forEach((f,g)=>{J(f.length===u,()=>`Error in concat${u}D: rank of tensors[${g}] must be the same as the rank of the rest (${u})`)}),J(l>=0&&l<u,()=>`Error in concat${u}D: axis must be between 0 and ${u-1}.`);const d=r[0];r.forEach((f,g)=>{for(let I=0;I<u;I++)J(I===l||f[I]===d[I],()=>`Error in concat${u}D: Shape of tensors[${g}] (${f}) does not match the shape of the rest (${d}) along the non-concatenated axis ${g}.`)})}function JO(r,l){const u=r[0].slice();for(let d=1;d<r.length;d++)u[l]+=r[d][l];return u}function gZ(r,l=0){J(r.length>=1,()=>"Pass at least one tensor to concat");let u=Sg(r,"tensors","concat");u[0].dtype==="complex64"&&u.forEach(I=>{if(I.dtype!=="complex64")throw new Error(`Cannot concatenate complex64 tensors with a tensor
with dtype ${I.dtype}. `)});const d=(I,S)=>{const x=ft(l,u[0].shape)[0],N=JO(u.map(A=>A.shape),x);if(Zt(N)===0)return PI([],N);if(u=u.filter(A=>A.size>0),u.length===1)return u[0];const E=u.map(A=>A.shape);XO(E,x);const _=I.concat(u,x);return S(u),_},f=u,g={axis:l};return H.runKernelFunc(d,f,null,Tf,g)}const An=V({concat_:gZ});function yZ(r){const l=P(r,"x","sigmoid"),u={x:l};return H.runKernelFunc((d,f)=>{const g=d.sigmoid(l);return f([g]),g},u,null,sg)}const qI=V({sigmoid_:yZ});function bZ(r,l,u){const d=P(r,"x","slice");if(d.rank===0)throw new Error("Slicing scalar is not possible");const f=(S,x)=>{const[N,E]=Ig(d,l,u);return YO(d,N,E),x([d]),S.slice(d,N,E)},g={x:d},I={begin:l,size:u};return H.runKernelFunc(f,g,null,eg,I)}const Tt=V({slice_:bZ});function wZ(r,l,u){const d=P(r,"x","batchToSpaceND"),f=l.reduce((x,N)=>x*N);J(d.rank>=1+l.length,()=>`input rank is ${d.rank} but should be > than blockShape.length ${l.length}`),J(u.length===l.length,()=>`crops.length is ${u.length} but should be equal to blockShape.length ${l.length}`),J(d.shape[0]%f===0,()=>`input tensor batch is ${d.shape[0]} but is not divisible by the product of the elements of blockShape ${l.join(" * ")} === ${f}`);const g=x=>x.batchToSpaceND(d,l,u),I={x:d},S={blockShape:l,crops:u};return H.runKernelFunc(g,I,null,If,S)}const jI=V({batchToSpaceND_:wZ});function LZ(r,l){let u=P(r,"broadcastTo","x");const d=u.shape;if(l.some(E=>!(E>0)||E%1!==0))throw new Error(`broadcastTo(): Invalid broadcast shape [${l}].`);if(l.length<u.rank)throw new Error(`broadcastTo(): shape.length=${l.length} < input.rank=${u.rank}.`);if(l.length>u.rank){const E=u.shape.slice();for(;E.length<l.length;)E.unshift(1);u=oe(u,E)}const f=u.shape,g=Array.from(l);for(let E=l.length-1;E>=0;E--)if(f[E]===l[E])g[E]=1;else if(u.shape[E]!==1)throw new Error(`broadcastTo(): [${d}] cannot be broadcast to [${l}].`);const I=g.map((E,_)=>E>1?_:-1).filter(E=>E>=0);if(I.length===0)return bi(u);const S=E=>E.tile(u,g),x={x:u},N={shape:l,inputShape:f};return H.runKernelFunc(S,x,null,xf,N)}const vg=V({broadcastTo_:LZ});function SZ(r,l,u,d,f="NHWC",g=[1,1],I){const S=P(r,"x","conv2d"),x=P(l,"filter","conv2d");let N=S,E=!1;S.rank===3&&(E=!0,N=oe(S,[1,S.shape[0],S.shape[1],S.shape[2]])),J(N.rank===4,()=>`Error in conv2d: input must be rank 4, but got rank ${N.rank}.`),J(x.rank===4,()=>`Error in conv2d: filter must be rank 4, but got rank ${x.rank}.`),I!=null&&J(nn(d),()=>`Error in conv2d: pad must be an integer when using, dimRoundingMode ${I} but got pad ${d}.`);const _=f==="NHWC"?N.shape[3]:N.shape[1];J(_===x.shape[2],()=>`Error in conv2d: depth of input (${_}) must match input depth for filter ${x.shape[2]}.`),J(bo(u,g),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${u} and dilations '${g}'`);const A=(M,fe)=>{const ie=Zc(f),we=wi(N.shape,x.shape,u,g,d,I,!1,ie),Ae=M.conv2d(N,x,we);return fe([N,x]),Ae},U={x:N,filter:x},ne={strides:u,pad:d,dataFormat:f,dilations:g,dimRoundingMode:I},Q=H.runKernelFunc(A,U,null,Af,ne);return E?oe(Q,[Q.shape[1],Q.shape[2],Q.shape[3]]):Q}const KI=V({conv2d_:SZ});function IZ(r,l,u,d,f,g="NHWC",I){J(r.length===l.rank,()=>`Length of inShape (${r.length}) and rank of dy (${l.rank}) must match`);let S=r,x=l,N=!1;l.rank===3&&(N=!0,x=oe(l,[1,l.shape[0],l.shape[1],l.shape[2]]),S=[1,r[0],r[1],r[2]]),J(S.length===4,()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${S.length}.`),J(x.rank===4,()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${x.rank}`),J(u.rank===4,()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${u.rank}`);const E=g==="NHWC"?S[3]:S[1],_=g==="NHWC"?x.shape[3]:x.shape[1];J(E===u.shape[2],()=>`Error in conv2dDerInput: depth of input (${E}) must match input depth for filter ${u.shape[2]}.`),J(_===u.shape[3],()=>`Error in conv2dDerInput: depth of output (${_}) must match output depth for filter ${u.shape[3]}.`),I!=null&&J(nn(f),()=>`Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode ${I} but got pad ${f}.`);const A=(M,fe)=>{const ie=1,we=Zc(g),Ae=wi(S,u.shape,d,ie,f,I,!1,we),Me=M.conv2dDerInput(x,u,Ae);return fe([x,u]),Me},U={dy:x,filter:u},ne={strides:d,pad:f,dataFormat:g,dimRoundingMode:I,inputShape:S},Q=H.runKernelFunc(A,U,null,vf,ne);return N?oe(Q,[Q.shape[1],Q.shape[2],Q.shape[3]]):Q}const ZO=V({conv2DBackpropInput_:IZ});function xZ(r,l,u,d,f){J(r.length===l.rank,()=>`Length of inShape (${r.length}) and rank of dy (${l.rank}) must match`);let g=r,I=l,S=!1;l.rank===4&&(S=!0,I=oe(l,[1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]]),g=[1,r[0],r[1],r[2],r[3]]);const x=g[4],N=I.shape[4];J(g.length===5,()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${g.length}.`),J(I.rank===5,()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${I.rank}`),J(u.rank===5,()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${u.rank}`),J(x===u.shape[3],()=>`Error in conv3dDerInput: depth of input (${x}) must match input depth for filter ${u.shape[3]}.`),J(N===u.shape[4],()=>`Error in conv3dDerInput: depth of output (${N}) must match output depth for filter ${u.shape[4]}.`);const E=ne=>{const Q=1,M=Ku(g,u.shape,d,Q,f);return ne.conv3dDerInput(I,u,M)},_={dy:I,filter:u},A={pad:f,strides:d,inputShape:g},U=H.runKernelFunc(E,_,null,wR,A);return S?oe(U,[U.shape[1],U.shape[2],U.shape[3],U.shape[4]]):U}const QO=V({conv3DBackpropInput_:xZ});function TZ(r){const l=P(r,"x","cos"),u={x:l};return H.runKernelFunc((d,f)=>{const g=d.cos(l);return f([l]),g},u,null,Nf)}const Xu=V({cos_:TZ});function AZ(r){const l=P(r,"x","cosh"),u={x:l};return H.runKernelFunc((d,f)=>{const g=d.cosh(l);return f([l]),g},u,null,Cf)}const XI=V({cosh_:AZ});function vZ(r,l=0,u=!1,d=!1){const f=P(r,"x","cumsum"),g=(x,N)=>{const E=ji([l],f.rank);let _=f;E!=null&&(_=Tn(f,E));const A=go(1,f.rank)[0];let U=x.cumsum(_,A,u,d);if(N([f]),E!=null){const ne=Xc(E);U=Tn(U,ne)}return U},I={x:f},S={axis:l,exclusive:u,reverse:d};return H.runKernelFunc(g,I,null,Rf,S)}const JI=V({cumsum_:vZ});function Ot(r,l){const u=[];for(let d=0;d<l.length;d++){const f=r[r.length-d-1],g=l.length-d-1,I=l[g];(f==null||f===1&&I>1)&&u.unshift(g)}return u}function at(r,l){const u=[],d=Math.max(r.length,l.length);for(let f=0;f<d;f++){let g=r[r.length-f-1];g==null&&(g=1);let I=l[l.length-f-1];if(I==null&&(I=1),g===1)u.unshift(I);else if(I===1)u.unshift(g);else if(g!==I){const S=`Operands could not be broadcast together with shapes ${r} and ${l}.`;throw Error(S)}else u.unshift(g)}return u}function NZ(r,l){let u=P(r,"a","equal"),d=P(l,"b","equal");[u,d]=Lt(u,d),at(u.shape,d.shape);const f=I=>I.equal(u,d),g={a:u,b:d};return H.runKernelFunc(f,g,null,OR)}const ZI=V({equal_:NZ});function CZ(r,l,u){const d=P(l,"a","where"),f=P(u,"b","where"),g=P(r,"condition","where","bool"),I=at(d.shape,f.shape),S=vg(d,I),x=vg(f,I);g.rank===1&&J(g.shape[0]===d.shape[0],()=>"The first dimension of `a` must match the size of `condition`."),g.rank!==1&&tn(g.shape,x.shape,"Error in where: ");const N=(_,A)=>{const U=_.select(g,S,x);return A([g]),U},E={condition:g,t:S,e:x};return H.runKernelFunc(N,E,null,Qf)}const Hn=V({where_:CZ});function RZ(r){const l=P(r,"x","zerosLike"),u={x:l};return H.runKernelFunc(d=>d.zerosLike(l),u,null,mg)}const Xe=V({zerosLike_:RZ});function OZ(r){const l=P(r,"x","exp"),u={x:l};return H.runKernelFunc((d,f)=>{const g=d.exp(l);return f([g]),g},u,null,Ef)}const qn=V({exp_:OZ});function EZ(r,l=0){const u=null,d=P(r,"x","expandDims",u);J(l<=d.rank,()=>"Axis must be <= rank of the tensor");const f=d.shape.slice();return l<0&&(J(-(d.rank+1)<=l,()=>`Axis must be in the interval [${-(d.rank+1)}, ${d.rank}]`),l=d.rank+l+1),f.splice(l,0,1),oe(d,f)}const _s=V({expandDims_:EZ});function DZ(r,l){const u=null,d=P(r,"x","tile",u);J(d.rank===l.length,()=>`Error in transpose: rank of input ${d.rank} must match length of reps ${l}.`);const f=(x,N)=>{const E=x.tile(d,l);return N([d]),E},g=[d],I={x:d},S={reps:l};return H.runKernelFunc(f,I,null,hg,S,g)}const ga=V({tile_:DZ});function kZ(r,l,u,d="float32"){l==null&&(l=r);const f=ju([r,l],d),g=r<=l?r:l;for(let S=0;S<g;++S)f.set(1,S,S);const I=oe(f.toTensor(),[r,l]);if(u==null)return I;if(u.length===1)return ga(_s(I,0),[u[0],1,1]);if(u.length===2)return ga(_s(_s(I,0),0),[u[0],u[1],1,1]);if(u.length===3)return ga(_s(_s(_s(I,0),0),0),[u[0],u[1],u[2],1,1]);throw new Error(`eye() currently supports only 1D and 2D batchShapes, but received ${u.length}D.`)}const QI=V({eye_:kZ});function ex(r,l,u){const d={shape:r,value:l,dtype:u};return H.runKernelFunc(f=>f.fill(r,l,u),{},null,kR,d)}function FZ(r){const l=P(r,"x","floor"),u={x:l};return H.runKernelFunc(d=>d.floor(l),u,null,Df)}const tx=V({floor_:FZ});function e1(r,l,u){const d=r.shape[u],f=[];let g=1,I=1;for(let S=0;S<u;S++)f.push(r.shape[S]),g*=r.shape[S];for(let S=0;S<l.rank;S++)f.push(l.shape[S]);for(let S=u+1;S<r.rank;S++)f.push(r.shape[S]),I*=r.shape[S];return{batchSize:g,sliceSize:I,dimSize:d,outputShape:f}}function _Z(r,l,u=0){const d=P(r,"x","gather"),f=P(l,"indices","gather","int32"),g={x:d,indices:f},I={axis:u},S=(x,N)=>{const E=ft(u,d.shape)[0],_=e1(d,f,E),A=x.gather(d,oe(f,[f.size]),E);return N([d,f]),oe(A,_.outputShape)};return H.runKernelFunc(S,g,null,Ff,I)}const nx=V({gather_:_Z});function WZ(r,l){let u=P(r,"a","greater"),d=P(l,"b","greater");[u,d]=Lt(u,d),at(u.shape,d.shape);const f=I=>I.greater(u,d),g={a:u,b:d};return H.runKernelFunc(f,g,null,WR)}const Li=V({greater_:WZ});function $Z(r,l){let u=P(r,"a","greaterEqual"),d=P(l,"b","greaterEqual");[u,d]=Lt(u,d),at(u.shape,d.shape);const f=(I,S)=>{const x=I.greaterEqual(u,d);return S([u,d]),x},g={a:u,b:d};return H.runKernelFunc(f,g,null,_f)}const Nr=V({greaterEqual_:$Z});function UZ(r){const l=P(r,"input","imag"),u=f=>f.imag(l),d={input:l};return H.runKernelFunc(u,d,null,UR)}const Ju=V({imag_:UZ});function BZ(r,l){let u=P(r,"a","maximum"),d=P(l,"b","maximum");[u,d]=Lt(u,d),u.dtype==="bool"&&(u=Ie(u,"int32"),d=Ie(d,"int32")),at(u.shape,d.shape);const f=(I,S)=>{const x=I.maximum(u,d);return S([u,d]),x},g={a:u,b:d};return H.runKernelFunc(f,g,null,Mf)}const sx=V({maximum_:BZ});function Fe(r,l){if((ks(r)&&l!=="string"||Array.isArray(r))&&l!=="complex64")throw new Error("Error creating a new Scalar: value must be a primitive (number|boolean|string)");if(l==="string"&&ks(r)&&!(r instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");const u=[],d=[];return qi(r,u,d,l)}function MZ(r,l){let u=P(r,"a","less"),d=P(l,"b","less");[u,d]=Lt(u,d),at(u.shape,d.shape);const f=I=>I.less(u,d),g={a:u,b:d};return H.runKernelFunc(f,g,null,zR)}const ix=V({less_:MZ});function PZ(r,l){let u=P(r,"a","lessEqual"),d=P(l,"b","lessEqual");[u,d]=Lt(u,d),at(u.shape,d.shape);const f=(I,S)=>{const x=I.lessEqual(u,d);return S([u,d]),x},g={a:u,b:d};return H.runKernelFunc(f,g,null,VR)}const Cr=V({lessEqual_:PZ});function zZ(r){const l=P(r,"x","log"),u={x:l};return H.runKernelFunc((d,f)=>{const g=d.log(l);return f([l]),g},u,null,$f)}const wo=V({log_:zZ});function VZ(r){const l=P(r,"x","log1p"),u={x:l};return H.runKernelFunc((d,f)=>{const g=d.log1p(l);return f([l]),g},u,null,Uf)}const rx=V({log1p_:VZ});function Ng(r){return H.customGrad(r)}function GZ(r){const l=P(r,"x","neg"),u={x:l};return H.runKernelFunc(d=>d.neg(l),u,null,Gf)}const It=V({neg_:GZ});function YZ(r,l=null,u=!1){const d=P(r,"x","max"),f=(S,x)=>{const N=ft(l,d.shape);let E=N;const _=ji(E,d.rank);let A=d;_!=null&&(A=Tn(d,_),E=go(E.length,A.rank));const U=S.max(A,E);_!=null&&A.dispose();let ne=U;if(u){const Q=cs(ne.shape,ft(l,d.shape));ne=oe(ne,Q),U.dispose()}return x([d,ne]),ne},g={x:d},I={reductionIndices:l,keepDims:u};return H.runKernelFunc(f,g,null,Bf,I)}const ya=V({max_:YZ});function HZ(r,l){let u=P(r,"a","sub"),d=P(l,"b","sub");[u,d]=Lt(u,d);const f=(I,S)=>{const x=I.subtract(u,d);return S([u,d]),x},g={a:u,b:d};return H.runKernelFunc(f,g,null,lg)}const Be=V({sub_:HZ});function qZ(r,l=null,u=!1){let d=P(r,"x","sum");d.dtype==="bool"&&(d=Ie(d,"int32"));const f=(S,x)=>{x([d]);const N=ft(l,d.shape),E=ji(N,d.rank);let _=N,A=d;E!=null&&(A=Tn(d,E),_=go(_.length,d.rank));let U=S.sum(A,_);if(u){const ne=cs(U.shape,N);U=oe(U,ne)}return U},g={x:d},I={axis:l,keepDims:u};return H.runKernelFunc(f,g,null,rg,I)}const _e=V({sum_:qZ});function jZ(r,l=null,u=!1){const d=P(r,"x","logSumExp"),f=ft(l,d.shape),g=ya(d,f,!0),I=Be(d,g),S=qn(I),x=_e(S,f),N=wo(x),E=vt(oe(g,N.shape),N);if(u){const _=cs(E.shape,f);return oe(E,_)}return E}const ox=V({logSumExp_:jZ});function KZ(r,l){const u=P(r,"a","logicalAnd","bool"),d=P(l,"b","logicalAnd","bool");at(u.shape,d.shape);const f={a:u,b:d};return H.runKernelFunc(g=>g.logicalAnd(u,d),f,null,GR)}const ba=V({logicalAnd_:KZ});function XZ(r){const l=P(r,"x","logicalNot","bool"),u={x:l};return H.runKernelFunc(d=>d.logicalNot(l),u,null,YR)}const ax=V({logicalNot_:XZ});function Ws(r,l="float32"){if(l==="complex64"){const d=Ws(r,"float32"),f=Ws(r,"float32");return Hi(d,f)}const u=ma(Zt(r),l);return H.makeTensor(u,r,l)}function Ki(r,l="float32"){if(l==="complex64"){const d=Ki(r,"float32"),f=Ws(r,"float32");return Hi(d,f)}const u=yf(Zt(r),l);return H.makeTensor(u,r,l)}function JZ(r,l=null,u=!1){const d=P(r,"x","mean"),f=ft(l,d.shape),g=jO(d.shape,f),I=g[1],S=Zt(I),x={x:d},N={axis:l,keepDims:u},E=()=>{const A=Fe(S),U=A.dtype===d.dtype?d:Ie(d,A.dtype),ne=Pe(U,A);return _e(ne,l,u)},_=Ng(A=>{const U=H.runKernelFunc(E,x,null,QR,N),ne=Q=>{const M=A.shape.slice();f.forEach(we=>{M[we]=1});const fe=oe(Q,M),ie=Pe(le(fe,Ki(A.shape,"float32")),S);return ie};return{value:U,gradFunc:ne}});return _(d)}const cx=V({mean_:JZ});function ZZ(r,l=null,u=!1){const d=P(r,"x","min"),f=(S,x)=>{const N=ft(l,d.shape);let E=N;const _=ji(E,d.rank);let A=d;_!=null&&(A=Tn(d,_),E=go(E.length,d.rank));const U=S.min(A,E);_!=null&&A.dispose();let ne=U;if(u){const Q=cs(ne.shape,N);ne=oe(U,Q),U.dispose()}return x([d,ne]),ne},g={x:d},I={axis:l,keepDims:u};return H.runKernelFunc(f,g,null,Pf,I)}const Cg=V({min_:ZZ});function QZ(r,l){let u=P(r,"a","minimum"),d=P(l,"b","minimum");[u,d]=Lt(u,d),u.dtype==="bool"&&(u=Ie(u,"int32"),d=Ie(d,"int32")),at(u.shape,d.shape);const f=(I,S)=>{const x=I.minimum(u,d);return S([u,d]),x},g={a:u,b:d};return H.runKernelFunc(f,g,null,zf)}const lx=V({minimum_:QZ});function eQ(r){const l=P(r,"x","square"),u={},d=[l],f=[];return H.runKernelFunc((g,I)=>(I([l]),g.square(l)),{x:l},null,"Square",u,d,f)}const gt=V({square_:eQ});function tQ(r,l){let u=P(r,"a","notEqual"),d=P(l,"b","notEqual");[u,d]=Lt(u,d),at(u.shape,d.shape);const f=I=>I.notEqual(u,d),g={a:u,b:d};return H.runKernelFunc(f,g,null,nO)}const hx=V({notEqual_:tQ});function nQ(r){const l=P(r,"input","real"),u=f=>f.real(l),d={input:l};return H.runKernelFunc(u,d,null,hO)}const Qc=V({real_:nQ});function sQ(r,l,u=0){const d=P(r,"x","pad");if(d.rank===0)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");const f=(S,x)=>(x([d]),S.pad(d,l,u)),g={paddings:l,constantValue:u},I={x:d};return H.runKernelFunc(f,I,null,Yf,g)}const ux=V({pad_:sQ});function iQ(r,l,u){const d=P(r,"x","spaceToBatchND");J(d.rank>=1+l.length,()=>`input rank ${d.rank} should be > than [blockShape] ${l.length}`),J(u.length===l.length,()=>`paddings.shape[0] ${u.length} must be equal to [blockShape] ${l.length}`),J(d.shape.reduce((S,x,N)=>N>0&&N<=l.length?S&&(x+u[N-1][0]+u[N-1][1])%l[N-1]===0:S,!0),()=>`input spatial dimensions ${d.shape.slice(1)} with paddings ${u.toString()} must be divisible by blockShapes ${l.toString()}`);const f=S=>S.spaceToBatchND(d,l,u),g={x:d},I={blockShape:l,paddings:u};return H.runKernelFunc(f,g,null,og,I)}const dx=V({spaceToBatchND_:iQ});function rQ(r,l){let u=P(r,"base","pow"),d=P(l,"exp","pow");[u,d]=Lt(u,d);const f={a:u,b:d},g=(I,S)=>{const x=I.pow(u,d);return S([u,d,x]),x};return H.runKernelFunc(g,f,null,Hf)}const wa=V({pow_:rQ});function Lo(r,l){Gc(r);const u=vr(r,l);if(u.length!==1)throw new Error("tensor1d() requires values to be a flat/TypedArray");const d=null;return qi(r,d,u,l)}function Rg(r,l,u=1,d="float32"){if(u===0)throw new Error("Cannot have a step of zero");const f=()=>{const I=r===l,S=r<l&&u<0,x=l<r&&u>1;if(I||S||x)return Ws([0],d);const N=Math.abs(Math.ceil((l-r)/u)),E=ma(N,d);l<r&&u===1&&(u=-1),E[0]=r;for(let _=1;_<E.length;_++)E[_]=E[_-1]+u;return Lo(E,d)},g={start:r,stop:l,step:u,dtype:d};return H.runKernelFunc(f,{},null,lO,g)}function oQ(r){const l=P(r,"x","relu"),u=(f,g)=>(g([l]),l.dtype==="bool"?Ie(l,"int32"):f.relu(l)),d={x:l};return H.runKernelFunc(u,d,null,qf)}const Zu=V({relu_:oQ});function aQ(r,l){const u=P(r,"x","reverse"),d=I=>{const S=ft(l,u.shape);if(u.rank===0)return bi(u);const x=I.reverse(u,S);return oe(x,u.shape)},f={x:u},g={dims:l};return H.runKernelFunc(d,f,null,Jf,g)}const el=V({reverse_:aQ});function cQ(r){const l=P(r,"x","rsqrt"),u={x:l};return H.runKernelFunc((d,f)=>{const g=d.rsqrt(l);return f([l]),g},u,null,Zf)}const px=V({rsqrt_:cQ});function lQ(r){const l=P(r,"x","sin"),u={x:l};return H.runKernelFunc((d,f)=>{const g=d.sin(l);return f([l]),g},u,null,tg)}const mx=V({sin_:lQ});function hQ(r){const l=P(r,"x","sinh"),u={x:l};return H.runKernelFunc((d,f)=>{const g=d.sinh(l);return f([l]),g},u,null,ng)}const fx=V({sinh_:hQ});function uQ(r){J(r.dtype==="complex64",()=>`The dtype for tf.spectral.fft() must be complex64 but got ${r.dtype}.`);const l={input:r};return H.runKernelFunc(u=>{const d=r.shape[r.shape.length-1],f=r.size/d,g=r.as2D(f,d),I=u.fft(g);return I.reshape(r.shape)},l,null,DR)}const Qu=V({fft_:uQ});function dQ(r){J(r.dtype==="complex64",()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${r.dtype}.`);const l={input:r};return H.runKernelFunc(u=>{const d=r.shape[r.shape.length-1],f=r.size/d,g=oe(r,[f,d]),I=u.ifft(g);return oe(I,r.shape)},l,null,$R)}const tl=V({ifft_:dQ});function pQ(r){const l=r.shape[r.shape.length-1],u=r.size/l;let d;if(l<=2){const f=oe(r,[u,l]);d=tl(f)}else{const f=[u,2*(l-1)],g=oe(Qc(r),[u,l]),I=oe(Ju(r),[u,l]),S=el(Tt(g,[0,1],[u,l-2]),1),x=le(el(Tt(I,[0,1],[u,l-2]),1),Fe(-1)),N=An([g,S],1),E=An([I,x],1),_=oe(Hi(N,E),[f[0],f[1]]);d=tl(_)}if(d=Qc(d),r.rank===3&&r.shape[0]!==0){const f=d,g=r.shape[0];d=oe(d,[g,d.shape[0]/g,d.shape[1]]),f.dispose()}return d}const gx=V({irfft_:pQ});function t1(r,l,u=0){let d=[];if(typeof l=="number")J(r.shape[u]%l===0,()=>"Number of splits must evenly divide the axis."),d=new Array(l).fill(r.shape[u]/l);else{const f=l.reduce((I,S)=>(S===-1&&(I+=1),I),0);J(f<=1,()=>"There should be only one negative value in split array.");const g=l.indexOf(-1);if(g!==-1){const I=l.reduce((S,x)=>x>0?S+x:S);l[g]=r.shape[u]-I}J(r.shape[u]===l.reduce((I,S)=>I+S),()=>"The sum of sizes must match the size of the axis dimension."),d=l}return d}function mQ(r,l,u=0){const d=P(r,"x","split"),f=(S,x)=>{const N=ft(u,d.shape)[0],E=t1(d,l,N);return S.split(d,E,N)},g={x:d},I={numOrSizeSplits:l,axis:u};return H.runKernelFunc(f,g,null,ag,I)}const So=V({split_:mQ});function fQ(r,l){J(r.dtype==="float32",()=>`The dtype for rfft() must be real value but got ${r.dtype}`);let u=r.shape[r.shape.length-1];const d=r.size/u;let f;if(l!=null&&l<u){const ne=r.shape.map(M=>0),Q=r.shape.map(M=>M);Q[r.shape.length-1]=l,f=Tt(r,ne,Q),u=l}else if(l!=null&&l>u){const ne=r.shape.map(Q=>Q);ne[r.shape.length-1]=l-u,f=An([r,Ws(ne)],r.shape.length-1),u=l}else f=r;const g=Xe(f),I=oe(Hi(f,g),[d,u]),S=Qu(I),x=Math.floor(u/2)+1,N=Qc(S),E=Ju(S),_=So(N,[x,u-x],N.shape.length-1),A=So(E,[x,u-x],E.shape.length-1),U=f.shape.slice();return U[f.shape.length-1]=x,oe(Hi(_[0],A[0]),U)}const ed=V({rfft_:fQ});function gQ(r){const l=P(r,"x","sqrt"),u={x:l};return H.runKernelFunc((d,f)=>{const g=d.sqrt(l);return f([l]),g},u,null,ig)}const bs=V({sqrt_:gQ});function yQ(r,l){let u=P(r,"a","squaredDifference"),d=P(l,"b","squaredDifference");[u,d]=Lt(u,d),at(u.shape,d.shape);const f=(S,x)=>{const N=S.squaredDifference(u,d);return x([u,d]),N},g={a:u,b:d},I={};return H.runKernelFunc(f,g,null,cg,I)}const yx=V({squaredDifference_:yQ});function bQ(r,l){const u=P(r,"x","squeeze");return oe(u,z2(u.shape,l).newShape)}const bx=V({squeeze_:bQ});function wQ(r,l=0){const u=Sg(r,"tensors","stack");if(J(u.length>=1,()=>"Pass at least one tensor to tf.stack"),u.length===1)return _s(u[0],l);const d=u[0].rank,f=u[0].shape,g=u[0].dtype;J(l<=d,()=>"Axis must be <= rank of the tensor"),u.forEach(S=>{tn(f,S.shape,"All tensors passed to stack must have matching shapes"),J(g===S.dtype,()=>"All tensors passed to stack must have matching dtypes")});const I=u.map(S=>_s(S,l));return An(I,l)}const Ks=V({stack_:wQ});function LQ(r,l=0){const u=P(r,"x","step"),d={x:u},f={alpha:l};return H.runKernelFunc(g=>g.step(u,l),d,null,fg,f)}const La=V({step_:LQ});function Sa(r,l,u){if(Gc(r),l!=null&&l.length!==2)throw new Error("tensor2d() requires shape to have two numbers");const d=vr(r,u);if(d.length!==2&&d.length!==1)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(d.length===1&&l==null)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return qi(r,l,d,u)}function SQ(r,l,u){const d=P(r,"x","unsortedSegmentSum"),f=P(l,"segmentIds","unsortedSegmentSum","int32");J(nn(u),()=>"numSegments must be of dtype int");const g={x:d,segmentIds:f},I={numSegments:u},S=(x,N)=>{const E=x.unsortedSegmentSum(d,f,u);return N([f]),E};return H.runKernelFunc(S,g,null,pg,I)}const wx=V({unsortedSegmentSum_:SQ});function IQ(r,l=0){const u=P(r,"x","unstack");J(l>=-u.shape.length&&l<u.shape.length,()=>`Axis = ${l} is not in [-${u.shape.length}, ${u.shape.length})`),l<0&&(l+=u.shape.length);const d={value:u},f={axis:l},g=I=>I.unstack(u,l);return H.runKernelFunc(g,d,null,dg,f)}const td=V({unstack_:IQ});function xQ(r,l="euclidean",u=null,d=!1){r=P(r,"x","norm");const f=n1(r,l,u);let g=f.shape;if(d){const I=ft(u,r.shape);g=cs(f.shape,I)}return oe(f,g)}function n1(r,l,u=null){if(r.rank===0)return Yn(r);if(r.rank!==1&&u===null)return n1(oe(r,[-1]),l,u);if(r.rank===1||typeof u=="number"||Array.isArray(u)&&u.length===1){if(l===1)return _e(Yn(r),u);if(l===Infinity)return ya(Yn(r),u);if(l===-Infinity)return Cg(Yn(r),u);if(l==="euclidean"||l===2)return bs(_e(wa(Yn(r),Fe(2,"int32")),u));throw new Error(`Error in norm: invalid ord value: ${l}`)}if(Array.isArray(u)&&u.length===2){if(l===1)return ya(_e(Yn(r),u[0]),u[1]-1);if(l===Infinity)return ya(_e(Yn(r),u[1]),u[0]);if(l===-Infinity)return Cg(_e(Yn(r),u[1]),u[0]);if(l==="fro"||l==="euclidean")return bs(_e(gt(r),u));throw new Error(`Error in norm: invalid ord value: ${l}`)}throw new Error(`Error in norm: invalid axis: ${u}`)}const Og=V({norm_:xQ});function s1(r){return Math.floor(Math.pow(2,Math.ceil(Math.log(r)/Math.log(2))))}function Eg(r,l,u){const d=1-r%2,f=new Float32Array(r);for(let g=0;g<r;++g){const I=2*Math.PI*g/(r+d-1);f[g]=l-u*Math.cos(I)}return Lo(f,"float32")}function TQ(r,l,u,d,f,g="NHWC",I){let S=r;r.rank===3&&(S=oe(r,[1,r.shape[0],r.shape[1],r.shape[2]]));let x=l;x.rank===3&&(x=oe(l,[1,l.shape[0],l.shape[1],l.shape[2]])),J(S.rank===4,()=>`Error in conv2dDerFilter: input must be rank 4, but got shape ${S.shape}.`),J(x.rank===4,()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${x.shape}.`),J(u.length===4,()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${u}.`);const N=g==="NHWC"?S.shape[3]:S.shape[1],E=g==="NHWC"?x.shape[3]:x.shape[1];J(N===u[2],()=>`Error in conv2dDerFilter: depth of input ${N}) must match input depth in filter (${u[2]}.`),J(E===u[3],()=>`Error in conv2dDerFilter: depth of dy (${E}) must match output depth for filter (${u[3]}).`),I!=null&&J(nn(f),()=>`Error in conv2dDerFilter: pad must be an integer when using, dimRoundingMode ${I} but got pad ${f}.`);const _=ne=>{const Q=1,M=Zc(g),fe=wi(S.shape,u,d,Q,f,I,!1,M);return ne.conv2dDerFilter(S,x,fe)},A={x:S,dy:x},U={strides:d,pad:f,dataFormat:g,dimRoundingMode:I,filterShape:u};return H.runKernelFunc(_,A,null,gR,U)}const Dg=V({conv2DBackpropFilter_:TQ});function AQ(r,l,u,d,f,g=[1,1],I){let S=r;r.rank===3&&(S=oe(r,[1,r.shape[0],r.shape[1],r.shape[2]]));let x=l;x.rank===3&&(x=oe(l,[1,l.shape[0],l.shape[1],l.shape[2]]));const N=A=>{const U=wi(r.shape,u,d,g,f,I,!0);return A.depthwiseConv2DDerFilter(S,x,U)},E={x:S,dy:x},_={strides:d,pad:f,dimRoundingMode:I,dilations:g,filterShape:u};return H.runKernelFunc(N,E,null,IR,_)}const i1=V({depthwiseConv2dNativeBackpropFilter_:AQ});function vQ(r,l,u,d,f,g=[1,1],I){let S=l,x=!1;l.rank===3&&(x=!0,S=oe(l,[1,l.shape[0],l.shape[1],l.shape[2]]));const N=U=>{const ne=wi(r,u.shape,d,g,f,I,!0);return U.depthwiseConv2DDerInput(S,u,ne)},E={dy:S,filter:u},_={strides:d,pad:f,dimRoundingMode:I,dilations:g,inputShape:r},A=H.runKernelFunc(N,E,null,xR,_);return x?oe(A,[A.shape[1],A.shape[2],A.shape[3]]):A}const r1=V({depthwiseConv2dNativeBackpropInput_:vQ});function NQ(r){return Eg(r,.54,.46)}const o1=V({hammingWindow_:NQ});function CQ(r){return Eg(r,.5,.5)}const kg=V({hannWindow_:CQ});function RQ(r,l,u,d=!1,f=0){let g=0;const I=[];for(;g+l<=r.size;)I.push(Tt(r,g,l)),g+=u;if(d)for(;g<r.size;){const S=g+l-r.size,x=An([Tt(r,g,l-S),ex([S],f)]);I.push(x),g+=u}return I.length===0?Sa([],[0,l]):oe(An(I),[I.length,l])}const Fg=V({frame_:RQ});function OQ(r,l,u,d,f=kg){d==null&&(d=s1(l));const g=Fg(r,l,u),I=le(g,f(l)),S=[];for(let x=0;x<g.shape[0];x++)S.push(ed(Tt(I,[x,0],[1,l]),d));return An(S)}const a1=V({stft_:OQ});function EQ(r,l,u,d,f,g){const I=P(r,"image","cropAndResize"),S=P(l,"boxes","cropAndResize","float32"),x=P(u,"boxInd","cropAndResize","int32");f=f||"bilinear",g=g||0;const N=S.shape[0];J(I.rank===4,()=>`Error in cropAndResize: image must be rank 4,but got rank ${I.rank}.`),J(S.rank===2&&S.shape[1]===4,()=>`Error in cropAndResize: boxes must be have size [${N},4] but had shape ${S.shape}.`),J(x.rank===1&&x.shape[0]===N,()=>`Error in cropAndResize: boxInd must be have size [${N}] but had shape ${S.shape}.`),J(d.length===2,()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${d.length}.`),J(d[0]>=1&&d[1]>=1,()=>`cropSize must be atleast [1,1], but was ${d}`),J(f==="bilinear"||f==="nearest",()=>`method must be bilinear or nearest, but was ${f}`);const E=ne=>ne.cropAndResize(I,S,x,d,f,g),_={image:I,boxes:S,boxInd:x},A={method:f,extrapolationValue:g,cropSize:d},U=H.runKernelFunc(E,_,null,LR,A);return U}const c1=V({cropAndResize_:EQ});function DQ(r){const l=P(r,"image","flipLeftRight","float32");J(l.rank===4,()=>`Error in flipLeftRight: image must be rank 4,but got rank ${l.rank}.`);const u={image:l},d=H.runKernel(FR,u,{});return d}const l1=V({flipLeftRight_:DQ});function kQ(r,l,u=0,d=.5){const f=P(r,"image","rotateWithOffset","float32");J(f.rank===4,()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${f.rank}.`);const g={image:f},I={radians:l,fillValue:u,center:d},S=H.runKernel(xO,g,I);return S}const h1=V({rotateWithOffset_:kQ});function Xs(r,l,u,d,f,g){d==null&&(d=.5),f==null&&(f=Number.NEGATIVE_INFINITY),g==null&&(g=0);const I=r.shape[0];return u=Math.min(u,I),J(0<=d&&d<=1,()=>`iouThreshold must be in [0, 1], but was '${d}'`),J(r.rank===2,()=>`boxes must be a 2D tensor, but was of rank '${r.rank}'`),J(r.shape[1]===4,()=>`boxes must have 4 columns, but 2nd dimension was ${r.shape[1]}`),J(l.rank===1,()=>"scores must be a 1D tensor"),J(l.shape[0]===I,()=>`scores has incompatible shape with boxes. Expected ${I}, but was ${l.shape[0]}`),J(0<=g&&g<=1,()=>`softNmsSigma must be in [0, 1], but was '${g}'`),{maxOutputSize:u,iouThreshold:d,scoreThreshold:f,softNmsSigma:g}}function FQ(r,l,u,d=.5,f=Number.NEGATIVE_INFINITY){const g=P(r,"boxes","nonMaxSuppression"),I=P(l,"scores","nonMaxSuppression"),S=Xs(g,I,u,d,f);u=S.maxOutputSize,d=S.iouThreshold,f=S.scoreThreshold;const x={maxOutputSize:u,iouThreshold:d,scoreThreshold:f};return H.runKernelFunc(N=>N.nonMaxSuppression(g,I,u,d,f),{boxes:g,scores:I},null,sO,x)}const u1=V({nonMaxSuppression_:FQ});function d1(r,l,u){const d=_Q(r,l,u),f=d<0?-(d+1):d;r.splice(f,0,l)}function _Q(r,l,u){return $Q(r,l,u||WQ)}function WQ(r,l){return r>l?1:r<l?-1:0}function $Q(r,l,u){let d=0,f=r.length,g=0,I=!1;for(;d<f;){g=d+(f-d>>>1);const S=u(l,r[g]);S>0?d=g+1:(f=g,I=!S)}return I?d:-d-1}function p1(r,l,u,d,f){return Lx(r,l,u,d,f,0).selectedIndices}function m1(r,l,u,d,f,g){return Lx(r,l,u,d,f,0,!1,g,!0)}function f1(r,l,u,d,f,g){return Lx(r,l,u,d,f,g,!0)}function Lx(r,l,u,d,f,g,I=!1,S=!1,x=!1){const N=[];for(let M=0;M<l.length;M++)l[M]>f&&N.push({score:l[M],boxIndex:M,suppressBeginIndex:0});N.sort(g1);const E=g>0?-.5/g:0,_=[],A=[];for(;_.length<u&&N.length>0;){const M=N.pop(),{score:fe,boxIndex:ie,suppressBeginIndex:we}=M;if(fe<f)break;let Ae=!1;for(let Me=_.length-1;Me>=we;--Me){const et=UQ(r,ie,_[Me]);if(et>=d){Ae=!0;break}if(M.score=M.score*BQ(d,E,et),M.score<=f)break}M.suppressBeginIndex=_.length,Ae||(M.score===fe?(_.push(ie),A.push(M.score)):M.score>f&&d1(N,M,g1))}const U=_.length,ne=u-U;S&&ne>0&&(_.push(...new Array(ne).fill(0)),A.push(...new Array(ne).fill(0)));const Q={selectedIndices:Lo(_,"int32")};return I&&(Q.selectedScores=Lo(A,"float32")),x&&(Q.validOutputs=Fe(U,"int32")),Q}function UQ(r,l,u){const d=r.subarray(l*4,l*4+4),f=r.subarray(u*4,u*4+4),g=Math.min(d[0],d[2]),I=Math.min(d[1],d[3]),S=Math.max(d[0],d[2]),x=Math.max(d[1],d[3]),N=Math.min(f[0],f[2]),E=Math.min(f[1],f[3]),_=Math.max(f[0],f[2]),A=Math.max(f[1],f[3]),U=(S-g)*(x-I),ne=(_-N)*(A-E);if(U<=0||ne<=0)return 0;const Q=Math.max(g,N),M=Math.max(I,E),fe=Math.min(S,_),ie=Math.min(x,A),we=Math.max(fe-Q,0)*Math.max(ie-M,0);return we/(U+ne-we)}function BQ(r,l,u){const d=Math.exp(l*u*u);return u<=r?d:0}function g1(r,l){return r.score-l.score||r.score===l.score&&l.boxIndex-r.boxIndex}async function MQ(r,l,u,d=.5,f=Number.NEGATIVE_INFINITY){const g=P(r,"boxes","nonMaxSuppressionAsync"),I=P(l,"scores","nonMaxSuppressionAsync"),S=Xs(g,I,u,d,f);u=S.maxOutputSize,d=S.iouThreshold,f=S.scoreThreshold;const x=await Promise.all([g.data(),I.data()]),N=x[0],E=x[1],_=p1(N,E,u,d,f);return g!==r&&g.dispose(),I!==l&&I.dispose(),_}const y1=MQ;function PQ(r,l,u,d=.5,f=Number.NEGATIVE_INFINITY,g=0){const I=P(r,"boxes","nonMaxSuppression"),S=P(l,"scores","nonMaxSuppression"),x=Xs(I,S,u,d,f,g);u=x.maxOutputSize,d=x.iouThreshold,f=x.scoreThreshold,g=x.softNmsSigma;const N={boxes:I,scores:S},E={maxOutputSize:u,iouThreshold:d,scoreThreshold:f,softNmsSigma:g},_=H.runKernel(rO,N,E);return{selectedIndices:_[0],selectedScores:_[1]}}const b1=V({nonMaxSuppressionWithScore_:PQ});async function zQ(r,l,u,d=.5,f=Number.NEGATIVE_INFINITY,g=0){const I=P(r,"boxes","nonMaxSuppressionAsync"),S=P(l,"scores","nonMaxSuppressionAsync"),x=Xs(I,S,u,d,f,g);u=x.maxOutputSize,d=x.iouThreshold,f=x.scoreThreshold,g=x.softNmsSigma;const N=await Promise.all([I.data(),S.data()]),E=N[0],_=N[1],A=f1(E,_,u,d,f,g);return I!==r&&I.dispose(),S!==l&&S.dispose(),A}const w1=zQ;function VQ(r,l,u,d=.5,f=Number.NEGATIVE_INFINITY,g=!1){const I=P(r,"boxes","nonMaxSuppression"),S=P(l,"scores","nonMaxSuppression"),x=Xs(I,S,u,d,f,null),N=x.maxOutputSize,E=x.iouThreshold,_=x.scoreThreshold,A={boxes:I,scores:S},U={maxOutputSize:N,iouThreshold:E,scoreThreshold:_,padToMaxOutputSize:g},ne=H.runKernel(iO,A,U);return{selectedIndices:ne[0],validOutputs:ne[1]}}const L1=V({nonMaxSuppressionPadded_:VQ});async function GQ(r,l,u,d=.5,f=Number.NEGATIVE_INFINITY,g=!1){const I=P(r,"boxes","nonMaxSuppressionAsync"),S=P(l,"scores","nonMaxSuppressionAsync"),x=Xs(I,S,u,d,f,null),N=x.maxOutputSize,E=x.iouThreshold,_=x.scoreThreshold,[A,U]=await Promise.all([I.data(),S.data()]),ne=m1(A,U,N,E,_,g);return I!==r&&I.dispose(),S!==l&&S.dispose(),ne}const S1=GQ;function YQ(r,l,u=!1){const d=P(r,"images","resizeBilinear");J(d.rank===3||d.rank===4,()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${d.rank}.`),J(l.length===2,()=>`Error in resizeBilinear: new shape must 2D, but got shape ${l}.`);let f=d,g=!1;d.rank===3&&(g=!0,f=oe(d,[1,d.shape[0],d.shape[1],d.shape[2]]));const[I,S]=l,x=(A,U)=>(U([f]),A.resizeBilinear(f,I,S,u)),N={images:f},E={alignCorners:u,size:l},_=H.runKernelFunc(x,N,null,Xf,E);return g?oe(_,[_.shape[1],_.shape[2],_.shape[3]]):_}const I1=V({resizeBilinear_:YQ});function HQ(r,l,u=!1){const d=P(r,"images","resizeNearestNeighbor");J(d.rank===3||d.rank===4,()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${d.rank}.`),J(l.length===2,()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${l}.`),J(d.dtype==="float32"||d.dtype==="int32",()=>"`images` must have `int32` or `float32` as dtype");let f=d,g=!1;d.rank===3&&(g=!0,f=oe(d,[1,d.shape[0],d.shape[1],d.shape[2]]));const[I,S]=l,x={images:f},N={alignCorners:u,size:l},E=(A,U)=>(U([f]),A.resizeNearestNeighbor(f,I,S,u)),_=H.runKernelFunc(E,x,null,Kf,N);return g?oe(_,[_.shape[1],_.shape[2],_.shape[3]]):_}const x1=V({resizeNearestNeighbor_:HQ});function qQ(r,l,u){J(l%1===0,()=>`bandPart(): numLower must be an integer, got ${l}.`),J(u%1===0,()=>`bandPart(): numUpper must be an integer, got ${u}.`);const d=P(r,"a","bandPart");J(d.rank>=2,()=>`bandPart(): Rank must be at least 2, got ${d.rank}.`);const f=d.shape,[g,I]=d.shape.slice(-2);if(!(l<=g))throw new Error(`bandPart(): numLower (${l}) must not be greater than the number of rows (${g}).`);if(!(u<=I))throw new Error(`bandPart(): numUpper (${u}) must not be greater than the number of columns (${I}).`);l<0&&(l=g),u<0&&(u=I);const S=oe(Rg(0,g,1,"int32"),[-1,1]),x=Rg(0,I,1,"int32"),N=Be(S,x),E=ba(Cr(N,Fe(+l,"int32")),Nr(N,Fe(-u,"int32"))),_=Ws([g,I],d.dtype);return oe(Ks(td(oe(d,[-1,g,I])).map(A=>Hn(E,A,_))),f)}const T1=V({bandPart_:qQ});function jQ(r){let l;if(Array.isArray(r)){l=!1,J(r!=null&&r.length>0,()=>"Gram-Schmidt process: input must not be null, undefined, or empty");const f=r[0].shape[0];for(let g=1;g<r.length;++g)J(r[g].shape[0]===f,()=>`Gram-Schmidt: Non-unique lengths found in the input vectors: (${r[g].shape[0]} vs. ${f})`)}else l=!0,r=So(r,r.shape[0],0).map(f=>bx(f,[0]));J(r.length<=r[0].shape[0],()=>`Gram-Schmidt: Number of vectors (${r.length}) exceeds number of dimensions (${r[0].shape[0]}).`);const u=[],d=r;for(let f=0;f<r.length;++f)u.push(H.tidy(()=>{let g=d[f];if(f>0)for(let I=0;I<f;++I){const S=le(_e(le(u[I],g)),u[I]);g=Be(g,S)}return Pe(g,Og(g,"euclidean"))}));return l?Ks(u,0):u}const A1=V({gramSchmidt_:jQ});function KQ(r,l=!1){if(J(r.rank>=2,()=>`qr() requires input tensor to have a rank >= 2, but got rank ${r.rank}`),r.rank===2)return v1(r,l);{const u=r.shape.slice(0,r.shape.length-2).reduce((x,N)=>x*N),d=td(oe(r,[u,r.shape[r.shape.length-2],r.shape[r.shape.length-1]]),0),f=[],g=[];d.forEach(x=>{const[N,E]=v1(x,l);f.push(N),g.push(E)});const I=oe(Ks(f,0),r.shape),S=oe(Ks(g,0),r.shape);return[I,S]}}function v1(r,l=!1){return H.tidy(()=>{J(r.shape.length===2,()=>`qr2d() requires a 2D Tensor, but got a ${r.shape.length}D Tensor.`);const u=r.shape[0],d=r.shape[1];let f=QI(u),g=bi(r);const I=Sa([[1]],[1,1]);let S=bi(I);const x=u>=d?d:u;for(let N=0;N<x;++N){const E=g,_=S,A=f;[S,g,f]=H.tidy(()=>{const U=Tt(g,[N,N],[u-N,1]),ne=Og(U),Q=Tt(g,[N,N],[1,1]),M=Hn(Li(Q,0),Sa([[-1]]),Sa([[1]])),fe=Be(Q,le(M,ne)),ie=Pe(U,fe);ie.shape[0]===1?S=bi(I):S=An([I,Tt(ie,[1,0],[ie.shape[0]-1,ie.shape[1]])],0);const we=It(Pe(bn(M,fe),ne)),Ae=Tt(g,[N,0],[u-N,d]),Me=le(we,S),et=Tn(S);if(N===0)g=Be(Ae,bn(Me,bn(et,Ae)));else{const Vt=Be(Ae,bn(Me,bn(et,Ae)));g=An([Tt(g,[0,0],[N,d]),Vt],0)}const ct=Tn(Me),$t=Tt(f,[0,N],[u,f.shape[1]-N]);if(N===0)f=Be($t,bn(bn($t,S),ct));else{const Vt=Be($t,bn(bn($t,S),ct));f=An([Tt(f,[0,0],[u,N]),Vt],1)}return[S,g,f]}),qO([E,_,A])}return!l&&u>d&&(f=Tt(f,[0,0],[u,d]),g=Tt(g,[0,0],[d,d])),[f,g]})}const N1=V({qr_:KQ});var Qt;(function(r){r[r.NONE=0]="NONE",r[r.MEAN=1]="MEAN",r[r.SUM=2]="SUM",r[r.SUM_BY_NONZERO_WEIGHTS=3]="SUM_BY_NONZERO_WEIGHTS"})(Qt||(Qt={}));function XQ(r,l,u=Qt.SUM_BY_NONZERO_WEIGHTS){const d=P(r,"losses","computeWeightedLoss");let f=null;l!=null&&(f=P(l,"weights","computeWeightedLoss"));const g=f==null?d:le(d,f);if(u===Qt.NONE)return g;if(u===Qt.SUM)return _e(g);if(u===Qt.MEAN){if(f==null)return cx(g);{const I=d.size/f.size,S=Pe(_e(g),_e(f));return I>1?Pe(S,Fe(I)):S}}if(u===Qt.SUM_BY_NONZERO_WEIGHTS){if(f==null)return Pe(_e(g),Fe(d.size));{const I=le(f,Ki(d.shape)),S=Ie(_e(hx(I,Fe(0))),"float32");return Pe(_e(g),S)}}throw Error(`Unknown reduction: ${u}`)}const Fn=V({computeWeightedLoss_:XQ});function JQ(r,l,u,d=Qt.SUM_BY_NONZERO_WEIGHTS){const f=P(r,"labels","absoluteDifference"),g=P(l,"predictions","absoluteDifference");let I=null;u!=null&&(I=P(u,"weights","absoluteDifference")),tn(f.shape,g.shape,"Error in absoluteDifference: ");const S=Yn(Be(f,g));return Fn(S,I,d)}const C1=V({absoluteDifference_:JQ});function ZQ(r,l,u,d,f=Qt.SUM_BY_NONZERO_WEIGHTS){const g=P(r,"labels","cosineDistance"),I=P(l,"predictions","cosineDistance");let S=null;d!=null&&(S=P(d,"weights","cosineDistance")),tn(g.shape,I.shape,"Error in cosineDistance: ");const x=Fe(1),N=Be(x,_e(le(g,I),u,!0));return Fn(N,S,f)}const R1=V({cosineDistance_:ZQ});function QQ(r,l,u,d=Qt.SUM_BY_NONZERO_WEIGHTS){let f=P(r,"labels","hingeLoss");const g=P(l,"predictions","hingeLoss");let I=null;u!=null&&(I=P(u,"weights","hingeLoss")),tn(f.shape,g.shape,"Error in hingeLoss: ");const S=Fe(1);f=Be(le(Fe(2),f),S);const x=Zu(Be(S,le(f,g)));return Fn(x,I,d)}const O1=V({hingeLoss_:QQ});function eee(r,l,u,d=1,f=Qt.SUM_BY_NONZERO_WEIGHTS){const g=P(r,"labels","huberLoss"),I=P(l,"predictions","huberLoss");let S=null;u!=null&&(S=P(u,"weights","huberLoss")),tn(g.shape,I.shape,"Error in huberLoss: ");const x=Fe(d),N=Yn(Be(I,g)),E=lx(N,x),_=Be(N,E),A=vt(le(Fe(.5),gt(E)),le(x,_));return Fn(A,S,f)}const E1=V({huberLoss_:eee});function tee(r,l,u,d=1e-7,f=Qt.SUM_BY_NONZERO_WEIGHTS){const g=P(r,"labels","logLoss"),I=P(l,"predictions","logLoss");let S=null;u!=null&&(S=P(u,"weights","logLoss")),tn(g.shape,I.shape,"Error in logLoss: ");const x=Fe(1),N=Fe(d),E=It(le(g,wo(vt(I,N)))),_=le(Be(x,g),wo(vt(Be(x,I),N))),A=Be(E,_);return Fn(A,S,f)}const D1=V({logLoss_:tee});function nee(r,l,u,d=Qt.SUM_BY_NONZERO_WEIGHTS){const f=P(r,"labels","meanSquaredError"),g=P(l,"predictions","meanSquaredError");let I=null;u!=null&&(I=P(u,"weights","meanSquaredError")),tn(f.shape,g.shape,"Error in meanSquaredError: ");const S=yx(f,g);return Fn(S,I,d)}const k1=V({meanSquaredError_:nee});function see(r,l){const u=P(r,"labels","sigmoidCrossEntropyWithLogits"),d=P(l,"logits","sigmoidCrossEntropyWithLogits");tn(u.shape,d.shape,"Error in sigmoidCrossEntropyWithLogits: ");const f=Zu(d),g=le(d,u),I=rx(qn(It(Yn(d))));return vt(Be(f,g),I)}function iee(r,l,u,d=0,f=Qt.SUM_BY_NONZERO_WEIGHTS){let g=P(r,"multiClassLabels","sigmoidCrossEntropy");const I=P(l,"logits","sigmoidCrossEntropy");let S=null;if(u!=null&&(S=P(u,"weights","sigmoidCrossEntropy")),tn(g.shape,I.shape,"Error in sigmoidCrossEntropy: "),d>0){const N=Fe(d),E=Fe(1),_=Fe(.5);g=vt(le(g,Be(E,N)),le(_,N))}const x=see(g,I);return Fn(x,S,f)}const F1=V({sigmoidCrossEntropy_:iee});function ree(r,l,u=-1){if(u===-1&&(u=l.rank-1),u!==l.rank-1)throw Error(`Softmax cross entropy along a non-last dimension is not yet supported. Labels / logits was rank ${l.rank} and dim was ${u}`);const d=Ng((f,g,I)=>{const S=!0,x=ox(g,[u],S),N=Be(Ie(g,"float32"),x);I([f,N]);const E=It(le(N,f)),_=_e(E,[u]),A=(U,ne)=>{const[Q,M]=ne,fe=cs(U.shape,[u]);return[le(oe(U,fe),Be(Ie(Q,"float32"),qn(M))),le(oe(U,fe),Be(qn(M),Ie(Q,"float32")))]};return{value:_,gradFunc:A}});return d(r,l)}function oee(r,l,u,d=0,f=Qt.SUM_BY_NONZERO_WEIGHTS){let g=P(r,"onehotLabels","softmaxCrossEntropy");const I=P(l,"logits","softmaxCrossEntropy");let S=null;if(u!=null&&(S=P(u,"weights","softmaxCrossEntropy")),tn(g.shape,I.shape,"Error in softmaxCrossEntropy: "),d>0){const N=Fe(d),E=Fe(1),_=Fe(g.shape[1]);g=vt(le(g,Be(E,N)),Pe(N,_))}const x=ree(g,I);return Fn(x,S,f)}const _1=V({softmaxCrossEntropy_:oee});const bNe={fft:Qu,ifft:tl,rfft:ed,irfft:gx},xNe={hammingWindow:o1,hannWindow:kg,frame:Fg,stft:a1},W1={flipLeftRight:l1,resizeNearestNeighbor:x1,resizeBilinear:I1,rotateWithOffset:h1,cropAndResize:c1,nonMaxSuppression:u1,nonMaxSuppressionAsync:y1,nonMaxSuppressionWithScore:b1,nonMaxSuppressionWithScoreAsync:w1,nonMaxSuppressionPadded:L1,nonMaxSuppressionPaddedAsync:S1},UNe={bandPart:T1,gramSchmidt:A1,qr:N1},jNe={absoluteDifference:C1,computeWeightedLoss:Fn,cosineDistance:R1,hingeLoss:O1,huberLoss:E1,logLoss:D1,meanSquaredError:k1,sigmoidCrossEntropy:F1,softmaxCrossEntropy:_1};const $1=1.7580993408473768,U1=1.0507009873554805;const B1={kernelName:Lf,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>le(r,La(Ie(u,"float32"),-1))}}};const M1={kernelName:Q2,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>{const d=gt(Ie(u,"float32")),f=bs(Be(Fe(1),d));return It(Pe(r,f))}}}};const P1={kernelName:eR,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>{const d=bs(Be(gt(Ie(u,"float32")),1));return Pe(r,d)}}}};const z1={kernelName:Hc,inputsToSave:["a","b"],gradFunc:(r,l)=>{const[u,d]=l,f=at(u.shape,d.shape),g=()=>{let S=r;const x=Ot(u.shape,f);return x.length>0&&(S=_e(S,x)),oe(S,u.shape)},I=()=>{let S=r;const x=Ot(d.shape,f);return x.length>0&&(S=_e(S,x)),oe(S,d.shape)};return{a:g,b:I}}};const V1={kernelName:tR,saveAllInputs:!0,gradFunc:(r,l)=>{const u={};return l.forEach((d,f)=>{u[f]=()=>r.clone()}),u}};const G1={kernelName:nR,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>Xe(u)}}};const Y1={kernelName:sR,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>Xe(u)}}};const H1={kernelName:iR,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>Pe(r,bs(Be(Fe(1),gt(Ie(u,"float32")))))}}};const q1={kernelName:rR,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>{const d=bs(vt(Fe(1),gt(Ie(u,"float32"))));return Pe(r,d)}}}};const j1={kernelName:cR,inputsToSave:["a","b"],gradFunc:(r,l)=>{const[u,d]=l,f=at(u.shape,d.shape),g=()=>{const S=vt(gt(u),gt(d));let x=le(r,Pe(d,S));const N=Ot(u.shape,f);return N.length>0&&(x=_e(x,N)),oe(x,u.shape)},I=()=>{const S=vt(gt(u),gt(d));let x=It(le(r,Pe(u,S)));const N=Ot(d.shape,f);return N.length>0&&(x=_e(x,N)),oe(x,d.shape)};return{a:g,b:I}}};const K1={kernelName:oR,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>Pe(r,vt(gt(Ie(u,"float32")),1))}}};const X1={kernelName:aR,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>Pe(r,Be(Fe(1),gt(Ie(u,"float32"))))}}};function aee(r,l,u,d,f=[1,1,1],g,I){const S=P(r,"dy","avgPool3dBackprop"),x=P(l,"input","avgPool3dBackprop");let N=S,E=x,_=!1;x.rank===4&&(_=!0,N=oe(S,[1,S.shape[0],S.shape[1],S.shape[2],S.shape[3]]),E=oe(x,[1,x.shape[0],x.shape[1],x.shape[2],x.shape[3]])),J(N.rank===5,()=>`Error in avgPool3dBackprop: dy must be rank 5 but got rank ${N.rank}.`),J(E.rank===5,()=>`Error in avgPool3dBackprop: input must be rank 5 but got rank ${E.rank}.`),J(bo(d,f),()=>`Error in avgPool3dBackprop: Either strides or dilations must be 1. Got strides ${d} and dilations '${f}'`),I!=null&&J(nn(g),()=>`Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode ${I} but got pad ${g}.`);const A=M=>{const fe=Ag(E.shape,u,d,f,g,I);return M.avgPool3dBackprop(N,E,fe)},U={dy:N,input:E},ne={filterSize:u,strides:d,dilations:f,pad:g,dimRoundingMode:I},Q=H.runKernelFunc(A,U,null,dR,ne);return _?oe(Q,[Q.shape[1],Q.shape[2],Q.shape[3],Q.shape[4]]):Q}const J1=V({avgPool3dBackprop_:aee});const Z1={kernelName:uR,inputsToSave:["x"],gradFunc:(r,l,u)=>{const[d]=l,{filterSize:f,strides:g,dilations:I,pad:S,dimRoundingMode:x}=u,N=I==null?[1,1,1]:I;return{x:()=>J1(r,d,f,g,N,S,x)}}};function cee(r,l,u,d,f){const g=P(r,"dy","avgPoolBackprop"),I=P(l,"input","avgPoolBackprop");J(I.rank===g.rank,()=>`Rank of input (${I.rank}) does not match rank of dy (${g.rank})`);let S=I,x=g,N=!1;I.rank===3&&(N=!0,S=oe(I,[1,I.shape[0],I.shape[1],I.shape[2]]),x=oe(g,[1,g.shape[0],g.shape[1],g.shape[2]])),J(x.rank===4,()=>`Error in avgPoolBackprop: dy must be rank 4 but got rank ${x.rank}.`),J(S.rank===4,()=>`Error in avgPoolBackprop: input must be rank 4 but got rank ${S.rank}.`);const E=ne=>{const Q=Tg(S.shape,u,d,1,f);return ne.avgPoolBackprop(x,S,Q)},_={dy:x,input:S},A={filterSize:u,strides:d,pad:f},U=H.runKernelFunc(E,_,null,hR,A);return N?oe(U,[U.shape[1],U.shape[2],U.shape[3]]):U}const Q1=V({avgPoolBackprop_:cee});const eE={kernelName:lR,inputsToSave:["x"],gradFunc:(r,l,u)=>{const[d]=l,{filterSize:f,strides:g,pad:I}=u;return{x:()=>Q1(r,d,f,g,I)}}};const tE={kernelName:Sf,inputsToSave:["a","b"],gradFunc:(r,l,u)=>{const[d,f]=l,{transposeA:g,transposeB:I}=u;return!g&&!I?{a:()=>bn(r,f,!1,!0),b:()=>bn(d,r,!0,!1)}:!g&&I?{a:()=>bn(r,f,!1,!1),b:()=>bn(r,d,!0,!1)}:g&&!I?{a:()=>bn(f,r,!1,!0),b:()=>bn(d,r,!1,!1)}:{a:()=>bn(f,r,!0,!0),b:()=>bn(r,d,!0,!0)}}};const nE={kernelName:If,gradFunc:(r,l,u)=>{const{blockShape:d,crops:f}=u;return{x:()=>dx(r,d,f)}}};const sE={kernelName:xf,gradFunc:(r,l,u)=>{const d=u,f=d.inputShape,g=d.shape,I=Array.from(g);for(let x=f.length-1;x>=0;x--)if(f[x]===g[x])I[x]=1;else if(f[x]!==1)throw new Error(`broadcastTo(): [${f}] cannot be broadcast to [${g}].`);const S=[];for(let x=0;x<I.length;x++)I[x]>1&&S.push(x);return{x:()=>_e(r,S,!0)}}};const iE={kernelName:qc,gradFunc:r=>({x:()=>r.clone()})};const rE={kernelName:pR,gradFunc:r=>({x:()=>Xe(r)})};const oE={kernelName:mR,inputsToSave:["x"],gradFunc:(r,l,u)=>{const[d]=l,{clipValueMin:f,clipValueMax:g}=u;return{x:()=>Hn(ba(Nr(d,f),Cr(d,g)),r,Xe(r))}}};const aE={kernelName:Tf,saveAllInputs:!0,gradFunc:(r,l,u)=>{const d=l.map(x=>x.shape),{axis:f}=u,g=ft(f,l[0].shape)[0],I=d.map(x=>x[g]),S=So(r,I,g);return S.map(x=>()=>x)}};const cE={kernelName:Af,inputsToSave:["x","filter"],gradFunc:(r,l,u)=>{const[d,f]=l,{dilations:g,strides:I,pad:S,dataFormat:x}=u;return J(yo(g),()=>`Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${g}'`),{x:()=>ZO(d.shape,r,f,I,S,x),filter:()=>Dg(d,r,f.shape,I,S,x)}}};const lE={kernelName:vf,inputsToSave:["dy","filter"],gradFunc:(r,l,u)=>{const[d,f]=l,{strides:g,pad:I,dataFormat:S,dimRoundingMode:x}=u;return{dy:()=>KI(r,f,g,I,S,1,x),filter:()=>Dg(r,d,f.shape,g,I,S,x)}}};function lee(r,l,u,d,f){let g=r;r.rank===4&&(g=oe(r,[1,r.shape[0],r.shape[1],r.shape[2],r.shape[3]]));let I=l;I.rank===4&&(I=oe(l,[1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]])),J(g.rank===5,()=>`Error in conv3dDerFilter: input must be rank 5, but got shape ${g.shape}.`),J(I.rank===5,()=>`Error in conv3dDerFilter: dy must be rank 5, but got shape ${I.shape}.`),J(u.length===5,()=>`Error in conv3dDerFilter: filterShape must be length 5, but got ${u}.`),J(g.shape[4]===u[3],()=>`Error in conv3dDerFilter: depth of input ${g.shape[4]}) must match input depth in filter (${u[3]}.`),J(I.shape[4]===u[4],()=>`Error in conv3dDerFilter: depth of dy (${I.shape[4]}) must match output depth for filter (${u[4]}).`);const S=E=>{const _=1,A=Ku(g.shape,u,d,_,f);return E.conv3dDerFilter(g,I,A)},x={x:g,dy:I},N={strides:d,pad:f,filterShape:u};return H.runKernelFunc(S,x,null,bR,N)}const hE=V({conv3DBackpropFilter_:lee});const uE={kernelName:yR,inputsToSave:["x","filter"],gradFunc:(r,l,u)=>{const{dilations:d,strides:f,pad:g}=u;J(yo(d),()=>`Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${d}'`);const[I,S]=l;return{x:()=>QO(I.shape,r,S,f,g),filter:()=>hE(I,r,S.shape,f,g)}}};const dE={kernelName:Nf,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>le(It(mx(Ie(u,"float32"))),r)}}};const pE={kernelName:Cf,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>le(fx(Ie(u,"float32")),r)}}};const mE={kernelName:Rf,inputsToSave:["x"],gradFunc:(r,l,u)=>{const[d]=l,{axis:f,exclusive:g,reverse:I}=u;return{x:()=>{const S=ji([f],d.rank);let x=JI(r,f,g,!I);return S!=null&&(x=Tn(x,S)),x}}}};const fE={kernelName:SR,inputsToSave:["x","filter"],gradFunc:(r,l,u)=>{const{dilations:d,strides:f,pad:g,dimRoundingMode:I}=u,S=d==null?[1,1]:d;J(yo(S),()=>`Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations '${S}'`);const[x,N]=l;return J(x.rank===4,()=>`Error in gradient of depthwiseConv2dNative: input must be rank 4, but got rank ${x.rank}.`),J(N.rank===4,()=>`Error in gradient of depthwiseConv2dNative: filter must be rank 4, but got rank ${N.rank}.`),J(x.shape[3]===N.shape[2],()=>`Error in gradient of depthwiseConv2d: number of input channels (${x.shape[3]}) must match the inChannels dimension in filter ${N.shape[2]}.`),J(bo(f,S),()=>`Error in gradient of depthwiseConv2d: Either strides or dilations must be 1. Got strides ${f} and dilations '${S}'.`),I!=null&&J(nn(g),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${I} but got pad ${g}.`),{x:()=>r1(x.shape,r,N,f,g,d,I),filter:()=>i1(x,r,N.shape,f,g,d,I)}}};const gE={kernelName:TR,inputsToSave:["x","filter"],gradFunc:(r,l,u)=>{const[d,f]=l,g={x:d,filter:f,dy:r},I={x:d,filter:f,dy:r};return{x:()=>H.runKernel(AR,g,u),filter:()=>H.runKernel(vR,I,u)}}};const yE={kernelName:Of,inputsToSave:["a","b"],gradFunc:(r,l)=>{const[u,d]=l,f=at(u.shape,d.shape),g=()=>{const S=Pe(r,Ie(d,"float32")),x=Ot(u.shape,f);return x.length>0?oe(_e(S,x),u.shape):S},I=()=>{let S=le(r,Ie(u,"float32"));const x=Ot(d.shape,f);x.length>0&&(S=oe(_e(S,x),d.shape));const N=gt(d);return It(Pe(S,Ie(N,"float32")))};return{a:g,b:I}}};const bE={kernelName:NR,outputsToSave:[!0],gradFunc:(r,l)=>{const[u]=l,d=g=>g.eluDer(r,u),f={dy:r,y:u};return{x:()=>H.runKernelFunc(d,f,null,CR)}}};const wE={kernelName:RR,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l,d=le(qn(It(gt(u))),2/Math.sqrt(Math.PI));return{x:()=>le(r,d)}}};const LE={kernelName:Ef,outputsToSave:[!0],gradFunc:(r,l)=>{const[u]=l;return{x:()=>le(r,u)}}};const SE={kernelName:ER,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>le(r,qn(u))}}};const IE={kernelName:Df,gradFunc:r=>({x:()=>Xe(r)})};const xE={kernelName:kf,inputsToSave:["a","b"],gradFunc:(r,l)=>{const[u,d]=l,f=at(u.shape,d.shape),g=()=>{const S=Pe(r,Ie(d,"float32")),x=Ot(u.shape,f);return x.length>0?oe(_e(S,x),u.shape):S},I=()=>{let S=le(r,Ie(u,"float32"));const x=Ot(d.shape,f);x.length>0&&(S=oe(_e(S,x),d.shape));const N=gt(d);return It(Pe(S,Ie(N,"float32")))};return{a:g,b:I}}};const TE={kernelName:_R,inputsToSave:["x","mean","variance","scale"],gradFunc:(r,l,u)=>{const{varianceEpsilon:d}=u,[f,g,I,S]=l,x=S==null?Fe(1):S,N=Ot(g.shape,f.shape),E=[];if(g.rank===1){for(let Ae=0;Ae<f.shape.length-1;++Ae)E.push(f.shape[Ae]);E.push(1)}const _=Be(f,g),A=le(r,x),U=px(vt(I,Fe(d))),ne=le(le(le(U,U),U),Fe(-.5)),Q=()=>g.rank===1?oe(le(le(r,ga(oe(U,[1,1,1,g.shape[0]]),E)),x),f.shape):oe(le(le(r,U),x),f.shape),M=()=>{let Ae=le(le(U,Fe(-1)),A);return g.rank===1&&(Ae=_e(Ae,N)),oe(Ae,g.shape)},fe=()=>{let Ae=le(le(ne,_),A);return g.rank===1&&(Ae=_e(Ae,N)),oe(Ae,g.shape)},ie=()=>{const Ae=le(_,U);let Me=le(r,Ae);return g.rank===1&&(Me=_e(Me,N)),oe(Me,g.shape)},we=()=>{let Ae=r;return g.rank===1&&(Ae=_e(Ae,N)),oe(Ae,g.shape)};return{x:Q,mean:M,variance:fe,scale:ie,offset:we}}};const NE={kernelName:Ff,inputsToSave:["x","indices"],gradFunc:(r,l,u)=>{const[d,f]=l,{axis:g}=u,I=ft(g,d.shape)[0],S=()=>{const x=d.shape,N=f.size,E=x.slice(0,I),_=E.length,A=x.slice(g,x.length).slice(1),U=A.length,ne=AE(0,_),Q=AE(_+1,_+1+U),M=vE([E,[N],A]),fe=oe(r,M),ie=oe(f,[N]),we=vE([[_],ne,Q]),Ae=Tn(fe,we);let Me=wx(Ae,ie,d.shape[I]);const et=Xc(we);return Me=Tn(Me,et),Me};return{x:S,indices:()=>f}}};function AE(r,l){const u=[];for(let d=r;d<l;++d)u.push(d);return u}function vE(r){const l=[];for(let u=0;u<r.length;++u)for(let d=0;d<r[u].length;++d)l.push(r[u][d]);return l}const CE={kernelName:_f,inputsToSave:["a","b"],gradFunc:(r,l)=>{const[u,d]=l;return{a:()=>Xe(u),b:()=>Xe(d)}}};const RE={kernelName:Wf,gradFunc:r=>({x:()=>Ie(r,"float32")})};const OE={kernelName:BR,gradFunc:r=>({x:()=>Xe(r)})};const EE={kernelName:MR,gradFunc:r=>({x:()=>Xe(r)})};const DE={kernelName:PR,gradFunc:r=>({x:()=>Xe(r)})};const kE={kernelName:Uf,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>Pe(r,vt(u,1))}}};const FE={kernelName:$f,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>Pe(r,Ie(u,"float32"))}}};const _E={kernelName:HR,inputsToSave:[],outputsToSave:[!0],gradFunc:(r,l,u)=>{const[d]=l,{axis:f}=u;return{logits:()=>{const g=!0,I=qn(d);return Be(r,le(_e(r,f,g),I))}}}};function hee(r,l,u,d=5,f=1,g=1,I=.5){const S=E=>E.LRNGrad(u,r,l,d,f,g,I),x={x:r,y:l,dy:u},N={depthRadius:d,bias:f,alpha:g,beta:I};return H.runKernelFunc(S,x,null,jR,N)}const WE=V({localResponseNormalizationBackprop_:hee});const $E={kernelName:qR,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(r,l,u)=>{const[d,f]=l,{depthRadius:g,bias:I,alpha:S,beta:x}=u;return{x:()=>WE(d,f,r,g,I,S,x)}}};function _g(r,l,u,d){return l.rank<u.rank&&(l=oe(l,cs(l.shape,d))),r.rank<u.rank&&(r=oe(r,cs(r.shape,d))),{x:()=>{const f=le(r,Ie(ZI(u,l),r.dtype));return f}}}const Sx={kernelName:Bf,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(r,l,u)=>{const d=u,{reductionIndices:f}=d,g=l[0],I=l[1],S=ft(f,g.shape),x=_g(r,I,g,S);return{x:()=>x.x()}}};const UE={kernelName:Mf,inputsToSave:["a","b"],gradFunc:(r,l)=>{const[u,d]=l,f=()=>le(r,Ie(Nr(u,d),"float32")),g=()=>le(r,Ie(ix(u,d),"float32"));return{a:f,b:g}}};function uee(r,l,u,d,f,g=[1,1,1],I,S){const x=P(r,"dy","maxPool3dBackprop"),N=P(l,"input","maxPool3dBackprop"),E=P(u,"output","maxPool3dBackprop");let _=x,A=N,U=E,ne=!1;N.rank===4&&(ne=!0,_=oe(x,[1,x.shape[0],x.shape[1],x.shape[2],x.shape[3]]),A=oe(N,[1,N.shape[0],N.shape[1],N.shape[2],N.shape[3]]),U=oe(E,[1,E.shape[0],E.shape[1],E.shape[2],E.shape[3]])),J(_.rank===5,()=>`Error in maxPool3dBackprop: dy must be rank 5 but got rank ${_.rank}.`),J(A.rank===5,()=>`Error in maxPool3dBackprop: input must be rank 5 but got rank ${A.rank}.`),J(U.rank===5,()=>`Error in maxPool3dBackprop: output must be rank 5 but got rank ${U.rank}.`),J(bo(f,g),()=>`Error in maxPool3dBackprop: Either strides or dilations must be 1. Got strides ${f} and dilations '${g}'`),S!=null&&J(nn(I),()=>`Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode ${S} but got pad ${I}.`);const Q=we=>{const Ae=Ag(A.shape,d,f,g,I,S);return we.maxPool3dBackprop(_,A,U,Ae)},M={dy:_,input:A,output:U},fe={filterSize:d,strides:f,dilations:g,pad:I,dimRoundingMode:S},ie=H.runKernelFunc(Q,M,null,ZR,fe);return ne?oe(ie,[ie.shape[1],ie.shape[2],ie.shape[3],ie.shape[4]]):ie}const BE=V({maxPool3dBackprop_:uee});const ME={kernelName:JR,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(r,l,u)=>{const[d,f]=l,{filterSize:g,strides:I,dilations:S,pad:x,dimRoundingMode:N}=u,E=S==null?[1,1,1]:S;return{x:()=>BE(r,d,f,g,I,E,x,N)}}};function dee(r,l,u,d,f,g,I){const S=P(r,"dy","maxPoolBackprop"),x=P(l,"input","maxPoolBackprop"),N=P(u,"output","maxPoolBackprop");J(x.rank===S.rank,()=>`Rank of input (${x.rank}) does not match rank of dy (${S.rank})`),J(S.rank===4,()=>`Error in maxPoolBackprop: dy must be rank 4 but got rank ${S.rank}.`),J(x.rank===4,()=>`Error in maxPoolBackprop: input must be rank 4 but got rank ${x.rank}.`),I!=null&&J(nn(g),()=>`Error in maxPoolBackprop: pad must be an integer when using, dimRoundingMode ${I} but got pad ${g}.`);const E=U=>{const ne=Tg(x.shape,d,f,1,g,I);return U.maxPoolBackprop(S,x,N,ne)},_={dy:S,input:x,output:N},A={filterSize:d,strides:f,pad:g,dimRoundingMode:I};return H.runKernelFunc(E,_,null,XR,A)}const PE=V({maxPoolBackprop_:dee});const zE={kernelName:KR,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(r,l,u)=>{const[d,f]=l,{filterSize:g,strides:I,pad:S}=u;return{x:()=>PE(r,d,f,g,I,S)}}};const VE={kernelName:Pf,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(r,l,u)=>{const d=u,{axis:f}=d,[g,I]=l,S=ft(f,g.shape),x=_g(r,I,g,S);return{x:()=>x.x()}}};const GE={kernelName:zf,inputsToSave:["a","b"],gradFunc:(r,l)=>{const[u,d]=l,f=()=>le(r,Ie(Cr(u,d),"float32")),g=()=>le(r,Ie(Li(u,d),"float32"));return{a:f,b:g}}};const YE={kernelName:eO,inputsToSave:["x"],gradFunc:(r,l,u)=>{const d=l[0],{paddings:f}=u,g=f.map(I=>I[0]);return{x:()=>Tt(r,g,d.shape)}}};const HE={kernelName:tO,inputsToSave:["a","b"],gradFunc:(r,l)=>{const[u,d]=l,f=at(u.shape,d.shape),g=()=>{const S=Ot(u.shape,f);return S.length>0?oe(_e(r,S),u.shape):r},I=()=>{const S=le(r,It(tx(Pe(u,d)))),x=Ot(d.shape,f);return x.length>0?oe(_e(S,x),d.shape):S};return{a:g,b:I}}};const qE={kernelName:Vf,inputsToSave:["a","b"],gradFunc:(r,l)=>{const[u,d]=l,f=at(u.shape,d.shape),g=()=>{const S=le(r,Ie(d,"float32")),x=Ot(u.shape,f);return x.length>0?oe(_e(S,x),u.shape):S},I=()=>{const S=le(r,Ie(u,"float32")),x=Ot(d.shape,f);return x.length>0?oe(_e(S,x),d.shape):S};return{a:g,b:I}}};const jE={kernelName:Gf,gradFunc:r=>({x:()=>It(r)})};const KE={kernelName:aO,inputsToSave:["indices"],gradFunc:(r,l)=>{const u=l[0];return{indices:()=>Ws(u.shape,"float32")}}};const XE={kernelName:oO,gradFunc:r=>({x:()=>Xe(r)})};const Ix={kernelName:Yf,inputsToSave:["x"],gradFunc:(r,l,u)=>{const d=l[0],{paddings:f}=u,g=f.map(I=>I[0]);return{x:()=>Tt(r,g,d.shape)}}};const JE={kernelName:Hf,inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:(r,l)=>{const[u,d,f]=l,g=u,I=d,S=at(g.shape,I.shape),x=()=>{const E=Ie(I,"float32");let _=le(r,le(E,wa(g,Be(E,Fe(1)))));const A=Ot(g.shape,S);return A.length>0&&(_=_e(_,A)),oe(_,g.shape)},N=()=>{const E=Li(g,0),_=Hn(E,wo(g),Xe(g));let A=le(r,le(f,_));const U=Ot(I.shape,S);return U.length>0&&(A=_e(A,U)),oe(A,I.shape)};return{a:x,b:N}}};const ZE={kernelName:cO,inputsToSave:["x","alpha"],gradFunc:(r,l)=>{const[u,d]=l,f=Li(u,0);return{x:()=>Hn(f,r,le(r,d)),alpha:()=>{let g=Hn(f,Xe(r),le(r,u));const I=Ot(d.shape,r.shape);return I.length>0&&(g=_e(g,I)),oe(g,d.shape)}}}};const QE={kernelName:uO,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>Pe(r,It(gt(u)))}}};const eD={kernelName:mO,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l,d=le(Cr(u,6),La(u));return{x:()=>le(r,Ie(d,"float32"))}}};const tD={kernelName:qf,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>le(r,Ie(La(u),"float32"))}}};const nD={kernelName:jf,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>oe(r,u.shape)}}};const sD={kernelName:Xf,inputsToSave:["images"],gradFunc:(r,l,u)=>{const[d]=l,f=S=>{const{alignCorners:x}=u;return S.resizeBilinearBackprop(r,d,x)},g={images:d},I=()=>H.runKernelFunc(f,g,null,pO,u);return{images:I}}};const iD={kernelName:Kf,inputsToSave:["images"],gradFunc:(r,l,u)=>{const[d]=l,f=S=>{const{alignCorners:x}=u;return S.resizeNearestNeighborBackprop(r,d,x)},g={images:d},I=()=>H.runKernelFunc(f,g,null,dO,u);return{images:I}}};const rD={kernelName:Jf,gradFunc:(r,l,u)=>{const{dims:d}=u,f=ft(d,r.shape);return{x:()=>el(r,f)}}};const oD={kernelName:fO,gradFunc:r=>({x:()=>Xe(r)})};const aD={kernelName:Zf,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>It(Pe(r,le(wa(u,1.5),2)))}}};const cD={kernelName:Qf,inputsToSave:["condition"],gradFunc:(r,l)=>{const[u]=l;return{condition:()=>Ie(Xe(u),"float32"),t:()=>le(r,Ie(u,r.dtype)),e:()=>le(r,Ie(ax(u),r.dtype))}}};const lD={kernelName:gO,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>{const d=Li(u,Fe(0)),f=Fe($1),g=Fe(U1),I=le(r,g),S=le(le(r,f),qn(Ie(u,"float32")));return Hn(d,I,S)}}}};const hD={kernelName:sg,outputsToSave:[!0],gradFunc:(r,l)=>{const[u]=l;return{x:()=>le(r,le(u,Be(Fe(1),u)))}}};const uD={kernelName:yO,gradFunc:r=>({x:()=>Xe(r)})};const dD={kernelName:tg,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>le(Xu(Ie(u,"float32")),r)}}};const pD={kernelName:ng,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>le(XI(Ie(u,"float32")),r)}}};const mD={kernelName:eg,inputsToSave:["x"],gradFunc:(r,l,u)=>{const[d]=l,{begin:f,size:g}=u,I=d.shape,[S,x]=Ig(d,f,g),N=[];for(let E=0;E<r.rank;E++)N.push([S[E],I[E]-S[E]-x[E]]);return{x:()=>ux(r,N)}}};const fD={kernelName:wO,outputsToSave:[!0],gradFunc:(r,l,u)=>{const[d]=l,{dim:f}=u,g=!0,I=le(r,d);return{logits:()=>Be(I,le(_e(I,[f],g),d))}}};const gD={kernelName:bO,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>le(r,qI(u))}}};const xx={kernelName:og,gradFunc:(r,l,u)=>{const{blockShape:d,paddings:f}=u;return{x:()=>jI(r,d,f)}}};const Tx={kernelName:ag,gradFunc:(r,l,u)=>{const{axis:d}=u;return{x:()=>An(r,d)}}};const yD={kernelName:ig,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>Pe(r,le(bs(Ie(u,"float32")),2))}}};const bD={kernelName:LO,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>le(r,le(Ie(u,"float32"),2))}}};const wD={kernelName:cg,inputsToSave:["a","b"],gradFunc:(r,l)=>{const[u,d]=l,f=Fe(2),g=()=>le(r,le(f,Be(u,d))),I=()=>le(r,le(f,Be(d,u)));return{a:g,b:I}}};const LD={kernelName:fg,gradFunc:r=>({x:()=>Xe(r)})};const SD={kernelName:lg,inputsToSave:["a","b"],gradFunc:(r,l)=>{const[u,d]=l,f=at(u.shape,d.shape),g=()=>{let S=r;const x=Ot(u.shape,f);return x.length>0&&(S=_e(S,x)),oe(S,u.shape)},I=()=>{let S=r;const x=Ot(d.shape,f);return x.length>0&&(S=_e(S,x)),oe(It(S),d.shape)};return{a:g,b:I}}};const ID={kernelName:rg,inputsToSave:["x"],gradFunc:(r,l,u)=>{const[d]=l,f=d.shape.slice(),{axis:g}=u,I=ft(g,d.shape);I.forEach(N=>{f[N]=1});const S=oe(r,f),x=le(S,Ki(d.shape,"float32"));return{x:()=>x}}};const xD={kernelName:SO,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>Pe(r,gt(Xu(u)))}}};const TD={kernelName:IO,outputsToSave:[!0],gradFunc:(r,l)=>{const[u]=l;return{x:()=>le(Be(Fe(1),gt(u)),r)}}};const AD={kernelName:hg,inputsToSave:["x"],gradFunc:(r,l,u)=>{const[d]=l,{reps:f}=u,g=()=>{let I=Xe(d);if(d.rank===1)for(let S=0;S<f[0];++S)I=vt(I,Tt(r,[S*d.shape[0]],[d.shape[0]]));else if(d.rank===2)for(let S=0;S<f[0];++S)for(let x=0;x<f[1];++x)I=vt(I,Tt(r,[S*d.shape[0],x*d.shape[1]],[d.shape[0],d.shape[1]]));else if(d.rank===3)for(let S=0;S<f[0];++S)for(let x=0;x<f[1];++x)for(let N=0;N<f[2];++N)I=vt(I,Tt(r,[S*d.shape[0],x*d.shape[1],N*d.shape[2]],[d.shape[0],d.shape[1],d.shape[2]]));else if(d.rank===4)for(let S=0;S<f[0];++S)for(let x=0;x<f[1];++x)for(let N=0;N<f[2];++N)for(let E=0;E<f[3];++E)I=vt(I,Tt(r,[S*d.shape[0],x*d.shape[1],N*d.shape[2],E*d.shape[3]],[d.shape[0],d.shape[1],d.shape[2],d.shape[3]]));else throw new Error(`Gradient for tile operation is not implemented for rank-${d.rank} tensors yet.`);return I};return{x:g}}};const vD={kernelName:ug,gradFunc:(r,l,u)=>{const d=u,{perm:f}=d,g=Xc(f);return{x:()=>Tn(r,g)}}};const ND={kernelName:dg,gradFunc:(r,l,u)=>{const d=u,{axis:f}=d;return{value:()=>Ks(r,f)}}};const CD={kernelName:pg,inputsToSave:["segmentIds"],gradFunc:(r,l)=>{const[u]=l,d=()=>pee(r,u);return{x:d}}};function pee(r,l){const u=sx(l,Xe(l)),d=nx(r,u);let f=Nr(l,Fe(0,"int32"));const g=d.rank-f.rank;for(let S=0;S<g;++S)f=_s(f,S+1);f=ba(f,Ki(d.shape,"bool"));const I=Xe(d);return Hn(f,d,I)}const RD={kernelName:mg,gradFunc:r=>({x:()=>Xe(r)})};const mee=[B1,M1,P1,z1,V1,G1,Y1,H1,q1,j1,K1,X1,Z1,eE,tE,nE,sE,iE,rE,oE,aE,lE,cE,uE,dE,pE,mE,fE,gE,yE,bE,wE,LE,SE,xE,IE,TE,NE,CE,RE,OE,EE,DE,kE,FE,_E,$E,Sx,Sx,UE,ME,zE,VE,GE,YE,HE,qE,jE,KE,XE,Ix,Ix,JE,ZE,QE,eD,tD,nD,sD,iD,rD,oD,aD,cD,lD,hD,uD,dD,pD,mD,fD,gD,xx,xx,Tx,Tx,yD,wD,bD,LD,SD,ID,xD,TD,AD,vD,ND,CD,RD];for(const r of mee)AO(r);function Ax(r,l,u=!1){const{Image:d,Canvas:f}=St.getEnv();if(!(r instanceof d||r instanceof f))throw new Error("imageToSquare - expected arg0 to be HTMLImageElement | HTMLCanvasElement");const g=da(r),I=l/Math.max(g.height,g.width),S=I*g.width,x=I*g.height,N=Vc({width:l,height:l}),E=r instanceof f?r:Bu(r),_=Math.abs(S-x)/2,A=u&&S<x?_:0,U=u&&x<S?_:0;return as(N).drawImage(E,A,U,S,x),N}class Io{constructor(r,l=!1){this._imageTensors=[];this._canvases=[];this._treatAsBatchInput=!1;this._inputDimensions=[];if(!Array.isArray(r))throw new Error(`NetInput.constructor - expected inputs to be an Array of TResolvedNetInput or to be instanceof tf.Tensor4D, instead have ${r}`);this._treatAsBatchInput=l,this._batchSize=r.length,r.forEach((u,d)=>{if(Tr(u)){this._imageTensors[d]=u,this._inputDimensions[d]=u.shape;return}if(Ds(u)){const g=u.shape[0];if(g!==1)throw new Error(`NetInput - tf.Tensor4D with batchSize ${g} passed, but not supported in input array`);this._imageTensors[d]=u,this._inputDimensions[d]=u.shape.slice(1);return}const f=u instanceof St.getEnv().Canvas?u:Bu(u);this._canvases[d]=f,this._inputDimensions[d]=[f.height,f.width,3]})}get imageTensors(){return this._imageTensors}get canvases(){return this._canvases}get isBatchInput(){return this.batchSize>1||this._treatAsBatchInput}get batchSize(){return this._batchSize}get inputDimensions(){return this._inputDimensions}get inputSize(){return this._inputSize}get reshapedInputDimensions(){return Pi(this.batchSize,0,1).map((r,l)=>this.getReshapedInputDimensions(l))}getInput(r){return this.canvases[r]||this.imageTensors[r]}getInputDimensions(r){return this._inputDimensions[r]}getInputHeight(r){return this._inputDimensions[r][0]}getInputWidth(r){return this._inputDimensions[r][1]}getReshapedInputDimensions(r){if(typeof this.inputSize!="number")throw new Error("getReshapedInputDimensions - inputSize not set, toBatchTensor has not been called yet");const l=this.getInputWidth(r),u=this.getInputHeight(r);return lI({width:l,height:u},this.inputSize)}toBatchTensor(r,l=!0){return this._inputSize=r,HO(()=>{const u=Pi(this.batchSize,0,1).map(f=>{const g=this.getInput(f);if(g instanceof kn){let I=Ds(g)?g:g.expandDims();return I=pI(I,l),(I.shape[1]!==r||I.shape[2]!==r)&&(I=W1.resizeBilinear(I,[r,r])),I.as3D(r,r,3)}if(g instanceof St.getEnv().Canvas)return GI.fromPixels(Ax(g,r,l));throw new Error(`toBatchTensor - at batchIdx ${f}, expected input to be instanceof tf.Tensor or instanceof HTMLCanvasElement, instead have ${g}`)}),d=Ks(u.map(f=>Ie(f,"float32"))).as4D(this.batchSize,r,r,3);return d})}}async function Wt(r){if(r instanceof Io)return r;let l=Array.isArray(r)?r:[r];if(!l.length)throw new Error("toNetInput - empty array passed as input");const u=f=>Array.isArray(r)?` at input index ${f}:`:"",d=l.map(ua);return d.forEach((f,g)=>{if(!gf(f)&&!Tr(f)&&!Ds(f))throw typeof l[g]=="string"?new Error(`toNetInput -${u(g)} string passed, but could not resolve HTMLElement for element id ${l[g]}`):new Error(`toNetInput -${u(g)} expected media to be of type HTMLImageElement | HTMLVideoElement | HTMLCanvasElement | tf.Tensor3D, or to be an element id`);if(Ds(f)){const I=f.shape[0];if(I!==1)throw new Error(`toNetInput -${u(g)} tf.Tensor4D with batchSize ${I} passed, but not supported in input array`)}}),await Promise.all(d.map(f=>gf(f)&&SI(f))),new Io(d,Array.isArray(r))}async function nl(r,l){const{Canvas:u}=St.getEnv();let d=r;if(!(r instanceof u)){const I=await Wt(r);if(I.batchSize>1)throw new Error("extractFaces - batchSize > 1 not supported");const S=I.getInput(0);d=S instanceof u?S:await xI(S)}const f=as(d),g=l.map(I=>I instanceof Jt?I.forSize(d.width,d.height).box.floor():I).map(I=>I.clipAtImageBorders(d.width,d.height));return g.map(({x:I,y:S,width:x,height:N})=>{const E=Vc({width:x,height:N});return as(E).putImageData(f.getImageData(I,S,x,N),0,0),E})}const Wg=He(Ze());async function sl(r,l){if(!Tr(r)&&!Ds(r))throw new Error("extractFaceTensors - expected image tensor to be 3D or 4D");if(Ds(r)&&r.shape[0]>1)throw new Error("extractFaceTensors - batchSize > 1 not supported");return Wg.tidy(()=>{const[u,d,f]=r.shape.slice(Ds(r)?1:0),g=l.map(S=>S instanceof Jt?S.forSize(d,u).box:S).map(S=>S.clipAtImageBorders(d,u)),I=g.map(({x:S,y:x,width:N,height:E})=>Wg.slice3d(r.as3D(u,d,f),[x,S,0],[E,N,f]));return I})}async function Ia(r,l){const u=St.getEnv().fetch,d=await u(r,l);if(!(d.status<400))throw new Error(`failed to fetch: (${d.status}) ${d.statusText}, from url: ${d.url}`);return d}async function fee(r){const l=await Ia(r),u=await l.blob();if(!u.type.startsWith("image/"))throw new Error(`fetchImage - expected blob type to be of type image/*, instead have: ${u.type}, for url: ${l.url}`);return II(u)}async function vx(r){return(await Ia(r)).json()}async function gee(r){return new Float32Array(await(await Ia(r)).arrayBuffer())}function $g(r,l){const u=`${l}-weights_manifest.json`;if(!r)return{modelBaseUri:"",manifestUri:u};if(r==="/")return{modelBaseUri:"/",manifestUri:`/${u}`};const d=r.startsWith("http://")?"http://":r.startsWith("https://")?"https://":"";r=r.replace(d,"");const f=r.split("/").filter(S=>S),g=r.endsWith(".json")?f[f.length-1]:u;let I=d+(r.endsWith(".json")?f.slice(0,f.length-1):f).join("/");return I=r.startsWith("/")?`/${I}`:I,{modelBaseUri:I,manifestUri:I==="/"?`/${g}`:`${I}/${g}`}}const OD=He(Ze());async function Nx(r,l){const{manifestUri:u,modelBaseUri:d}=$g(r,l);let f=await vx(u);return OD.io.loadWeights(f,d)}function yee(r,l,u=!1){const{width:d,height:f}=u?da(l):l;return r.width=d,r.height=f,{width:d,height:f}}const Rr=He(Ze());class Un{constructor(r){this._name=r;this._params=void 0;this._paramMappings=[]}get params(){return this._params}get paramMappings(){return this._paramMappings}get isLoaded(){return!!this.params}getParamFromPath(r){const{obj:l,objProp:u}=this.traversePropertyPath(r);return l[u]}reassignParamFromPath(r,l){const{obj:u,objProp:d}=this.traversePropertyPath(r);u[d].dispose(),u[d]=l}getParamList(){return this._paramMappings.map(({paramPath:r})=>({path:r,tensor:this.getParamFromPath(r)}))}getTrainableParams(){return this.getParamList().filter(r=>r.tensor instanceof Rr.Variable)}getFrozenParams(){return this.getParamList().filter(r=>!(r.tensor instanceof Rr.Variable))}variable(){this.getFrozenParams().forEach(({path:r,tensor:l})=>{this.reassignParamFromPath(r,l.variable())})}freeze(){this.getTrainableParams().forEach(({path:r,tensor:l})=>{const u=Rr.tensor(l.dataSync());l.dispose(),this.reassignParamFromPath(r,u)})}dispose(r=!0){this.getParamList().forEach(l=>{if(r&&l.tensor.isDisposed)throw new Error(`param tensor has already been disposed for path ${l.path}`);l.tensor.dispose()}),this._params=void 0}serializeParams(){return new Float32Array(this.getParamList().map(({tensor:r})=>Array.from(r.dataSync())).reduce((r,l)=>r.concat(l)))}async load(r){if(r instanceof Float32Array){this.extractWeights(r);return}await this.loadFromUri(r)}async loadFromUri(r){if(r&&typeof r!="string")throw new Error(`${this._name}.loadFromUri - expected model uri`);const l=await Nx(r,this.getDefaultModelName());this.loadFromWeightMap(l)}async loadFromDisk(r){if(r&&typeof r!="string")throw new Error(`${this._name}.loadFromDisk - expected model file path`);const{readFile:l}=St.getEnv(),{manifestUri:u,modelBaseUri:d}=$g(r,this.getDefaultModelName()),f=x=>Promise.all(x.map(N=>l(N).then(E=>E.buffer))),g=Rr.io.weightsLoaderFactory(f),I=JSON.parse((await l(u)).toString()),S=await g(I,d);this.loadFromWeightMap(S)}loadFromWeightMap(r){const{paramMappings:l,params:u}=this.extractParamsFromWeigthMap(r);this._paramMappings=l,this._params=u}extractWeights(r){const{paramMappings:l,params:u}=this.extractParams(r);this._paramMappings=l,this._params=u}traversePropertyPath(r){if(!this.params)throw new Error("traversePropertyPath - model has no loaded params");const l=r.split("/").reduce((f,g)=>{if(!f.nextObj.hasOwnProperty(g))throw new Error(`traversePropertyPath - object does not have property ${g}, for path ${r}`);return{obj:f.nextObj,objProp:g,nextObj:f.nextObj[g]}},{nextObj:this.params}),{obj:u,objProp:d}=l;if(!u||!d||!(u[d]instanceof Rr.Tensor))throw new Error(`traversePropertyPath - parameter is not a tensor, for path ${r}`);return{obj:u,objProp:d}}}const il=He(Ze());function ls(r,l,u){return il.tidy(()=>{let d=il.separableConv2d(r,l.depthwise_filter,l.pointwise_filter,u,"same");return d=il.add(d,l.bias),d})}const Bt=He(Ze());function Ug(r,l,u=!1){return Bt.tidy(()=>{const d=Bt.relu(u?Bt.add(Bt.conv2d(r,l.conv0.filters,[2,2],"same"),l.conv0.bias):ls(r,l.conv0,[2,2])),f=ls(d,l.conv1,[1,1]),g=Bt.relu(Bt.add(d,f)),I=ls(g,l.conv2,[1,1]);return Bt.relu(Bt.add(d,Bt.add(f,I)))})}function nd(r,l,u=!1,d=!0){return Bt.tidy(()=>{const f=Bt.relu(u?Bt.add(Bt.conv2d(r,l.conv0.filters,d?[2,2]:[1,1],"same"),l.conv0.bias):ls(r,l.conv0,d?[2,2]:[1,1])),g=ls(f,l.conv1,[1,1]),I=Bt.relu(Bt.add(f,g)),S=ls(I,l.conv2,[1,1]),x=Bt.relu(Bt.add(f,Bt.add(g,S))),N=ls(x,l.conv3,[1,1]);return Bt.relu(Bt.add(f,Bt.add(g,Bt.add(S,N))))})}const xo=He(Ze());function xa(r,l,u="same",d=!1){return xo.tidy(()=>{const f=xo.add(xo.conv2d(r,l.filters,[1,1],u),l.bias);return d?xo.relu(f):f})}function jn(r,l){Object.keys(r).forEach(u=>{l.some(d=>d.originalPath===u)||r[u].dispose()})}const Bg=He(Ze());function rl(r,l){return function(u,d,f,g){const I=Bg.tensor4d(r(u*d*f*f),[f,f,u,d]),S=Bg.tensor1d(r(d));return l.push({paramPath:`${g}/filters`},{paramPath:`${g}/bias`}),{filters:I,bias:S}}}const Mg=He(Ze());function Pg(r,l){return function(u,d,f){const g=Mg.tensor2d(r(u*d),[u,d]),I=Mg.tensor1d(r(d));return l.push({paramPath:`${f}/weights`},{paramPath:`${f}/bias`}),{weights:g,bias:I}}}class Cx{constructor(r,l,u){this.depthwise_filter=r;this.pointwise_filter=l;this.bias=u}}const sd=He(Ze());function ol(r,l){return function(u,d,f){const g=sd.tensor4d(r(3*3*u),[3,3,u,1]),I=sd.tensor4d(r(u*d),[1,1,u,d]),S=sd.tensor1d(r(d));return l.push({paramPath:`${f}/depthwise_filter`},{paramPath:`${f}/pointwise_filter`},{paramPath:`${f}/bias`}),new Cx(g,I,S)}}function al(r){return function(l){const u=r(`${l}/depthwise_filter`,4),d=r(`${l}/pointwise_filter`,4),f=r(`${l}/bias`,1);return new Cx(u,d,f)}}function ws(r,l){return function(u,d,f){const g=r[u];if(!oa(g,d))throw new Error(`expected weightMap[${u}] to be a Tensor${d}D, instead have ${g}`);return l.push({originalPath:u,paramPath:f||u}),g}}function Kn(r){let l=r;function u(f){const g=l.slice(0,f);return l=l.slice(f),g}function d(){return l}return{extractWeights:u,getRemainingWeights:d}}function zg(r,l){const u=rl(r,l),d=ol(r,l);function f(I,S,x,N=!1){const E=N?u(I,S,3,`${x}/conv0`):d(I,S,`${x}/conv0`),_=d(S,S,`${x}/conv1`),A=d(S,S,`${x}/conv2`);return{conv0:E,conv1:_,conv2:A}}function g(I,S,x,N=!1){const{conv0:E,conv1:_,conv2:A}=f(I,S,x,N),U=d(S,S,`${x}/conv3`);return{conv0:E,conv1:_,conv2:A,conv3:U}}return{extractDenseBlock3Params:f,extractDenseBlock4Params:g}}function ED(r){const l=[],{extractWeights:u,getRemainingWeights:d}=Kn(r),{extractDenseBlock4Params:f}=zg(u,l),g=f(3,32,"dense0",!0),I=f(32,64,"dense1"),S=f(64,128,"dense2"),x=f(128,256,"dense3");if(d().length!==0)throw new Error(`weights remaing after extract: ${d().length}`);return{paramMappings:l,params:{dense0:g,dense1:I,dense2:S,dense3:x}}}function Vg(r){return function(l){const u=r(`${l}/filters`,4),d=r(`${l}/bias`,1);return{filters:u,bias:d}}}function Gg(r,l){const u=ws(r,l),d=Vg(u),f=al(u);function g(S,x=!1){const N=x?d(`${S}/conv0`):f(`${S}/conv0`),E=f(`${S}/conv1`),_=f(`${S}/conv2`);return{conv0:N,conv1:E,conv2:_}}function I(S,x=!1){const N=x?d(`${S}/conv0`):f(`${S}/conv0`),E=f(`${S}/conv1`),_=f(`${S}/conv2`),A=f(`${S}/conv3`);return{conv0:N,conv1:E,conv2:_,conv3:A}}return{extractDenseBlock3Params:g,extractDenseBlock4Params:I}}function DD(r){const l=[],{extractDenseBlock4Params:u}=Gg(r,l),d={dense0:u("dense0",!0),dense1:u("dense1"),dense2:u("dense2"),dense3:u("dense3")};return jn(r,l),{params:d,paramMappings:l}}const To=He(Ze());class Yg extends Un{constructor(){super("FaceFeatureExtractor")}forwardInput(r){const{params:l}=this;if(!l)throw new Error("FaceFeatureExtractor - load model before inference");return To.tidy(()=>{const u=To.cast(r.toBatchTensor(112,!0),"float32"),d=[122.782,117.001,104.298],f=yi(u,d).div(To.scalar(255));let g=nd(f,l.dense0,!0);return g=nd(g,l.dense1),g=nd(g,l.dense2),g=nd(g,l.dense3),g=To.avgPool(g,[7,7],[2,2],"valid"),g})}async forward(r){return this.forwardInput(await Wt(r))}getDefaultModelName(){return"face_feature_extractor_model"}extractParamsFromWeigthMap(r){return DD(r)}extractParams(r){return ED(r)}}const cl=He(Ze());function id(r,l){return cl.tidy(()=>cl.add(cl.matMul(r,l.weights),l.bias))}function kD(r,l,u){const d=[],{extractWeights:f,getRemainingWeights:g}=Kn(r),I=Pg(f,d),S=I(l,u,"fc");if(g().length!==0)throw new Error(`weights remaing after extract: ${g().length}`);return{paramMappings:d,params:{fc:S}}}function FD(r){const l=[],u=ws(r,l);function d(g){const I=u(`${g}/weights`,2),S=u(`${g}/bias`,1);return{weights:I,bias:S}}const f={fc:d("fc")};return jn(r,l),{params:f,paramMappings:l}}function Hg(r){const l={},u={};return Object.keys(r).forEach(d=>{const f=d.startsWith("fc")?u:l;f[d]=r[d]}),{featureExtractorMap:l,classifierMap:u}}const _D=He(Ze());class qg extends Un{constructor(r,l){super(r);this._faceFeatureExtractor=l}get faceFeatureExtractor(){return this._faceFeatureExtractor}runNet(r){const{params:l}=this;if(!l)throw new Error(`${this._name} - load model before inference`);return _D.tidy(()=>{const u=r instanceof Io?this.faceFeatureExtractor.forwardInput(r):r;return id(u.as2D(u.shape[0],-1),l.fc)})}dispose(r=!0){this.faceFeatureExtractor.dispose(r),super.dispose(r)}loadClassifierParams(r){const{params:l,paramMappings:u}=this.extractClassifierParams(r);this._params=l,this._paramMappings=u}extractClassifierParams(r){return kD(r,this.getClassifierChannelsIn(),this.getClassifierChannelsOut())}extractParamsFromWeigthMap(r){const{featureExtractorMap:l,classifierMap:u}=Hg(r);return this.faceFeatureExtractor.loadFromWeightMap(l),FD(u)}extractParams(r){const l=this.getClassifierChannelsIn(),u=this.getClassifierChannelsOut(),d=u*l+u,f=r.slice(0,r.length-d),g=r.slice(r.length-d);return this.faceFeatureExtractor.extractWeights(f),this.extractClassifierParams(g)}}const Rx=["neutral","happy","sad","angry","fearful","disgusted","surprised"];class Ta{constructor(r){if(r.length!==7)throw new Error(`FaceExpressions.constructor - expected probabilities.length to be 7, have: ${r.length}`);Rx.forEach((l,u)=>{this[l]=r[u]})}asSortedArray(){return Rx.map(r=>({expression:r,probability:this[r]})).sort((r,l)=>l.probability-r.probability)}}const ll=He(Ze());class Ox extends qg{constructor(r=new Yg){super("FaceExpressionNet",r)}forwardInput(r){return ll.tidy(()=>ll.softmax(this.runNet(r)))}async forward(r){return this.forwardInput(await Wt(r))}async predictExpressions(r){const l=await Wt(r),u=await this.forwardInput(l),d=await Promise.all(ll.unstack(u).map(async g=>{const I=await g.data();return g.dispose(),I}));u.dispose();const f=d.map(g=>new Ta(g));return l.isBatchInput?f:f[0]}getDefaultModelName(){return"face_expression_model"}getClassifierChannelsIn(){return 256}getClassifierChannelsOut(){return 7}}function Ex(r){return r.expressions instanceof Ta}function jg(r,l){const u={expressions:l};return Object.assign({},r,u)}function bee(r,l,u=.1,d){const f=Array.isArray(l)?l:[l];f.forEach(g=>{const I=g instanceof Ta?g:Ex(g)?g.expressions:void 0;if(!I)throw new Error("drawFaceExpressions - expected faceExpressions to be FaceExpressions | WithFaceExpressions<{}> or array thereof");const S=I.asSortedArray(),x=S.filter(_=>_.probability>u),N=Vi(g)?g.detection.box.bottomLeft:d||new Qe(0,0),E=new zc(x.map(_=>`${_.expression} (${aa(_.probability)})`),N);E.draw(r)})}function Aa(r){return Vi(r)&&r.landmarks instanceof js&&r.unshiftedLandmarks instanceof js&&r.alignedRect instanceof Jt}function hl(r,l){const{box:u}=r.detection,d=l.shiftBy(u.x,u.y),f=d.align(),{imageDims:g}=r.detection,I=new Jt(r.detection.score,f.rescale(g.reverse()),g),S={landmarks:d,unshiftedLandmarks:l,alignedRect:I};return Object.assign({},r,S)}class WD{constructor(r={}){const{drawLines:l=!0,drawPoints:u=!0,lineWidth:d,lineColor:f,pointSize:g,pointColor:I}=r;this.drawLines=l,this.drawPoints=u,this.lineWidth=d||1,this.pointSize=g||2,this.lineColor=f||"rgba(0, 255, 255, 1)",this.pointColor=I||"rgba(255, 0, 255, 1)"}}class $D{constructor(r,l={}){this.faceLandmarks=r,this.options=new WD(l)}draw(r){const l=as(r),{drawLines:u,drawPoints:d,lineWidth:f,lineColor:g,pointSize:I,pointColor:S}=this.options;if(u&&this.faceLandmarks instanceof $u&&(l.strokeStyle=g,l.lineWidth=f,xr(l,this.faceLandmarks.getJawOutline()),xr(l,this.faceLandmarks.getLeftEyeBrow()),xr(l,this.faceLandmarks.getRightEyeBrow()),xr(l,this.faceLandmarks.getNose()),xr(l,this.faceLandmarks.getLeftEye(),!0),xr(l,this.faceLandmarks.getRightEye(),!0),xr(l,this.faceLandmarks.getMouth(),!0)),d){l.strokeStyle=S,l.fillStyle=S;const x=N=>{l.beginPath(),l.arc(N.x,N.y,I,0,2*Math.PI),l.fill()};this.faceLandmarks.positions.forEach(x)}}}function wee(r,l){const u=Array.isArray(l)?l:[l];u.forEach(d=>{const f=d instanceof js?d:Aa(d)?d.landmarks:void 0;if(!f)throw new Error("drawFaceLandmarks - expected faceExpressions to be FaceLandmarks | WithFaceLandmarks<WithFaceDetection<{}>> or array thereof");new $D(f).draw(r)})}const Dx={};$c(Dx,{AnchorPosition:()=>Gi,DrawBox:()=>LI,DrawBoxOptions:()=>B2,DrawFaceLandmarks:()=>$D,DrawFaceLandmarksOptions:()=>WD,DrawTextField:()=>zc,DrawTextFieldOptions:()=>mf,drawContour:()=>xr,drawDetections:()=>R9,drawFaceExpressions:()=>bee,drawFaceLandmarks:()=>wee});function Lee(r,l){const u=rl(r,l),d=ol(r,l);function f(I,S,x){const N=d(I,S,`${x}/separable_conv0`),E=d(S,S,`${x}/separable_conv1`),_=u(I,S,1,`${x}/expansion_conv`);return{separable_conv0:N,separable_conv1:E,expansion_conv:_}}function g(I,S){const x=d(I,I,`${S}/separable_conv0`),N=d(I,I,`${S}/separable_conv1`),E=d(I,I,`${S}/separable_conv2`);return{separable_conv0:x,separable_conv1:N,separable_conv2:E}}return{extractConvParams:u,extractSeparableConvParams:d,extractReductionBlockParams:f,extractMainBlockParams:g}}function UD(r,l){const u=[],{extractWeights:d,getRemainingWeights:f}=Kn(r),{extractConvParams:g,extractSeparableConvParams:I,extractReductionBlockParams:S,extractMainBlockParams:x}=Lee(d,u),N=g(3,32,3,"entry_flow/conv_in"),E=S(32,64,"entry_flow/reduction_block_0"),_=S(64,128,"entry_flow/reduction_block_1"),A={conv_in:N,reduction_block_0:E,reduction_block_1:_},U={};Pi(l,0,1).forEach(fe=>{U[`main_block_${fe}`]=x(128,`middle_flow/main_block_${fe}`)});const ne=S(128,256,"exit_flow/reduction_block"),Q=I(256,512,"exit_flow/separable_conv"),M={reduction_block:ne,separable_conv:Q};if(f().length!==0)throw new Error(`weights remaing after extract: ${f().length}`);return{paramMappings:u,params:{entry_flow:A,middle_flow:U,exit_flow:M}}}function See(r,l){const u=ws(r,l),d=Vg(u),f=al(u);function g(S){const x=f(`${S}/separable_conv0`),N=f(`${S}/separable_conv1`),E=d(`${S}/expansion_conv`);return{separable_conv0:x,separable_conv1:N,expansion_conv:E}}function I(S){const x=f(`${S}/separable_conv0`),N=f(`${S}/separable_conv1`),E=f(`${S}/separable_conv2`);return{separable_conv0:x,separable_conv1:N,separable_conv2:E}}return{extractConvParams:d,extractSeparableConvParams:f,extractReductionBlockParams:g,extractMainBlockParams:I}}function BD(r,l){const u=[],{extractConvParams:d,extractSeparableConvParams:f,extractReductionBlockParams:g,extractMainBlockParams:I}=See(r,u),S=d("entry_flow/conv_in"),x=g("entry_flow/reduction_block_0"),N=g("entry_flow/reduction_block_1"),E={conv_in:S,reduction_block_0:x,reduction_block_1:N},_={};Pi(l,0,1).forEach(Q=>{_[`main_block_${Q}`]=I(`middle_flow/main_block_${Q}`)});const A=g("exit_flow/reduction_block"),U=f("exit_flow/separable_conv"),ne={reduction_block:A,separable_conv:U};return jn(r,u),{params:{entry_flow:E,middle_flow:_,exit_flow:ne},paramMappings:u}}const on=He(Ze());function MD(r,l,u){return on.add(on.conv2d(r,l.filters,u,"same"),l.bias)}function kx(r,l,u=!0){let d=u?on.relu(r):r;return d=ls(d,l.separable_conv0,[1,1]),d=ls(on.relu(d),l.separable_conv1,[1,1]),d=on.maxPool(d,[3,3],[2,2],"same"),d=on.add(d,MD(r,l.expansion_conv,[2,2])),d}function Iee(r,l){let u=ls(on.relu(r),l.separable_conv0,[1,1]);return u=ls(on.relu(u),l.separable_conv1,[1,1]),u=ls(on.relu(u),l.separable_conv2,[1,1]),u=on.add(u,r),u}class PD extends Un{constructor(r){super("TinyXception");this._numMainBlocks=r}forwardInput(r){const{params:l}=this;if(!l)throw new Error("TinyXception - load model before inference");return on.tidy(()=>{const u=on.cast(r.toBatchTensor(112,!0),"float32"),d=[122.782,117.001,104.298],f=yi(u,d).div(on.scalar(256));let g=on.relu(MD(f,l.entry_flow.conv_in,[2,2]));return g=kx(g,l.entry_flow.reduction_block_0,!1),g=kx(g,l.entry_flow.reduction_block_1),Pi(this._numMainBlocks,0,1).forEach(I=>{g=Iee(g,l.middle_flow[`main_block_${I}`])}),g=kx(g,l.exit_flow.reduction_block),g=on.relu(ls(g,l.exit_flow.separable_conv,[1,1])),g})}async forward(r){return this.forwardInput(await Wt(r))}getDefaultModelName(){return"tiny_xception_model"}extractParamsFromWeigthMap(r){return BD(r,this._numMainBlocks)}extractParams(r){return UD(r,this._numMainBlocks)}}function zD(r){const l=[],{extractWeights:u,getRemainingWeights:d}=Kn(r),f=Pg(u,l),g=f(512,1,"fc/age"),I=f(512,2,"fc/gender");if(d().length!==0)throw new Error(`weights remaing after extract: ${d().length}`);return{paramMappings:l,params:{fc:{age:g,gender:I}}}}function VD(r){const l=[],u=ws(r,l);function d(g){const I=u(`${g}/weights`,2),S=u(`${g}/bias`,1);return{weights:I,bias:S}}const f={fc:{age:d("fc/age"),gender:d("fc/gender")}};return jn(r,l),{params:f,paramMappings:l}}var Or;(function(r){r.FEMALE="female",r.MALE="male"})(Or||(Or={}));const Xi=He(Ze());class Fx extends Un{constructor(r=new PD(2)){super("AgeGenderNet");this._faceFeatureExtractor=r}get faceFeatureExtractor(){return this._faceFeatureExtractor}runNet(r){const{params:l}=this;if(!l)throw new Error(`${this._name} - load model before inference`);return Xi.tidy(()=>{const u=r instanceof Io?this.faceFeatureExtractor.forwardInput(r):r,d=Xi.avgPool(u,[7,7],[2,2],"valid").as2D(u.shape[0],-1),f=id(d,l.fc.age).as1D(),g=id(d,l.fc.gender);return{age:f,gender:g}})}forwardInput(r){return Xi.tidy(()=>{const{age:l,gender:u}=this.runNet(r);return{age:l,gender:Xi.softmax(u)}})}async forward(r){return this.forwardInput(await Wt(r))}async predictAgeAndGender(r){const l=await Wt(r),u=await this.forwardInput(l),d=Xi.unstack(u.age),f=Xi.unstack(u.gender),g=d.map((S,x)=>({ageTensor:S,genderTensor:f[x]})),I=await Promise.all(g.map(async({ageTensor:S,genderTensor:x})=>{const N=(await S.data())[0],E=(await x.data())[0],_=E>.5,A=_?Or.MALE:Or.FEMALE,U=_?E:1-E;return S.dispose(),x.dispose(),{age:N,gender:A,genderProbability:U}}));return u.age.dispose(),u.gender.dispose(),l.isBatchInput?I:I[0]}getDefaultModelName(){return"age_gender_model"}dispose(r=!0){this.faceFeatureExtractor.dispose(r),super.dispose(r)}loadClassifierParams(r){const{params:l,paramMappings:u}=this.extractClassifierParams(r);this._params=l,this._paramMappings=u}extractClassifierParams(r){return zD(r)}extractParamsFromWeigthMap(r){const{featureExtractorMap:l,classifierMap:u}=Hg(r);return this.faceFeatureExtractor.loadFromWeightMap(l),VD(u)}extractParams(r){const l=512*1+1+(512*2+2),u=r.slice(0,r.length-l),d=r.slice(r.length-l);return this.faceFeatureExtractor.extractWeights(u),this.extractClassifierParams(d)}}const Ls=He(Ze());class Kg extends qg{postProcess(r,l,u){const d=u.map(({width:g,height:I})=>{const S=l/Math.max(I,g);return{width:g*S,height:I*S}}),f=d.length;return Ls.tidy(()=>{const g=(E,_)=>Ls.stack([Ls.fill([68],E,"float32"),Ls.fill([68],_,"float32")],1).as2D(1,136).as1D(),I=(E,_)=>{const{width:A,height:U}=d[E];return _(A,U)?Math.abs(A-U)/2:0},S=E=>I(E,(_,A)=>_<A),x=E=>I(E,(_,A)=>A<_),N=r.mul(Ls.fill([f,136],l,"float32")).sub(Ls.stack(Array.from(Array(f),(E,_)=>g(S(_),x(_))))).div(Ls.stack(Array.from(Array(f),(E,_)=>g(d[_].width,d[_].height))));return N})}forwardInput(r){return Ls.tidy(()=>{const l=this.runNet(r);return this.postProcess(l,r.inputSize,r.inputDimensions.map(([u,d])=>({height:u,width:d})))})}async forward(r){return this.forwardInput(await Wt(r))}async detectLandmarks(r){const l=await Wt(r),u=Ls.tidy(()=>Ls.unstack(this.forwardInput(l))),d=await Promise.all(u.map(async(f,g)=>{const I=Array.from(await f.data()),S=I.filter((N,E)=>lf(E)),x=I.filter((N,E)=>!lf(E));return new $u(Array(68).fill(0).map((N,E)=>new Qe(S[E],x[E])),{height:l.getInputHeight(g),width:l.getInputWidth(g)})}));return u.forEach(f=>f.dispose()),l.isBatchInput?d:d[0]}getClassifierChannelsOut(){return 136}}class rd extends Kg{constructor(r=new Yg){super("FaceLandmark68Net",r)}getDefaultModelName(){return"face_landmark_68_model"}getClassifierChannelsIn(){return 256}}function GD(r){const l=[],{extractDenseBlock3Params:u}=Gg(r,l),d={dense0:u("dense0",!0),dense1:u("dense1"),dense2:u("dense2")};return jn(r,l),{params:d,paramMappings:l}}function YD(r){const l=[],{extractWeights:u,getRemainingWeights:d}=Kn(r),{extractDenseBlock3Params:f}=zg(u,l),g=f(3,32,"dense0",!0),I=f(32,64,"dense1"),S=f(64,128,"dense2");if(d().length!==0)throw new Error(`weights remaing after extract: ${d().length}`);return{paramMappings:l,params:{dense0:g,dense1:I,dense2:S}}}const Ao=He(Ze());class HD extends Un{constructor(){super("TinyFaceFeatureExtractor")}forwardInput(r){const{params:l}=this;if(!l)throw new Error("TinyFaceFeatureExtractor - load model before inference");return Ao.tidy(()=>{const u=Ao.cast(r.toBatchTensor(112,!0),"float32"),d=[122.782,117.001,104.298],f=yi(u,d).div(Ao.scalar(255));let g=Ug(f,l.dense0,!0);return g=Ug(g,l.dense1),g=Ug(g,l.dense2),g=Ao.avgPool(g,[14,14],[2,2],"valid"),g})}async forward(r){return this.forwardInput(await Wt(r))}getDefaultModelName(){return"face_feature_extractor_tiny_model"}extractParamsFromWeigthMap(r){return GD(r)}extractParams(r){return YD(r)}}class _x extends Kg{constructor(r=new HD){super("FaceLandmark68TinyNet",r)}getDefaultModelName(){return"face_landmark_68_tiny_model"}getClassifierChannelsIn(){return 128}}class xee extends rd{}const Xg=He(Ze());function qD(r,l){return Xg.add(Xg.mul(r,l.weights),l.biases)}const ul=He(Ze());function Wx(r,l,u,d,f="same"){const{filters:g,bias:I}=l.conv;let S=ul.conv2d(r,g,u,f);return S=ul.add(S,I),S=qD(S,l.scale),d?ul.relu(S):S}function jD(r,l){return Wx(r,l,[1,1],!0)}function $x(r,l){return Wx(r,l,[1,1],!1)}function Jg(r,l){return Wx(r,l,[2,2],!0,"valid")}const Ss=He(Ze());function Tee(r,l){function u(S,x,N){const E=r(S),_=E.length/(x*N*N);if(cI(_))throw new Error(`depth has to be an integer: ${_}, weights.length: ${E.length}, numFilters: ${x}, filterSize: ${N}`);return Ss.tidy(()=>Ss.transpose(Ss.tensor4d(E,[x,_,N,N]),[2,3,1,0]))}function d(S,x,N,E){const _=u(S,x,N),A=Ss.tensor1d(r(x));return l.push({paramPath:`${E}/filters`},{paramPath:`${E}/bias`}),{filters:_,bias:A}}function f(S,x){const N=Ss.tensor1d(r(S)),E=Ss.tensor1d(r(S));return l.push({paramPath:`${x}/weights`},{paramPath:`${x}/biases`}),{weights:N,biases:E}}function g(S,x,N,E){const _=d(S,x,N,`${E}/conv`),A=f(x,`${E}/scale`);return{conv:_,scale:A}}function I(S,x,N,E,_=!1){const A=g((_?.5:1)*S,x,N,`${E}/conv1`),U=g(S,x,N,`${E}/conv2`);return{conv1:A,conv2:U}}return{extractConvLayerParams:g,extractResidualLayerParams:I}}function KD(r){const{extractWeights:l,getRemainingWeights:u}=Kn(r),d=[],{extractConvLayerParams:f,extractResidualLayerParams:g}=Tee(l,d),I=f(4704,32,7,"conv32_down"),S=g(9216,32,3,"conv32_1"),x=g(9216,32,3,"conv32_2"),N=g(9216,32,3,"conv32_3"),E=g(36864,64,3,"conv64_down",!0),_=g(36864,64,3,"conv64_1"),A=g(36864,64,3,"conv64_2"),U=g(36864,64,3,"conv64_3"),ne=g(147456,128,3,"conv128_down",!0),Q=g(147456,128,3,"conv128_1"),M=g(147456,128,3,"conv128_2"),fe=g(589824,256,3,"conv256_down",!0),ie=g(589824,256,3,"conv256_1"),we=g(589824,256,3,"conv256_2"),Ae=g(589824,256,3,"conv256_down_out"),Me=Ss.tidy(()=>Ss.transpose(Ss.tensor2d(l(256*128),[128,256]),[1,0]));if(d.push({paramPath:"fc"}),u().length!==0)throw new Error(`weights remaing after extract: ${u().length}`);const et={conv32_down:I,conv32_1:S,conv32_2:x,conv32_3:N,conv64_down:E,conv64_1:_,conv64_2:A,conv64_3:U,conv128_down:ne,conv128_1:Q,conv128_2:M,conv256_down:fe,conv256_1:ie,conv256_2:we,conv256_down_out:Ae,fc:Me};return{params:et,paramMappings:d}}function Aee(r,l){const u=ws(r,l);function d(I){const S=u(`${I}/scale/weights`,1),x=u(`${I}/scale/biases`,1);return{weights:S,biases:x}}function f(I){const S=u(`${I}/conv/filters`,4),x=u(`${I}/conv/bias`,1),N=d(I);return{conv:{filters:S,bias:x},scale:N}}function g(I){return{conv1:f(`${I}/conv1`),conv2:f(`${I}/conv2`)}}return{extractConvLayerParams:f,extractResidualLayerParams:g}}function XD(r){const l=[],{extractConvLayerParams:u,extractResidualLayerParams:d}=Aee(r,l),f=u("conv32_down"),g=d("conv32_1"),I=d("conv32_2"),S=d("conv32_3"),x=d("conv64_down"),N=d("conv64_1"),E=d("conv64_2"),_=d("conv64_3"),A=d("conv128_down"),U=d("conv128_1"),ne=d("conv128_2"),Q=d("conv256_down"),M=d("conv256_1"),fe=d("conv256_2"),ie=d("conv256_down_out"),we=r.fc;if(l.push({originalPath:"fc",paramPath:"fc"}),!aI(we))throw new Error(`expected weightMap[fc] to be a Tensor2D, instead have ${we}`);const Ae={conv32_down:f,conv32_1:g,conv32_2:I,conv32_3:S,conv64_down:x,conv64_1:N,conv64_2:E,conv64_3:_,conv128_down:A,conv128_1:U,conv128_2:ne,conv256_down:Q,conv256_1:M,conv256_2:fe,conv256_down_out:ie,fc:we};return jn(r,l),{params:Ae,paramMappings:l}}const Xn=He(Ze());function Si(r,l){let u=jD(r,l.conv1);return u=$x(u,l.conv2),u=Xn.add(u,r),u=Xn.relu(u),u}function od(r,l){let u=Jg(r,l.conv1);u=$x(u,l.conv2);let d=Xn.avgPool(r,2,2,"valid");const f=Xn.zeros(d.shape),g=d.shape[3]!==u.shape[3],I=d.shape[1]!==u.shape[1]||d.shape[2]!==u.shape[2];if(I){const S=[...u.shape];S[1]=1;const x=Xn.zeros(S);u=Xn.concat([u,x],1);const N=[...u.shape];N[2]=1;const E=Xn.zeros(N);u=Xn.concat([u,E],2)}return d=g?Xn.concat([d,f],3):d,u=Xn.add(d,u),u=Xn.relu(u),u}const $s=He(Ze());class ad extends Un{constructor(){super("FaceRecognitionNet")}forwardInput(r){const{params:l}=this;if(!l)throw new Error("FaceRecognitionNet - load model before inference");return $s.tidy(()=>{const u=$s.cast(r.toBatchTensor(150,!0),"float32"),d=[122.782,117.001,104.298],f=yi(u,d).div($s.scalar(256));let g=Jg(f,l.conv32_down);g=$s.maxPool(g,3,2,"valid"),g=Si(g,l.conv32_1),g=Si(g,l.conv32_2),g=Si(g,l.conv32_3),g=od(g,l.conv64_down),g=Si(g,l.conv64_1),g=Si(g,l.conv64_2),g=Si(g,l.conv64_3),g=od(g,l.conv128_down),g=Si(g,l.conv128_1),g=Si(g,l.conv128_2),g=od(g,l.conv256_down),g=Si(g,l.conv256_1),g=Si(g,l.conv256_2),g=od(g,l.conv256_down_out);const I=g.mean([1,2]),S=$s.matMul(I,l.fc);return S})}async forward(r){return this.forwardInput(await Wt(r))}async computeFaceDescriptor(r){const l=await Wt(r),u=$s.tidy(()=>$s.unstack(this.forwardInput(l))),d=await Promise.all(u.map(f=>f.data()));return u.forEach(f=>f.dispose()),l.isBatchInput?d:d[0]}getDefaultModelName(){return"face_recognition_model"}extractParamsFromWeigthMap(r){return XD(r)}extractParams(r){return KD(r)}}function vee(r){const l=new ad;return l.extractWeights(r),l}function Zg(r,l){const u={descriptor:l};return Object.assign({},r,u)}function Nee(r){return typeof r.age=="number"}function Qg(r,l){const u={age:l};return Object.assign({},r,u)}function Cee(r){return(r.gender===Or.MALE||r.gender===Or.FEMALE)&&Mc(r.genderProbability)}function ey(r,l,u){const d={gender:l,genderProbability:u};return Object.assign({},r,d)}const Ii=He(Ze());function Ree(r,l){function u(x,N){const E=Ii.tensor4d(r(3*3*x),[3,3,x,1]),_=Ii.tensor1d(r(x)),A=Ii.tensor1d(r(x)),U=Ii.tensor1d(r(x)),ne=Ii.tensor1d(r(x));return l.push({paramPath:`${N}/filters`},{paramPath:`${N}/batch_norm_scale`},{paramPath:`${N}/batch_norm_offset`},{paramPath:`${N}/batch_norm_mean`},{paramPath:`${N}/batch_norm_variance`}),{filters:E,batch_norm_scale:_,batch_norm_offset:A,batch_norm_mean:U,batch_norm_variance:ne}}function d(x,N,E,_,A){const U=Ii.tensor4d(r(x*N*E*E),[E,E,x,N]),ne=Ii.tensor1d(r(N));return l.push({paramPath:`${_}/filters`},{paramPath:`${_}/${A?"batch_norm_offset":"bias"}`}),{filters:U,bias:ne}}function f(x,N,E,_){const{filters:A,bias:U}=d(x,N,E,_,!0);return{filters:A,batch_norm_offset:U}}function g(x,N,E){const _=u(x,`${E}/depthwise_conv`),A=f(x,N,1,`${E}/pointwise_conv`);return{depthwise_conv:_,pointwise_conv:A}}function I(){const x=f(3,32,3,"mobilenetv1/conv_0"),N=g(32,64,"mobilenetv1/conv_1"),E=g(64,128,"mobilenetv1/conv_2"),_=g(128,128,"mobilenetv1/conv_3"),A=g(128,256,"mobilenetv1/conv_4"),U=g(256,256,"mobilenetv1/conv_5"),ne=g(256,512,"mobilenetv1/conv_6"),Q=g(512,512,"mobilenetv1/conv_7"),M=g(512,512,"mobilenetv1/conv_8"),fe=g(512,512,"mobilenetv1/conv_9"),ie=g(512,512,"mobilenetv1/conv_10"),we=g(512,512,"mobilenetv1/conv_11"),Ae=g(512,1024,"mobilenetv1/conv_12"),Me=g(1024,1024,"mobilenetv1/conv_13");return{conv_0:x,conv_1:N,conv_2:E,conv_3:_,conv_4:A,conv_5:U,conv_6:ne,conv_7:Q,conv_8:M,conv_9:fe,conv_10:ie,conv_11:we,conv_12:Ae,conv_13:Me}}function S(){const x=f(1024,256,1,"prediction_layer/conv_0"),N=f(256,512,3,"prediction_layer/conv_1"),E=f(512,128,1,"prediction_layer/conv_2"),_=f(128,256,3,"prediction_layer/conv_3"),A=f(256,128,1,"prediction_layer/conv_4"),U=f(128,256,3,"prediction_layer/conv_5"),ne=f(256,64,1,"prediction_layer/conv_6"),Q=f(64,128,3,"prediction_layer/conv_7"),M=d(512,12,1,"prediction_layer/box_predictor_0/box_encoding_predictor"),fe=d(512,9,1,"prediction_layer/box_predictor_0/class_predictor"),ie=d(1024,24,1,"prediction_layer/box_predictor_1/box_encoding_predictor"),we=d(1024,18,1,"prediction_layer/box_predictor_1/class_predictor"),Ae=d(512,24,1,"prediction_layer/box_predictor_2/box_encoding_predictor"),Me=d(512,18,1,"prediction_layer/box_predictor_2/class_predictor"),et=d(256,24,1,"prediction_layer/box_predictor_3/box_encoding_predictor"),ct=d(256,18,1,"prediction_layer/box_predictor_3/class_predictor"),$t=d(256,24,1,"prediction_layer/box_predictor_4/box_encoding_predictor"),Vt=d(256,18,1,"prediction_layer/box_predictor_4/class_predictor"),je=d(128,24,1,"prediction_layer/box_predictor_5/box_encoding_predictor"),hn=d(128,18,1,"prediction_layer/box_predictor_5/class_predictor"),bt={box_encoding_predictor:M,class_predictor:fe},Is={box_encoding_predictor:ie,class_predictor:we},_r={box_encoding_predictor:Ae,class_predictor:Me},Wr={box_encoding_predictor:et,class_predictor:ct},Oa={box_encoding_predictor:$t,class_predictor:Vt},un={box_encoding_predictor:je,class_predictor:hn};return{conv_0:x,conv_1:N,conv_2:E,conv_3:_,conv_4:A,conv_5:U,conv_6:ne,conv_7:Q,box_predictor_0:bt,box_predictor_1:Is,box_predictor_2:_r,box_predictor_3:Wr,box_predictor_4:Oa,box_predictor_5:un}}return{extractMobilenetV1Params:I,extractPredictionLayerParams:S}}function JD(r){const l=[],{extractWeights:u,getRemainingWeights:d}=Kn(r),{extractMobilenetV1Params:f,extractPredictionLayerParams:g}=Ree(u,l),I=f(),S=g(),x=Ii.tensor3d(u(5118*4),[1,5118,4]),N={extra_dim:x};if(l.push({paramPath:"output_layer/extra_dim"}),d().length!==0)throw new Error(`weights remaing after extract: ${d().length}`);return{params:{mobilenetv1:I,prediction_layer:S,output_layer:N},paramMappings:l}}function Oee(r,l){const u=ws(r,l);function d(N,E,_){const A=u(`${N}/Conv2d_${E}_pointwise/weights`,4,`${_}/filters`),U=u(`${N}/Conv2d_${E}_pointwise/convolution_bn_offset`,1,`${_}/batch_norm_offset`);return{filters:A,batch_norm_offset:U}}function f(N){const E=`mobilenetv1/conv_${N}`,_=`MobilenetV1/Conv2d_${N}_depthwise`,A=`${E}/depthwise_conv`,U=`${E}/pointwise_conv`,ne=u(`${_}/depthwise_weights`,4,`${A}/filters`),Q=u(`${_}/BatchNorm/gamma`,1,`${A}/batch_norm_scale`),M=u(`${_}/BatchNorm/beta`,1,`${A}/batch_norm_offset`),fe=u(`${_}/BatchNorm/moving_mean`,1,`${A}/batch_norm_mean`),ie=u(`${_}/BatchNorm/moving_variance`,1,`${A}/batch_norm_variance`);return{depthwise_conv:{filters:ne,batch_norm_scale:Q,batch_norm_offset:M,batch_norm_mean:fe,batch_norm_variance:ie},pointwise_conv:d("MobilenetV1",N,U)}}function g(){return{conv_0:d("MobilenetV1",0,"mobilenetv1/conv_0"),conv_1:f(1),conv_2:f(2),conv_3:f(3),conv_4:f(4),conv_5:f(5),conv_6:f(6),conv_7:f(7),conv_8:f(8),conv_9:f(9),conv_10:f(10),conv_11:f(11),conv_12:f(12),conv_13:f(13)}}function I(N,E){const _=u(`${N}/weights`,4,`${E}/filters`),A=u(`${N}/biases`,1,`${E}/bias`);return{filters:_,bias:A}}function S(N){const E=I(`Prediction/BoxPredictor_${N}/BoxEncodingPredictor`,`prediction_layer/box_predictor_${N}/box_encoding_predictor`),_=I(`Prediction/BoxPredictor_${N}/ClassPredictor`,`prediction_layer/box_predictor_${N}/class_predictor`);return{box_encoding_predictor:E,class_predictor:_}}function x(){return{conv_0:d("Prediction",0,"prediction_layer/conv_0"),conv_1:d("Prediction",1,"prediction_layer/conv_1"),conv_2:d("Prediction",2,"prediction_layer/conv_2"),conv_3:d("Prediction",3,"prediction_layer/conv_3"),conv_4:d("Prediction",4,"prediction_layer/conv_4"),conv_5:d("Prediction",5,"prediction_layer/conv_5"),conv_6:d("Prediction",6,"prediction_layer/conv_6"),conv_7:d("Prediction",7,"prediction_layer/conv_7"),box_predictor_0:S(0),box_predictor_1:S(1),box_predictor_2:S(2),box_predictor_3:S(3),box_predictor_4:S(4),box_predictor_5:S(5)}}return{extractMobilenetV1Params:g,extractPredictionLayerParams:x}}function ZD(r){const l=[],{extractMobilenetV1Params:u,extractPredictionLayerParams:d}=Oee(r,l),f=r["Output/extra_dim"];if(l.push({originalPath:"Output/extra_dim",paramPath:"output_layer/extra_dim"}),!Tr(f))throw new Error(`expected weightMap['Output/extra_dim'] to be a Tensor3D, instead have ${f}`);const g={mobilenetv1:u(),prediction_layer:d(),output_layer:{extra_dim:f}};return jn(r,l),{params:g,paramMappings:l}}const vo=He(Ze());function Js(r,l,u){return vo.tidy(()=>{let d=vo.conv2d(r,l.filters,u,"same");return d=vo.add(d,l.batch_norm_offset),vo.clipByValue(d,0,6)})}const Er=He(Ze()),Eee=.0010000000474974513;function Dee(r,l,u){return Er.tidy(()=>{let d=Er.depthwiseConv2d(r,l.filters,u,"same");return d=Er.batchNorm(d,l.batch_norm_mean,l.batch_norm_variance,l.batch_norm_offset,l.batch_norm_scale,Eee),Er.clipByValue(d,0,6)})}function kee(r){return[2,4,6,12].some(l=>l===r)?[2,2]:[1,1]}function QD(r,l){return Er.tidy(()=>{let u,d=Js(r,l.conv_0,[2,2]);const f=[l.conv_1,l.conv_2,l.conv_3,l.conv_4,l.conv_5,l.conv_6,l.conv_7,l.conv_8,l.conv_9,l.conv_10,l.conv_11,l.conv_12,l.conv_13];if(f.forEach((g,I)=>{const S=I+1,x=kee(S);d=Dee(d,g.depthwise_conv,x),d=Js(d,g.pointwise_conv,[1,1]),S===11&&(u=d)}),u===null)throw new Error("mobileNetV1 - output of conv layer 11 is null");return{out:d,conv11:u}})}function ek(r,l,u,d,f){const g=r.shape[0],I=Math.min(u,g),S=l.map((E,_)=>({score:E,boxIndex:_})).filter(E=>E.score>f).sort((E,_)=>_.score-E.score),x=E=>E<=d?1:0,N=[];return S.forEach(E=>{if(N.length>=I)return;const _=E.score;for(let A=N.length-1;A>=0;--A){const U=Fee(r,E.boxIndex,N[A]);if(U===0)continue;if(E.score*=x(U),E.score<=f)break}_===E.score&&N.push(E.boxIndex)}),N}function Fee(r,l,u){const d=r.arraySync(),f=Math.min(d[l][0],d[l][2]),g=Math.min(d[l][1],d[l][3]),I=Math.max(d[l][0],d[l][2]),S=Math.max(d[l][1],d[l][3]),x=Math.min(d[u][0],d[u][2]),N=Math.min(d[u][1],d[u][3]),E=Math.max(d[u][0],d[u][2]),_=Math.max(d[u][1],d[u][3]),A=(I-f)*(S-g),U=(E-x)*(_-N);if(A<=0||U<=0)return 0;const ne=Math.max(f,x),Q=Math.max(g,N),M=Math.min(I,E),fe=Math.min(S,_),ie=Math.max(M-ne,0)*Math.max(fe-Q,0);return ie/(A+U-ie)}const ke=He(Ze());function _ee(r){const l=ke.unstack(ke.transpose(r,[1,0])),u=[ke.sub(l[2],l[0]),ke.sub(l[3],l[1])],d=[ke.add(l[0],ke.div(u[0],ke.scalar(2))),ke.add(l[1],ke.div(u[1],ke.scalar(2)))];return{sizes:u,centers:d}}function Wee(r,l){const{sizes:u,centers:d}=_ee(r),f=ke.unstack(ke.transpose(l,[1,0])),g=ke.div(ke.mul(ke.exp(ke.div(f[2],ke.scalar(5))),u[0]),ke.scalar(2)),I=ke.add(ke.mul(ke.div(f[0],ke.scalar(10)),u[0]),d[0]),S=ke.div(ke.mul(ke.exp(ke.div(f[3],ke.scalar(5))),u[1]),ke.scalar(2)),x=ke.add(ke.mul(ke.div(f[1],ke.scalar(10)),u[1]),d[1]);return ke.transpose(ke.stack([ke.sub(I,g),ke.sub(x,S),ke.add(I,g),ke.add(x,S)]),[1,0])}function tk(r,l,u){return ke.tidy(()=>{const d=r.shape[0];let f=Wee(ke.reshape(ke.tile(u.extra_dim,[d,1,1]),[-1,4]),ke.reshape(r,[-1,4]));f=ke.reshape(f,[d,f.shape[0]/d,4]);const g=ke.sigmoid(ke.slice(l,[0,0,1],[-1,-1,-1]));let I=ke.slice(g,[0,0,0],[-1,-1,1]);I=ke.reshape(I,[d,I.shape[1]]);const S=ke.unstack(f),x=ke.unstack(I);return{boxes:S,scores:x}})}const cd=He(Ze());function va(r,l){return cd.tidy(()=>{const u=r.shape[0],d=cd.reshape(xa(r,l.box_encoding_predictor),[u,-1,1,4]),f=cd.reshape(xa(r,l.class_predictor),[u,-1,3]);return{boxPredictionEncoding:d,classPrediction:f}})}const ld=He(Ze());function nk(r,l,u){return ld.tidy(()=>{const d=Js(r,u.conv_0,[1,1]),f=Js(d,u.conv_1,[2,2]),g=Js(f,u.conv_2,[1,1]),I=Js(g,u.conv_3,[2,2]),S=Js(I,u.conv_4,[1,1]),x=Js(S,u.conv_5,[2,2]),N=Js(x,u.conv_6,[1,1]),E=Js(N,u.conv_7,[2,2]),_=va(l,u.box_predictor_0),A=va(r,u.box_predictor_1),U=va(f,u.box_predictor_2),ne=va(I,u.box_predictor_3),Q=va(x,u.box_predictor_4),M=va(E,u.box_predictor_5),fe=ld.concat([_.boxPredictionEncoding,A.boxPredictionEncoding,U.boxPredictionEncoding,ne.boxPredictionEncoding,Q.boxPredictionEncoding,M.boxPredictionEncoding],1),ie=ld.concat([_.classPrediction,A.classPrediction,U.classPrediction,ne.classPrediction,Q.classPrediction,M.classPrediction],1);return{boxPredictions:fe,classPredictions:ie}})}class xi{constructor({minConfidence:r,maxResults:l}={}){this._name="SsdMobilenetv1Options";if(this._minConfidence=r||.5,this._maxResults=l||100,typeof this._minConfidence!="number"||this._minConfidence<=0||this._minConfidence>=1)throw new Error(`${this._name} - expected minConfidence to be a number between 0 and 1`);if(typeof this._maxResults!="number")throw new Error(`${this._name} - expected maxResults to be a number`)}get minConfidence(){return this._minConfidence}get maxResults(){return this._maxResults}}const Ti=He(Ze());class dl extends Un{constructor(){super("SsdMobilenetv1")}forwardInput(r){const{params:l}=this;if(!l)throw new Error("SsdMobilenetv1 - load model before inference");return Ti.tidy(()=>{const u=Ti.cast(r.toBatchTensor(512,!1),"float32"),d=Ti.sub(Ti.mul(u,Ti.scalar(.007843137718737125)),Ti.scalar(1)),f=QD(d,l.mobilenetv1),{boxPredictions:g,classPredictions:I}=nk(f.out,f.conv11,l.prediction_layer);return tk(g,I,l.output_layer)})}async forward(r){return this.forwardInput(await Wt(r))}async locateFaces(r,l={}){const{maxResults:u,minConfidence:d}=new xi(l),f=await Wt(r),{boxes:g,scores:I}=this.forwardInput(f),S=g[0],x=I[0];for(let ie=1;ie<g.length;ie++)g[ie].dispose(),I[ie].dispose();const N=Array.from(await x.data()),E=.5,_=ek(S,N,u,E,d),A=f.getReshapedInputDimensions(0),U=f.inputSize,ne=U/A.width,Q=U/A.height,M=S.arraySync(),fe=_.map(ie=>{const[we,Ae]=[Math.max(0,M[ie][0]),Math.min(1,M[ie][2])].map(ct=>ct*Q),[Me,et]=[Math.max(0,M[ie][1]),Math.min(1,M[ie][3])].map(ct=>ct*ne);return new Jt(N[ie],new Wu(Me,we,et-Me,Ae-we),{height:f.getInputHeight(0),width:f.getInputWidth(0)})});return S.dispose(),x.dispose(),fe}getDefaultModelName(){return"ssd_mobilenetv1_model"}extractParamsFromWeigthMap(r){return ZD(r)}extractParams(r){return JD(r)}}function sk(r){const l=new dl;return l.extractWeights(r),l}function $ee(r){return sk(r)}class Uee extends dl{}const ik=.4,rk=[new Qe(.738768,.874946),new Qe(2.42204,2.65704),new Qe(4.30971,7.04493),new Qe(10.246,4.59428),new Qe(12.6868,11.8741)],ok=[new Qe(1.603231,2.094468),new Qe(6.041143,7.080126),new Qe(2.882459,3.518061),new Qe(4.266906,5.178857),new Qe(9.041765,10.66308)],ak=[117.001,114.697,97.404],ck="tiny_yolov2_model",lk="tiny_yolov2_separable_conv_model";const ty=r=>typeof r=="number";function Ux(r){if(!r)throw new Error(`invalid config: ${r}`);if(typeof r.withSeparableConvs!="boolean")throw new Error(`config.withSeparableConvs has to be a boolean, have: ${r.withSeparableConvs}`);if(!ty(r.iouThreshold)||r.iouThreshold<0||r.iouThreshold>1)throw new Error(`config.iouThreshold has to be a number between [0, 1], have: ${r.iouThreshold}`);if(!Array.isArray(r.classes)||!r.classes.length||!r.classes.every(l=>typeof l=="string"))throw new Error(`config.classes has to be an array class names: string[], have: ${JSON.stringify(r.classes)}`);if(!Array.isArray(r.anchors)||!r.anchors.length||!r.anchors.map(l=>l||{}).every(l=>ty(l.x)&&ty(l.y)))throw new Error(`config.anchors has to be an array of { x: number, y: number }, have: ${JSON.stringify(r.anchors)}`);if(r.meanRgb&&(!Array.isArray(r.meanRgb)||r.meanRgb.length!==3||!r.meanRgb.every(ty)))throw new Error(`config.meanRgb has to be an array of shape [number, number, number], have: ${JSON.stringify(r.meanRgb)}`)}const Zs=He(Ze());function pl(r){return Zs.tidy(()=>{const l=Zs.mul(r,Zs.scalar(.10000000149011612));return Zs.add(Zs.relu(Zs.sub(r,l)),l)})}const Qs=He(Ze());function Dr(r,l){return Qs.tidy(()=>{let u=Qs.pad(r,[[0,0],[1,1],[1,1],[0,0]]);return u=Qs.conv2d(u,l.conv.filters,[1,1],"valid"),u=Qs.sub(u,l.bn.sub),u=Qs.mul(u,l.bn.truediv),u=Qs.add(u,l.conv.bias),pl(u)})}const No=He(Ze());function kr(r,l){return No.tidy(()=>{let u=No.pad(r,[[0,0],[1,1],[1,1],[0,0]]);return u=No.separableConv2d(u,l.depthwise_filter,l.pointwise_filter,[1,1],"valid"),u=No.add(u,l.bias),pl(u)})}const Bx=He(Ze());function Bee(r,l){const u=rl(r,l);function d(I,S){const x=Bx.tensor1d(r(I)),N=Bx.tensor1d(r(I));return l.push({paramPath:`${S}/sub`},{paramPath:`${S}/truediv`}),{sub:x,truediv:N}}function f(I,S,x){const N=u(I,S,3,`${x}/conv`),E=d(S,`${x}/bn`);return{conv:N,bn:E}}const g=ol(r,l);return{extractConvParams:u,extractConvWithBatchNormParams:f,extractSeparableConvParams:g}}function hk(r,l,u,d){const{extractWeights:f,getRemainingWeights:g}=Kn(r),I=[],{extractConvParams:S,extractConvWithBatchNormParams:x,extractSeparableConvParams:N}=Bee(f,I);let E;if(l.withSeparableConvs){const[_,A,U,ne,Q,M,fe,ie,we]=d,Ae=l.isFirstLayerConv2d?S(_,A,3,"conv0"):N(_,A,"conv0"),Me=N(A,U,"conv1"),et=N(U,ne,"conv2"),ct=N(ne,Q,"conv3"),$t=N(Q,M,"conv4"),Vt=N(M,fe,"conv5"),je=ie?N(fe,ie,"conv6"):void 0,hn=we?N(ie,we,"conv7"):void 0,bt=S(we||ie||fe,5*u,1,"conv8");E={conv0:Ae,conv1:Me,conv2:et,conv3:ct,conv4:$t,conv5:Vt,conv6:je,conv7:hn,conv8:bt}}else{const[_,A,U,ne,Q,M,fe,ie,we]=d,Ae=x(_,A,"conv0"),Me=x(A,U,"conv1"),et=x(U,ne,"conv2"),ct=x(ne,Q,"conv3"),$t=x(Q,M,"conv4"),Vt=x(M,fe,"conv5"),je=x(fe,ie,"conv6"),hn=x(ie,we,"conv7"),bt=S(we,5*u,1,"conv8");E={conv0:Ae,conv1:Me,conv2:et,conv3:ct,conv4:$t,conv5:Vt,conv6:je,conv7:hn,conv8:bt}}if(g().length!==0)throw new Error(`weights remaing after extract: ${g().length}`);return{params:E,paramMappings:I}}function Mee(r,l){const u=ws(r,l);function d(S){const x=u(`${S}/sub`,1),N=u(`${S}/truediv`,1);return{sub:x,truediv:N}}function f(S){const x=u(`${S}/filters`,4),N=u(`${S}/bias`,1);return{filters:x,bias:N}}function g(S){const x=f(`${S}/conv`),N=d(`${S}/bn`);return{conv:x,bn:N}}const I=al(u);return{extractConvParams:f,extractConvWithBatchNormParams:g,extractSeparableConvParams:I}}function uk(r,l){const u=[],{extractConvParams:d,extractConvWithBatchNormParams:f,extractSeparableConvParams:g}=Mee(r,u);let I;if(l.withSeparableConvs){const S=l.filterSizes&&l.filterSizes.length||9;I={conv0:l.isFirstLayerConv2d?d("conv0"):g("conv0"),conv1:g("conv1"),conv2:g("conv2"),conv3:g("conv3"),conv4:g("conv4"),conv5:g("conv5"),conv6:S>7?g("conv6"):void 0,conv7:S>8?g("conv7"):void 0,conv8:d("conv8")}}else I={conv0:f("conv0"),conv1:f("conv1"),conv2:f("conv2"),conv3:f("conv3"),conv4:f("conv4"),conv5:f("conv5"),conv6:f("conv6"),conv7:f("conv7"),conv8:d("conv8")};return jn(r,u),{params:I,paramMappings:u}}var Mx;(function(r){r[r.XS=224]="XS",r[r.SM=320]="SM",r[r.MD=416]="MD",r[r.LG=608]="LG"})(Mx||(Mx={}));class Fr{constructor({inputSize:r,scoreThreshold:l}={}){this._name="TinyYolov2Options";if(this._inputSize=r||416,this._scoreThreshold=l||.5,typeof this._inputSize!="number"||this._inputSize%32!==0)throw new Error(`${this._name} - expected inputSize to be a number divisible by 32`);if(typeof this._scoreThreshold!="number"||this._scoreThreshold<=0||this._scoreThreshold>=1)throw new Error(`${this._name} - expected scoreThreshold to be a number between 0 and 1`)}get inputSize(){return this._inputSize}get scoreThreshold(){return this._scoreThreshold}}const Mt=He(Ze());class ml extends Un{constructor(r){super("TinyYolov2");Ux(r),this._config=r}get config(){return this._config}get withClassScores(){return this.config.withClassScores||this.config.classes.length>1}get boxEncodingSize(){return 5+(this.withClassScores?this.config.classes.length:0)}runTinyYolov2(r,l){let u=Dr(r,l.conv0);return u=Mt.maxPool(u,[2,2],[2,2],"same"),u=Dr(u,l.conv1),u=Mt.maxPool(u,[2,2],[2,2],"same"),u=Dr(u,l.conv2),u=Mt.maxPool(u,[2,2],[2,2],"same"),u=Dr(u,l.conv3),u=Mt.maxPool(u,[2,2],[2,2],"same"),u=Dr(u,l.conv4),u=Mt.maxPool(u,[2,2],[2,2],"same"),u=Dr(u,l.conv5),u=Mt.maxPool(u,[2,2],[1,1],"same"),u=Dr(u,l.conv6),u=Dr(u,l.conv7),xa(u,l.conv8,"valid",!1)}runMobilenet(r,l){let u=this.config.isFirstLayerConv2d?pl(xa(r,l.conv0,"valid",!1)):kr(r,l.conv0);return u=Mt.maxPool(u,[2,2],[2,2],"same"),u=kr(u,l.conv1),u=Mt.maxPool(u,[2,2],[2,2],"same"),u=kr(u,l.conv2),u=Mt.maxPool(u,[2,2],[2,2],"same"),u=kr(u,l.conv3),u=Mt.maxPool(u,[2,2],[2,2],"same"),u=kr(u,l.conv4),u=Mt.maxPool(u,[2,2],[2,2],"same"),u=kr(u,l.conv5),u=Mt.maxPool(u,[2,2],[1,1],"same"),u=l.conv6?kr(u,l.conv6):u,u=l.conv7?kr(u,l.conv7):u,xa(u,l.conv8,"valid",!1)}forwardInput(r,l){const{params:u}=this;if(!u)throw new Error("TinyYolov2 - load model before inference");return Mt.tidy(()=>{let d=Mt.cast(r.toBatchTensor(l,!1),"float32");return d=this.config.meanRgb?yi(d,this.config.meanRgb):d,d=d.div(Mt.scalar(256)),this.config.withSeparableConvs?this.runMobilenet(d,u):this.runTinyYolov2(d,u)})}async forward(r,l){return await this.forwardInput(await Wt(r),l)}async detect(r,l={}){const{inputSize:u,scoreThreshold:d}=new Fr(l),f=await Wt(r),g=await this.forwardInput(f,u),I=Mt.tidy(()=>Mt.unstack(g)[0].expandDims()),S={width:f.getInputWidth(0),height:f.getInputHeight(0)},x=await this.extractBoxes(I,f.getReshapedInputDimensions(0),d);g.dispose(),I.dispose();const N=x.map(Q=>Q.box),E=x.map(Q=>Q.score),_=x.map(Q=>Q.classScore),A=x.map(Q=>this.config.classes[Q.label]),U=dI(N.map(Q=>Q.rescale(u)),E,this.config.iouThreshold,!0),ne=U.map(Q=>new Pc(E[Q],_[Q],A[Q],N[Q],S));return ne}getDefaultModelName(){return""}extractParamsFromWeigthMap(r){return uk(r,this.config)}extractParams(r){const l=this.config.filterSizes||ml.DEFAULT_FILTER_SIZES,u=l?l.length:void 0;if(u!==7&&u!==8&&u!==9)throw new Error(`TinyYolov2 - expected 7 | 8 | 9 convolutional filters, but found ${u} filterSizes in config`);return hk(r,this.config,this.boxEncodingSize,l)}async extractBoxes(r,l,u){const{width:d,height:f}=l,g=Math.max(d,f),I=g/d,S=g/f,x=r.shape[1],N=this.config.anchors.length,[E,_,A]=Mt.tidy(()=>{const M=r.reshape([x,x,N,this.boxEncodingSize]),fe=M.slice([0,0,0,0],[x,x,N,4]),ie=M.slice([0,0,0,4],[x,x,N,1]),we=this.withClassScores?Mt.softmax(M.slice([0,0,0,5],[x,x,N,this.config.classes.length]),3):Mt.scalar(0);return[fe,ie,we]}),U=[],ne=await _.array(),Q=await E.array();for(let M=0;M<x;M++)for(let fe=0;fe<x;fe++)for(let ie=0;ie<N;ie++){const we=_u(ne[M][fe][ie][0]);if(!u||we>u){const Ae=(fe+_u(Q[M][fe][ie][0]))/x*I,Me=(M+_u(Q[M][fe][ie][1]))/x*S,et=Math.exp(Q[M][fe][ie][2])*this.config.anchors[ie].x/x*I,ct=Math.exp(Q[M][fe][ie][3])*this.config.anchors[ie].y/x*S,$t=Ae-et/2,Vt=Me-ct/2,je={row:M,col:fe,anchor:ie},{classScore:hn,label:bt}=this.withClassScores?await this.extractPredictedClass(A,je):{classScore:1,label:0};U.push({box:new Fu($t,Vt,$t+et,Vt+ct),score:we,classScore:we*hn,label:bt,...je})}}return E.dispose(),_.dispose(),A.dispose(),U}async extractPredictedClass(r,l){const{row:u,col:d,anchor:f}=l,g=await r.array();return Array(this.config.classes.length).fill(0).map((I,S)=>g[u][d][f][S]).map((I,S)=>({classScore:I,label:S})).reduce((I,S)=>I.classScore>S.classScore?I:S)}}ml.DEFAULT_FILTER_SIZES=[3,16,32,64,128,256,512,1024,1024];class hd extends ml{constructor(r=!0){const l=Object.assign({},{withSeparableConvs:r,iouThreshold:ik,classes:["face"]},r?{anchors:ok,meanRgb:ak}:{anchors:rk,withClassScores:!0});super(l)}get withSeparableConvs(){return this.config.withSeparableConvs}get anchors(){return this.config.anchors}async locateFaces(r,l){const u=await this.detect(r,l);return u.map(d=>new Jt(d.score,d.relativeBox,{width:d.imageWidth,height:d.imageHeight}))}getDefaultModelName(){return this.withSeparableConvs?lk:ck}extractParamsFromWeigthMap(r){return super.extractParamsFromWeigthMap(r)}}function Pee(r,l=!0){const u=new hd(l);return u.extractWeights(r),u}class Px extends Fr{constructor(){super(...arguments);this._name="TinyFaceDetectorOptions"}}class Ai{async then(r){return r(await this.run())}async run(){throw new Error("ComposableTask - run is not implemented")}}const zx=He(Ze());async function Na(r,l,u,d,f=({alignedRect:g})=>g){const g=r.map(x=>Aa(x)?f(x):x.detection),I=d||(l instanceof zx.Tensor?await sl(l,g):await nl(l,g)),S=await u(I);return I.forEach(x=>x instanceof zx.Tensor&&x.dispose()),S}async function fl(r,l,u,d,f){return Na([r],l,async g=>u(g[0]),d,f)}const dk=.4,pk=[new Qe(1.603231,2.094468),new Qe(6.041143,7.080126),new Qe(2.882459,3.518061),new Qe(4.266906,5.178857),new Qe(9.041765,10.66308)],mk=[117.001,114.697,97.404];class ud extends ml{constructor(){const r={withSeparableConvs:!0,iouThreshold:dk,classes:["face"],anchors:pk,meanRgb:mk,isFirstLayerConv2d:!0,filterSizes:[3,16,32,64,128,256,512]};super(r)}get anchors(){return this.config.anchors}async locateFaces(r,l){const u=await this.detect(r,l);return u.map(d=>new Jt(d.score,d.relativeBox,{width:d.imageWidth,height:d.imageHeight}))}getDefaultModelName(){return"tiny_face_detector_model"}extractParamsFromWeigthMap(r){return super.extractParamsFromWeigthMap(r)}}const yt={ssdMobilenetv1:new dl,tinyFaceDetector:new ud,tinyYolov2:new hd,faceLandmark68Net:new rd,faceLandmark68TinyNet:new _x,faceRecognitionNet:new ad,faceExpressionNet:new Ox,ageGenderNet:new Fx},fk=(r,l)=>yt.ssdMobilenetv1.locateFaces(r,l),zee=(r,l)=>yt.tinyFaceDetector.locateFaces(r,l),Vee=(r,l)=>yt.tinyYolov2.locateFaces(r,l),gk=r=>yt.faceLandmark68Net.detectLandmarks(r),Gee=r=>yt.faceLandmark68TinyNet.detectLandmarks(r),Yee=r=>yt.faceRecognitionNet.computeFaceDescriptor(r),Hee=r=>yt.faceExpressionNet.predictExpressions(r),qee=r=>yt.ageGenderNet.predictAgeAndGender(r),yk=r=>yt.ssdMobilenetv1.load(r),jee=r=>yt.tinyFaceDetector.load(r),Kee=r=>yt.tinyYolov2.load(r),Xee=r=>yt.faceLandmark68Net.load(r),Jee=r=>yt.faceLandmark68TinyNet.load(r),Zee=r=>yt.faceRecognitionNet.load(r),Qee=r=>yt.faceExpressionNet.load(r),ete=r=>yt.ageGenderNet.load(r),tte=yk,nte=fk,ste=gk;class bk extends Ai{constructor(r,l,u){super();this.parentTask=r;this.input=l;this.extractedFaces=u}}class md extends bk{async run(){const r=await this.parentTask,l=await Na(r,this.input,async u=>await Promise.all(u.map(d=>yt.faceExpressionNet.predictExpressions(d))),this.extractedFaces);return r.map((u,d)=>jg(u,l[d]))}withAgeAndGender(){return new dd(this,this.input)}}class fd extends bk{async run(){const r=await this.parentTask;if(!r)return;const l=await fl(r,this.input,u=>yt.faceExpressionNet.predictExpressions(u),this.extractedFaces);return jg(r,l)}withAgeAndGender(){return new pd(this,this.input)}}class bl extends md{withAgeAndGender(){return new gl(this,this.input)}withFaceDescriptors(){return new Ca(this,this.input)}}class wl extends fd{withAgeAndGender(){return new yl(this,this.input)}withFaceDescriptor(){return new Ra(this,this.input)}}class wk extends Ai{constructor(r,l,u){super();this.parentTask=r;this.input=l;this.extractedFaces=u}}class dd extends wk{async run(){const r=await this.parentTask,l=await Na(r,this.input,async u=>await Promise.all(u.map(d=>yt.ageGenderNet.predictAgeAndGender(d))),this.extractedFaces);return r.map((u,d)=>{const{age:f,gender:g,genderProbability:I}=l[d];return Qg(ey(u,g,I),f)})}withFaceExpressions(){return new md(this,this.input)}}class pd extends wk{async run(){const r=await this.parentTask;if(!r)return;const{age:l,gender:u,genderProbability:d}=await fl(r,this.input,f=>yt.ageGenderNet.predictAgeAndGender(f),this.extractedFaces);return Qg(ey(r,u,d),l)}withFaceExpressions(){return new fd(this,this.input)}}class gl extends dd{withFaceExpressions(){return new bl(this,this.input)}withFaceDescriptors(){return new Ca(this,this.input)}}class yl extends pd{withFaceExpressions(){return new wl(this,this.input)}withFaceDescriptor(){return new Ra(this,this.input)}}class Vx extends Ai{constructor(r,l){super();this.parentTask=r;this.input=l}}class Ca extends Vx{async run(){const r=await this.parentTask,l=await Na(r,this.input,u=>Promise.all(u.map(d=>yt.faceRecognitionNet.computeFaceDescriptor(d))),null,u=>u.landmarks.align(null,{useDlibAlignment:!0}));return l.map((u,d)=>Zg(r[d],u))}withFaceExpressions(){return new bl(this,this.input)}withAgeAndGender(){return new gl(this,this.input)}}class Ra extends Vx{async run(){const r=await this.parentTask;if(!r)return;const l=await fl(r,this.input,u=>yt.faceRecognitionNet.computeFaceDescriptor(u),null,u=>u.landmarks.align(null,{useDlibAlignment:!0}));return Zg(r,l)}withFaceExpressions(){return new wl(this,this.input)}withAgeAndGender(){return new yl(this,this.input)}}const gd=He(Ze());class Gx extends Ai{constructor(r,l,u){super();this.parentTask=r;this.input=l;this.useTinyLandmarkNet=u}get landmarkNet(){return this.useTinyLandmarkNet?yt.faceLandmark68TinyNet:yt.faceLandmark68Net}}class Yx extends Gx{async run(){const r=await this.parentTask,l=r.map(f=>f.detection),u=this.input instanceof gd.Tensor?await sl(this.input,l):await nl(this.input,l),d=await Promise.all(u.map(f=>this.landmarkNet.detectLandmarks(f)));return u.forEach(f=>f instanceof gd.Tensor&&f.dispose()),r.map((f,g)=>hl(f,d[g]))}withFaceExpressions(){return new bl(this,this.input)}withAgeAndGender(){return new gl(this,this.input)}withFaceDescriptors(){return new Ca(this,this.input)}}class Hx extends Gx{async run(){const r=await this.parentTask;if(!r)return;const{detection:l}=r,u=this.input instanceof gd.Tensor?await sl(this.input,[l]):await nl(this.input,[l]),d=await this.landmarkNet.detectLandmarks(u[0]);return u.forEach(f=>f instanceof gd.Tensor&&f.dispose()),hl(r,d)}withFaceExpressions(){return new wl(this,this.input)}withAgeAndGender(){return new yl(this,this.input)}withFaceDescriptor(){return new Ra(this,this.input)}}class qx extends Ai{constructor(r,l=new xi){super();this.input=r;this.options=l}}class ny extends qx{async run(){const{input:r,options:l}=this,u=l instanceof Px?d=>yt.tinyFaceDetector.locateFaces(d,l):l instanceof xi?d=>yt.ssdMobilenetv1.locateFaces(d,l):l instanceof Fr?d=>yt.tinyYolov2.locateFaces(d,l):null;if(!u)throw new Error("detectFaces - expected options to be instance of TinyFaceDetectorOptions | SsdMobilenetv1Options | MtcnnOptions | TinyYolov2Options");return u(r)}runAndExtendWithFaceDetections(){return new Promise(async r=>{const l=await this.run();return r(l.map(u=>ha({},u)))})}withFaceLandmarks(r=!1){return new Yx(this.runAndExtendWithFaceDetections(),this.input,r)}withFaceExpressions(){return new md(this.runAndExtendWithFaceDetections(),this.input)}withAgeAndGender(){return new dd(this.runAndExtendWithFaceDetections(),this.input)}}class jx extends qx{async run(){const r=await new ny(this.input,this.options);let l=r[0];return r.forEach(u=>{u.score>l.score&&(l=u)}),l}runAndExtendWithFaceDetection(){return new Promise(async r=>{const l=await this.run();return r(l?ha({},l):void 0)})}withFaceLandmarks(r=!1){return new Hx(this.runAndExtendWithFaceDetection(),this.input,r)}withFaceExpressions(){return new fd(this.runAndExtendWithFaceDetection(),this.input)}withAgeAndGender(){return new pd(this.runAndExtendWithFaceDetection(),this.input)}}function ite(r,l=new xi){return new jx(r,l)}function sy(r,l=new xi){return new ny(r,l)}async function Lk(r,l){return console.warn("allFacesSsdMobilenetv1 is deprecated and will be removed soon, use the high level api instead"),await sy(r,new xi(l?{minConfidence:l}:{})).withFaceLandmarks().withFaceDescriptors()}async function rte(r,l={}){return console.warn("allFacesTinyYolov2 is deprecated and will be removed soon, use the high level api instead"),await sy(r,new Fr(l)).withFaceLandmarks().withFaceDescriptors()}const ote=Lk;function Kx(r,l){if(r.length!==l.length)throw new Error("euclideanDistance: arr1.length !== arr2.length");const u=Array.from(r),d=Array.from(l);return Math.sqrt(u.map((f,g)=>f-d[g]).reduce((f,g)=>f+Math.pow(g,2),0))}class Sk{constructor(r,l=.6){this._distanceThreshold=l;const u=Array.isArray(r)?r:[r];if(!u.length)throw new Error("FaceRecognizer.constructor - expected atleast one input");let d=1;const f=()=>`person ${d++}`;this._labeledDescriptors=u.map(g=>{if(g instanceof la)return g;if(g instanceof Float32Array)return new la(f(),[g]);if(g.descriptor&&g.descriptor instanceof Float32Array)return new la(f(),[g.descriptor]);throw new Error("FaceRecognizer.constructor - expected inputs to be of type LabeledFaceDescriptors | WithFaceDescriptor<any> | Float32Array | Array<LabeledFaceDescriptors | WithFaceDescriptor<any> | Float32Array>")})}get labeledDescriptors(){return this._labeledDescriptors}get distanceThreshold(){return this._distanceThreshold}computeMeanDistance(r,l){return l.map(u=>Kx(u,r)).reduce((u,d)=>u+d,0)/(l.length||1)}matchDescriptor(r){return this.labeledDescriptors.map(({descriptors:l,label:u})=>new uf(u,this.computeMeanDistance(r,l))).reduce((l,u)=>l.distance<u.distance?l:u)}findBestMatch(r){const l=this.matchDescriptor(r);return l.distance<this.distanceThreshold?l:new uf("unknown",l.distance)}toJSON(){return{distanceThreshold:this.distanceThreshold,labeledDescriptors:this.labeledDescriptors.map(r=>r.toJSON())}}static fromJSON(r){const l=r.labeledDescriptors.map(u=>la.fromJSON(u));return new Sk(l,r.distanceThreshold)}}function ate(r){const l=new ud;return l.extractWeights(r),l}function Ik(r,l){const{width:u,height:d}=new ys(l.width,l.height);if(u<=0||d<=0)throw new Error(`resizeResults - invalid dimensions: ${JSON.stringify({width:u,height:d})}`);if(Array.isArray(r))return r.map(f=>Ik(f,{width:u,height:d}));if(Aa(r)){const f=r.detection.forSize(u,d),g=r.unshiftedLandmarks.forSize(f.box.width,f.box.height);return hl(ha(r,f),g)}return Vi(r)?ha(r,r.detection.forSize(u,d)):r instanceof js||r instanceof Jt?r.forSize(u,d):r}var xk="0.8.6";$c(exports,{AgeGenderNet:()=>Fx,BoundingBox:()=>Fu,Box:()=>_t,ComposableTask:()=>Ai,ComputeAllFaceDescriptorsTask:()=>Ca,ComputeFaceDescriptorsTaskBase:()=>Vx,ComputeSingleFaceDescriptorTask:()=>Ra,DetectAllFaceLandmarksTask:()=>Yx,DetectAllFacesTask:()=>ny,DetectFaceLandmarksTaskBase:()=>Gx,DetectFacesTaskBase:()=>qx,DetectSingleFaceLandmarksTask:()=>Hx,DetectSingleFaceTask:()=>jx,Dimensions:()=>ys,FACE_EXPRESSION_LABELS:()=>Rx,FaceDetection:()=>Jt,FaceDetectionNet:()=>Uee,FaceExpressionNet:()=>Ox,FaceExpressions:()=>Ta,FaceLandmark68Net:()=>rd,FaceLandmark68TinyNet:()=>_x,FaceLandmarkNet:()=>xee,FaceLandmarks:()=>js,FaceLandmarks5:()=>A9,FaceLandmarks68:()=>$u,FaceMatch:()=>uf,FaceMatcher:()=>Sk,FaceRecognitionNet:()=>ad,Gender:()=>Or,LabeledBox:()=>df,LabeledFaceDescriptors:()=>la,NetInput:()=>Io,NeuralNetwork:()=>Un,ObjectDetection:()=>Pc,Point:()=>Qe,PredictedBox:()=>v9,Rect:()=>Wu,SsdMobilenetv1:()=>dl,SsdMobilenetv1Options:()=>xi,TinyFaceDetector:()=>ud,TinyFaceDetectorOptions:()=>Px,TinyYolov2:()=>hd,TinyYolov2Options:()=>Fr,TinyYolov2SizeType:()=>Mx,allFaces:()=>ote,allFacesSsdMobilenetv1:()=>Lk,allFacesTinyYolov2:()=>rte,awaitMediaLoaded:()=>SI,bufferToImage:()=>II,computeFaceDescriptor:()=>Yee,createCanvas:()=>Vc,createCanvasFromMedia:()=>Bu,createFaceDetectionNet:()=>$ee,createFaceRecognitionNet:()=>vee,createSsdMobilenetv1:()=>sk,createTinyFaceDetector:()=>ate,createTinyYolov2:()=>Pee,detectAllFaces:()=>sy,detectFaceLandmarks:()=>gk,detectFaceLandmarksTiny:()=>Gee,detectLandmarks:()=>ste,detectSingleFace:()=>ite,draw:()=>Dx,env:()=>St,euclideanDistance:()=>Kx,extendWithAge:()=>Qg,extendWithFaceDescriptor:()=>Zg,extendWithFaceDetection:()=>ha,extendWithFaceExpressions:()=>jg,extendWithFaceLandmarks:()=>hl,extendWithGender:()=>ey,extractFaceTensors:()=>sl,extractFaces:()=>nl,fetchImage:()=>fee,fetchJson:()=>vx,fetchNetWeights:()=>gee,fetchOrThrow:()=>Ia,getContext2dOrThrow:()=>as,getMediaDimensions:()=>da,imageTensorToCanvas:()=>xI,imageToSquare:()=>Ax,inverseSigmoid:()=>S9,iou:()=>hI,isMediaElement:()=>gf,isMediaLoaded:()=>Uu,isWithAge:()=>Nee,isWithFaceDetection:()=>Vi,isWithFaceExpressions:()=>Ex,isWithFaceLandmarks:()=>Aa,isWithGender:()=>Cee,loadAgeGenderModel:()=>ete,loadFaceDetectionModel:()=>tte,loadFaceExpressionModel:()=>Qee,loadFaceLandmarkModel:()=>Xee,loadFaceLandmarkTinyModel:()=>Jee,loadFaceRecognitionModel:()=>Zee,loadSsdMobilenetv1Model:()=>yk,loadTinyFaceDetectorModel:()=>jee,loadTinyYolov2Model:()=>Kee,loadWeightMap:()=>Nx,locateFaces:()=>nte,matchDimensions:()=>yee,minBbox:()=>uI,nets:()=>yt,nonMaxSuppression:()=>dI,normalize:()=>yi,padToSquare:()=>pI,predictAgeAndGender:()=>qee,recognizeFaceExpressions:()=>Hee,resizeResults:()=>Ik,resolveInput:()=>ua,shuffleArray:()=>L9,sigmoid:()=>_u,ssdMobilenetv1:()=>fk,tf:()=>cte,tinyFaceDetector:()=>zee,tinyYolov2:()=>Vee,toNetInput:()=>Wt,utils:()=>oI,validateConfig:()=>Ux,version:()=>ute});const cte=He(Ze()),lte=typeof process!="undefined",hte=typeof navigator!="undefined"&&typeof navigator.userAgent!="undefined",ute={faceapi:xk,node:lte,browser:hte};
/**
* @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.node.js.map