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

3982 lines
1.1 MiB

var Nm=Object.defineProperty,gX=Object.prototype.hasOwnProperty,CS=(r,l)=>()=>(l||(l={exports:{}},r(l.exports,l)),l.exports),jC=r=>Nm(r,"__esModule",{value:!0}),vc=(r,l)=>{jC(r);for(var h in l)Nm(r,h,{get:l[h],enumerable:!0})},yX=(r,l)=>{if(jC(r),typeof l=="object"||typeof l=="function")for(let h in l)!gX.call(r,h)&&h!=="default"&&Nm(r,h,{get:()=>l[h],enumerable:!0});return r},Ye=r=>r&&r.__esModule?r:yX(Nm({},"default",{value:r,enumerable:!0}),r);var i2=CS(bX=>{vc(bX,{FetchError:()=>Mn,Headers:()=>fi,Request:()=>Zo,Response:()=>Pi,default:()=>OX});const Ys=Ye(require("stream")),RS=Ye(require("http")),Cm=Ye(require("url")),KC=Ye(require("https")),no=Ye(require("zlib")),wX=Ys.default.Readable,pr=Symbol("buffer"),OS=Symbol("type");class fu{constructor(){this[OS]="";const r=arguments[0],l=arguments[1],h=[];let d=0;if(r){const g=r,S=Number(g.length);for(let L=0;L<S;L++){const x=g[L];let A;x instanceof Buffer?A=x:ArrayBuffer.isView(x)?A=Buffer.from(x.buffer,x.byteOffset,x.byteLength):x instanceof ArrayBuffer?A=Buffer.from(x):x instanceof fu?A=x[pr]:A=Buffer.from(typeof x=="string"?x:String(x)),d+=A.length,h.push(A)}}this[pr]=Buffer.concat(h);let f=l&&l.type!==void 0&&String(l.type).toLowerCase();f&&!/[^\u0020-\u007E]/.test(f)&&(this[OS]=f)}get size(){return this[pr].length}get type(){return this[OS]}text(){return Promise.resolve(this[pr].toString())}arrayBuffer(){const r=this[pr],l=r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength);return Promise.resolve(l)}stream(){const r=new wX;return r._read=function(){},r.push(this[pr]),r.push(null),r}toString(){return"[object Blob]"}slice(){const r=this.size,l=arguments[0],h=arguments[1];let d,f;l===void 0?d=0:l<0?d=Math.max(r+l,0):d=Math.min(l,r),h===void 0?f=r:h<0?f=Math.max(r+h,0):f=Math.min(h,r);const g=Math.max(f-d,0),S=this[pr],L=S.slice(d,d+g),x=new fu([],{type:arguments[2]});return x[pr]=L,x}}Object.defineProperties(fu.prototype,{size:{enumerable:!0},type:{enumerable:!0},slice:{enumerable:!0}});Object.defineProperty(fu.prototype,Symbol.toStringTag,{value:"Blob",writable:!1,enumerable:!1,configurable:!0});function Mn(r,l,h){Error.call(this,r),this.message=r,this.type=l,h&&(this.code=this.errno=h.code),Error.captureStackTrace(this,this.constructor)}Mn.prototype=Object.create(Error.prototype);Mn.prototype.constructor=Mn;Mn.prototype.name="FetchError";let ES;try{ES=require("encoding").convert}catch(r){}const mr=Symbol("Body internals"),XC=Ys.default.PassThrough;function xn(r){var l=this,h=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},d=h.size;let f=d===void 0?0:d;var g=h.timeout;let S=g===void 0?0:g;r==null?r=null:JC(r)?r=Buffer.from(r.toString()):gu(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 Ys.default||(r=Buffer.from(String(r))))),this[mr]={body:r,disturbed:!1,error:null},this.size=f,this.timeout=S,r instanceof Ys.default&&r.on("error",function(L){const x=L.name==="AbortError"?L:new Mn(`Invalid response body while trying to fetch ${l.url}: ${L.message}`,"system",L);l[mr].error=x})}xn.prototype={get body(){return this[mr].body},get bodyUsed(){return this[mr].disturbed},arrayBuffer(){return Nc.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 Nc.call(this).then(function(l){return Object.assign(new fu([],{type:r.toLowerCase()}),{[pr]:l})})},json(){var r=this;return Nc.call(this).then(function(l){try{return JSON.parse(l.toString())}catch(h){return xn.Promise.reject(new Mn(`invalid json response body at ${r.url} reason: ${h.message}`,"invalid-json"))}})},text(){return Nc.call(this).then(function(r){return r.toString()})},buffer(){return Nc.call(this)},textConverted(){var r=this;return Nc.call(this).then(function(l){return LX(l,r.headers)})}};Object.defineProperties(xn.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0}});xn.mixIn=function(r){for(const l of Object.getOwnPropertyNames(xn.prototype))if(!(l in r)){const h=Object.getOwnPropertyDescriptor(xn.prototype,l);Object.defineProperty(r,l,h)}};function Nc(){var r=this;if(this[mr].disturbed)return xn.Promise.reject(new TypeError(`body used already for: ${this.url}`));if(this[mr].disturbed=!0,this[mr].error)return xn.Promise.reject(this[mr].error);let l=this.body;if(l===null)return xn.Promise.resolve(Buffer.alloc(0));if(gu(l)&&(l=l.stream()),Buffer.isBuffer(l))return xn.Promise.resolve(l);if(!(l instanceof Ys.default))return xn.Promise.resolve(Buffer.alloc(0));let h=[],d=0,f=!1;return new xn.Promise(function(g,S){let L;r.timeout&&(L=setTimeout(function(){f=!0,S(new Mn(`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,S(x)):S(new Mn(`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,S(new Mn(`content size at ${r.url} over limit: ${r.size}`,"max-size"));return}d+=x.length,h.push(x)}),l.on("end",function(){if(f)return;clearTimeout(L);try{g(Buffer.concat(h,d))}catch(x){S(new Mn(`Could not create Buffer from response body for ${r.url}: ${x.message}`,"system",x))}})})}function LX(r,l){if(typeof ES!="function")throw new Error("The package `encoding` must be installed to use the textConverted() function");const h=l.get("content-type");let d="utf-8",f,g;return h&&(f=/charset=([^;]*)/i.exec(h)),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")),ES(r,"UTF-8",d).toString()}function JC(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 gu(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 ZC(r){let l,h,d=r.body;if(r.bodyUsed)throw new Error("cannot clone body after it is used");return d instanceof Ys.default&&typeof d.getBoundary!="function"&&(l=new XC,h=new XC,d.pipe(l),d.pipe(h),r[mr].body=l,d=h),d}function QC(r){return r===null?null:typeof r=="string"?"text/plain;charset=UTF-8":JC(r)?"application/x-www-form-urlencoded;charset=UTF-8":gu(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 Ys.default?null:"text/plain;charset=UTF-8"}function e2(r){const l=r.body;return l===null?0:gu(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 SX(r,l){const h=l.body;h===null?r.end():gu(h)?h.stream().pipe(r):Buffer.isBuffer(h)?(r.write(h),r.end()):h.pipe(r)}xn.Promise=global.Promise;const t2=/[^\^_`a-zA-Z\-0-9!#$%&'*+.|~]/,DS=/[^\t\x20-\x7e\x80-\xff]/;function yu(r){if(r=`${r}`,t2.test(r)||r==="")throw new TypeError(`${r} is not a legal HTTP header name`)}function n2(r){if(r=`${r}`,DS.test(r))throw new TypeError(`${r} is not a legal HTTP header value`)}function Cc(r,l){l=l.toLowerCase();for(const h in r)if(h.toLowerCase()===l)return h;return}const nn=Symbol("map");class fi{constructor(){let r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:void 0;if(this[nn]=Object.create(null),r instanceof fi){const l=r.raw(),h=Object.keys(l);for(const d of h)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 h=[];for(const d of r){if(typeof d!="object"||typeof d[Symbol.iterator]!="function")throw new TypeError("Each header pair must be iterable");h.push(Array.from(d))}for(const d of h){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 h of Object.keys(r)){const d=r[h];this.append(h,d)}}else throw new TypeError("Provided initializer must be an object")}get(r){r=`${r}`,yu(r);const l=Cc(this[nn],r);return l===void 0?null:this[nn][l].join(", ")}forEach(r){let l=arguments.length>1&&arguments[1]!==void 0?arguments[1]:void 0,h=kS(this),d=0;for(;d<h.length;){var f=h[d];const g=f[0],S=f[1];r.call(l,S,g,this),h=kS(this),d++}}set(r,l){r=`${r}`,l=`${l}`,yu(r),n2(l);const h=Cc(this[nn],r);this[nn][h!==void 0?h:r]=[l]}append(r,l){r=`${r}`,l=`${l}`,yu(r),n2(l);const h=Cc(this[nn],r);h!==void 0?this[nn][h].push(l):this[nn][r]=[l]}has(r){return r=`${r}`,yu(r),Cc(this[nn],r)!==void 0}delete(r){r=`${r}`,yu(r);const l=Cc(this[nn],r);l!==void 0&&delete this[nn][l]}raw(){return this[nn]}keys(){return FS(this,"key")}values(){return FS(this,"value")}[Symbol.iterator](){return FS(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 kS(r){let l=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"key+value";const h=Object.keys(r[nn]).sort();return h.map(l==="key"?function(d){return d.toLowerCase()}:l==="value"?function(d){return r[nn][d].join(", ")}:function(d){return[d.toLowerCase(),r[nn][d].join(", ")]})}const _S=Symbol("internal");function FS(r,l){const h=Object.create(WS);return h[_S]={target:r,kind:l,index:0},h}const WS=Object.setPrototypeOf({next(){if(!this||Object.getPrototypeOf(this)!==WS)throw new TypeError("Value of `this` is not a HeadersIterator");var r=this[_S];const l=r.target,h=r.kind,d=r.index,f=kS(l,h),g=f.length;return d>=g?{value:void 0,done:!0}:(this[_S].index=d+1,{value:f[d],done:!1})}},Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())));Object.defineProperty(WS,Symbol.toStringTag,{value:"HeadersIterator",writable:!1,enumerable:!1,configurable:!0});function IX(r){const l=Object.assign({__proto__:null},r[nn]),h=Cc(r[nn],"Host");return h!==void 0&&(l[h]=l[h][0]),l}function xX(r){const l=new fi;for(const h of Object.keys(r)){if(t2.test(h))continue;if(Array.isArray(r[h]))for(const d of r[h]){if(DS.test(d))continue;l[nn][h]===void 0?l[nn][h]=[d]:l[nn][h].push(d)}else DS.test(r[h])||(l[nn][h]=[r[h]])}return l}const so=Symbol("Response internals"),TX=RS.default.STATUS_CODES;class Pi{constructor(){let r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:null,l=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};xn.call(this,r,l);const h=l.status||200,d=new fi(l.headers);if(r!=null&&!d.has("Content-Type")){const f=QC(r);f&&d.append("Content-Type",f)}this[so]={url:l.url,status:h,statusText:l.statusText||TX[h],headers:d,counter:l.counter}}get url(){return this[so].url||""}get status(){return this[so].status}get ok(){return this[so].status>=200&&this[so].status<300}get redirected(){return this[so].counter>0}get statusText(){return this[so].statusText}get headers(){return this[so].headers}clone(){return new Pi(ZC(this),{url:this.url,status:this.status,statusText:this.statusText,headers:this.headers,ok:this.ok,redirected:this.redirected})}}xn.mixIn(Pi.prototype);Object.defineProperties(Pi.prototype,{url:{enumerable:!0},status:{enumerable:!0},ok:{enumerable:!0},redirected:{enumerable:!0},statusText:{enumerable:!0},headers:{enumerable:!0},clone:{enumerable:!0}});Object.defineProperty(Pi.prototype,Symbol.toStringTag,{value:"Response",writable:!1,enumerable:!1,configurable:!0});const fr=Symbol("Request internals"),$S=Cm.default.parse,AX=Cm.default.format,vX="destroy"in Ys.default.Readable.prototype;function Rm(r){return typeof r=="object"&&typeof r[fr]=="object"}function NX(r){const l=r&&typeof r=="object"&&Object.getPrototypeOf(r);return!!(l&&l.constructor.name==="AbortSignal")}class Zo{constructor(r){let l=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},h;Rm(r)?h=$S(r.url):(r&&r.href?h=$S(r.href):h=$S(`${r}`),r={});let d=l.method||r.method||"GET";if(d=d.toUpperCase(),(l.body!=null||Rm(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:Rm(r)&&r.body!==null?ZC(r):null;xn.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 L=QC(f);L&&g.append("Content-Type",L)}let S=Rm(r)?r.signal:null;if("signal"in l&&(S=l.signal),S!=null&&!NX(S))throw new TypeError("Expected signal to be an instanceof AbortSignal");this[fr]={method:d,redirect:l.redirect||r.redirect||"follow",headers:g,parsedURL:h,signal:S},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[fr].method}get url(){return AX(this[fr].parsedURL)}get headers(){return this[fr].headers}get redirect(){return this[fr].redirect}get signal(){return this[fr].signal}clone(){return new Zo(this)}}xn.mixIn(Zo.prototype);Object.defineProperty(Zo.prototype,Symbol.toStringTag,{value:"Request",writable:!1,enumerable:!1,configurable:!0});Object.defineProperties(Zo.prototype,{method:{enumerable:!0},url:{enumerable:!0},headers:{enumerable:!0},redirect:{enumerable:!0},clone:{enumerable:!0},signal:{enumerable:!0}});function CX(r){const l=r[fr].parsedURL,h=new fi(r[fr].headers);if(h.has("Accept")||h.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 Ys.default.Readable&&!vX)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=e2(r);typeof g=="number"&&(d=String(g))}d&&h.set("Content-Length",d),h.has("User-Agent")||h.set("User-Agent","node-fetch/1.0 (+https://github.com/bitinn/node-fetch)"),r.compress&&!h.has("Accept-Encoding")&&h.set("Accept-Encoding","gzip,deflate");let f=r.agent;return typeof f=="function"&&(f=f(l)),!h.has("Connection")&&!f&&h.set("Connection","close"),Object.assign({},l,{method:r.method,headers:IX(h),agent:f})}function bu(r){Error.call(this,r),this.type="aborted",this.message=r,Error.captureStackTrace(this,this.constructor)}bu.prototype=Object.create(Error.prototype);bu.prototype.constructor=bu;bu.prototype.name="AbortError";const s2=Ys.default.PassThrough,RX=Cm.default.resolve;function io(r,l){if(!io.Promise)throw new Error("native promise missing, set fetch.Promise to your favorite alternative");return xn.Promise=io.Promise,new io.Promise(function(h,d){const f=new Zo(r,l),g=CX(f),S=(g.protocol==="https:"?KC.default:RS.default).request,L=f.signal;let x=null;const A=function(){let te=new bu("The user aborted a request.");if(d(te),f.body&&f.body instanceof Ys.default.Readable&&f.body.destroy(te),!x||!x.body)return;x.body.emit("error",te)};if(L&&L.aborted){A();return}const O=function(){A(),z()},C=S(g);let $;L&&L.addEventListener("abort",O);function z(){C.abort(),L&&L.removeEventListener("abort",O),clearTimeout($)}f.timeout&&C.once("socket",function(ne){$=setTimeout(function(){d(new Mn(`network timeout at: ${f.url}`,"request-timeout")),z()},f.timeout)}),C.on("error",function(ne){d(new Mn(`request to ${f.url} failed, reason: ${ne.message}`,"system",ne)),z()}),C.on("response",function(ne){clearTimeout($);const te=xX(ne.headers);if(io.isRedirect(ne.statusCode)){const xe=te.get("Location"),Me=xe===null?null:RX(f.url,xe);switch(f.redirect){case"error":d(new Mn(`uri requested responds with a redirect, redirect mode is set to error: ${f.url}`,"no-redirect")),z();return;case"manual":if(Me!==null)try{te.set("Location",Me)}catch(wt){d(wt)}break;case"follow":if(Me===null)break;if(f.counter>=f.follow){d(new Mn(`maximum redirect reached at: ${f.url}`,"max-redirect")),z();return}const Ke={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&&e2(f)===null){d(new Mn("Cannot follow redirect with body being a readable stream","unsupported-redirect")),z();return}(ne.statusCode===303||(ne.statusCode===301||ne.statusCode===302)&&f.method==="POST")&&(Ke.method="GET",Ke.body=void 0,Ke.headers.delete("content-length")),h(io(new Zo(Me,Ke))),z();return}}ne.once("end",function(){L&&L.removeEventListener("abort",O)});let se=ne.pipe(new s2);const fe={url:f.url,status:ne.statusCode,statusText:ne.statusMessage,headers:te,size:f.size,timeout:f.timeout,counter:f.counter},de=te.get("Content-Encoding");if(!f.compress||f.method==="HEAD"||de===null||ne.statusCode===204||ne.statusCode===304){x=new Pi(se,fe),h(x);return}const Ae={flush:no.default.Z_SYNC_FLUSH,finishFlush:no.default.Z_SYNC_FLUSH};if(de=="gzip"||de=="x-gzip"){se=se.pipe(no.default.createGunzip(Ae)),x=new Pi(se,fe),h(x);return}if(de=="deflate"||de=="x-deflate"){const xe=ne.pipe(new s2);xe.once("data",function(Me){(Me[0]&15)===8?se=se.pipe(no.default.createInflate()):se=se.pipe(no.default.createInflateRaw()),x=new Pi(se,fe),h(x)});return}if(de=="br"&&typeof no.default.createBrotliDecompress=="function"){se=se.pipe(no.default.createBrotliDecompress()),x=new Pi(se,fe),h(x);return}x=new Pi(se,fe),h(x)}),SX(C,f)})}io.isRedirect=function(r){return r===301||r===302||r===303||r===307||r===308};io.Promise=global.Promise;var OX=io});var Je=CS((Om,r2)=>{(function(r,l){typeof Om=="object"&&typeof r2!="undefined"?l(Om):typeof define=="function"&&define.amd?define(["exports"],l):(r=r||self,l(r.tf=r.tf||{}))})(Om,function(r){"use strict";const l=1e-7,h=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:h}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`)}const S="tfjsflags";class L{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(t instanceof Promise)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=x(this.global.location.search);if(S in e){const t=e[S].split(",");t.forEach(n=>{const[s,i]=n.split(":");this.urlFlags[s]=O(s,i)})}}}function x(e){const t={};return e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(n,...s)=>(A(t,s[0],s[1]),s.join("="))),t}function A(e,t,n){e[decodeURIComponent(t)]=decodeURIComponent(n||"")}function O(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 C(){return r.ENV}r.ENV=null;function $(e){r.ENV=e}let z;function ne(){if(z==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");z=e}return z}function te(){const e=ne();return e._tfGlobals==null&&(e._tfGlobals=new Map),e._tfGlobals}function se(e,t){const n=te();if(n.has(e))return n.get(e);{const s=t();return n.set(e,s),n.get(e)}}const fe="Abs",de="Acos",Ae="Acosh",xe="Add",Me="AddN",Ke="All",wt="Any",$t="ArgMax",Kt="ArgMin",Fn="Asin",vn="Asinh",Nn="Atan",Qs="Atanh",Ai="Atan2",ei="AvgPool",xa="AvgPoolBackprop",hl="AvgPool3D",Cx="AvgPool3DBackprop",vg="BatchMatMul",Ng="BatchToSpaceND",Cg="BroadcastTo",ul="Cast",dl="Ceil",pl="ClipByValue",Rg="Complex",td="Concat",Og="Conv2D",Rx="Conv2DBackpropFilter",Eg="Conv2DBackpropInput",Dg="Conv3D",Ox="Conv3DBackpropFilterV2",Ex="Conv3DBackpropInputV2",Ta="Cos",ml="Cosh",kg="Cumsum",Dx="CropAndResize",kx="DepthToSpace",Fg="DepthwiseConv2dNative",Fx="DepthwiseConv2dNativeBackpropFilter",_x="DepthwiseConv2dNativeBackpropInput",Wx="Diag",nd="Dilation2D",sd="Dilation2DBackpropInput",id="Dilation2DBackpropFilter",Aa="Div",fl="Elu",$x="EluGrad",gl="Erf",Ux="Equal",yl="Exp",bl="Expm1",_g="FFT",Bx="Fill",rd="FlipLeftRight",wl="Floor",Wg="FloorDiv",Ll="FusedBatchNorm",$g="GatherV2",Mx="GatherNd",Px="Greater",Ug="GreaterEqual",Sl="Identity",Bg="IFFT",Mg="Imag",Il="IsFinite",xl="IsInf",Tl="IsNan",zx="Less",Gx="LessEqual",Vx="LinSpace",Al="Log",vl="Log1p",Hx="LogicalAnd",od="LogicalNot",Yx="LogicalOr",Pg="LogSoftmax",zg="LRN",qx="LRNBackprop",Nl="Max",Gg="Maximum",Cl="MaxPool",ad="MaxPoolBackprop",Vg="MaxPool3D",jx="MaxPool3DBackprop",cd="MaxPoolWithArgmax",VD="Mean",Hg="Min",Yg="Minimum",qg="Mod",Rl="Multiply",jg="Negate",ld="NotEqual",Kg="NonMaxSuppressionV3",hd="NonMaxSuppressionV4",ud="NonMaxSuppressionV5",Xg="OnesLike",Jg="OneHot",dd="PadV2",HD="Pool",Zg="Pow",Qg="Prelu",Kx="Prod",Xx="Range",ey="Real",Ol="Reciprocal",ty="Relu",El="Reshape",ny="ResizeNearestNeighbor",Jx="ResizeNearestNeighborGrad",sy="ResizeBilinear",Zx="ResizeBilinearGrad",iy="Relu6",ry="Reverse",Dl="Round",kl="Rsqrt",Qx="ScatterNd",oy="SelectV2",Fl="Selu",pd="Slice",va="Sin",_l="Sinh",Wl="Sign",$l="Sigmoid",Ul="Softplus",Bl="Sqrt",ay="Sum",md="SpaceToBatchND",cy="SplitV",ly="Softmax",Na="SquaredDifference",fd="Square",Ml="Sub",eT="SparseToDense",tT="StridedSlice",Ca="Tan",Pl="Tanh",hy="Tile",nT="TopK",zl="Transpose",gd="Unique",uy="Unpack",dy="UnsortedSegmentSum",py="ZerosLike",Gl="Step",yd="FromPixels",bd="RotateWithOffset",my="_FusedMatMul",fy="FusedConv2D",gy="FusedDepthwiseConv2D";const Ra=se("kernelRegistry",()=>new Map),Vl=se("gradRegistry",()=>new Map);function yy(e,t){const n=wy(e,t);return Ra.get(n)}function by(e){return Vl.get(e)}function wd(e){const t=Ra.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 Ld(e){const{kernelName:t,backendName:n}=e,s=wy(t,n);Ra.has(s)&&console.warn(`The kernel '${t}' for backend '${n}' is already registered`),Ra.set(s,e)}function sT(e){const{kernelName:t}=e;Vl.has(t)&&(C().getBool("DEBUG")&&console.warn(`Overriding the gradient for '${t}'`)),Vl.set(t,e)}function YD(e,t){const n=wy(e,t);if(!Ra.has(n))throw new Error(`The kernel '${e}' for backend '${t}' is not registered`);Ra.delete(n)}function qD(e){if(!Vl.has(e))throw new Error(`The gradient '${e}' for backend is not registered`);Vl.delete(e)}function jD(e,t){const n=wd(e);n.forEach(s=>{const i=Object.assign({},s,{backendName:t});Ld(i)})}function wy(e,t){return`${t}_${e}`}function Ly(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 Hl(e,t,n){return Math.max(e,Math.min(t,n))}function Sy(e){return e%2===0?e:e+1}function iT(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n];return t}function KD(e,t){const n=Math.random();return t*n+(1-n)*e}function XD(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 k(e,t){if(!e)throw new Error(typeof t=="string"?t:t())}function dt(e,t,n=""){k(ot(e,t),()=>n+` Shapes ${e} and ${t} must match`)}function wo(e){k(e!=null,()=>"The input to the tensor constructor must be a non-null value.")}function Ji(e,t=[],n=!1){if(t==null&&(t=[]),Array.isArray(e)||Ln(e)&&!n)for(let s=0;s<e.length;++s)Ji(e[s],t,n);else t.push(e);return t}function we(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 JD(e){return e.length===0}function ot(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 Ut(e){return e%1===0}function ZD(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 Sd(e){const t=Math.ceil(Math.sqrt(e));return[t,Math.ceil(e/t)]}function QD(e){const t=new Uint32Array(e);for(let n=0;n<e;++n)t[n]=n;return Ly(t),t}function Lo(e,t){return t<=e.length?e:e+" ".repeat(t-e.length)}function Iy(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 Id(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 ft(e,t){const n=t.length;return e=e==null?t.map((s,i)=>i):[].concat(e),k(e.every(s=>s>=-n&&s<n),()=>`All values in axis param must be in range [-${n}, ${n}) but got axis ${e}`),k(e.every(s=>Ut(s)),()=>`All values in axis param must be integers but got axis ${e}`),e.map(s=>s<0?n+s:s)}function Rr(e,t){const n=[],s=[],i=t!=null&&Array.isArray(t)&&t.length===0,o=t==null||i?null:ft(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 wn(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 So(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 rT(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 oT(e){return e==="bool"||e==="complex64"||e==="float32"||e==="int32"||e==="string"}function xy(e,t){return t==="complex64"||(t==="float32"&&e!=="complex64"||t==="int32"&&e!=="float32"&&e!=="complex64")?!1:!(t==="bool"&&e==="bool")}function Ln(e){return e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array}function Ty(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 aT(e){if(e==null)return 0;let t=0;return e.forEach(n=>t+=n.length),t}function Or(e){return typeof e=="string"||e instanceof String}function cT(e){return typeof e=="boolean"}function xd(e){return typeof e=="number"}function Oa(e){return Array.isArray(e)?Oa(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array?"int32":xd(e)?"float32":Or(e)?"string":cT(e)?"bool":"float32"}function Er(e){return!!(e&&e.constructor&&e.call&&e.apply)}function Td(e,t){for(let n=t;n<e;++n)if(e%n===0)return n;return e}function Ot(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 lT(e,t){return t==="string"?Cy(e):Dr([e],t)}function Dr(e,t){if(t==="string")throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=Ji(e)),C().getBool("DEBUG")&&rT(e,t),ek(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 hT(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,u)=>c*u);for(let c=0;c<i;c++)s[c]=hT(e+c*a,o,n)}return s}function Ls(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 hT(0,e,t)}function ek(e,t){return e instanceof Float32Array&&t==="float32"||e instanceof Int32Array&&t==="int32"||e instanceof Uint8Array&&t==="bool"}function Ay(e,t){const n=Ea(e,t);for(let s=0;s<n.length;s++)n[s]=1;return n}function Ea(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 vy(e,t){const n=e.reduce((s,i)=>s*i,1);if(t==null||t==="float32")return Ls(e,new Float32Array(n));if(t==="int32")return Ls(e,new Int32Array(n));if(t==="bool")return Ls(e,new Uint8Array(n));throw new Error(`Unknown data type ${t}`)}function qn(){return C().platform.now()}function Ny(e){e.forEach(t=>{k(Number.isInteger(t)&&t>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`)})}function uT(e,t){return C().platform.fetch(e,t)}function Cy(e,t="utf-8"){return t=t||"utf-8",C().platform.encode(e,t)}function Yl(e,t="utf-8"){return t=t||"utf-8",C().platform.decode(e,t)}function ti(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 Da(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}var tk=Object.freeze({__proto__:null,shuffle:Ly,clamp:Hl,nearestLargerEven:Sy,sum:iT,randUniform:KD,distSquared:XD,assert:k,assertShapesMatch:dt,assertNonNull:wo,flatten:Ji,sizeFromShape:we,isScalarShape:JD,arraysEqual:ot,isInt:Ut,tanh:ZD,sizeToSquarishShape:Sd,createShuffledIndices:QD,rightPad:Lo,repeatedTry:Iy,inferFromImplicitShape:Id,parseAxisParam:ft,squeezeShape:Rr,getTypedArrayFromDType:wn,getArrayFromDType:So,checkConversionForErrors:rT,isValidDtype:oT,hasEncodingLoss:xy,isTypedArray:Ln,bytesPerElement:Ty,bytesFromStringArray:aT,isString:Or,isBoolean:cT,isNumber:xd,inferDtype:Oa,isFunction:Er,nearestDivisor:Td,computeStrides:Ot,createScalarValue:lT,toTypedArray:Dr,toNestedArray:Ls,makeOnesTypedArray:Ay,makeZerosTypedArray:Ea,makeZerosNestedTypedArray:vy,now:qn,assertNonNegativeIntegerDimensions:Ny,fetch:uT,encodeString:Cy,decodeString:Yl,locToIndex:ti,indexToLoc:Da});class nk{constructor(e,t){this.backendTimer=e,this.logger=t,t==null&&(this.logger=new ik)}profileKernel(e,t,n){let s;const i=()=>{s=n()},o=this.backendTimer.time(i);for(let c=0;c<s.length;c++){const u=s[c];u.data().then(p=>{sk(p,u.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 sk(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 ik{logKernelProfile(e,t,n,s,i,o){const a=typeof s=="number"?Lo(`${s}ms`,9):s.error,c=Lo(e,25),u=t.rank,p=t.size,m=Lo(t.shape.toString(),14);let y="";for(const b in i){const w=i[b];if(w!=null){const I=w.shape||t.shape,T=I.length;y+=`${b}: ${T}D ${T>0?I:""} `}}console.log(`%c${c} %c${a} %c${u}D ${m} %c${p} %c${y} %c${o}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}}function rk(e,t,n){const s={},i={};for(let u=0;u<t.length;u++)s[t[u].id]=!0;for(let u=0;u<e.length;u++){const p=e[u],m=p.inputs;for(const y in m){const b=m[y];let w=!1;for(let I=0;I<t.length;I++)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 u=e.length-1;u>=0;u--){const p=e[u],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 u=0;u<e.length;u++){const p=e[u];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 ok(e,t,n,s){for(let i=t.length-1;i>=0;i--){const o=t[i],a=[];if(o.outputs.forEach(u=>{const p=e[u.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 u in o.inputs){if(!(u in c))throw new Error(`Cannot backprop through input ${u}. Available gradients found: ${Object.keys(c)}.`);const p=n(()=>c[u]());if(p.dtype!=="float32")throw new Error(`Error in gradient for op ${o.kernelName}. The gradient of input ${u} must have 'float32' dtype, but has '${p.dtype}'`);const m=o.inputs[u];if(!ot(p.shape,m.shape))throw new Error(`Error in gradient for op ${o.kernelName}. The gradient of input '${u}' 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 dT=20,ql=3,Ry=7;function ak(e,t,n,s){const i=Ot(t),o=ck(e,t,n,i),a=t.length,c=Ad(e,t,n,i,o),u=["Tensor"];return s&&(u.push(` dtype: ${n}`),u.push(` rank: ${a}`),u.push(` shape: [${t}]`),u.push(" values:")),u.push(c.map(p=>" "+p).join(`
`)),u.join(`
`)}function ck(e,t,n,s){const i=we(t),o=s[s.length-1],a=new Array(o).fill(0),c=t.length,u=n==="complex64"?Kl(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],jl(u[m+y],0,n).length)}return a}function jl(e,t,n){let s;return Array.isArray(e)?s=`${parseFloat(e[0].toFixed(Ry))} + ${parseFloat(e[1].toFixed(Ry))}j`:Or(e)?s=`'${e}'`:n==="bool"?s=pT(e):s=parseFloat(e.toFixed(Ry)).toString(),Lo(s,t)}function pT(e){return e===0?"false":"true"}function Ad(e,t,n,s,i,o=!0){const a=n==="complex64"?2:1,c=t[0],u=t.length;if(u===0){if(n==="complex64"){const T=Kl(e);return[jl(T[0],0,n)]}return n==="bool"?[pT(e[0])]:[e[0].toString()]}if(u===1){if(c>dT){const v=ql*a;let N=Array.from(e.slice(0,v)),E=Array.from(e.slice((c-ql)*a,c*a));return n==="complex64"&&(N=Kl(N),E=Kl(E)),["["+N.map((D,F)=>jl(D,i[F],n)).join(", ")+", ..., "+E.map((D,F)=>jl(D,i[c-ql+F],n)).join(", ")+"]"]}const T=n==="complex64"?Kl(e):Array.from(e);return["["+T.map((v,N)=>jl(v,i[N],n)).join(", ")+"]"]}const p=t.slice(1),m=s.slice(1),y=s[0]*a,b=[];if(c>dT){for(let T=0;T<ql;T++){const v=T*y,N=v+y;b.push(...Ad(e.slice(v,N),p,n,m,i,!1))}b.push("...");for(let T=c-ql;T<c;T++){const v=T*y,N=v+y;b.push(...Ad(e.slice(v,N),p,n,m,i,T===c-1))}}else for(let T=0;T<c;T++){const v=T*y,N=v+y;b.push(...Ad(e.slice(v,N),p,n,m,i,T===c-1))}const w=u===2?",":"";b[0]="["+b[0]+w;for(let T=1;T<b.length-1;T++)b[T]=" "+b[T]+w;let I=`,
`;for(let T=2;T<u;T++)I+=`
`;return b[b.length-1]=" "+b[b.length-1]+"]"+(o?"":I),b}function Kl(e){const t=[];for(let n=0;n<e.length;n+=2)t.push([e[n],e[n+1]]);return t}class kr{constructor(e,t,n){if(this.dtype=t,this.shape=e.slice(),this.size=we(e),n!=null){const s=n.length;k(s===this.size,()=>`Length of values '${s}' does not match the size inferred by the shape '${this.size}'.`)}if(t==="complex64")throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=n||So(t,this.size),this.strides=Ot(e)}set(e,...t){t.length===0&&(t=[0]),k(t.length===this.rank,()=>`The number of provided coordinates (${t.length}) must match the rank (${this.rank})`);const n=this.locToIndex(t);this.values[n]=e}get(...e){e.length===0&&(e=[0]);let t=0;for(const s of e){if(s<0||s>=this.shape[t]){const i=`Requested out of range element at ${e}. Buffer shape=${this.shape}`;throw new Error(i)}t++}let n=e[e.length-1];for(let s=0;s<e.length-1;++s)n+=this.strides[s]*e[s];return this.values[n]}locToIndex(e){if(this.rank===0)return 0;if(this.rank===1)return e[0];let t=e[e.length-1];for(let n=0;n<e.length-1;++n)t+=this.strides[n]*e[n];return t}indexToLoc(e){if(this.rank===0)return[];if(this.rank===1)return[e];const t=new Array(this.shape.length);for(let n=0;n<t.length-1;++n)t[n]=Math.floor(e/this.strides[n]),e-=t[n]*this.strides[n];return t[t.length-1]=e,t}get rank(){return this.shape.length}toTensor(){return vi().makeTensor(this.values,this.shape,this.dtype)}}let vi=null,ka=null,mT=null;function lk(e){vi=e}function hk(e){ka=e}function uk(e){mT=e}class Q{constructor(e,t,n,s){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=we(e),this.strides=Ot(e),this.dataId=n,this.id=s,this.rankType=this.rank<5?this.rank.toString():"higher"}get rank(){return this.shape.length}async buffer(){const e=await this.data();return ka.buffer(this.shape,this.dtype,e)}bufferSync(){return ka.buffer(this.shape,this.dtype,this.dataSync())}async array(){const e=await this.data();return Ls(this.shape,e)}arraySync(){return Ls(this.shape,this.dataSync())}async data(){this.throwIfDisposed();const e=vi().read(this.dataId);if(this.dtype==="string"){const t=await e;try{return t.map(n=>Yl(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=>Yl(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 ka.print(this,e)}clone(){return this.throwIfDisposed(),ka.clone(this)}toString(e=!1){const t=this.dataSync();return ak(t,this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),ka.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),vi().makeVariable(this,e,t,n)}}Object.defineProperty(Q,Symbol.hasInstance,{value:e=>!!e&&e.data!=null&&e.dataSync!=null&&e.throwIfDisposed!=null});class Xl extends Q{constructor(e,t,n,s){super(e.shape,e.dtype,e.dataId,s);this.trainable=t,this.name=n}assign(e){if(e.dtype!==this.dtype)throw new Error(`dtype of the new value (${e.dtype}) and previous value (${this.dtype}) must match`);if(!ot(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);vi().disposeTensor(this),this.dataId=e.dataId,vi().incRef(this,null)}dispose(){vi().disposeVariable(this),this.isDisposedInternal=!0}}Object.defineProperty(Xl,Symbol.hasInstance,{value:e=>e instanceof Q&&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 Oy;(function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"})(Oy||(Oy={}));var Ey;(function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"})(Ey||(Ey={}));var Dy;(function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"})(Dy||(Dy={}));var ky;(function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"})(ky||(ky={}));const dk={float32:Dy,int32:Oy,bool:Ey,complex64:ky};function Cn(e,t){if(e==="string"||t==="string"){if(e==="string"&&t==="string")return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return dk[e][t]}function vd(e){return Cn(e,"int32")}function Bt(e,t){if(e.dtype===t.dtype)return[e,t];const n=Cn(e.dtype,t.dtype);return[e.cast(n),t.cast(n)]}function fT(e,t){k(e.dtype===t.dtype,()=>`The dtypes of the first(${e.dtype}) and second(${t.dtype}) input must match`)}function Nd(e,t){return t.some(n=>n.id===e.id)}function Zi(e){const t=[],n=new Set;return gT(e,t,n),t}function gT(e,t,n){if(e==null)return;if(e instanceof Q){t.push(e);return}if(!pk(e))return;const s=e;for(const i in s){const o=s[i];n.has(o)||(n.add(o),gT(o,t,n))}}function pk(e){return Array.isArray(e)||typeof e=="object"}var mk=Object.freeze({__proto__:null,makeTypesMatch:Bt,assertTypesMatch:fT,isTensorInList:Nd,getTensorsInContainer:Zi});class yT{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 Jl{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new yT}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 nk(this.backendInstance),!0}setupRegisteredKernels(){const e=wd(this.backendName);e.forEach(t=>{t.setupFunc!=null&&t.setupFunc(this.backendInstance)})}disposeRegisteredKernels(e){const t=wd(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 Jl.nextTensorId++}nextVariableId(){return Jl.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},u={dtype:a};return V.runKernelFunc(p=>p.cast(o,a),c,null,ul,u)}}),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,u=[];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=yy(s,this.backendName);let I;if(w!=null)b=()=>{const v=this.backend.numDataIds();I=w.kernelFunc({inputs:t,attrs:i,backend:this.backend});const N=Array.isArray(I)?I:[I];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(s,v,N);const E=N.map(({dataId:D,shape:F,dtype:_})=>this.makeTensorFromDataId(D,F,_));if(p){let D=this.getTensorsForGradient(s,t,E);if(D==null){a==null&&(a=[]);const F=E.filter((_,B)=>a[B]);D=(o||[]).slice().concat(F)}u=this.saveTensorsForBackwardMode(D)}return E};else{const v=N=>{if(!p)return;u=N.map(E=>this.keep(this.clone(E)))};b=()=>{const N=this.backend.numDataIds();I=this.tidy(()=>e(this.backend,v));const E=Array.isArray(I)?I:[I];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(s,N,E),E}}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,u,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(I)?c:c[0]}saveTensorsForBackwardMode(e){const t=e.map(n=>this.keep(this.clone(n)));return t}getTensorsForGradient(e,t,n){const s=by(e);if(s!=null){const i=s.inputsToSave||[],o=s.outputsToSave||[];let a;s.saveAllInputs?(k(Array.isArray(t),()=>"saveAllInputs is true, expected inputs to be an array."),a=Object.keys(t).map(u=>t[u])):a=i.map(u=>t[u]);const c=n.filter((u,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"&&Or(e[0])&&(i=e.map(c=>Cy(c)));const o=s.write(i,t,n),a=new Q(t,n,o,this.nextTensorId());if(this.incRef(a,s),n==="string"){const c=this.state.tensorInfo.get(o),u=aT(i);this.state.numBytes+=u-c.bytes,c.bytes=u}return a}makeTensorFromDataId(e,t,n,s){n=n||"float32";const i=new Q(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 Xl(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*Ty(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 Xl||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=by(e);c!=null&&(s=c.gradFunc),s!=null&&(a.gradient=u=>(u=u.map((p,m)=>{if(p==null){const y=n[m],b=Ea(y.size,y.dtype);return this.makeTensor(b,y.shape,y.dtype)}return p}),s(u.length>1?u:u[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(k(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));k(i instanceof Q,()=>"The result y returned by f() must be a tensor.");const o=rk(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?fk(i.shape):n,ok(a,o,u=>this.tidy(u),gk);const c=t.map(u=>a[u.id]);return this.state.gradientDepth===0&&(this.state.activeTape.forEach(u=>{for(const p of u.saved)p.dispose()}),this.state.activeTape=null),{value:i,grads:c}})}customGrad(e){return k(Er(e),()=>"The f passed in customGrad(f) must be a function."),(...t)=>{k(t.every(i=>i instanceof Q),()=>"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),k(n.value instanceof Q,()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),k(Er(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];k(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(...)."),k(c.every(p=>p instanceof Q),()=>"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 u={};return c.forEach((p,m)=>{u[m]=()=>p}),u})}}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=qn(),n=await this.backend.time(e);return n.wallMs=qn()-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 yT;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}}Jl.nextTensorId=0,Jl.nextVariableId=0;function fk(e){const t=Ay(we(e),"float32");return V.makeTensor(t,e,"float32")}function bT(){const e=ne();if(e._tfengine==null){const t=new L(e);e._tfengine=new Jl(t)}return $(e._tfengine.ENV),lk(()=>e._tfengine),e._tfengine}const V=bT();function gk(e,t){const n={a:e,b:t};return V.runKernelFunc((s,i)=>{const o=s.add(e,t);return i([e,t]),o},n,null,xe)}function yk(){return typeof navigator!="undefined"&&navigator!=null}function wT(){if(yk()){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 Fy(){return typeof window!="undefined"&&window.document!=null||typeof WorkerGlobalScope!="undefined"}var bk=Object.freeze({__proto__:null,isMobile:wT,isBrowser:Fy});const Qi=C();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",()=>Fy()),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(Ln(e))return t==="string"?[]:[e.length];if(!Array.isArray(e))return[];const s=[];for(;Array.isArray(n)||Ln(n)&&t!=="string";)s.push(n.length),n=n[0];return Array.isArray(e)&&C().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&LT(e,s,[]),s}function LT(e,t,n){if(n=n||[],!Array.isArray(e)&&!Ln(e)){k(t.length===0,()=>`Element arr[${n.join("][")}] is a primitive, but should be an array/TypedArray of ${t[0]} elements`);return}k(t.length>0,()=>`Element arr[${n.join("][")}] should be a primitive, but is an array of ${e.length} elements`),k(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)LT(e[i],s,n.concat(i))}function ST(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 Q)return ST(s,e.dtype,t,n),e;let i=Oa(e);if(i!=="string"&&["bool","int32","float32"].indexOf(s)>=0&&(i=s),ST(s,i,t,n),e==null||!Ln(e)&&!Array.isArray(e)&&typeof e!="number"&&typeof e!="boolean"&&typeof e!="string"){const u=e==null?"null":e.constructor.name;throw new Error(`Argument '${t}' passed to '${n}' must be a Tensor or TensorLike, but got '${u}'`)}const o=Ni(e,i);!Ln(e)&&!Array.isArray(e)&&(e=[e]);const a=!0,c=i!=="string"?Dr(e,i):Ji(e,[],a);return V.makeTensor(c,o,i)}function Zl(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 IT="__op";function P(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+IT;const i=(...o)=>{V.startScope(n);try{const a=s(...o);return a instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),V.endScope(a),a}catch(a){throw V.endScope(null),a}};return Object.defineProperty(i,"name",{value:n,configurable:!0}),i}function wk(e,t){const n=W(e,"real","complex"),s=W(t,"imag","complex");dt(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 V.runKernelFunc(i,o,null,Rg)}const Ci=P({complex_:wk});function Fr(e,t,n,s){if(s==null&&(s=Oa(e)),s==="complex64")throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!Ln(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){Ny(t);const i=we(t),o=we(n);k(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],u=a===n.length-1?c!==we(t.slice(a)):!0;k(n[a]===t[a]||!u,()=>`Error creating a new Tensor. Inferred shape (${n}) does not match the provided shape (${t}). `)}}return!Ln(e)&&!Array.isArray(e)&&(e=[e]),t=t||n,e=s!=="string"?Dr(e,s):Ji(e,[],!0),V.makeTensor(e,t,s)}function en(e,t,n){const s=Ni(e,n);return Fr(e,t,s,n)}const _y={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8};const Cd=4;async function Wy(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],u=Array.isArray(e)?e[a].tensor:e[c];if(u.dtype!=="float32"&&u.dtype!=="int32"&&u.dtype!=="bool"&&u.dtype!=="string"&&u.dtype!=="complex64")throw new Error(`Unsupported dtype in weight '${c}': ${u.dtype}`);const p={name:c,shape:u.shape,dtype:u.dtype};if(u.dtype==="string"){const m=new Promise(async y=>{const b=await u.bytes(),w=b.reduce((v,N)=>v+N.length,0)+Cd*b.length,I=new Uint8Array(w);let T=0;for(let v=0;v<b.length;v++){const N=b[v],E=new Uint8Array(new Uint32Array([N.length]).buffer);I.set(E,T),T+=Cd,I.set(N,T),T+=N.length}y(I)});s.push(m)}else s.push(u.data());t!=null&&(p.group=t),n.push(p)}const o=await Promise.all(s);return{data:Lk(o),specs:n}}function Rd(e,t){const n={};let s,i=0;for(const o of t){const a=o.name,c=o.dtype,u=o.shape,p=we(u);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=_y[y.dtype],w=e.slice(i,i+p*b),I=y.dtype==="uint8"?new Uint8Array(w):new Uint16Array(w);if(c==="float32")if(y.dtype==="uint8"||y.dtype==="uint16"){m=new Float32Array(I.length);for(let T=0;T<I.length;T++){const v=I[T];m[T]=v*y.scale+y.min}}else if(y.dtype==="float16")s===void 0&&(s=vk()),m=s(I);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(I.length);for(let T=0;T<I.length;T++){const v=I[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=we(o.shape);m=[];for(let b=0;b<y;b++){const w=new Uint32Array(e.slice(i,i+Cd))[0];i+=Cd;const I=new Uint8Array(e.slice(i,i+w));m.push(I),i+=w}}else{const y=_y[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),I=new Float32Array(m.length/2);for(let N=0;N<w.length;N++)w[N]=m[N*2],I[N]=m[N*2+1];const T=en(w,u,"float32"),v=en(I,u,"float32");n[a]=Ci(T,v)}else throw new Error(`Unsupported dtype in weight '${a}': ${c}`);i+=p*y}c!=="complex64"&&(n[a]=en(m,u,c))}return n}function Lk(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 $y=typeof Buffer!="undefined"&&(typeof Blob=="undefined"||typeof atob=="undefined"||typeof btoa=="undefined");function xT(e){return $y?Buffer.byteLength(e):new Blob([e]).size}function Sk(e){if($y)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 Ik(e){if($y){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 Od(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 TT(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 Ql(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:xT(JSON.stringify(e.modelTopology)),weightSpecsBytes:e.weightSpecs==null?0:xT(JSON.stringify(e.weightSpecs)),weightDataBytes:e.weightData==null?0:e.weightData.byteLength}}function xk(){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 Tk(){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 Ak(){const e=new Uint32Array(64);for(let t=0;t<64;t++)e[t]=1024;return e[0]=e[32]=0,e}function vk(){const e=xk(),t=Tk(),n=Ak();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],u=e[n[c>>10]+(c&1023)]+t[c>>10];o[a]=u}return new Float32Array(i)}}class Xt{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return Xt.instance==null&&(Xt.instance=new Xt),Xt.instance}static registerSaveRouter(e){Xt.getInstance().saveRouters.push(e)}static registerLoadRouter(e){Xt.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return Xt.getHandlers(e,"save")}static getLoadHandlers(e,t){return Xt.getHandlers(e,"load",t)}static getHandlers(e,t,n){const s=[],i=t==="load"?Xt.getInstance().loadRouters:Xt.getInstance().saveRouters;return i.forEach(o=>{const a=o(e,n);a!==null&&s.push(a)}),s}}const Nk=e=>Xt.registerSaveRouter(e),Ck=e=>Xt.registerLoadRouter(e),Uy=e=>Xt.getSaveHandlers(e),By=(e,t)=>Xt.getLoadHandlers(e,t);const Ed="tensorflowjs",My=1,Io="models_store",_r="model_info_store";async function NQ(){const e=Py();return new Promise((t,n)=>{const s=e.deleteDatabase(Ed);s.onsuccess=()=>t(),s.onerror=i=>n(i)})}function Py(){if(!C().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 zy(e){const t=e.result;t.createObjectStore(Io,{keyPath:"modelPath"}),t.createObjectStore(_r,{keyPath:"modelPath"})}class xo{constructor(e){if(this.indexedDB=Py(),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(Ed,My);i.onupgradeneeded=()=>zy(i),i.onsuccess=()=>{const o=i.result;if(t==null){const a=o.transaction(Io,"readonly"),c=a.objectStore(Io),u=c.get(this.modelPath);u.onsuccess=()=>{if(u.result==null)return o.close(),s(new Error(`Cannot find model with path '${this.modelPath}' in IndexedDB.`));n(u.result.modelArtifacts)},u.onerror=p=>(o.close(),s(u.error)),a.oncomplete=()=>o.close()}else{const a=Ql(t),c=o.transaction(_r,"readwrite");let u=c.objectStore(_r);const p=u.put({modelPath:this.modelPath,modelArtifactsInfo:a});let m;p.onsuccess=()=>{m=o.transaction(Io,"readwrite");const y=m.objectStore(Io),b=y.put({modelPath:this.modelPath,modelArtifacts:t,modelArtifactsInfo:a});b.onsuccess=()=>n({modelArtifactsInfo:a}),b.onerror=w=>{u=c.objectStore(_r);const I=u.delete(this.modelPath);I.onsuccess=()=>(o.close(),s(b.error)),I.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)})}}xo.URL_SCHEME="indexeddb://";const AT=e=>C().getBool("IS_BROWSER")&&(!Array.isArray(e)&&e.startsWith(xo.URL_SCHEME))?Rk(e.slice(xo.URL_SCHEME.length)):null;Xt.registerSaveRouter(AT),Xt.registerLoadRouter(AT);function Rk(e){return new xo(e)}function Ok(e){return e.startsWith(xo.URL_SCHEME)?e.slice(xo.URL_SCHEME.length):e}class Ek{constructor(){this.indexedDB=Py()}async listModels(){return new Promise((e,t)=>{const n=this.indexedDB.open(Ed,My);n.onupgradeneeded=()=>zy(n),n.onsuccess=()=>{const s=n.result,i=s.transaction(_r,"readonly"),o=i.objectStore(_r),a=o.getAll();a.onsuccess=()=>{const c={};for(const u of a.result)c[u.modelPath]=u.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=Ok(e),new Promise((t,n)=>{const s=this.indexedDB.open(Ed,My);s.onupgradeneeded=()=>zy(s),s.onsuccess=()=>{const i=s.result,o=i.transaction(_r,"readwrite"),a=o.objectStore(_r),c=a.get(e);let u;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=()=>{u=i.transaction(Io,"readwrite");const y=u.objectStore(Io),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=()=>{u==null?i.close():u.oncomplete=()=>i.close()}},s.onerror=i=>n(s.error)})}}const Ri="/",To="tensorflowjs_models",vT="info",Dk="model_topology",kk="weight_specs",Fk="weight_data",_k="model_metadata";function CQ(){if(!C().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=To+Ri;if(s.startsWith(i)&&s.length>i.length){e.removeItem(s);const o=CT(s);t.indexOf(o)===-1&&t.push(o)}}return t}function NT(e){return{info:[To,e,vT].join(Ri),topology:[To,e,Dk].join(Ri),weightSpecs:[To,e,kk].join(Ri),weightData:[To,e,Fk].join(Ri),modelMetadata:[To,e,_k].join(Ri)}}function CT(e){const t=e.split(Ri);if(t.length<3)throw new Error(`Invalid key format: ${e}`);return t.slice(1,t.length-1).join(Ri)}function Wk(e){return e.startsWith(Ao.URL_SCHEME)?e.slice(Ao.URL_SCHEME.length):e}class Ao{constructor(e){if(!C().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=NT(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=Ql(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,Sk(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=Ik(o),t}}Ao.URL_SCHEME="localstorage://";const RT=e=>C().getBool("IS_BROWSER")&&(!Array.isArray(e)&&e.startsWith(Ao.URL_SCHEME))?$k(e.slice(Ao.URL_SCHEME.length)):null;Xt.registerSaveRouter(RT),Xt.registerLoadRouter(RT);function $k(e){return new Ao(e)}class Uk{constructor(){k(C().getBool("IS_BROWSER"),()=>"Current environment is not a web browser"),k(typeof window=="undefined"||typeof window.localStorage!="undefined",()=>"Current browser does not appear to support localStorage"),this.LS=window.localStorage}async listModels(){const e={},t=To+Ri,n=Ri+vT;for(let s=0;s<this.LS.length;++s){const i=this.LS.key(s);if(i.startsWith(t)&&i.endsWith(n)){const o=CT(i);e[o]=JSON.parse(this.LS.getItem(i))}}return e}async removeModel(e){e=Wk(e);const t=NT(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 Fa="://";class Ss{constructor(){this.managers={}}static getInstance(){return Ss.instance==null&&(Ss.instance=new Ss),Ss.instance}static registerManager(e,t){k(e!=null,()=>"scheme must not be undefined or null."),e.endsWith(Fa)&&(e=e.slice(0,e.indexOf(Fa))),k(e.length>0,()=>"scheme must not be an empty string.");const n=Ss.getInstance();k(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 Dd(e){if(e.indexOf(Fa)===-1)throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${Ss.getSchemes().join(",")}`);return{scheme:e.split(Fa)[0],path:e.split(Fa)[1]}}async function OT(e,t,n=!1){k(e!==t,()=>`Old path and new path are the same: '${e}'`);const s=Xt.getLoadHandlers(e);k(s.length>0,()=>`Copying failed because no load handler is found for source URL ${e}.`),k(s.length<2,()=>`Copying failed because more than one (${s.length}) load handlers for source URL ${e}.`);const i=s[0],o=Xt.getSaveHandlers(t);k(o.length>0,()=>`Copying failed because no save handler is found for destination URL ${t}.`),k(o.length<2,()=>`Copying failed because more than one (${s.length}) save handlers for destination URL ${t}.`);const a=o[0],c=Dd(e).scheme,u=Dd(e).path,p=c===Dd(e).scheme,m=await i.load();n&&p&&await Ss.getManager(c).removeModel(u);const y=await a.save(m);return n&&!p&&await Ss.getManager(c).removeModel(u),y.modelArtifactsInfo}async function Bk(){const e=Ss.getSchemes(),t={};for(const n of e){const s=await Ss.getManager(n).listModels();for(const i in s){const o=n+Fa+i;t[o]=s[i]}}return t}async function Mk(e){const t=Dd(e),n=Ss.getManager(t.scheme);return n.removeModel(t.path)}async function Pk(e,t){const n=!1;return OT(e,t,n)}async function zk(e,t){const n=!0;return OT(e,t,n)}class Gk{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(C().get("IS_BROWSER")){C().setPlatform("browser",new Gk);try{Ss.registerManager(Ao.URL_SCHEME,new Uk)}catch(e){}try{Ss.registerManager(xo.URL_SCHEME,new Ek)}catch(e){}}const Vk={importFetch:()=>i2()};let _a;function RQ(){_a=null}function OQ(e){_a=e}function EQ(){return _a}class Hk{constructor(){this.util=require("util"),this.textEncoder=new this.util.TextEncoder}fetch(e,t){return C().global.fetch!=null?C().global.fetch(e,t):(_a==null&&(_a=Vk.importFetch()),_a(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)}}C().get("IS_NODE")&&C().setPlatform("node",new Hk);function Qe(e,t="float32",n){return t=t||"float32",Ny(e),new kr(e,t,n)}function Yk(e,t){const n=W(e,"x","cast");if(!oT(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 V.runKernelFunc(o=>o.cast(n,t),s,null,ul,i)}const ve=P({cast_:Yk});function qk(e){const t=W(e,"x","clone",null),n=()=>V.makeTensorFromDataId(t.dataId,t.shape,t.dtype),s={x:t};return V.runKernelFunc(n,s,null,Sl)}const Wr=P({clone_:qk});function ET(e,t=!1){console.log(e.toString(t))}bT();const jk={buffer:Qe,cast:ve,clone:Wr,print:ET};hk(jk);const Kk="model",Xk=".json",Jk=".weights.bin";function DT(e){return new Promise(t=>setTimeout(t)).then(e)}class Wa{constructor(e){if(!C().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(Wa.URL_SCHEME)&&(e=e.slice(Wa.URL_SCHEME.length)),(e==null||e.length===0)&&(e=Kk),this.modelTopologyFileName=e+Xk,this.weightDataFileName=e+Jk}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 DT(()=>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 DT(()=>a.dispatchEvent(new MouseEvent("click")))}return{modelArtifactsInfo:Ql(e)}}}}Wa.URL_SCHEME="downloads://";class Zk{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 u=a.weightsManifest;if(u==null){s(new Error(`weightManifest field is missing from file ${e.name}`));return}let p;try{p=this.checkManifestAndWeightFiles(u,t)}catch(w){s(w);return}const m=[],y=[],b=[];u.forEach(w=>{w.paths.forEach(I=>{y.push(I),b.push(null)}),m.push(...w.weights)}),u.forEach(w=>{w.paths.forEach(I=>{const T=new FileReader;T.onload=v=>{const N=v.target.result,E=y.indexOf(I);b[E]=N,b.indexOf(null)===-1&&n({modelTopology:c,weightSpecs:m,weightData:Od(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 '${I}'.`),T.readAsArrayBuffer(p[I])})})},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=>TT(o.name)),i={};for(const o of e)o.paths.forEach(a=>{const c=TT(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 Qk=e=>C().getBool("IS_BROWSER")&&(!Array.isArray(e)&&e.startsWith(Wa.URL_SCHEME))?eF(e.slice(Wa.URL_SCHEME.length)):null;Xt.registerSaveRouter(Qk);function eF(e="model"){return new Wa(e)}function tF(e){return new Zk(e)}function kT(e,t,n,s){a(e),n=n==null?0:n,s=s==null?1:s,c(n,s);let i=0;const o=u=>(u.then(p=>{const m=n+ ++i/e.length*(s-n);return t(m),p}),u);function a(u){k(u!=null&&Array.isArray(u)&&u.length>0,()=>"promises must be a none empty array")}function c(u,p){k(u>=0&&u<=1,()=>`Progress fraction must be in range [0, 1], but got startFraction ${u}`),k(p>=0&&p<=1,()=>`Progress fraction must be in range [0, 1], but got endFraction ${p}`),k(p>=u,()=>`startFraction must be no more than endFraction, but got startFraction ${u} and endFraction ${p}`)}return Promise.all(e.map(o))}async function FT(e,t){t==null&&(t={});const n=t.fetchFunc==null?C().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 kT(s,t.onProgress,i,o),c=a.map(y=>y.arrayBuffer()),u=.5,p=1,m=t.onProgress==null?await Promise.all(c):await kT(c,t.onProgress,u,p);return m}async function _T(e,t="",n,s){const i=a=>FT(a,{requestInit:s}),o=WT(i);return o(e,t,n)}function WT(e){return async(t,n="",s)=>{const i=t.map(()=>!1),o={},a=s!=null?s.map(()=>!1):[],c=[];if(t.forEach((w,I)=>{let T=0;w.weights.forEach(v=>{const N="quantization"in v?v.quantization.dtype:v.dtype,E=_y[N]*we(v.shape),D=()=>{i[I]=!0,o[I]==null&&(o[I]=[]),o[I].push({manifestEntry:v,groupOffset:T,sizeBytes:E})};s!=null?s.forEach((F,_)=>{F===v.name&&(D(),a[_]=!0)}):D(),c.push(v.name),T+=E})}),!a.every(w=>w)){const w=s.filter((I,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 u=i.reduce((w,I,T)=>(I&&w.push(T),w),[]),p=[];u.forEach(w=>{t[w].paths.forEach(I=>{const T=n+(n.endsWith("/")?"":"/")+I;p.push(T)})});const m=await e(p),y={};let b=0;return u.forEach(w=>{const I=t[w].paths.length;let T=0;for(let F=0;F<I;F++)T+=m[b+F].byteLength;const v=new ArrayBuffer(T),N=new Uint8Array(v);let E=0;for(let F=0;F<I;F++){const _=new Uint8Array(m[b+F]);N.set(_,E),E+=_.byteLength}const D=o[w];D.forEach(F=>{const _=v.slice(F.groupOffset,F.groupOffset+F.sizeBytes),B=Rd(_,[F.manifestEntry]);for(const U in B)y[U]=B[U]}),b+=I}),y}}const nF="application/octet-stream",sF="application/json";class Gy{constructor(e,t){if(this.DEFAULT_METHOD="POST",t==null&&(t={}),this.weightPathPrefix=t.weightPathPrefix,this.onProgress=t.onProgress,this.weightUrlConverter=t.weightUrlConverter,t.fetchFunc!=null?(k(typeof t.fetchFunc=="function",()=>"Must pass a function that matches the signature of `fetch` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)"),this.fetch=t.fetchFunc):this.fetch=C().platform.fetch,k(e!=null&&e.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(e)&&k(e.length===2,()=>`URL paths for http must have a length of 2, (actual length is ${e.length}).`),this.path=e,t.requestInit!=null&&t.requestInit.body!=null)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=t.requestInit||{}}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");const t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit);t.body=new FormData;const n=[{paths:["./model.weights.bin"],weights:e.weightSpecs}],s={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,userDefinedMetadata:e.userDefinedMetadata,weightsManifest:n};t.body.append("model.json",new Blob([JSON.stringify(s)],{type:sF}),"model.json"),e.weightData!=null&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:nF}),"model.weights.bin");const i=await this.fetch(this.path,t);if(i.ok)return{modelArtifactsInfo:Ql(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 u,p;if(s!=null){const b=await this.loadWeights(s);[u,p]=b}const m={modelTopology:n,weightSpecs:u,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]=iF(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 u=await FT(a,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress});return[o,Od(u)]}}Gy.URL_SCHEME_REGEX=/^https?:\/\//;function iF(e){const t=e.lastIndexOf("/"),n=e.lastIndexOf("?"),s=e.substring(0,t),i=n>t?e.substring(n):"";return[s+"/",i]}function Vy(e){return e.match(Gy.URL_SCHEME_REGEX)!=null}const $T=(e,t)=>{if(typeof fetch=="undefined"&&(t==null||t.fetchFunc==null))return null;{let n=!0;if(Array.isArray(e)?n=e.every(s=>Vy(s)):n=Vy(e),n)return Hy(e,t)}return null};Xt.registerSaveRouter($T),Xt.registerLoadRouter($T);function Hy(e,t){return new Gy(e,t)}function kd(e,t){return Hy(e,t)}class Yy{constructor(e){this.modelArtifacts=e}async load(){return this.modelArtifacts}}class rF{constructor(e){this.saveHandler=e}async save(e){return this.saveHandler(e)}}function oF(e,t,n,s){if(arguments.length===1){const i=e.modelTopology!=null||e.weightSpecs!=null;return i?new Yy(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 Yy({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 Yy({modelTopology:e,weightSpecs:t,weightData:n,trainingConfig:s})}function aF(e){return new rF(e)}var cF=Object.freeze({__proto__:null,browserFiles:tF,browserHTTPRequest:kd,concatenateArrayBuffers:Od,decodeWeights:Rd,encodeWeights:Wy,fromMemory:oF,getLoadHandlers:By,getModelArtifactsInfoForJSON:Ql,getSaveHandlers:Uy,http:Hy,isHTTPScheme:Vy,loadWeights:_T,registerLoadRouter:Ck,registerSaveRouter:Nk,weightsLoaderFactory:WT,withSaveHandler:aF,copyModel:Pk,listModels:Bk,moveModel:zk,removeModel:Mk});function lF(e,t){const n=W(e,"x","reshape",null),s={x:n},i={shape:t},o=(a,c)=>(t=Id(t,n.size),k(n.size===we(t),()=>"new shape and old shape must have the same number of elements."),c([n]),a.reshape(n,t));return V.runKernelFunc(o,s,null,El,i)}const K=P({reshape_:lF});function hF(e,t,n=!1,s=!1){let i=W(e,"a","matMul"),o=W(t,"b","matMul");[i,o]=Bt(i,o),k(i.rank>=2&&o.rank>=2&&i.rank===o.rank,()=>`Error in matMul: inputs must have the same rank of at least 2, got ranks ${i.rank} and ${o.rank}.`);const a=n?i.shape[i.rank-2]:i.shape[i.rank-1],c=s?o.shape[o.rank-1]:o.shape[o.rank-2],u=n?i.shape[i.rank-1]:i.shape[i.rank-2],p=s?o.shape[o.rank-2]:o.shape[o.rank-1],m=i.shape.slice(0,-2),y=o.shape.slice(0,-2),b=we(m),w=we(y);k(ot(m,y),()=>`Error in matMul: outer dimensions (${m}) and (${y}) of Tensors with shapes ${i.shape} and ${o.shape} must match.`),k(a===c,()=>`Error in matMul: inner shapes (${a}) and (${c}) of Tensors with shapes ${i.shape} and ${o.shape} and transposeA=${n} and transposeB=${s} must match.`);const I=i.shape.slice(0,-2).concat([u,p]),T=n?K(i,[b,a,u]):K(i,[b,u,a]),v=s?K(o,[w,p,c]):K(o,[w,c,p]),N=(_,B)=>(B([T,v]),_.batchMatMul(T,v,n,s)),E={a:T,b:v},D={transposeA:n,transposeB:s},F=V.runKernelFunc(N,E,null,vg,D);return K(F,I)}const at=P({matMul_:hF});function uF(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},u={depth:t,onValue:n,offValue:s};return V.runKernelFunc(a,c,null,Jg,u)}const vo=P({oneHot_:uF});function dF(e,t){const n=W(e,"x","transpose");if(t==null&&(t=n.shape.map((o,a)=>a).reverse()),k(n.rank===t.length,()=>`Error in transpose: rank of input ${n.rank} must match length of perm ${t}.`),t.forEach(o=>{k(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 V.runKernelFunc(o=>o.transpose(n,t),s,null,zl,i)}const Pe=P({transpose_:dF});function pF(e,t,n){const s=W(e,"labels","confusionMatrix"),i=W(t,"predictions","confusionMatrix");k(n==null||n>0&&Number.isInteger(n),()=>`If provided, numClasses must be a positive integer, but got ${n}`),k(s.rank===1,()=>`Expected the rank of labels to be 1, but got ${s.rank}`),k(i.rank===1,()=>`Expected the rank of predictions to be 1, but got ${i.rank}`),k(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.`),k(n>0&&Number.isInteger(n),()=>`numClasses is required to be a positive integer, but got ${n}`);const o=vo(ve(s,"int32"),n),a=vo(ve(i,"int32"),n),c=Pe(o);return ve(at(c,a),"int32")}const mF=P({confusionMatrix_:pF});var fF=Object.freeze({__proto__:null,confusionMatrix:mF});function UT(e,t,n){if(wo(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 Fr(e,t,s,n)}let $a;function gF(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=yy(yd,V.backendName);if(c!=null){const w={pixels:e},I={numChannels:t};return V.runKernel(yd,w,I)}const[u,p]=i?[e.videoWidth,e.videoHeight]:[e.width,e.height];let m;a?m=e.getContext("2d").getImageData(0,0,u,p).data:s||n?m=e.data:(o||i)&&($a==null&&($a=document.createElement("canvas").getContext("2d")),$a.canvas.width=u,$a.canvas.height=p,$a.drawImage(e,0,0,u,p),m=$a.getImageData(0,0,u,p).data);let y;if(t===4)y=new Int32Array(m);else{const w=u*p;y=new Int32Array(w*t);for(let I=0;I<w;I++)for(let T=0;T<t;++T)y[I*t+T]=m[I*4+T]}const b=[p,u,t];return UT(y,b,"int32")}async function yF(e,t){let n=W(e,"img","toPixels");if(!(e instanceof Q)){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,u=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;u[y+0]=Math.round(m[0]),u[y+1]=Math.round(m[1]),u[y+2]=Math.round(m[2]),u[y+3]=Math.round(m[3])}if(t!=null){t.width=i,t.height=s;const p=t.getContext("2d"),m=new ImageData(u,i,s);p.putImageData(m,0,0)}return n!==e&&n.dispose(),u}const BT=P({fromPixels_:gF});var bF=Object.freeze({__proto__:null,toPixels:yF,fromPixels:BT});function Fd(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 u=[...Ot(e.shape).map(p=>p/c),1].slice(0,s);return[a,i,c,u]}var wF=Object.freeze({__proto__:null,prepareAndValidate:Fd});function qy(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 jy(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}`)}qy(n,t,e)}function Ua(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,u=we(t.shape)/c,p=[...Ot(n.slice(0,i)),1],m=we(n);return{sliceRank:i,numUpdates:u,sliceSize:a,strides:p,outputSize:m}}var LF=Object.freeze({__proto__:null,validateUpdateShape:qy,validateInput:jy,calculateShapes:Ua});function Ky(e,t,n){const s=e.shape.length;k(s===t.length,()=>`Error in slice${s}D: Length of begin ${t} must match the rank of the array (${s}).`),k(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)k(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 _d(e){const t=[];let n=0;for(;e>0;)e&1&&t.push(n),e/=2,n++;return t}function Wd(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 MT(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 PT(e,t,n){return n<=e?n:n-(t-1)}function zT(e,t){const n=[];for(let s=0;s<e;s++)n.push(t+s);return n}function GT(e,t,n,s,i,o,a,c,u){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],I=n+1;m=VT(a,w,I,s,e),y=HT(c,w,I,i,e),b=MT(o,w,I,e)}else for(let w=0;w<p;w++)m[w]=qT(a,s,o,e,w,u),y[w]=jT(c,i,o,e,w,u),b[w]=YT(o,w,u);return{begin:m,end:y,strides:b}}function VT(e,t,n,s,i){const o=[...i],a=zT(n,t);for(let c=0;c<o.length;c++)if(a.indexOf(c)>-1)o[c]=0;else{const u=PT(t,n,c);let p=s[u];e&1<<u&&(p=0),o[c]=p}return o}function HT(e,t,n,s,i){const o=[...i],a=zT(n,t);for(let c=0;c<o.length;c++)if(a.indexOf(c)>-1)o[c]=Number.MAX_SAFE_INTEGER;else{const u=PT(t,n,c);let p=s[u];e&1<<u&&(p=Number.MAX_SAFE_INTEGER),o[c]=p}for(let c=0;c<o.length;c++){const u=i[c];o[c]<0&&(o[c]+=u),o[c]=Hl(0,o[c],i[c])}return o}function YT(e,t,n){let s=e[t];return(n&1<<t||s==null)&&(s=1),s}function qT(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 u=s[i];return a<0&&(a+=u),a=Hl(0,a,u-1),a}function jT(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 u=s[i];return a<0&&(a+=u),c>0?a=Hl(0,a,u):a=Hl(-1,a,u-1),a}function Xy(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 Jy(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 $d(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=>{k(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:(k(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 KT=Object.freeze({__proto__:null,assertParamsValid:Ky,maskToAxes:_d,computeOutShape:Wd,stridesWithElidedDims:MT,getNormalizedAxes:GT,startIndicesWithElidedDims:VT,stopIndicesWithElidedDims:HT,stridesForAxis:YT,startForAxis:qT,stopForAxis:jT,isSliceContinous:Xy,computeFlatOffset:Jy,parseSliceParams:$d});class No{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}}class Ws{constructor(){this.classNameMap={}}static getMap(){return Ws.instance==null&&(Ws.instance=new Ws),Ws.instance}static register(e){Ws.getMap().classNameMap[e.className]=[e,e.fromConfig]}}function ge(e){k(e.className!=null,()=>"Class being registered does not have the static className property defined."),k(typeof e.className=="string",()=>"className is required to be a string, but got type "+typeof e.className),k(e.className.length>0,()=>"Class being registered has an empty-string as its className, which is disallowed."),Ws.register(e)}var SF=Object.freeze({__proto__:null,Serializable:No,SerializationMap:Ws,registerClass:ge});const IF=.001,XT=.1;function xF(e,t,n){return n==null&&(n=Ud()),Zy(e,t,(s,i)=>eb(s,i,n))}function Ud(){return V.backend.floatPrecision()===32?IF:XT}function Zy(e,t,n){let s=!0;if((Ln(e)||Ln(t))&&(s=!1),Ln(e)&&Ln(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(!ot(a,c))throw new Error(`Arrays have different shapes. Actual: [${a}]. Expected: [${c}]`)}const i=Ln(e)?e:Ji(e),o=Ln(t)?t:Ji(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],u=o[a];if(!n(c,u))throw new Error(`Arrays differ: actual[${a}] = ${c}, expected[${a}] = ${u}.
Actual: ${i}.
Expected: ${o}.`)}}function TF(e,t){e().then(()=>t.fail(),()=>t())}function AF(e,t){const n=typeof t=="string"||typeof t=="number"||typeof t=="boolean"?[t]:t;return Or(e)||Or(e[0])||Or(t)||Or(t[0])?Zy(e,n,(s,i)=>s==i):Zy(e,t,(s,i)=>eb(s,i,0))}function Qy(e,t,n){if(n==null&&(n=Ud()),!eb(e,t,n))throw new Error(`Numbers differ: actual === ${e}, expected === ${t}`)}function eb(e,t,n){return!isFinite(e)&&!isFinite(t)?!0:!(isNaN(e)||isNaN(t)||Math.abs(e-t)>n)}function vF(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 NF(e,t){expect(new Float32Array(e)).toEqual(new Float32Array(t))}var CF=Object.freeze({__proto__:null,TEST_EPSILON_FLOAT16:XT,expectArraysClose:xF,testEpsilon:Ud,expectPromiseToFail:TF,expectArraysEqual:AF,expectNumbersClose:Qy,expectValuesInRange:vF,expectArrayBuffersEqual:NF});const JT="2.6.0";function RF(){C().set("PROD",!0)}function OF(){C().set("DEBUG",!0)}function EF(){C().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function sn(e){C().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(e+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}uk(sn);function DF(){V.disposeVariables()}function $s(){return V}function Bd(){return V.memory()}function kF(e){return V.profile(e)}function ee(e,t){return V.tidy(e,t)}function qe(e){const t=Zi(e);t.forEach(n=>n.dispose())}function Rn(e){return V.keep(e)}function FF(e){return V.time(e)}function ZT(e){return V.setBackend(e)}function _F(){return V.ready()}function WF(){return V.backendName}function $F(e){V.removeBackend(e)}function UF(e){return V.findBackend(e)}function BF(e){return V.findBackendFactory(e)}function tb(e,t,n=1){return V.registerBackend(e,t,n)}function QT(){return V.backend}function MF(e,t){C().setPlatform(e,t)}function PF(e,t){let n=W(e,"a","add"),s=W(t,"b","add");[n,s]=Bt(n,s);const i=(a,c)=>{const u=a.add(n,s);return c([n,s]),u},o={a:n,b:s};return V.runKernelFunc(i,o,null,xe)}const be=P({add_:PF});function zF(e,t){let n=W(e,"a","floorDiv"),s=W(t,"b","floorDiv");[n,s]=Bt(n,s);const i=(a,c)=>{const u=a.floorDiv(n,s);return c([n,s]),u},o={a:n,b:s};return V.runKernelFunc(i,o,null,Wg)}const Md=P({floorDiv_:zF});function GF(e,t){let n=W(e,"a","div"),s=W(t,"b","div");if([n,s]=Bt(n,s),n.dtype==="int32"&&s.dtype==="int32")return Md(n,s);const i=(c,u)=>{const p=c.realDivide(n,s);return u([n,s]),p},o={a:n,b:s},a={};return V.runKernelFunc(i,o,null,Aa,a)}const _e=P({div_:GF});function VF(e,t){let n=W(e,"a","mul"),s=W(t,"b","mul");[n,s]=Bt(n,s);const i=(a,c)=>{const u=a.multiply(n,s);return c([n,s]),u},o={a:n,b:s};return V.runKernelFunc(i,o,null,Rl)}const X=P({mul_:VF});function HF(e){const t=W(e,"x","abs"),n={x:t};return V.runKernelFunc((s,i)=>(i([t]),t.dtype==="complex64"?s.complexAbs(t):s.abs(t)),n,null,fe)}const rn=P({abs_:HF});function YF(e){const t=W(e,"x","acos"),n={x:t};return V.runKernelFunc((s,i)=>{const o=s.acos(t);return i([t]),o},n,null,de)}const nb=P({acos_:YF});function qF(e){const t=W(e,"x","acosh"),n={x:t};return V.runKernelFunc((s,i)=>{const o=s.acosh(t);return i([t]),o},n,null,Ae)}const sb=P({acosh_:qF});function jF(e){k(Array.isArray(e),()=>"The argument passed to tf.addN() must be a list of tensors"),k(e.length>=1,()=>`Must pass at least one tensor to tf.addN(), but got ${e.length}`);const t=e.map((o,a)=>W(o,`tensors${a}`,"addN")),n=t[0];t.forEach(o=>{if(o.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),t.forEach(o=>{if(!ot(o.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});const s=(o,a)=>{const c=o.addN(t);return a(t),c},i=t;return V.runKernelFunc(s,i,null,Me)}const eA=P({addN_:jF});function ib(e,t){for(let n=0;n<e.length;++n)if(e[e.length-n-1]!==t-1-n)return!1;return!0}function tA(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 On(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 En(e,t){const n=t.map(s=>1);return tA(e,n,t)}function ss(e,t,n){k(ib(t,n),()=>`${e} supports only inner-most axes for now. Got axes ${t} and rank-${n} input.`)}function _n(e,t){if(ib(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 eh(e){return e.map((t,n)=>[n,t]).sort((t,n)=>t[1]-n[1]).map(t=>t[0])}function Is(e,t){const n=[];for(let s=t-e;s<t;++s)n.push(s);return n}function KF(e,t=null,n=!1){let s=W(e,"x","all","bool");const i=c=>{const u=ft(t,s.shape);let p=u;const m=_n(p,s.rank);m!=null&&(s=Pe(s,m),p=Is(p.length,s.rank));const y=c.all(s,p);if(n){const b=En(y.shape,u);return K(y,b)}return y},o={x:s},a={axis:t,keepDims:n};return V.runKernelFunc(i,o,null,Ke,a)}const Pd=P({all_:KF});function XF(e,t=null,n=!1){let s=W(e,"x","any","bool");const i=c=>{const u=ft(t,s.shape);let p=u;const m=_n(p,s.rank);m!=null&&(s=Pe(s,m),p=Is(p.length,s.rank));const y=c.any(s,p);if(n){const b=En(y.shape,u);return K(y,b)}return y},o={x:s},a={axis:t,keepDims:n};return V.runKernelFunc(i,o,null,wt,a)}const th=P({any_:XF});function JF(e,t=0){let n=W(e,"x","argMax");const s=(a,c)=>{c([n]);let u=ft(t,n.shape);const p=_n(u,n.rank);return p!=null&&(n=Pe(n,p),u=Is(u.length,n.rank)),a.argMax(n,u[0])},i={x:n},o={axis:t};return V.runKernelFunc(s,i,null,$t,o)}const nh=P({argMax_:JF});function ZF(e,t=0){let n=W(e,"x","argMin");const s=(a,c)=>{c([n]),t==null&&(t=0);let u=ft(t,n.shape);const p=_n(u,n.rank);return p!=null&&(n=Pe(n,p),u=Is(u.length,n.rank)),a.argMin(n,u[0])},i={x:n},o={axis:t};return V.runKernelFunc(s,i,null,Kt,o)}const rb=P({argMin_:ZF});function QF(e){const t=W(e,"x","asin"),n={x:t};return V.runKernelFunc((s,i)=>{const o=s.asin(t);return i([t]),o},n,null,Fn)}const ob=P({asin_:QF});function e_(e){const t=W(e,"x","asinh"),n={x:t};return V.runKernelFunc((s,i)=>{const o=s.asinh(t);return i([t]),o},n,null,vn)}const ab=P({asinh_:e_});function t_(e){const t=W(e,"x","atan"),n={x:t};return V.runKernelFunc((s,i)=>{const o=s.atan(t);return i([t]),o},n,null,Nn)}const cb=P({atan_:t_});function n_(e,t){let n=W(e,"a","atan2"),s=W(t,"b","atan2");[n,s]=Bt(n,s);const i=(a,c)=>{const u=a.atan2(n,s);return c([n,s]),u},o={a:n,b:s};return V.runKernelFunc(i,o,null,Ai)}const lb=P({atan2_:n_});function s_(e){const t=W(e,"x","atanh"),n={x:t};return V.runKernelFunc((s,i)=>{const o=s.atanh(t);return i([t]),o},n,null,Qs)}const hb=P({atanh_:s_});function zd(e,t,n,s,i="NHWC",o){const a=e[3],c=[...t,a],u=rh(i);return Oi(e,c,n,o,s,null,null,u)}function Wn(e,t,n,s,i,o,a="channelsLast"){const[c,u]=Gd(t);let p;if(a==="channelsLast")p=[c,u,e[3],e[3]];else if(a==="channelsFirst")p=[c,u,e[1],e[1]];else throw new Error(`Unknown dataFormat ${a}`);return Oi(e,p,n,s,i,o,!1,a)}function sh(e,t,n,s,i,o,a="NDHWC"){const[c,u,p]=db(t);let m,y;if(a==="NDHWC")y="channelsLast",m=[c,u,p,e[4],e[4]];else if(a==="NCDHW")y="channelsFirst",m=[c,u,p,e[1],e[1]];else throw new Error(`Unknown dataFormat ${a}`);return ih(e,m,n,s,i,!1,y,o)}function Oi(e,t,n,s,i,o,a=!1,c="channelsLast"){let[u,p,m,y]=[-1,-1,-1,-1];if(c==="channelsLast")[u,p,m,y]=e;else if(c==="channelsFirst")[u,y,p,m]=e;else throw new Error(`Unknown dataFormat ${c}`);const[b,w,,I]=t,[T,v]=Gd(n),[N,E]=Gd(s),D=Ba(b,N),F=Ba(w,E),{padInfo:_,outHeight:B,outWidth:U}=o_(i,p,m,T,v,D,F,o,c),Y=a?I*y:I;let q;return c==="channelsFirst"?q=[u,Y,B,U]:c==="channelsLast"&&(q=[u,B,U,Y]),{batchSize:u,dataFormat:c,inHeight:p,inWidth:m,inChannels:y,outHeight:B,outWidth:U,outChannels:Y,padInfo:_,strideHeight:T,strideWidth:v,filterHeight:b,filterWidth:w,effectiveFilterHeight:D,effectiveFilterWidth:F,dilationHeight:N,dilationWidth:E,inShape:e,outShape:q,filterShape:t}}function ih(e,t,n,s,i,o=!1,a="channelsLast",c){let[u,p,m,y,b]=[-1,-1,-1,-1,-1];if(a==="channelsLast")[u,p,m,y,b]=e;else if(a==="channelsFirst")[u,b,p,m,y]=e;else throw new Error(`Unknown dataFormat ${a}`);const[w,I,T,,v]=t,[N,E,D]=db(n),[F,_,B]=db(s),U=Ba(w,F),Y=Ba(I,_),q=Ba(T,B),{padInfo:J,outDepth:oe,outHeight:ce,outWidth:ue}=a_(i,p,m,y,N,E,D,U,Y,q,c),he=o?v*b:v;let pe;return a==="channelsFirst"?pe=[u,he,oe,ce,ue]:a==="channelsLast"&&(pe=[u,oe,ce,ue,he]),{batchSize:u,dataFormat:a,inDepth:p,inHeight:m,inWidth:y,inChannels:b,outDepth:oe,outHeight:ce,outWidth:ue,outChannels:he,padInfo:J,strideDepth:N,strideHeight:E,strideWidth:D,filterDepth:w,filterHeight:I,filterWidth:T,effectiveFilterDepth:U,effectiveFilterHeight:Y,effectiveFilterWidth:q,dilationDepth:F,dilationHeight:_,dilationWidth:B,inShape:e,outShape:pe,filterShape:t}}function i_(e,t,n,s,i){s==null&&(s=ub(e,t,n));const o=e[0],a=e[1],c=Co((o-t+2*s)/n+1,i);k(Ut(c),()=>`The output # of rows (${c}) must be an integer. Change the stride and/or zero pad parameters`);const u=Co((a-t+2*s)/n+1,i);return k(Ut(u),()=>`The output # of columns (${u}) must be an integer. Change the stride and/or zero pad parameters`),[c,u]}function r_(e,t,n,s,i,o){i==null&&(i=ub(e,t,s));const a=e[0],c=e[1],u=e[2],p=Co((a-t+2*i)/s+1,o);k(Ut(p),()=>`The output # of depths (${p}) must be an integer. Change the stride and/or zero pad parameters`);const m=Co((c-t+2*i)/s+1,o);k(Ut(m),()=>`The output # of rows (${m}) must be an integer. Change the stride and/or zero pad parameters`);const y=Co((u-t+2*i)/s+1,o);return k(Ut(y),()=>`The output # of columns (${y}) must be an integer. Change the stride and/or zero pad parameters`),[p,m,y,n]}function ub(e,t,n,s=1){const i=Ba(t,s);return Math.floor((e[0]*(n-1)-n+i)/2)}function Gd(e){return typeof e=="number"?[e,e,e]:e.length===2?[e[0],e[1],1]:e}function db(e){return typeof e=="number"?[e,e,e]:e}function Ba(e,t){return t<=1?e:e+(e-1)*(t-1)}function o_(e,t,n,s,i,o,a,c,u){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=i_([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),I=Math.floor(b/2),T=b-I,v=Math.floor(w/2),N=w-v;p={top:I,bottom:T,left:v,right:N,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=u==="channelsLast"?e[1][0]:e[2][0],w=u==="channelsLast"?e[1][1]:e[2][1],I=u==="channelsLast"?e[2][0]:e[3][0],T=u==="channelsLast"?e[2][1]:e[3][1],v=b===0&&w===0&&I===0&&T===0?"VALID":"EXPLICIT";p={top:b,bottom:w,left:I,right:T,type:v},m=Co((t-o+b+w)/s+1,c),y=Co((n-a+I+T)/i+1,c)}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:p,outHeight:m,outWidth:y}}function a_(e,t,n,s,i,o,a,c,u,p,m){let y,b,w,I;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=r_([t,n,s,1],c,1,i,e,m);b=v[0],w=v[1],I=v[2]}else if(e==="same"){b=Math.ceil(t/i),w=Math.ceil(n/o),I=Math.ceil(s/a);const T=(b-1)*i+c-t,v=(w-1)*o+u-n,N=(I-1)*a+p-s,E=Math.floor(T/2),D=T-E,F=Math.floor(v/2),_=v-F,B=Math.floor(N/2),U=N-B;y={top:F,bottom:_,left:B,right:U,front:E,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-u+1)/o),I=Math.ceil((s-p+1)/a);else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:y,outDepth:b,outHeight:w,outWidth:I}}function Co(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 $r(e){const[t,n,s]=Gd(e);return t===1&&n===1&&s===1}function on(e,t){return $r(e)||$r(t)}function rh(e){if(e==="NHWC")return"channelsLast";if(e==="NCHW")return"channelsFirst";throw new Error(`Unknown dataFormat ${e}`)}function c_(e,t,n,s,i){const o=W(e,"x","avgPool","float32"),a=1;k(on(n,a),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`);let c=o,u=!1;o.rank===3&&(u=!0,c=K(o,[1,o.shape[0],o.shape[1],o.shape[2]])),k(c.rank===4,()=>`Error in avgPool: x must be rank 4 but got rank ${c.rank}.`),i!=null&&k(Ut(s),()=>`Error in avgPool: pad must be an integer when using, dimRoundingMode ${i} but got pad ${s}.`);const p=(w,I)=>{const T=Wn(c.shape,t,n,1,s,i);return I([c]),T.filterWidth===1&&T.filterHeight===1&&ot(T.inShape,T.outShape)?c.clone():w.avgPool(c,T)},m={x:c},y={filterSize:t,strides:n,pad:s,dimRoundingMode:i};let b=V.runKernelFunc(p,m,null,ei,y);return b=ve(b,o.dtype),u?K(b,[b.shape[1],b.shape[2],b.shape[3]]):b}const oh=P({avgPool_:c_});function l_(e,t,n,s,i,o="NDHWC",a){a==null?a=[1,1,1]:sn("dilations is deprecated, this field will be gone in v3.0.0.");const c=W(e,"x","avgPool3d","float32");let u=c,p=!1;c.rank===4&&(p=!0,u=K(c,[1,c.shape[0],c.shape[1],c.shape[2],c.shape[3]])),k(u.rank===5,()=>`Error in avgPool3d: x must be rank 5 but got rank ${u.rank}.`),k(o==="NDHWC",()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${o}`),k(on(n,a),()=>`Error in avgPool3d: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`),i!=null&&k(Ut(s),()=>`Error in avgPool3d: pad must be an integer when using, dimRoundingMode ${i} but got pad ${s}.`);const m=(I,T)=>{a==null&&(a=[1,1,1]);const v=sh(u.shape,t,n,a,s,i,o);return T([u]),I.avgPool3d(u,v)},y={x:u},b={filterSize:t,strides:n,pad:s,dimRoundingMode:i,dataFormat:o,dilations:a};let w=V.runKernelFunc(m,y,null,hl,b);return w=ve(w,u.dtype),p?K(w,[w.shape[1],w.shape[2],w.shape[3],w.shape[4]]):w}const pb=P({avgPool3d_:l_});function mb(e,t){const n=e[0].length;e.forEach((i,o)=>{k(i.length===n,()=>`Error in concat${n}D: rank of tensors[${o}] must be the same as the rank of the rest (${n})`)}),k(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++)k(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 Ur(e,t){const n=e[0].slice();for(let s=1;s<e.length;s++)n[t]+=e[s][t];return n}function h_(e,t=0){k(e.length>=1,()=>"Pass at least one tensor to concat");let n=Zl(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 u=ft(t,n[0].shape)[0],p=Ur(n.map(b=>b.shape),u);if(we(p)===0)return en([],p);if(n=n.filter(b=>b.size>0),n.length===1)return n[0];const m=n.map(b=>b.shape);mb(m,u);const y=a.concat(n,u);return c(n),y},i=n,o={axis:t};return V.runKernelFunc(s,i,null,td,o)}const Mt=P({concat_:h_});function u_(e){const t=W(e,"x","sigmoid"),n={x:t};return V.runKernelFunc((s,i)=>{const o=s.sigmoid(t);return i([o]),o},n,null,$l)}const Ei=P({sigmoid_:u_});function d_(e,t,n){const s=W(e,"x","slice");if(s.rank===0)throw new Error("Slicing scalar is not possible");const i=(c,u)=>{const[p,m]=$d(s,t,n);return Ky(s,p,m),u([s]),c.slice(s,p,m)},o={x:s},a={begin:t,size:n};return V.runKernelFunc(i,o,null,pd,a)}const st=P({slice_:d_});function p_(e){const t=W(e,"x","tanh"),n={x:t};return V.runKernelFunc((s,i)=>{const o=s.tanh(t);return i([o]),o},n,null,Pl)}const Ma=P({tanh_:p_});function m_(e,t,n,s,i,o){const a=W(e,"forgetBias","basicLSTMCell"),c=W(t,"lstmKernel","basicLSTMCell"),u=W(n,"lstmBias","basicLSTMCell"),p=W(s,"data","basicLSTMCell"),m=W(i,"c","basicLSTMCell"),y=W(o,"h","basicLSTMCell"),b=Mt([p,y],1),w=at(b,c),I=be(w,u),T=I.shape[0],v=I.shape[1]/4,N=[T,v],E=st(I,[0,0],N),D=st(I,[0,v],N),F=st(I,[0,v*2],N),_=st(I,[0,v*3],N),B=be(X(Ei(E),Ma(D)),X(m,Ei(be(a,F)))),U=X(Ma(B),Ei(_));return[B,U]}const f_=P({basicLSTMCell_:m_});function g_(e,t,n){const s=W(e,"x","batchToSpaceND"),i=t.reduce((u,p)=>u*p);k(s.rank>=1+t.length,()=>`input rank is ${s.rank} but should be > than blockShape.length ${t.length}`),k(n.length===t.length,()=>`crops.length is ${n.length} but should be equal to blockShape.length ${t.length}`),k(s.shape[0]%i===0,()=>`input tensor batch is ${s.shape[0]} but is not divisible by the product of the elements of blockShape ${t.join(" * ")} === ${i}`);const o=u=>u.batchToSpaceND(s,t,n),a={x:s},c={blockShape:t,crops:n};return V.runKernelFunc(o,a,null,Ng,c)}const ah=P({batchToSpaceND_:g_});function y_(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 b_(e,t,n,s,i,o){o==null&&(o=.001);const a=W(e,"x","batchNorm"),c=W(t,"mean","batchNorm"),u=W(n,"variance","batchNorm");let p;i!=null&&(p=W(i,"scale","batchNorm"));let m;s!=null&&(m=W(s,"offset","batchNorm")),k(c.rank===u.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),k(m==null||c.rank===m.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),k(p==null||c.rank===p.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");const y=y_(a),b=(v,N)=>(N([y,c,u,p]),v.batchNorm(y,Vd(c),Vd(u),Vd(m),Vd(p),o)),w={x:y,scale:p,offset:m,mean:c,variance:u},I={varianceEpsilon:o},T=V.runKernelFunc(b,w,null,Ll,I);return K(T,a.shape)}function Vd(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 Ro=P({batchNorm_:b_});function w_(e,t,n,s,i,o){const a=W(e,"x","batchNorm"),c=W(t,"mean","batchNorm"),u=W(n,"variance","batchNorm");let p;i!=null&&(p=W(i,"scale","batchNorm"));let m;return s!=null&&(m=W(s,"offset","batchNorm")),k(a.rank===2,()=>`Error in batchNorm2D: x must be rank 2 but got rank ${a.rank}.`),k(c.rank===2||c.rank===1,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${c.rank}.`),k(u.rank===2||u.rank===1,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${u.rank}.`),p!=null&&k(p.rank===2||p.rank===1,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${p.rank}.`),m!=null&&k(m.rank===2||m.rank===1,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${m.rank}.`),Ro(a,c,u,m,p,o)}const nA=P({batchNorm2d_:w_});function L_(e,t,n,s,i,o){const a=W(e,"x","batchNorm"),c=W(t,"mean","batchNorm"),u=W(n,"variance","batchNorm");let p;i!=null&&(p=W(i,"scale","batchNorm"));let m;return s!=null&&(m=W(s,"offset","batchNorm")),k(a.rank===3,()=>`Error in batchNorm3D: x must be rank 3 but got rank ${a.rank}.`),k(c.rank===3||c.rank===1,()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${c.rank}.`),k(u.rank===3||u.rank===1,()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${u.rank}.`),p!=null&&k(p.rank===3||p.rank===1,()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${p.rank}.`),m!=null&&k(m.rank===3||m.rank===1,()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${m.rank}.`),Ro(a,c,u,m,p,o)}const sA=P({batchNorm3d_:L_});function S_(e,t,n,s,i,o){const a=W(e,"x","batchNorm"),c=W(t,"mean","batchNorm"),u=W(n,"variance","batchNorm");let p;i!=null&&(p=W(i,"scale","batchNorm"));let m;return s!=null&&(m=W(s,"offset","batchNorm")),k(a.rank===4,()=>`Error in batchNorm4D: x must be rank 4 but got rank ${a.rank}.`),k(c.rank===4||c.rank===1,()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${c.rank}.`),k(u.rank===4||u.rank===1,()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${u.rank}.`),p!=null&&k(p.rank===4||p.rank===1,()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${p.rank}.`),m!=null&&k(m.rank===4||m.rank===1,()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${m.rank}.`),Ro(a,c,u,m,p,o)}const iA=P({batchNorm4d_:S_});function I_(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 Wr(n);const c=m=>m.tile(n,o),u={x:n},p={shape:t,inputShape:i};return V.runKernelFunc(c,u,null,Cg,p)}const ch=P({broadcastTo_:I_});function x_(e){const t=W(e,"x","ceil"),n={x:t};return V.runKernelFunc(s=>s.ceil(t),n,null,dl)}const fb=P({ceil_:x_});function T_(e,t,n){const s=W(e,"x","clipByValue");k(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 V.runKernelFunc((a,c)=>{const u=a.clip(s,t,n);return c([s]),u},i,null,pl,o)}const jn=P({clipByValue_:T_});function A_(e){return Mt(e,0)}const rA=P({concat1d_:A_});function v_(e,t){return Mt(e,t)}const oA=P({concat2d_:v_});function N_(e,t){return Mt(e,t)}const aA=P({concat3d_:N_});function C_(e,t){return Mt(e,t)}const cA=P({concat4d_:C_});function R_(e,t,n,s,i="NHWC",o=[1,1],a){const c=W(e,"x","conv2d"),u=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]])),k(p.rank===4,()=>`Error in conv2d: input must be rank 4, but got rank ${p.rank}.`),k(u.rank===4,()=>`Error in conv2d: filter must be rank 4, but got rank ${u.rank}.`),a!=null&&k(Ut(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];k(y===u.shape[2],()=>`Error in conv2d: depth of input (${y}) must match input depth for filter ${u.shape[2]}.`),k(on(n,o),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${o}'`);const b=(v,N)=>{const E=rh(i),D=Oi(p.shape,u.shape,n,o,s,a,!1,E),F=v.conv2d(p,u,D);return N([p,u]),F},w={x:p,filter:u},I={strides:n,pad:s,dataFormat:i,dilations:o,dimRoundingMode:a},T=V.runKernelFunc(b,w,null,Og,I);return m?K(T,[T.shape[1],T.shape[2],T.shape[3]]):T}const er=P({conv2d_:R_});function O_(e,t,n,s,i="NWC",o=1,a){const c=W(e,"x","conv1d"),u=W(t,"filter","conv1d");let p=c,m=!1;c.rank===2&&(m=!0,p=K(c,[1,c.shape[0],c.shape[1]])),k(p.rank===3,()=>`Error in conv1d: input must be rank 3, but got rank ${p.rank}.`),k(u.rank===3,()=>`Error in conv1d: filter must be rank 3, but got rank ${u.rank}.`),a!=null&&k(Ut(s),()=>`Error in conv1d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${s}.`),k(p.shape[2]===u.shape[1],()=>`Error in conv1d: depth of input (${p.shape[2]}) must match input depth for filter ${u.shape[1]}.`),k(on(n,o),()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${n} and dilation '${o}'`),k(i==="NWC",()=>`Error in conv1d: got dataFormat of ${i} but only NWC is currently supported.`);const y=K(u,[1,u.shape[0],u.shape[1],u.shape[2]]),b=K(p,[p.shape[0],1,p.shape[1],p.shape[2]]),w=[1,n],I=[1,o],T="NHWC",v=er(b,y,w,s,T,I,a);return m?K(v,[v.shape[2],v.shape[3]]):K(v,[v.shape[0],v.shape[2],v.shape[3]])}const Hd=P({conv1d_:O_});function E_(e,t,n,s,i,o="NHWC",a){k(e.length===t.rank,()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);let c=e,u=t,p=!1;t.rank===3&&(p=!0,u=K(t,[1,t.shape[0],t.shape[1],t.shape[2]]),c=[1,e[0],e[1],e[2]]),k(c.length===4,()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${c.length}.`),k(u.rank===4,()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${u.rank}`),k(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"?u.shape[3]:u.shape[1];k(m===n.shape[2],()=>`Error in conv2dDerInput: depth of input (${m}) must match input depth for filter ${n.shape[2]}.`),k(y===n.shape[3],()=>`Error in conv2dDerInput: depth of output (${y}) must match output depth for filter ${n.shape[3]}.`),a!=null&&k(Ut(i),()=>`Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode ${a} but got pad ${i}.`);const b=(v,N)=>{const E=1,D=rh(o),F=Oi(c,n.shape,s,E,i,a,!1,D),_=v.conv2dDerInput(u,n,F);return N([u,n]),_},w={dy:u,filter:n},I={strides:s,pad:i,dataFormat:o,dimRoundingMode:a,inputShape:c},T=V.runKernelFunc(b,w,null,Eg,I);return p?K(T,[T.shape[1],T.shape[2],T.shape[3]]):T}const gb=P({conv2DBackpropInput_:E_});function D_(e,t,n,s,i,o){const a=W(e,"x","conv2dTranspose"),c=W(t,"filter","conv2dTranspose");return gb(n,a,c,s,i,"NHWC",o)}const Yd=P({conv2dTranspose_:D_});function k_(e,t,n,s,i="NDHWC",o=[1,1,1]){const a=W(e,"x","conv3d"),c=W(t,"filter","conv3d");let u=a,p=!1;a.rank===4&&(p=!0,u=K(a,[1,a.shape[0],a.shape[1],a.shape[2],a.shape[3]])),k(u.rank===5,()=>`Error in conv3d: input must be rank 5, but got rank ${u.rank}.`),k(c.rank===5,()=>`Error in conv3d: filter must be rank 5, but got rank ${c.rank}.`),k(u.shape[4]===c.shape[3],()=>`Error in conv3d: depth of input (${u.shape[4]}) must match input depth for filter ${c.shape[3]}.`),k(on(n,o),()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${n} and dilations '${o}'`),k(i==="NDHWC",()=>`Error in conv3d: got dataFormat of ${i} but only NDHWC is currently supported.`);const m=(I,T)=>{const v=ih(u.shape,c.shape,n,o,s),N=I.conv3d(u,c,v);return T([u,c]),N},y={x:u,filter:c},b={strides:n,pad:s,dataFormat:i,dilations:o},w=V.runKernelFunc(m,y,null,Dg,b);return p?K(w,[w.shape[1],w.shape[2],w.shape[3],w.shape[4]]):w}const yb=P({conv3d_:k_});function F_(e,t,n,s,i){k(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 u=o[4],p=a.shape[4];k(o.length===5,()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${o.length}.`),k(a.rank===5,()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${a.rank}`),k(n.rank===5,()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${n.rank}`),k(u===n.shape[3],()=>`Error in conv3dDerInput: depth of input (${u}) must match input depth for filter ${n.shape[3]}.`),k(p===n.shape[4],()=>`Error in conv3dDerInput: depth of output (${p}) must match output depth for filter ${n.shape[4]}.`);const m=I=>{const T=1,v=ih(o,n.shape,s,T,i);return I.conv3dDerInput(a,n,v)},y={dy:a},b={pad:i},w=V.runKernelFunc(m,y,null,Ex,b);return c?K(w,[w.shape[1],w.shape[2],w.shape[3],w.shape[4]]):w}const lA=P({conv3DBackpropInput_:F_});function __(e,t,n,s,i){const o=W(e,"x","conv3dTranspose"),a=W(t,"filter","conv3dTranspose");return lA(n,o,a,s,i)}const W_=P({conv3dTranspose_:__});function $_(e){const t=W(e,"x","cos"),n={x:t};return V.runKernelFunc((s,i)=>{const o=s.cos(t);return i([t]),o},n,null,Ta)}const lh=P({cos_:$_});function U_(e){const t=W(e,"x","cosh"),n={x:t};return V.runKernelFunc((s,i)=>{const o=s.cosh(t);return i([t]),o},n,null,ml)}const qd=P({cosh_:U_});function B_(e,t=0,n=!1,s=!1){const i=W(e,"x","cumsum"),o=(u,p)=>{const m=_n([t],i.rank);let y=i;m!=null&&(y=Pe(i,m));const b=Is(1,i.rank)[0];let w=u.cumsum(y,b,n,s);if(p([i]),m!=null){const I=eh(m);w=Pe(w,I)}return w},a={x:i},c={axis:t,exclusive:n,reverse:s};return V.runKernelFunc(o,a,null,kg,c)}const jd=P({cumsum_:B_});function M_(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];k(i*t>=0,()=>`Negative dimension size caused by overflow when multiplying
${i} and ${t} for depthToSpace with input shape
${s.shape}`),k(o*t>=0,()=>`Negative dimension size caused by overflow when multiplying
${o} and ${t} for depthToSpace with input shape
${s.shape}`),k(a%(t*t)===0,()=>`Dimension size must be evenly divisible by ${t*t} but is ${a} for depthToSpace with input shape ${s.shape}`);const c=m=>m.depthToSpace(s,t,n),u={x:s},p={blockSize:t,dataFormat:n};return V.runKernelFunc(c,u,null,kx,p)}const bb=P({depthToSpace_:M_});function P_(e,t,n,s,i="NHWC",o=[1,1],a){const c=W(e,"x","depthwiseConv2d"),u=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]])),k(p.rank===4,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${p.rank}.`),k(u.rank===4,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${u.rank}.`),k(p.shape[3]===u.shape[2],()=>`Error in depthwiseConv2d: number of input channels (${p.shape[3]}) must match the inChannels dimension in filter ${u.shape[2]}.`),a!=null&&k(Ut(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]),k(on(n,o),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${o}'`);const N=Oi(p.shape,u.shape,n,o,s,a,!0),E=T.depthwiseConv2D(p,u,N);return v([p,u]),E},b={x:p,filter:u},w={strides:n,pad:s,dataFormat:i,dilations:o,dimRoundingMode:a},I=V.runKernelFunc(y,b,null,Fg,w);return m?K(I,[I.shape[1],I.shape[2],I.shape[3]]):I}const Oo=P({depthwiseConv2d_:P_});function z_(e){const t=W(e,"x","diag"),n=i=>{const o=K(t,[t.size]),a=i.diag(o),c=[...e.shape,...e.shape];return K(a,c)},s={x:t};return V.runKernelFunc(n,s,null,Wx)}const G_=P({diag_:z_});function V_(e,t,n,s,i=[1,1],o="NHWC"){const a=W(e,"x","dilation2d"),c=W(t,"filter","dilation2d");k(a.rank===3||a.rank===4,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${a.rank}.`),k(c.rank===3,()=>`Error in dilation2d: filter must be rank 3, but got rank ${c.rank}.`),k(o==="NHWC",()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${o}`);let u=a,p=!1;a.rank===3&&(u=K(a,[1,a.shape[0],a.shape[1],a.shape[2]]),p=!0);const m={x:u,filter:c},y={strides:n,pad:s,dilations:i},b=V.runKernel(nd,m,y);return p?K(b,[b.shape[1],b.shape[2],b.shape[3]]):b}const wb=P({dilation2d_:V_});function Eo(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 an(e,t){const n=[];for(let s=0;s<t.length;s++){const i=e[e.length-s-1],o=t.length-s-1,a=t[o];(i==null||i===1&&a>1)&&n.unshift(o)}return n}function nt(e,t){const n=[],s=Math.max(e.length,t.length);for(let i=0;i<s;i++){let o=e[e.length-i-1];o==null&&(o=1);let a=t[t.length-i-1];if(a==null&&(a=1),o===1)n.unshift(a);else if(a===1)n.unshift(o);else if(o!==a){const c=`Operands could not be broadcast together with shapes ${e} and ${t}.`;throw Error(c)}else n.unshift(o)}return n}function H_(e,t){let n=W(e,"a","equal"),s=W(t,"b","equal");[n,s]=Bt(n,s),nt(n.shape,s.shape);const i=a=>a.equal(n,s),o={a:n,b:s};return V.runKernelFunc(i,o,null,Ux)}const ni=P({equal_:H_});function Y_(e,t,n){const s=W(t,"a","where"),i=W(n,"b","where"),o=W(e,"condition","where","bool"),a=nt(s.shape,i.shape),c=ch(s,a),u=ch(i,a);o.rank===1&&k(o.shape[0]===s.shape[0],()=>"The first dimension of `a` must match the size of `condition`."),o.rank!==1&&dt(o.shape,u.shape,"Error in where: ");const p=(y,b)=>{const w=y.select(o,c,u);return b([o]),w},m={condition:o,t:c,e:u};return V.runKernelFunc(p,m,null,oy)}const $n=P({where_:Y_});function q_(e){const t=W(e,"x","zerosLike"),n={x:t};return V.runKernelFunc(s=>s.zerosLike(t),n,null,py)}const et=P({zerosLike_:q_});function j_(e,t){let n=W(e,"a","div"),s=W(t,"b","div");[n,s]=Bt(n,s);const i=_e(n,s),o=et(i),a=ni(s,o);return $n(a,o,i)}const Lb=P({divNoNan_:j_});function K_(e,t){const n=W(e,"t1","dot"),s=W(t,"t2","dot");k((n.rank===1||n.rank===2)&&(s.rank===1||s.rank===2),()=>`Error in dot: inputs must all be rank 1 or 2, but got ranks ${n.rank} and ${s.rank}.`);const i=n.rank===1?n.size:n.shape[1],o=s.rank===1?s.size:s.shape[0];if(k(i===o,()=>`Error in dot: inner dimensions of inputs must match, but got ${i} and ${o}.`),n.rank===1&&s.rank===1){const a=K(n,[1,-1]),c=K(s,[-1,1]),u=at(a,c);return K(u,[])}else if(n.rank===1&&s.rank===2){const a=K(n,[1,-1]),c=K(s,[s.shape[0],s.shape[1]]),u=at(a,c);return K(u,[u.size])}else if(n.rank===2&&s.rank===1){const a=K(s,[-1,1]),c=at(n,a);return K(c,[c.size])}else{const a=K(s,[s.shape[0],s.shape[1]]),c=at(n,a);return c}}const hA=P({dot_:K_});function X_(e){const t=W(e,"x","elu"),n=(i,o)=>{const a=i.elu(t);return o([a]),a},s={x:t};return V.runKernelFunc(n,s,null,fl)}const Do=P({elu_:X_});function J_(e){let t=W(e,"x","erf");k(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 V.runKernelFunc((s,i)=>{const o=s.erf(t);return i([t]),o},n,null,gl)}const Sb=P({erf_:J_});function Z_(e){const t=W(e,"x","exp"),n={x:t};return V.runKernelFunc((s,i)=>{const o=s.exp(t);return i([o]),o},n,null,yl)}const xs=P({exp_:Z_});function Q_(e,t=0){const n=null,s=W(e,"x","expandDims",n);k(t<=s.rank,()=>"Axis must be <= rank of the tensor");const i=s.shape.slice();return t<0&&(k(-(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 Kn=P({expandDims_:Q_});function eW(e){const t=W(e,"x","expm1"),n={x:t};return V.runKernelFunc((s,i)=>{const o=s.expm1(t);return i([t]),o},n,null,bl)}const Ib=P({expm1_:eW});function tW(e,t){const n=null,s=W(e,"x","tile",n);k(s.rank===t.length,()=>`Error in transpose: rank of input ${s.rank} must match length of reps ${t}.`);const i=(u,p)=>{const m=u.tile(s,t);return p([s]),m},o=[s],a={x:s},c={reps:t};return V.runKernelFunc(i,a,null,hy,c,o)}const Br=P({tile_:tW});function nW(e,t,n,s="float32"){t==null&&(t=e);const i=Qe([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 Br(Kn(a,0),[n[0],1,1]);if(n.length===2)return Br(Kn(Kn(a,0),0),[n[0],n[1],1,1]);if(n.length===3)return Br(Kn(Kn(Kn(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 Kd=P({eye_:nW});function hh(e,t,n){const s={shape:e,value:t,dtype:n};return V.runKernelFunc(i=>i.fill(e,t,n),{},null,Bx,s)}function sW(e){const t=W(e,"x","floor"),n={x:t};return V.runKernelFunc(s=>s.floor(t),n,null,wl)}const Pa=P({floor_:sW});const xb=30;function uh(e){return e<=xb?e:Td(e,Math.floor(Math.sqrt(e)))}function iW(e,t){let n=!1,s;for(e<=xb?(s=e,n=!0):s=Td(e,Math.floor(Math.sqrt(e)));!n;)s>t||s===e?n=!0:s=Td(e,s+1);return s}function rW(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 uA(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 oW=Object.freeze({__proto__:null,segOpComputeOptimalWindowSize:iW,computeOutShape:rW,collectGatherOpShapeInfo:uA});function aW(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=(u,p)=>{const m=ft(n,s.shape)[0],y=uA(s,i,m),b=u.gather(s,K(i,[i.size]),m);return p([s,i]),K(b,y.outputShape)};return V.runKernelFunc(c,o,null,$g,a)}const za=P({gather_:aW});function cW(e,t){let n=W(e,"a","greater"),s=W(t,"b","greater");[n,s]=Bt(n,s),nt(n.shape,s.shape);const i=a=>a.greater(n,s),o={a:n,b:s};return V.runKernelFunc(i,o,null,Px)}const Ts=P({greater_:cW});function lW(e,t){let n=W(e,"a","greaterEqual"),s=W(t,"b","greaterEqual");[n,s]=Bt(n,s),nt(n.shape,s.shape);const i=(a,c)=>{const u=a.greaterEqual(n,s);return c([n,s]),u},o={a:n,b:s};return V.runKernelFunc(i,o,null,Ug)}const tr=P({greaterEqual_:lW});function hW(e){const t=W(e,"input","imag"),n=i=>i.imag(t),s={input:t};return V.runKernelFunc(n,s,null,Mg)}const Ga=P({imag_:hW});function uW(e){const t=W(e,"x","isFinite"),n={x:t};return V.runKernelFunc(s=>s.isFinite(t),n,null,Il)}const dA=P({isFinite_:uW});function dW(e){const t=W(e,"x","isInf"),n={x:t};return V.runKernelFunc(s=>s.isInf(t),n,null,xl)}const pA=P({isInf_:dW});function pW(e){const t=W(e,"x","isNaN"),n={x:t};return V.runKernelFunc(s=>s.isNaN(t),n,null,Tl)}const mA=P({isNaN_:pW});function mW(e,t){let n=W(e,"a","maximum"),s=W(t,"b","maximum");[n,s]=Bt(n,s),n.dtype==="bool"&&(n=ve(n,"int32"),s=ve(s,"int32")),nt(n.shape,s.shape);const i=(a,c)=>{const u=a.maximum(n,s);return c([n,s]),u},o={a:n,b:s};return V.runKernelFunc(i,o,null,Gg)}const Us=P({maximum_:mW});function Ne(e,t){if((Ln(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"&&Ln(e)&&!(e instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");const n=[],s=[];return Fr(e,n,s,t)}function fW(e,t=.2){const n=W(e,"x","leakyRelu");return Us(X(Ne(t),n),n)}const Xd=P({leakyRelu_:fW});function gW(e,t){let n=W(e,"a","less"),s=W(t,"b","less");[n,s]=Bt(n,s),nt(n.shape,s.shape);const i=a=>a.less(n,s),o={a:n,b:s};return V.runKernelFunc(i,o,null,zx)}const dh=P({less_:gW});function yW(e,t){let n=W(e,"a","lessEqual"),s=W(t,"b","lessEqual");[n,s]=Bt(n,s),nt(n.shape,s.shape);const i=(a,c)=>{const u=a.lessEqual(n,s);return c([n,s]),u},o={a:n,b:s};return V.runKernelFunc(i,o,null,Gx)}const Mr=P({lessEqual_:yW});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 V.runKernelFunc(i=>i.linspace(e,t,n),{},null,Vx,s)}function bW(e,t=5,n=1,s=1,i=.5){const o=W(e,"x","localResponseNormalization");k(o.rank===4||o.rank===3,()=>`Error in localResponseNormalization: x must be rank 3 or 4 but got
rank ${o.rank}.`),k(Ut(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 u=(b,w)=>{const I=b.localResponseNormalization4D(a,t,n,s,i);return w([a,I]),I},p={x:a},m={depthRadius:t,bias:n,alpha:s,beta:i},y=V.runKernelFunc(u,p,null,zg,m);return c?K(y,[y.shape[1],y.shape[2],y.shape[3]]):y}const Tb=P({localResponseNormalization_:bW});function wW(e){const t=W(e,"x","log"),n={x:t};return V.runKernelFunc((s,i)=>{const o=s.log(t);return i([t]),o},n,null,Al)}const is=P({log_:wW});function LW(e){const t=W(e,"x","log1p"),n={x:t};return V.runKernelFunc((s,i)=>{const o=s.log1p(t);return i([t]),o},n,null,vl)}const Jd=P({log1p_:LW});function SW(e){return k(Er(e),()=>"The f passed in grad(f) must be a function"),(t,n)=>{const s=W(t,"x","tf.grad",null),i=n!=null?W(n,"dy","tf.grad"):null;return V.tidy(()=>{const{value:o,grads:a}=V.gradients(()=>e(s),[s],i);return i!=null&&dt(o.shape,i.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),Zd(a),a[0]})}}function IW(e){return k(Er(e),()=>"The f passed in grads(f) must be a function"),(t,n)=>{k(Array.isArray(t),()=>"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s");const s=Zl(t,"args","tf.grads",null),i=n!=null?W(n,"dy","tf.grads"):null;return V.tidy(()=>{const{value:o,grads:a}=V.gradients(()=>e(...s),s,i);return i!=null&&dt(o.shape,i.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Zd(a),a})}}function xW(e){return k(Er(e),()=>"The f passed in valueAndGrad(f) must be a function"),(t,n)=>{k(t instanceof Q,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),k(n==null||n instanceof Q,()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");const{grads:s,value:i}=V.gradients(()=>e(t),[t],n);return Zd(s),{grad:s[0],value:i}}}function TW(e){return k(Er(e),()=>"The f passed in valueAndGrads(f) must be a function"),(t,n)=>{k(Array.isArray(t)&&t.every(i=>i instanceof Q),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),k(n==null||n instanceof Q,()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");const s=V.gradients(()=>e(...t),t,n);return n!=null&&dt(s.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Zd(s.grads),s}}function Ab(e,t){k(Er(e),()=>"The f passed in variableGrads(f) must be a function"),k(t==null||Array.isArray(t)&&t.every(p=>p instanceof Xl),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");const n=t!=null;if(!n){t=[];for(const p in V.registeredVariables)t.push(V.registeredVariables[p])}const s=n?t.filter(p=>!p.trainable):null,i=t.length;t=t.filter(p=>p.trainable),k(t.length>0,()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${i} variables is trainable.`);const o=!0,{value:a,grads:c}=V.gradients(e,t,null,o);k(c.some(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()."),k(a.rank===0,()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${a.rank} tensor`);const u={};return t.forEach((p,m)=>{c[m]!=null&&(u[p.name]=c[m])}),s!=null&&s.forEach(p=>u[p.name]=null),{value:a,grads:u}}function Di(e){return V.customGrad(e)}function Zd(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 AW(e){const t=W(e,"x","neg"),n={x:t};return V.runKernelFunc(s=>s.neg(t),n,null,jg)}const Pt=P({neg_:AW});function vW(e){const t=W(e,"x","softplus"),n={x:t};return V.runKernelFunc((s,i)=>{const o=s.softplus(t);return i([t]),o},n,null,Ul)}const Va=P({softplus_:vW});function NW(e){const t=W(e,"x","logSigmoid"),n=Di(s=>{const i=Pt(Va(Pt(s))),o=a=>{const c=X(a,Ei(Pt(s)));return c};return{value:i,gradFunc:o}});return n(t)}const gA=P({logSigmoid_:NW});function CW(e,t=null,n=!1){const s=W(e,"x","max"),i=(c,u)=>{const p=ft(t,s.shape);let m=p;const y=_n(m,s.rank);let b=s;y!=null&&(b=Pe(s,y),m=Is(m.length,b.rank));const w=c.max(b,m);y!=null&&b.dispose();let I=w;if(n){const T=En(I.shape,ft(t,s.shape));I=K(I,T),w.dispose()}return u([s,I]),I},o={x:s},a={reductionIndices:t,keepDims:n};return V.runKernelFunc(i,o,null,Nl,a)}const Xn=P({max_:CW});function RW(e,t){let n=W(e,"a","sub"),s=W(t,"b","sub");[n,s]=Bt(n,s);const i=(a,c)=>{const u=a.subtract(n,s);return c([n,s]),u},o={a:n,b:s};return V.runKernelFunc(i,o,null,Ml)}const Ce=P({sub_:RW});function OW(e,t=null,n=!1){let s=W(e,"x","sum");s.dtype==="bool"&&(s=ve(s,"int32"));const i=(c,u)=>{u([s]);const p=ft(t,s.shape),m=_n(p,s.rank);let y=p,b=s;m!=null&&(b=Pe(s,m),y=Is(y.length,s.rank));let w=c.sum(b,y);if(n){const I=En(w.shape,p);w=K(w,I)}return w},o={x:s},a={axis:t,keepDims:n};return V.runKernelFunc(i,o,null,ay,a)}const Ue=P({sum_:OW});function EW(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 u=!0,p=Xn(e,t,!0),m=Ce(e,p),y=Ce(ve(m,"float32"),is(Ue(xs(m),t,u)));return c([y]),y},i={logits:n},o={axis:t};return V.runKernelFunc(s,i,null,Pg,o)}const Qd=P({logSoftmax_:EW});function DW(e,t=null,n=!1){const s=W(e,"x","logSumExp"),i=ft(t,s.shape),o=Xn(s,i,!0),a=Ce(s,o),c=xs(a),u=Ue(c,i),p=is(u),m=be(K(o,p.shape),p);if(n){const y=En(m.shape,i);return K(m,y)}return m}const vb=P({logSumExp_:DW});function kW(e,t){const n=W(e,"a","logicalAnd","bool"),s=W(t,"b","logicalAnd","bool");nt(n.shape,s.shape);const i={a:n,b:s};return V.runKernelFunc(o=>o.logicalAnd(n,s),i,null,Hx)}const Bs=P({logicalAnd_:kW});function FW(e){const t=W(e,"x","logicalNot","bool"),n={x:t};return V.runKernelFunc(s=>s.logicalNot(t),n,null,od)}const ph=P({logicalNot_:FW});function _W(e,t){const n=W(e,"a","logicalOr","bool"),s=W(t,"b","logicalOr","bool");nt(n.shape,s.shape);const i={a:n,b:s};return V.runKernelFunc(o=>o.logicalOr(n,s),i,null,Yx)}const ep=P({logicalOr_:_W});function WW(e,t){const n=W(e,"a","logicalXor","bool"),s=W(t,"b","logicalXor","bool");return nt(n.shape,s.shape),Bs(ep(e,t),ph(Bs(e,t)))}const yA=P({logicalXor_:WW});function $W(e,t,n,s,i){const o=W(e,"x","maxPool"),a=1;let c=o,u=!1;o.rank===3&&(u=!0,c=K(o,[1,o.shape[0],o.shape[1],o.shape[2]])),k(c.rank===4,()=>`Error in maxPool: input must be rank 4 but got rank ${c.rank}.`),k(on(n,a),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`),i!=null&&k(Ut(s),()=>`Error in maxPool: pad must be an integer when using, dimRoundingMode ${i} but got pad ${s}.`);const p=(w,I)=>{const T=Wn(c.shape,t,n,1,s,i);let v;return T.filterWidth===1&&T.filterHeight===1&&ot(T.inShape,T.outShape)?v=c.clone():v=w.maxPool(c,T),I([c,v]),v},m={x:c},y={filterSize:t,strides:n,pad:s,dimRoundingMode:i},b=V.runKernelFunc(p,m,null,Cl,y);return u?K(b,[b.shape[1],b.shape[2],b.shape[3]]):b}const mh=P({maxPool_:$W});function UW(e,t=[1,1,1],n,s,i,o="NDHWC",a){a==null?a=[1,1,1]:sn("dilations is deprecated, this field will be gone in v3.0.0.");const c=W(e,"x","maxPool3d");let u=c,p=!1;c.rank===4&&(p=!0,u=K(c,[1,c.shape[0],c.shape[1],c.shape[2],c.shape[3]])),k(u.rank===5,()=>`Error in maxPool3d: x must be rank 5 but got rank ${u.rank}.`),k(o==="NDHWC",()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${o}`),k(on(n,a),()=>`Error in maxPool3d: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`),i!=null&&k(Ut(s),()=>`Error in maxPool3d: pad must be an integer when using, dimRoundingMode ${i} but got pad ${s}.`);const m=(I,T)=>{a==null&&(a=[1,1,1]);const v=sh(u.shape,t,n,a,s,i,o),N=I.maxPool3d(u,v);return T([u,N]),N},y={x:u},b={filterSize:t,strides:n,pad:s,dimRoundingMode:i,dataFormat:o,dilations:a},w=V.runKernelFunc(m,y,null,Vg,b);return p?K(w,[w.shape[1],w.shape[2],w.shape[3],w.shape[4]]):w}const Nb=P({maxPool3d_:UW});function BW(e,t,n,s,i=!1){const o=W(e,"x","maxPoolWithArgmax"),a={x:o},c={filterSize:t,strides:n,pad:s,includeBatchInIndex:i},u=V.runKernel(cd,a,c);return{result:u[0],indexes:u[1]}}const bA=P({maxPoolWithArgmax_:BW});function ct(e,t="float32"){if(t==="complex64"){const s=ct(e,"float32"),i=ct(e,"float32");return Ci(s,i)}const n=Ea(we(e),t);return V.makeTensor(n,e,t)}function si(e,t="float32"){if(t==="complex64"){const s=si(e,"float32"),i=ct(e,"float32");return Ci(s,i)}const n=Ay(we(e),t);return V.makeTensor(n,e,t)}function MW(e,t=null,n=!1){const s=W(e,"x","mean"),i=ft(t,s.shape),o=On(s.shape,i),a=o[1],c=we(a),u=Di(p=>{const m=Ne(c),y=m.dtype===p.dtype?p:ve(p,m.dtype),b=_e(y,m),w=Ue(b,t,n),I=T=>{const v=p.shape.slice();i.forEach(D=>{v[D]=1});const N=K(T,v),E=_e(X(N,si(p.shape,"float32")),c);return E};return{value:w,gradFunc:I}});return u(s)}const zt=P({mean_:MW});function PW(e,t=null,n=!1){const s=W(e,"x","min"),i=(c,u)=>{const p=ft(t,s.shape);let m=p;const y=_n(m,s.rank);let b=s;y!=null&&(b=Pe(s,y),m=Is(m.length,s.rank));const w=c.min(b,m);y!=null&&b.dispose();let I=w;if(n){const T=En(I.shape,p);I=K(w,T),w.dispose()}return u([s,I]),I},o={x:s},a={axis:t,keepDims:n};return V.runKernelFunc(i,o,null,Hg,a)}const Ha=P({min_:PW});function zW(e,t){let n=W(e,"a","minimum"),s=W(t,"b","minimum");[n,s]=Bt(n,s),n.dtype==="bool"&&(n=ve(n,"int32"),s=ve(s,"int32")),nt(n.shape,s.shape);const i=(a,c)=>{const u=a.minimum(n,s);return c([n,s]),u},o={a:n,b:s};return V.runKernelFunc(i,o,null,Yg)}const ko=P({minimum_:zW});function GW(e,t){let n=W(e,"a","mod"),s=W(t,"b","mod");[n,s]=Bt(n,s);const i=(a,c)=>{const u=a.mod(n,s);return c([n,s]),u},o={a:n,b:s};return V.runKernelFunc(i,o,null,qg)}const tp=P({mod_:GW});function VW(e){const t=W(e,"x","square"),n={},s=[t],i=[];return V.runKernelFunc((o,a)=>(a([t]),o.square(t)),{x:t},null,"Square",n,s,i)}const Lt=P({square_:VW});function HW(e,t=null,n=!1){e=W(e,"x","moments");const s=ft(t,e.shape),i=zt(e,s,n);let o=i.shape;n||(o=En(i.shape,s));const a=Lt(Ce(ve(e,"float32"),K(i,o))),c=zt(a,s,n);return{mean:i,variance:c}}const np=P({moments_:HW});function YW(e,t,n,s){const i=W(t,"data","multiRNNCell"),o=Zl(n,"c","multiRNNCell"),a=Zl(s,"h","multiRNNCell");let c=i;const u=[];for(let y=0;y<e.length;y++){const b=e[y](c,o[y],a[y]);u.push(b[0]),u.push(b[1]),c=b[1]}const p=[],m=[];for(let y=0;y<u.length;y+=2)p.push(u[y]),m.push(u[y+1]);return[p,m]}const qW=P({multiRNNCell_:YW});function jW(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,u=V.runKernelFunc(p=>p.multinomial(c,s,t,n),{logits2D:c});return a===1?K(u,[u.size]):u}const wA=P({multinomial_:jW});function KW(e,t){let n=W(e,"a","notEqual"),s=W(t,"b","notEqual");[n,s]=Bt(n,s),nt(n.shape,s.shape);const i=a=>a.notEqual(n,s),o={a:n,b:s};return V.runKernelFunc(i,o,null,ld)}const Pr=P({notEqual_:KW});function XW(e){const t=W(e,"input","real"),n=i=>i.real(t),s={input:t};return V.runKernelFunc(n,s,null,ey)}const Fo=P({real_:XW});function JW(e){const t=W(e,"x","onesLike"),n=(i,o)=>{if(t.dtype==="complex64"){const a=Dn(Fo(t)),c=et(Ga(t));return Ci(a,c)}return i.onesLike(t)},s={x:t};return V.runKernelFunc(n,s,null,Xg)}const Dn=P({onesLike_:JW});function ZW(e,t){const n=W(e,"v1","outerProduct"),s=W(t,"v2","outerProduct");k(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 at(i,o)}const QW=P({outerProduct_:ZW});function e$(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,u)=>(u([s]),c.pad(s,t,n)),o={paddings:t,constantValue:n},a={x:s};return V.runKernelFunc(i,a,null,dd,o)}const ki=P({pad_:e$});function t$(e,t,n=0){return k(t.length===2,()=>"Invalid number of paddings. Must be length of 2."),ki(e,[t],n)}const n$=P({pad1d_:t$});function s$(e,t,n=0){return k(t.length===2&&t[0].length===2&&t[1].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),ki(e,t,n)}const i$=P({pad2d_:s$});function r$(e,t,n=0){return k(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."),ki(e,t,n)}const o$=P({pad3d_:r$});function a$(e,t,n=0){return k(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."),ki(e,t,n)}const c$=P({pad4d_:a$});function l$(e,t,n){const s=W(e,"x","spaceToBatchND");k(s.rank>=1+t.length,()=>`input rank ${s.rank} should be > than [blockShape] ${t.length}`),k(n.length===t.length,()=>`paddings.shape[0] ${n.length} must be equal to [blockShape] ${t.length}`),k(s.shape.reduce((c,u,p)=>p>0&&p<=t.length?c&&(u+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 V.runKernelFunc(i,o,null,md,a)}const fh=P({spaceToBatchND_:l$});function h$(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,u=!1;a.rank===3&&(u=!0,c=K(a,[1,a.shape[0],a.shape[1],a.shape[2]])),k(on(o,i),()=>`Error in pool: Either strides or dilations must be 1. Got strides ${o} and dilations '${i}'`);const p=Wn(c.shape,t,o,i,s),m=[p.dilationHeight,p.dilationWidth];let y;s==="same"?y=d$([p.filterHeight,p.filterWidth],m):y=[[0,0],[0,0]];const b=m[0]===1&&m[1]===1,[w,I]=u$([p.inHeight,p.inWidth],m,y),T=b?s:"valid",v=b?c:fh(c,m,w),N=n==="avg"?()=>oh(v,t,o,T):()=>mh(v,t,o,T),E=N(),D=b?E:ah(E,m,I);return u?K(D,[D.shape[1],D.shape[2],D.shape[3]]):D}function u$(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]),u=t.map((m,y)=>[s[y],c[y]]),p=t.map((m,y)=>[0,a[y]]);return[u,p]}function d$(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 LA=P({pool_:h$});function p$(e,t){let n=W(e,"base","pow"),s=W(t,"exp","pow");[n,s]=Bt(n,s);const i={a:n,b:s},o=(a,c)=>{const u=a.pow(n,s);return c([n,s,u]),u};return V.runKernelFunc(o,i,null,Zg)}const ii=P({pow_:p$});function m$(e,t){const n=W(e,"x","prelu"),s=W(t,"alpha","prelu"),i=(a,c)=>{const u=a.prelu(n,s);return c([n,s]),u},o={x:n,alpha:s};return V.runKernelFunc(i,o,null,Qg)}const gh=P({prelu_:m$});function f$(e,t=null,n=!1){let s=W(e,"x","prod");const i=c=>{s.dtype==="bool"&&(s=ve(s,"int32"));const u=ft(t,s.shape),p=_n(u,s.rank);let m=u,y=s;p!=null&&(y=Pe(s,p),m=Is(m.length,s.rank));let b=c.prod(y,m);if(n){const w=En(b.shape,u);b=K(b,w)}return b},o={x:s},a={axis:t,keepDims:n};return V.runKernelFunc(i,o,null,Kx,a)}const sp=P({prod_:f$});function g$(e,t,n){const s=we(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 V.makeTensor(i,e,n)}const y$=P({rand_:g$});var Ya=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function DQ(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function _o(e,t){return t={exports:{}},e(t,t.exports),t.exports}function kQ(e){return e&&e.default||e}function FQ(){throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs")}var b$=_o(function(e){(function(t,n,s){function i(u){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(u),p.s0<0&&(p.s0+=1),p.s1-=m(u),p.s1<0&&(p.s1+=1),p.s2-=m(u),p.s2<0&&(p.s2+=1),m=null}function o(u,p){return p.c=u.c,p.s0=u.s0,p.s1=u.s1,p.s2=u.s2,p}function a(u,p){var m=new i(u),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 u=4022871197,p=function(m){m=m.toString();for(var y=0;y<m.length;y++){u+=m.charCodeAt(y);var b=.02519603282416938*u;u=b>>>0,b-=u,b*=u,u=b>>>0,b-=u,u+=b*4294967296}return(u>>>0)*23283064365386963e-26};return p}n&&n.exports?n.exports=a:s&&s.amd?s(function(){return a}):this.alea=a})(Ya,e,!1)}),w$=_o(function(e){(function(t,n,s){function i(c){var u=this,p="";u.x=0,u.y=0,u.z=0,u.w=0,u.next=function(){var y=u.x^u.x<<11;return u.x=u.y,u.y=u.z,u.z=u.w,u.w^=u.w>>>19^y^y>>>8},c===(c|0)?u.x=c:p+=c;for(var m=0;m<p.length+64;m++)u.x^=p.charCodeAt(m)|0,u.next()}function o(c,u){return u.x=c.x,u.y=c.y,u.z=c.z,u.w=c.w,u}function a(c,u){var p=new i(c),m=u&&u.state,y=function(){return(p.next()>>>0)/4294967296};return y.double=function(){do var b=p.next()>>>11,w=(p.next()>>>0)/4294967296,I=(b+w)/(1<<21);while(I===0);return I},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})(Ya,e,!1)}),L$=_o(function(e){(function(t,n,s){function i(c){var u=this,p="";u.next=function(){var y=u.x^u.x>>>2;return u.x=u.y,u.y=u.z,u.z=u.w,u.w=u.v,(u.d=u.d+362437|0)+(u.v=u.v^u.v<<4^(y^y<<1))|0},u.x=0,u.y=0,u.z=0,u.w=0,u.v=0,c===(c|0)?u.x=c:p+=c;for(var m=0;m<p.length+64;m++)u.x^=p.charCodeAt(m)|0,m==p.length&&(u.d=u.x<<10^u.x>>>4),u.next()}function o(c,u){return u.x=c.x,u.y=c.y,u.z=c.z,u.w=c.w,u.v=c.v,u.d=c.d,u}function a(c,u){var p=new i(c),m=u&&u.state,y=function(){return(p.next()>>>0)/4294967296};return y.double=function(){do var b=p.next()>>>11,w=(p.next()>>>0)/4294967296,I=(b+w)/(1<<21);while(I===0);return I},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})(Ya,e,!1)}),S$=_o(function(e){(function(t,n,s){function i(c){var u=this;u.next=function(){var m=u.x,y=u.i,b,w,I;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,u.i=y+1&7,w};function p(m,y){var b,w,I=[];if(y===(y|0))w=I[0]=y;else for(y=""+y,b=0;b<y.length;++b)I[b&7]=I[b&7]<<15^y.charCodeAt(b)+I[b+1&7]<<13;for(;I.length<8;)I.push(0);for(b=0;b<8&&I[b]===0;++b);for(b==8?w=I[7]=-1:w=I[b],m.x=I,m.i=0,b=256;b>0;--b)m.next()}p(u,c)}function o(c,u){return u.x=c.x.slice(),u.i=c.i,u}function a(c,u){c==null&&(c=+new Date);var p=new i(c),m=u&&u.state,y=function(){return(p.next()>>>0)/4294967296};return y.double=function(){do var b=p.next()>>>11,w=(p.next()>>>0)/4294967296,I=(b+w)/(1<<21);while(I===0);return I},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})(Ya,e,!1)}),I$=_o(function(e){(function(t,n,s){function i(c){var u=this;u.next=function(){var m=u.w,y=u.X,b=u.i,w,I;return u.w=m=m+1640531527|0,I=y[b+34&127],w=y[b=b+1&127],I^=I<<13,w^=w<<17,I^=I>>>15,w^=w>>>12,I=y[b]=I^w,u.i=b,I+(m^m>>>16)|0};function p(m,y){var b,w,I,T,v,N=[],E=128;for(y===(y|0)?(w=y,y=null):(y=y+"\0",w=0,E=Math.max(E,y.length)),I=0,T=-32;T<E;++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=N[T&127]^=w+v,I=b==0?I+1:0);for(I>=128&&(N[(y&&y.length||0)&127]=-1),I=127,T=4*128;T>0;--T)w=N[I+34&127],b=N[I=I+1&127],w^=w<<13,b^=b<<17,w^=w>>>15,b^=b>>>12,N[I]=w^b;m.w=v,m.X=N,m.i=I}p(u,c)}function o(c,u){return u.i=c.i,u.w=c.w,u.X=c.X.slice(),u}function a(c,u){c==null&&(c=+new Date);var p=new i(c),m=u&&u.state,y=function(){return(p.next()>>>0)/4294967296};return y.double=function(){do var b=p.next()>>>11,w=(p.next()>>>0)/4294967296,I=(b+w)/(1<<21);while(I===0);return I},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})(Ya,e,!1)}),x$=_o(function(e){(function(t,n,s){function i(c){var u=this,p="";u.next=function(){var y=u.b,b=u.c,w=u.d,I=u.a;return y=y<<25^y>>>7^b,b=b-w|0,w=w<<24^w>>>8^I,I=I-y|0,u.b=y=y<<20^y>>>12^b,u.c=b=b-w|0,u.d=w<<16^b>>>16^I,u.a=I-y|0},u.a=0,u.b=0,u.c=2654435769|0,u.d=1367130551,c===Math.floor(c)?(u.a=c/4294967296|0,u.b=c|0):p+=c;for(var m=0;m<p.length+20;m++)u.b^=p.charCodeAt(m)|0,u.next()}function o(c,u){return u.a=c.a,u.b=c.b,u.c=c.c,u.d=c.d,u}function a(c,u){var p=new i(c),m=u&&u.state,y=function(){return(p.next()>>>0)/4294967296};return y.double=function(){do var b=p.next()>>>11,w=(p.next()>>>0)/4294967296,I=(b+w)/(1<<21);while(I===0);return I},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})(Ya,e,!1)}),Wo=_o(function(e){(function(t,n){var s=this,i=256,o=6,a=52,c="random",u=n.pow(i,o),p=n.pow(2,a),m=p*2,y=i-1,b;function w(F,_,B){var U=[];_=_==!0?{entropy:!0}:_||{};var Y=N(v(_.entropy?[F,D(t)]:F==null?E():F,3),U),q=new I(U),J=function(){for(var oe=q.g(o),ce=u,ue=0;oe<p;)oe=(oe+ue)*i,ce*=i,ue=q.g(1);for(;oe>=m;)oe/=2,ce/=2,ue>>>=1;return(oe+ue)/ce};return J.int32=function(){return q.g(4)|0},J.quick=function(){return q.g(4)/4294967296},J.double=J,N(D(q.S),t),(_.pass||B||function(oe,ce,ue,he){return he&&(he.S&&T(he,q),oe.state=function(){return T(q,{})}),ue?(n[c]=oe,ce):oe})(J,Y,"global"in _?_.global:this==n,_.state)}n["seed"+c]=w;function I(F){var _,B=F.length,U=this,Y=0,q=U.i=U.j=0,J=U.S=[];for(B||(F=[B++]);Y<i;)J[Y]=Y++;for(Y=0;Y<i;Y++)J[Y]=J[q=y&q+F[Y%B]+(_=J[Y])],J[q]=_;(U.g=function(oe){for(var ce,ue=0,he=U.i,pe=U.j,le=U.S;oe--;)ce=le[he=y&he+1],ue=ue*i+le[y&(le[he]=le[pe=y&pe+ce])+(le[pe]=ce)];return U.i=he,U.j=pe,ue})(i)}function T(F,_){return _.i=F.i,_.j=F.j,_.S=F.S.slice(),_}function v(F,_){var B=[],U=typeof F,Y;if(_&&U=="object")for(Y in F)try{B.push(v(F[Y],_-1))}catch(q){}return B.length?B:U=="string"?F:F+"\0"}function N(F,_){for(var B=F+"",U,Y=0;Y<B.length;)_[y&Y]=y&(U^=_[y&Y]*19)+B.charCodeAt(Y++);return D(_)}function E(){try{var F;return b&&(F=b.randomBytes)?F=F(i):(F=new Uint8Array(i),(s.crypto||s.msCrypto).getRandomValues(F)),D(F)}catch(U){var _=s.navigator,B=_&&_.plugins;return[+new Date,s,B,s.screen,D(t)]}}function D(F){return String.fromCharCode.apply(0,F)}if(N(n.random(),t),e.exports){e.exports=w;try{b=require("crypto")}catch(F){}}})([],Math)});Wo.alea=b$,Wo.xor128=w$,Wo.xorwow=L$,Wo.xorshift7=S$,Wo.xor4096=I$,Wo.tychei=x$;var T$=Wo,qa=T$.alea;class Cb{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=qa(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 A${constructor(e,t,n,s){this.alpha=e,this.beta=1/t,this.dtype=n;const i=s||Math.random();this.randu=qa(i.toString()),this.randn=new Cb(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 v${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=qa(s)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}}function _Q(e){const t=e.length,n=R$(e),s=C$(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 WQ(e,t,n,s){s==null&&(s=Ud());const i=Rb(e);Qy(i,t,s),Qy(N$(e,i),n,s)}function Rb(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n];return t/e.length}function N$(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 C$(e){const t=Rb(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 R$(e){const t=Rb(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 O$(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 A$(t,n,s,i),a=Qe(e,s);for(let c=0;c<a.values.length;c++)a.values[c]=o.nextValue();return a.toTensor()}const E$=P({randomGamma_:O$});function D$(e,t=0,n=1,s,i){if(s!=null&&s==="bool")throw new Error(`Unsupported data type ${s}`);const o=new Cb(t,n,s,!1,i),a=Qe(e,s);for(let c=0;c<a.values.length;c++)a.values[c]=o.nextValue();return a.toTensor()}const Ob=P({randomNormal_:D$});function k$(e,t=0,n=1,s="float32",i){const o=Qe(e,s),a=new v$(t,n,null,i);for(let c=0;c<o.values.length;c++)o.values[c]=a.nextValue();return o.toTensor()}const $o=P({randomUniform_:k$});function rs(e,t){wo(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 Fr(e,s,n,t)}function yh(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,u=t<e&&n>1;if(a||c||u)return ct([0],s);const p=Math.abs(Math.ceil((t-e)/n)),m=Ea(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 rs(m,s)},o={start:e,stop:t,step:n,dtype:s};return V.runKernelFunc(i,{},null,Xx,o)}function F$(e){const t=W(e,"x","reciprocal"),n={x:t};return V.runKernelFunc((s,i)=>{const o=s.reciprocal(t);return i([t]),o},n,null,Ol)}const Eb=P({reciprocal_:F$});function _$(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 V.runKernelFunc(n,s,null,ty)}const Fi=P({relu_:_$});function W$(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 V.runKernelFunc(n,s,null,iy)}const Db=P({relu6_:W$});function $$(e,t){const n=W(e,"x","reverse"),s=a=>{const c=ft(t,n.shape);if(n.rank===0)return Wr(n);const u=a.reverse(n,c);return K(u,n.shape)},i={x:n},o={dims:t};return V.runKernelFunc(s,i,null,ry,o)}const As=P({reverse_:$$});function U$(e){const t=W(e,"x","reverse");return k(t.rank===1,()=>`Error in reverse1D: x must be rank 1 but got rank ${t.rank}.`),As(t,0)}const B$=P({reverse1d_:U$});function M$(e,t){const n=W(e,"x","reverse");return k(n.rank===2,()=>`Error in reverse2D: x must be rank 2 but got rank ${n.rank}.`),As(n,t)}const P$=P({reverse2d_:M$});function z$(e,t){const n=W(e,"x","reverse");return k(n.rank===3,()=>`Error in reverse3D: x must be rank 3 but got rank ${n.rank}.`),As(n,t)}const G$=P({reverse3d_:z$});function V$(e,t){const n=W(e,"x","reverse");return k(n.rank===4,()=>`Error in reverse4D: x must be rank 4 but got rank ${n.rank}.`),As(n,t)}const H$=P({reverse4d_:V$});function Y$(e){const t=W(e,"x","round"),n={x:t};return V.runKernelFunc(s=>s.round(t),n,null,Dl)}const kb=P({round_:Y$});function q$(e){const t=W(e,"x","rsqrt"),n={x:t};return V.runKernelFunc((s,i)=>{const o=s.rsqrt(t);return i([t]),o},n,null,kl)}const ip=P({rsqrt_:q$});function j$(e){const t=W(e,"x","selu"),n=(i,o)=>{const a=i.selu(t);return o([t]),a},s={x:t};return V.runKernelFunc(n,s,null,Fl)}const rp=P({selu_:j$});function K$(e,t,n,s,i,o=[1,1],a="NHWC"){const c=W(e,"x","separableConv2d"),u=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");k(m.rank===4,()=>`Error in separableConv2d: input must be rank 4, but got rank ${m.rank}.`),k(u.rank===4,()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${u.rank}.`),k(p.rank===4,()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${u.rank}.`),k(p.shape[0]===1,()=>`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${p.shape[0]}.`),k(p.shape[1]===1,()=>`Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${p.shape[1]}.`);const b=u.shape[2],w=u.shape[3];k(p.shape[2]===b*w,()=>`Error in separableConv2d: the third dimension of pointwise filter must be ${b*w}, but got ${p.shape[2]}.`);const I=Oo(m,u,s,i,a,o),T=1,v=er(I,p,T,"valid",a);return y?K(v,[v.shape[1],v.shape[2],v.shape[3]]):v}const Fb=P({separableConv2d_:K$});async function X$(e,t){const n=W(e,"x","setdiff1d"),s=W(t,"y","setdiff1d");k(n.dtype===s.dtype,()=>`x and y should have the same dtype, but got x (${n.dtype}) and y (${s.dtype}).`),k(n.rank===1,()=>`x should be 1D tensor, but got x (${n.shape}).`),k(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 u=new kr([c],n.dtype),p=new kr([c],"int32");for(let m=0,y=0;m<i.length;m++)a.has(i[m])||(u.values[y]=i[m],p.values[y]=m,y++);return[u.toTensor(),p.toTensor()]}const SA=X$;function J$(e){const t=W(e,"x","sign"),n={x:t};return V.runKernelFunc(s=>s.sign(t),n,null,Wl)}const _b=P({sign_:J$});function Z$(e){const t=W(e,"x","sin"),n={x:t};return V.runKernelFunc((s,i)=>{const o=s.sin(t);return i([t]),o},n,null,va)}const op=P({sin_:Z$});function Q$(e){const t=W(e,"x","sinh"),n={x:t};return V.runKernelFunc((s,i)=>{const o=s.sinh(t);return i([t]),o},n,null,_l)}const ap=P({sinh_:Q$});function eU(e,t,n){const s=W(e,"x","slice1d");return k(s.rank===1,()=>`slice1d expects a rank-1 tensor, but got a rank-${s.rank} tensor`),st(s,[t],[n])}const cp=P({slice1d_:eU});function tU(e,t,n){const s=W(e,"x","slice2d");return k(s.rank===2,()=>`slice2d expects a rank-2 tensor, but got a rank-${s.rank} tensor`),st(s,t,n)}const Wb=P({slice2d_:tU});function nU(e,t,n){const s=W(e,"x","slice3d");return k(s.rank===3,()=>`slice3d expects a rank-3 tensor, but got a rank-${s.rank} tensor`),st(s,t,n)}const lp=P({slice3d_:nU});function sU(e,t,n){const s=W(e,"x","slice4d");return k(s.rank===4,()=>`slice4d expects a rank-4 tensor, but got a rank-${s.rank} tensor`),st(s,t,n)}const bh=P({slice4d_:sU});function iU(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 V.runKernelFunc((o,a)=>{const c=o.softmax(n,t);return a([c]),c},s,null,ly,i)}const Uo=P({softmax_:iU});function rU(e){k(e.dtype==="complex64",()=>`The dtype for tf.spectral.fft() must be complex64 but got ${e.dtype}.`);const t={input:e};return V.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,_g)}const wh=P({fft_:rU});function oU(e){k(e.dtype==="complex64",()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${e.dtype}.`);const t={input:e};return V.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,Bg)}const ja=P({ifft_:oU});function aU(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=ja(i)}else{const i=[n,2*(t-1)],o=K(Fo(e),[n,t]),a=K(Ga(e),[n,t]),c=As(st(o,[0,1],[n,t-2]),1),u=X(As(st(a,[0,1],[n,t-2]),1),Ne(-1)),p=Mt([o,c],1),m=Mt([a,u],1),y=K(Ci(p,m),[i[0],i[1]]);s=ja(y)}if(s=Fo(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 hp=P({irfft_:aU});function IA(e,t,n=0){let s=[];if(typeof t=="number")k(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);k(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,u)=>u>0?c+u:c);t[o]=e.shape[n]-a}k(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 cU(e,t,n=0){const s=W(e,"x","split"),i=(c,u)=>{const p=ft(n,s.shape)[0],m=IA(s,t,p);return c.split(s,m,p)},o={x:s},a={numOrSizeSplits:t,axis:n};return V.runKernelFunc(i,o,null,cy,a)}const os=P({split_:cU});function lU(e,t){k(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 I=e.shape.map(v=>0),T=e.shape.map(v=>v);T[e.shape.length-1]=t,i=st(e,I,T),n=t}else if(t!=null&&t>n){const I=e.shape.map(T=>T);I[e.shape.length-1]=t-n,i=Mt([e,ct(I)],e.shape.length-1),n=t}else i=e;const o=et(i),a=K(Ci(i,o),[s,n]),c=wh(a),u=Math.floor(n/2)+1,p=Fo(c),m=Ga(c),y=os(p,[u,n-u],p.shape.length-1),b=os(m,[u,n-u],m.shape.length-1),w=i.shape.slice();return w[i.shape.length-1]=u,K(Ci(y[0],b[0]),w)}const Lh=P({rfft_:lU});function hU(e){const t=W(e,"x","sqrt"),n={x:t};return V.runKernelFunc((s,i)=>{const o=s.sqrt(t);return i([t]),o},n,null,Bl)}const Sn=P({sqrt_:hU});function uU(e,t){let n=W(e,"a","squaredDifference"),s=W(t,"b","squaredDifference");[n,s]=Bt(n,s),nt(n.shape,s.shape);const i=(c,u)=>{const p=c.squaredDifference(n,s);return u([n,s]),p},o={a:n,b:s},a={};return V.runKernelFunc(i,o,null,Na,a)}const Sh=P({squaredDifference_:uU});function dU(e,t){const n=W(e,"x","squeeze");return K(n,Rr(n.shape,t).newShape)}const zr=P({squeeze_:dU});function pU(e,t=0){const n=Zl(e,"tensors","stack");if(k(n.length>=1,()=>"Pass at least one tensor to tf.stack"),n.length===1)return Kn(n[0],t);const s=n[0].rank,i=n[0].shape,o=n[0].dtype;k(t<=s,()=>"Axis must be <= rank of the tensor"),n.forEach(c=>{dt(i,c.shape,"All tensors passed to stack must have matching shapes"),k(o===c.dtype,()=>"All tensors passed to stack must have matching dtypes")});const a=n.map(c=>Kn(c,t));return Mt(a,t)}const as=P({stack_:pU});function mU(e,t=0){const n=W(e,"x","step"),s={x:n},i={alpha:t};return V.runKernelFunc(o=>o.step(n,t),s,null,Gl,i)}const Ka=P({step_:mU});function fU(e,t,n,s,i=0,o=0,a=0,c=0,u=0){let p=W(e,"x","stridedSlice");const m=w=>{s==null&&(s=new Array(t.length));const I=_d(a);if(I.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&&u!==0)throw new Error("Using both ellipsisMask and shrinkAxisMask is not yet supported.");const T=p.rank-t.length,v=_d(c),N=p.shape.slice();v.forEach(J=>{t[J]=0,n[J]=1,N.splice(J,0,1)}),p=K(p,N);const{begin:E,end:D,strides:F}=GT(p.shape,I,T,t,n,s,i,o,a);t=E,n=D,s=F;const _=_d(u);_.forEach(J=>{n[J]=t[J]+1,s[J]=1});const B=Wd(t,n,s),U=B.filter((J,oe)=>_.indexOf(oe)===-1),Y=s.every(J=>J===1);if(Y)return K(st(p,t,B),U);const q=w.stridedSlice(p,t,n,s);return K(q,U)},y={x:p},b={begin:t,end:n,strides:s,beginMask:i,endMask:o,ellipsisMask:a,newAxisMask:c,shrinkAxisMask:u};return V.runKernelFunc(m,y,null,tT,b)}const $b=P({stridedSlice_:fU});function gU(e){const t=W(e,"x","tan"),n={x:t};return V.runKernelFunc((s,i)=>{const o=s.tan(t);return i([t]),o},n,null,Ca)}const Ub=P({tan_:gU});function Gr(e,t,n){if(wo(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 Fr(e,t,s,n)}function Xa(e,t,n){if(wo(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 Fr(e,t,s,n)}function yU(e,t,n){if(wo(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 Fr(e,t,s,n)}function bU(e,t,n){if(wo(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,Fr(e,t,s,n)}function wU(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,u]=V.runKernelFunc(p=>p.topk(s,t,n),o,null,nT,a);return{values:c,indices:u}}const Bb=P({topk_:wU});function LU(e,t=0,n=1,s,i){if(s!=null&&s==="bool")throw new Error("Unsupported data type $ { dtype }");const o=new Cb(t,n,s,!0,i),a=Qe(e,s);for(let c=0;c<a.values.length;c++)a.values[c]=o.nextValue();return a.toTensor()}const Ih=P({truncatedNormal_:LU});function SU(e,t=0){const n=W(e,"x","unique",null);k(n.rank>0,()=>"The input tensor must be at least 1D");const s={x:n},i={axis:t},[o,a]=V.runKernel(gd,s,i);return{values:o,indices:a}}const up=P({unique_:SU});function IU(e,t,n){const s=W(e,"x","unsortedSegmentSum"),i=W(t,"segmentIds","unsortedSegmentSum","int32");k(Ut(n),()=>"numSegments must be of dtype int");const o={x:s,segmentIds:i},a={numSegments:n},c=(u,p)=>{const m=u.unsortedSegmentSum(s,i,n);return p([i]),m};return V.runKernelFunc(c,o,null,dy,a)}const Mb=P({unsortedSegmentSum_:IU});function xU(e,t=0){const n=W(e,"x","unstack");k(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 V.runKernelFunc(o,s,null,uy,i)}const _i=P({unstack_:xU});function xA(e,t=!0,n,s){return V.makeVariable(e,t,n,s)}function dp(e,t){const n=[];for(let o=0;o<t.length;o++)t[o]&&n.push(o);const s=Qe(e,"int32"),i=Qe([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 TU(e){const t=W(e,"condition","whereAsync","bool"),n=await t.data(),s=dp(t.shape,n);return e!==t&&t.dispose(),s}const Pb=TU;async function AU(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;k(a>0,()=>"mask cannot be scalar"),dt(c.slice(o,o+a),i.shape,"mask's shape must match the first K dimensions of tensor's shape,");let u=1;for(let T=o;T<o+a;T++)u*=c[T];const p=c.slice(0,o).concat([u],c.slice(o+a)),m=K(s,p),y=K(i,[-1]),b=await Pb(y),w=zr(b,[1]),I=za(m,w,o);return e!==s&&s.dispose(),t!==i&&i.dispose(),w.dispose(),m.dispose(),y.dispose(),b.dispose(),I}const vU=AU;function NU(e,t){sn("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 dt(n.shape,s.shape,"Error in notEqualStrict: "),Pr(n,s)}function CU(e,t){sn("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 dt(n.shape,s.shape,"Error in lessStrict: "),dh(n,s)}function RU(e,t){sn("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 dt(n.shape,s.shape,"Error in equalStrict: "),ni(n,s)}function OU(e,t){sn("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 dt(n.shape,s.shape,"Error in lessEqualStrict: "),Mr(n,s)}function EU(e,t){sn("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 dt(n.shape,s.shape,"Error in greaterStrict: "),Ts(n,s)}function DU(e,t){sn("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 dt(n.shape,s.shape,"Error in greaterEqualStrict: "),tr(n,s)}const TA=P({equalStrict_:RU}),AA=P({greaterEqualStrict_:DU}),vA=P({greaterStrict_:EU}),NA=P({lessEqualStrict_:OU}),CA=P({lessStrict_:CU}),RA=P({notEqualStrict_:NU});function kU(e,t){sn("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 dt(n.shape,s.shape,"Error in addStrict: "),be(n,s)}function FU(e,t){sn("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 dt(n.shape,s.shape,"Error in subStrict: "),Ce(n,s)}function _U(e,t){return sn("strict variants of ops have been deprecated and will be removed in future"),dt(e.shape,t.shape,"Error in powStrict: "),ii(e,t)}function WU(e,t){sn("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 dt(n.shape,s.shape,"Error in multiplyStrict: "),X(n,s)}function $U(e,t){sn("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 dt(n.shape,s.shape,"Error in divideStrict: "),_e(n,s)}function UU(e,t){sn("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 dt(n.shape,s.shape,"Error in modStrict: "),tp(n,s)}function BU(e,t){sn("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 dt(n.shape,s.shape,"Error in minimumStrict: "),ko(n,s)}function MU(e,t){sn("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 dt(n.shape,s.shape,"Error in maximumStrict: "),Us(n,s)}function PU(e,t){sn("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 dt(n.shape,s.shape,"Error in squaredDifferenceStrict: "),Sh(n,s)}const OA=P({addStrict_:kU}),EA=P({divStrict_:$U}),DA=P({maximumStrict_:MU}),kA=P({minimumStrict_:BU}),FA=P({modStrict_:UU}),_A=P({mulStrict_:WU}),WA=P({powStrict_:_U}),$A=P({squaredDifferenceStrict_:PU}),UA=P({subStrict_:FU});function zU(e,t="euclidean",n=null,s=!1){e=W(e,"x","norm");const i=BA(e,t,n);let o=i.shape;if(s){const a=ft(n,e.shape);o=En(i.shape,a)}return K(i,o)}function BA(e,t,n=null){if(e.rank===0)return rn(e);if(e.rank!==1&&n===null)return BA(K(e,[-1]),t,n);if(e.rank===1||typeof n=="number"||Array.isArray(n)&&n.length===1){if(t===1)return Ue(rn(e),n);if(t===Infinity)return Xn(rn(e),n);if(t===-Infinity)return Ha(rn(e),n);if(t==="euclidean"||t===2)return Sn(Ue(ii(rn(e),Ne(2,"int32")),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}if(Array.isArray(n)&&n.length===2){if(t===1)return Xn(Ue(rn(e),n[0]),n[1]-1);if(t===Infinity)return Xn(Ue(rn(e),n[1]),n[0]);if(t===-Infinity)return Ha(Ue(rn(e),n[1]),n[0]);if(t==="fro"||t==="euclidean")return Sn(Ue(Lt(e),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}throw new Error(`Error in norm: invalid axis: ${n}`)}const pp=P({norm_:zU});function GU(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),k(ot(o.shape,a.shape),()=>"Shape mismatch in v and x");const u=Ne(1),p=Ce(u,c);let m=X(Ce(a,o),p);if(i){k(s!=null,()=>"When using zeroDebias: true, step is required.");const y=W(s,"step","movingAverage");m=_e(m,Ce(u,ii(c,y)))}return be(o,m)}const VU=P({movingAverage_:GU});function HU(e,t,n){const s=W(e,"indices","scatterND","int32"),i=W(t,"updates","scatterND");jy(i,s,n);const o=u=>u.scatterND(s,i,n),a={indices:s,updates:i},c={shape:n};return V.runKernelFunc(o,a,null,Qx,c)}const MA=P({scatterND_:HU});function YU(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 qU(e,t,n,s=0){const i=W(e,"sparseIndices","sparseToDense","int32"),o=W(t,"sparseValues","sparseToDense"),a=W(s,"defaultValue","sparseToDense",o.dtype);YU(i,o,n,a);const c={sparseIndices:i,sparseValues:o,defaultValue:a},u={outputShape:n};return V.runKernelFunc(p=>p.sparseToDense(i,o,n,a),c,null,eT,u)}const zb=P({sparseToDense_:qU});function jU(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 V.runKernelFunc(i,o,null,Mx)}const PA=P({gatherND_:jU});function KU(e,t){if(t==null)return e.shape.slice();if(ot(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 XU(e,t,n,s){const i=W(e,"x","dropout");if(k(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.`),k(t>=0&&t<1,()=>`rate must be a float in the range [0, 1), but got ${t}.`),t===0)return e instanceof Q?i.clone():i;const o=KU(i,n),a=1-t,c=_e(Pa(be($o(o,0,1,"float32",s),a)),a);return X(i,c)}const zA=P({dropout_:XU});function GA(e){return Math.floor(Math.pow(2,Math.ceil(Math.log(e)/Math.log(2))))}function Gb(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 rs(i,"float32")}async function JU(e,t,n=1){const s=W(e,"predictions","inTopK"),i=W(t,"targets","inTopK");k(s.rank>1,()=>`inTopK() expects the predictions to be of rank 2 or higher, but got ${s.rank}`),k(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}`),dt(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];k(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(),[u,p]=[a.length/o,o],m=wn("bool",u);for(let y=0;y<u;y++){const b=y*p,w=a.subarray(b,b+p),I=[];for(let T=0;T<w.length;T++)I.push({value:w[T],index:T});I.sort((T,v)=>v.value-T.value),m[y]=0;for(let T=0;T<n;T++)if(I[T].index===c[y]){m[y]=1;break}}return e!==s&&s.dispose(),t!==i&&i.dispose(),en(m,i.shape,"bool")}const ZU=JU;function QU(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 u=t;u.rank===3&&(u=K(t,[1,t.shape[0],t.shape[1],t.shape[2]])),k(c.rank===4,()=>`Error in conv2dDerFilter: input must be rank 4, but got shape ${c.shape}.`),k(u.rank===4,()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${u.shape}.`),k(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"?u.shape[3]:u.shape[1];k(p===n[2],()=>`Error in conv2dDerFilter: depth of input ${p}) must match input depth in filter (${n[2]}.`),k(m===n[3],()=>`Error in conv2dDerFilter: depth of dy (${m}) must match output depth for filter (${n[3]}).`),a!=null&&k(Ut(i),()=>`Error in conv2dDerFilter: pad must be an integer when using, dimRoundingMode ${a} but got pad ${i}.`);const y=I=>{const T=1,v=rh(o),N=Oi(c.shape,n,s,T,i,a,!1,v);return I.conv2dDerFilter(c,u,N)},b={x:c,dy:u},w={strides:s,pad:i,dataFormat:o,dimRoundingMode:a};return V.runKernelFunc(y,b,null,Rx,w)}const Vb=P({conv2DBackpropFilter_:QU});function mp(e,t,n){if(n==null||n==="linear")return e;if(n==="relu")return X(e,Ka(t));throw new Error(`Cannot compute gradient for fused activation ${n}.`)}function fp(e,t){let n=t;const s=an(e.shape,t.shape);return s.length>0&&(n=Ue(n,s)),K(n,e.shape)}function gp(e,t,n){if(t==="linear")return e;if(t==="relu")return Fi(e);if(t==="elu")return Do(e);if(t==="relu6")return Db(e);if(t==="prelu")return gh(e,n);throw new Error(`Unknown fused activation ${t}.`)}const yp=(e,t)=>{const n=e>0;return!n||t==="linear"};function eB({x:e,filter:t,strides:n,pad:s,dataFormat:i="NHWC",dilations:o=[1,1],dimRoundingMode:a,bias:c,activation:u="linear",preluActivationWeights:p}){if(u=u||"linear",yp(V.state.gradientDepth,u)===!1){let _=er(e,t,n,s,i,o,a);return c!=null&&(_=be(_,c)),gp(_,u,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]])),k(b.rank===4,()=>`Error in fused conv2d: input must be rank 4, but got rank ${b.rank}.`),k(y.rank===4,()=>`Error in fused conv2d: filter must be rank 4, but got rank ${y.rank}.`),a!=null&&k(Ut(s),()=>`Error in fused conv2d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${s}.`),k(b.shape[3]===y.shape[2],()=>`Error in conv2d: depth of input (${b.shape[3]}) must match input depth for filter ${y.shape[2]}.`),k(on(n,o),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${o}'`),k(i==="NHWC",()=>`Error in conv2d: got dataFormat of ${i} but only NHWC is currently supported.`);const I=Oi(b.shape,y.shape,n,o,s,a);let T;c!=null&&(T=W(c,"bias","fused conv2d"),[T]=Bt(T,m),nt(I.outShape,T.shape));let v;p!=null&&(v=W(p,"prelu weights","fused conv2d"));const N=(_,B)=>{const[U,Y,q,J]=B,oe=mp(_,q,u);k($r(o),()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${o}'`);const ce=gb(Y.shape,oe,U,n,s),ue=Vb(Y,oe,U.shape,n,s),he=[ce,ue];if(J!=null){const pe=fp(J,oe);he.push(pe)}return he},E=_=>{const B=_.fusedConv2d({input:b,filter:y,convInfo:I,bias:T,activation:u,preluActivationWeights:v});return B},D={x:b,filter:y,bias:T,preluActivationWeights:v},F={strides:n,pad:s,dataFormat:i,dilations:o,dimRoundingMode:a,activation:u};if(c==null){const _=Di((B,U,Y)=>{let q=V.runKernelFunc(E,D,null,fy,F);return Y([U,B,q]),w&&(q=K(q,[q.shape[1],q.shape[2],q.shape[3]])),{value:q,gradFunc:N}});return _(b,y)}else{const _=Di((B,U,Y,q)=>{let J=V.runKernelFunc(E,D,null,fy,F);return q([U,B,J,Y]),w&&(J=K(J,[J.shape[1],J.shape[2],J.shape[3]])),{value:J,gradFunc:N}});return _(b,y,T)}}const Hb=P({fusedConv2d_:eB});function tB(e,t,n,s){let i=e;e.rank===3&&(i=K(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let o=t;o.rank===3&&(o=K(t,[1,t.shape[0],t.shape[1],t.shape[2]]));const a=u=>u.depthwiseConv2DDerFilter(i,o,s),c={x:i,dy:o};return V.runKernelFunc(a,c,null,Fx)}const VA=P({depthwiseConv2dNativeBackpropFilter_:tB});function nB(e,t,n,s){let i=t,o=!1;t.rank===3&&(o=!0,i=K(t,[1,t.shape[0],t.shape[1],t.shape[2]]));const a=p=>p.depthwiseConv2DDerInput(i,n,s),c={dy:i},u=V.runKernelFunc(a,c,null,_x);return o?K(u,[u.shape[1],u.shape[2],u.shape[3]]):u}const HA=P({depthwiseConv2dNativeBackpropInput_:nB});function sB({x:e,filter:t,strides:n,pad:s,dataFormat:i="NHWC",dilations:o=[1,1],dimRoundingMode:a,bias:c,activation:u="linear",preluActivationWeights:p}){if(yp(V.state.gradientDepth,u)===!1){let _=Oo(e,t,n,s,i,o,a);return c!=null&&(_=be(_,c)),gp(_,u,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]])),k(b.rank===4,()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${b.rank}.`),k(y.rank===4,()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${y.rank}.`),k(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]),k(on(n,o),()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${o}'`),a!=null&&k(Ut(s),()=>`Error in fused depthwiseConv2d: pad must be an integer when using dimRoundingMode ${a} but got pad ${s}.`);const I=Oi(b.shape,y.shape,n,o,s,a,!0);let T;c!=null&&(T=W(c,"bias","fused conv2d"),[T]=Bt(T,m),nt(I.outShape,T.shape));let v;p!=null&&(v=W(p,"prelu weights","fused depthwiseConv2d"));const N=(_,B)=>{k($r(o),()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${o}'`);const[U,Y,q,J]=B,oe=mp(_,q,u),ce=HA(Y.shape,oe,U,I),ue=VA(Y,oe,U.shape,I);if(J!=null){const he=fp(T,oe);return[ce,ue,he]}return[ce,ue]},E=_=>{const B=_.fusedDepthwiseConv2D({input:b,filter:y,convInfo:I,bias:T,activation:u,preluActivationWeights:v});return B},D={x:b,filter:y,bias:T,preluActivationWeights:v},F={strides:n,pad:s,dataFormat:i,dilations:o,dimRoundingMode:a,activation:u};if(c==null){const _=Di((B,U,Y)=>{let q=V.runKernelFunc(E,D,null,gy,F);return Y([U,B,q]),w&&(q=K(q,[q.shape[1],q.shape[2],q.shape[3]])),{value:q,gradFunc:N}});return _(b,y)}else{const _=Di((B,U,Y,q)=>{let J=V.runKernelFunc(E,D,null,gy,F);return q([U,B,J,Y]),w&&(J=K(J,[J.shape[1],J.shape[2],J.shape[3]])),{value:J,gradFunc:N}});return _(b,y,T)}}const YA=P({fusedDepthwiseConv2d_:sB});function iB({a:e,b:t,transposeA:n=!1,transposeB:s=!1,bias:i,activation:o="linear",preluActivationWeights:a}){if(yp(V.state.gradientDepth,o)===!1){let J=at(e,t,n,s);return i!=null&&(J=be(J,i)),gp(J,o,a)}let c=W(e,"a","fused matMul"),u=W(t,"b","fused matMul");[c,u]=Bt(c,u);const p=n?c.shape[c.rank-2]:c.shape[c.rank-1],m=s?u.shape[u.rank-1]:u.shape[u.rank-2],y=n?c.shape[c.rank-1]:c.shape[c.rank-2],b=s?u.shape[u.rank-2]:u.shape[u.rank-1],w=c.shape.slice(0,-2),I=u.shape.slice(0,-2),T=we(w),v=we(I);k(c.rank>=2&&u.rank>=2&&c.rank===u.rank,()=>`Error in fused matMul: inputs must have the same rank of at least 2, got ranks ${c.rank} and ${u.rank}.`),k(ot(w,I),()=>`Error in fused matMul: outer dimensions (${w}) and (${I}) of Tensors with shapes ${c.shape} and ${u.shape} must match.`),k(p===m,()=>`Error in fused matMul: inner shapes (${p}) and (${m}) of Tensors with shapes ${c.shape} and ${u.shape} and transposeA=${n} and transposeB=${s} must match.`);const N=c.shape.slice(0,-2).concat([y,b]),E=n?K(c,[T,p,y]):K(c,[T,y,p]),D=s?K(u,[v,b,m]):K(u,[v,m,b]);let F;i!=null&&(F=W(i,"bias","fused matMul"),[F]=Bt(F,c),nt(N,F.shape));let _;a!=null&&(_=W(a,"prelu weights","fused matMul"));const B=(J,oe)=>{const[ce,ue,he,pe]=oe,le=mp(K(J,he.shape),he,o);let ye,me;if(!n&&!s?(ye=at(le,ue,!1,!0),me=at(ce,le,!0,!1)):!n&&s?(ye=at(le,ue,!1,!1),me=at(le,ce,!0,!1)):n&&!s?(ye=at(ue,le,!1,!0),me=at(ce,le,!1,!1)):(ye=at(ue,le,!0,!0),me=at(le,ce,!0,!0)),i!=null){const Ie=fp(pe,le);return[ye,me,Ie]}else return[ye,me]},U=J=>{const oe=J.fusedBatchMatMul({a:E,b:D,transposeA:n,transposeB:s,bias:F,activation:o,preluActivationWeights:_});return oe},Y={a:E,b:D,bias:F,preluActivationWeights:_},q={transposeA:n,transposeB:s,activation:o};if(i==null){const J=Di((oe,ce,ue)=>{const he=V.runKernelFunc(U,Y,null,my,q);return ue([oe,ce,he]),{value:K(he,N),gradFunc:B}});return J(E,D)}else{const J=Di((oe,ce,ue,he)=>{const pe=V.runKernelFunc(U,Y,null,my,q);return he([oe,ce,pe,ue]),{value:K(pe,N),gradFunc:B}});return J(E,D,F)}}const bp=P({fusedMatMul_:iB});var rB=Object.freeze({__proto__:null,conv2d:Hb,depthwiseConv2d:YA,matMul:bp});function oB(e){return Gb(e,.54,.46)}const aB=P({hammingWindow_:oB});function cB(e){return Gb(e,.5,.5)}const qA=P({hannWindow_:cB});function lB(e,t,n,s=!1,i=0){let o=0;const a=[];for(;o+t<=e.size;)a.push(st(e,o,t)),o+=n;if(s)for(;o<e.size;){const c=o+t-e.size,u=Mt([st(e,o,t-c),hh([c],i)]);a.push(u),o+=n}return a.length===0?Gr([],[0,t]):K(Mt(a),[a.length,t])}const jA=P({frame_:lB});function hB(e,t,n,s,i=qA){s==null&&(s=GA(t));const o=jA(e,t,n),a=X(o,i(t)),c=[];for(let u=0;u<o.shape[0];u++)c.push(Lh(st(a,[u,0],[1,t]),s));return Mt(c)}const uB=P({stft_:hB});function dB(e,t,n,s,i,o){const a=W(e,"image","cropAndResize"),c=W(t,"boxes","cropAndResize","float32"),u=W(n,"boxInd","cropAndResize","int32");i=i||"bilinear",o=o||0;const p=c.shape[0];k(a.rank===4,()=>`Error in cropAndResize: image must be rank 4,but got rank ${a.rank}.`),k(c.rank===2&&c.shape[1]===4,()=>`Error in cropAndResize: boxes must be have size [${p},4] but had shape ${c.shape}.`),k(u.rank===1&&u.shape[0]===p,()=>`Error in cropAndResize: boxInd must be have size [${p}] but had shape ${c.shape}.`),k(s.length===2,()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${s.length}.`),k(s[0]>=1&&s[1]>=1,()=>`cropSize must be atleast [1,1], but was ${s}`),k(i==="bilinear"||i==="nearest",()=>`method must be bilinear or nearest, but was ${i}`);const m=I=>I.cropAndResize(a,c,u,s,i,o),y={image:a,boxes:c,boxInd:u},b={method:i,extrapolationValue:o,cropSize:s},w=V.runKernelFunc(m,y,null,Dx,b);return w}const pB=P({cropAndResize_:dB});function mB(e){const t=W(e,"image","flipLeftRight","float32");k(t.rank===4,()=>`Error in flipLeftRight: image must be rank 4,but got rank ${t.rank}.`);const n={image:t},s=V.runKernel(rd,n,{});return s}const fB=P({flipLeftRight_:mB});function gB(e,t,n=0,s=.5){const i=W(e,"image","rotateWithOffset","float32");k(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=V.runKernel(bd,o,a);return c}const yB=P({rotateWithOffset_:gB});function Ja(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),k(0<=s&&s<=1,()=>`iouThreshold must be in [0, 1], but was '${s}'`),k(e.rank===2,()=>`boxes must be a 2D tensor, but was of rank '${e.rank}'`),k(e.shape[1]===4,()=>`boxes must have 4 columns, but 2nd dimension was ${e.shape[1]}`),k(t.rank===1,()=>"scores must be a 1D tensor"),k(t.shape[0]===a,()=>`scores has incompatible shape with boxes. Expected ${a}, but was ${t.shape[0]}`),k(0<=o&&o<=1,()=>`softNmsSigma must be in [0, 1], but was '${o}'`),{maxOutputSize:n,iouThreshold:s,scoreThreshold:i,softNmsSigma:o}}function bB(e,t,n,s=.5,i=Number.NEGATIVE_INFINITY){const o=W(e,"boxes","nonMaxSuppression"),a=W(t,"scores","nonMaxSuppression"),c=Ja(o,a,n,s,i);n=c.maxOutputSize,s=c.iouThreshold,i=c.scoreThreshold;const u={maxOutputSize:n,iouThreshold:s,scoreThreshold:i};return V.runKernelFunc(p=>p.nonMaxSuppression(o,a,n,s,i),{boxes:o,scores:a},null,Kg,u)}const wB=P({nonMaxSuppression_:bB});function LB(e,t,n){const s=SB(e,t,n),i=s<0?-(s+1):s;e.splice(i,0,t)}function SB(e,t,n){return xB(e,t,n||IB)}function IB(e,t){return e>t?1:e<t?-1:0}function xB(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 wp(e,t,n,s,i){return Yb(e,t,n,s,i,0).selectedIndices}function Lp(e,t,n,s,i,o){return Yb(e,t,n,s,i,0,!1,o,!0)}function Sp(e,t,n,s,i,o){return Yb(e,t,n,s,i,o,!0)}function Yb(e,t,n,s,i,o,a=!1,c=!1,u=!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(KA);const m=o>0?-.5/o:0,y=[],b=[];for(;y.length<n&&p.length>0;){const v=p.pop(),{score:N,boxIndex:E,suppressBeginIndex:D}=v;if(N<i)break;let F=!1;for(let _=y.length-1;_>=D;--_){const B=TB(e,E,y[_]);if(B>=s){F=!0;break}if(v.score=v.score*AB(s,m,B),v.score<=i)break}v.suppressBeginIndex=y.length,F||(v.score===N?(y.push(E),b.push(v.score)):v.score>i&&LB(p,v,KA))}const w=y.length,I=n-w;c&&I>0&&(y.push(...new Array(I).fill(0)),b.push(...new Array(I).fill(0)));const T={selectedIndices:rs(y,"int32")};return a&&(T.selectedScores=rs(b,"float32")),u&&(T.validOutputs=Ne(w,"int32")),T}function TB(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]),u=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)*(u-a),I=(y-p)*(b-m);if(w<=0||I<=0)return 0;const T=Math.max(o,p),v=Math.max(a,m),N=Math.min(c,y),E=Math.min(u,b),D=Math.max(N-T,0)*Math.max(E-v,0);return D/(w+I-D)}function AB(e,t,n){const s=Math.exp(t*n*n);return n<=e?s:0}function KA(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex}async function vB(e,t,n,s=.5,i=Number.NEGATIVE_INFINITY){const o=W(e,"boxes","nonMaxSuppressionAsync"),a=W(t,"scores","nonMaxSuppressionAsync"),c=Ja(o,a,n,s,i);n=c.maxOutputSize,s=c.iouThreshold,i=c.scoreThreshold;const u=await Promise.all([o.data(),a.data()]),p=u[0],m=u[1],y=wp(p,m,n,s,i);return o!==e&&o.dispose(),a!==t&&a.dispose(),y}const NB=vB;function CB(e,t,n,s=.5,i=Number.NEGATIVE_INFINITY,o=0){const a=W(e,"boxes","nonMaxSuppression"),c=W(t,"scores","nonMaxSuppression"),u=Ja(a,c,n,s,i,o);n=u.maxOutputSize,s=u.iouThreshold,i=u.scoreThreshold,o=u.softNmsSigma;const p={boxes:a,scores:c},m={maxOutputSize:n,iouThreshold:s,scoreThreshold:i,softNmsSigma:o},y=V.runKernel(ud,p,m);return{selectedIndices:y[0],selectedScores:y[1]}}const RB=P({nonMaxSuppressionWithScore_:CB});async function OB(e,t,n,s=.5,i=Number.NEGATIVE_INFINITY,o=0){const a=W(e,"boxes","nonMaxSuppressionAsync"),c=W(t,"scores","nonMaxSuppressionAsync"),u=Ja(a,c,n,s,i,o);n=u.maxOutputSize,s=u.iouThreshold,i=u.scoreThreshold,o=u.softNmsSigma;const p=await Promise.all([a.data(),c.data()]),m=p[0],y=p[1],b=Sp(m,y,n,s,i,o);return a!==e&&a.dispose(),c!==t&&c.dispose(),b}const EB=OB;function DB(e,t,n,s=.5,i=Number.NEGATIVE_INFINITY,o=!1){const a=W(e,"boxes","nonMaxSuppression"),c=W(t,"scores","nonMaxSuppression"),u=Ja(a,c,n,s,i,null),p=u.maxOutputSize,m=u.iouThreshold,y=u.scoreThreshold,b={boxes:a,scores:c},w={maxOutputSize:p,iouThreshold:m,scoreThreshold:y,padToMaxOutputSize:o},I=V.runKernel(hd,b,w);return{selectedIndices:I[0],validOutputs:I[1]}}const kB=P({nonMaxSuppressionPadded_:DB});async function FB(e,t,n,s=.5,i=Number.NEGATIVE_INFINITY,o=!1){const a=W(e,"boxes","nonMaxSuppressionAsync"),c=W(t,"scores","nonMaxSuppressionAsync"),u=Ja(a,c,n,s,i,null),p=u.maxOutputSize,m=u.iouThreshold,y=u.scoreThreshold,[b,w]=await Promise.all([a.data(),c.data()]),I=Lp(b,w,p,m,y,o);return a!==e&&a.dispose(),c!==t&&c.dispose(),I}const _B=FB;function WB(e,t,n=!1){const s=W(e,"images","resizeBilinear");k(s.rank===3||s.rank===4,()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${s.rank}.`),k(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,u=(b,w)=>(w([i]),b.resizeBilinear(i,a,c,n)),p={images:i},m={alignCorners:n,size:t},y=V.runKernelFunc(u,p,null,sy,m);return o?K(y,[y.shape[1],y.shape[2],y.shape[3]]):y}const XA=P({resizeBilinear_:WB});function $B(e,t,n=!1){const s=W(e,"images","resizeNearestNeighbor");k(s.rank===3||s.rank===4,()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${s.rank}.`),k(t.length===2,()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${t}.`),k(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,u={images:i},p={alignCorners:n,size:t},m=(b,w)=>(w([i]),b.resizeNearestNeighbor(i,a,c,n)),y=V.runKernelFunc(m,u,null,ny,p);return o?K(y,[y.shape[1],y.shape[2],y.shape[3]]):y}const JA=P({resizeNearestNeighbor_:$B});function UB(e,t,n){k(t%1===0,()=>`bandPart(): numLower must be an integer, got ${t}.`),k(n%1===0,()=>`bandPart(): numUpper must be an integer, got ${n}.`);const s=W(e,"a","bandPart");k(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(yh(0,o,1,"int32"),[-1,1]),u=yh(0,a,1,"int32"),p=Ce(c,u),m=Bs(Mr(p,Ne(+t,"int32")),tr(p,Ne(-n,"int32"))),y=ct([o,a],s.dtype);return K(as(_i(K(s,[-1,o,a])).map(b=>$n(m,b,y))),i)}const BB=P({bandPart_:UB});function MB(e){let t;if(Array.isArray(e)){t=!1,k(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)k(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=os(e,e.shape[0],0).map(i=>zr(i,[0]));k(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(V.tidy(()=>{let o=s[i];if(i>0)for(let a=0;a<i;++a){const c=X(Ue(X(n[a],o)),n[a]);o=Ce(o,c)}return _e(o,pp(o,"euclidean"))}));return t?as(n,0):n}const PB=P({gramSchmidt_:MB});function zB(e,t=!1){if(k(e.rank>=2,()=>`qr() requires input tensor to have a rank >= 2, but got rank ${e.rank}`),e.rank===2)return ZA(e,t);{const n=e.shape.slice(0,e.shape.length-2).reduce((u,p)=>u*p),s=_i(K(e,[n,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),i=[],o=[];s.forEach(u=>{const[p,m]=ZA(u,t);i.push(p),o.push(m)});const a=K(as(i,0),e.shape),c=K(as(o,0),e.shape);return[a,c]}}function ZA(e,t=!1){return V.tidy(()=>{k(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=Kd(n),o=Wr(e);const a=Gr([[1]],[1,1]);let c=Wr(a);const u=n>=s?s:n;for(let p=0;p<u;++p){const m=o,y=c,b=i;[c,o,i]=V.tidy(()=>{const w=st(o,[p,p],[n-p,1]),I=pp(w),T=st(o,[p,p],[1,1]),v=$n(Ts(T,0),Gr([[-1]]),Gr([[1]])),N=Ce(T,X(v,I)),E=_e(w,N);E.shape[0]===1?c=Wr(a):c=Mt([a,st(E,[1,0],[E.shape[0]-1,E.shape[1]])],0);const D=Pt(_e(at(v,N),I)),F=st(o,[p,0],[n-p,s]),_=X(D,c),B=Pe(c);if(p===0)o=Ce(F,at(_,at(B,F)));else{const q=Ce(F,at(_,at(B,F)));o=Mt([st(o,[0,0],[p,s]),q],0)}const U=Pe(_),Y=st(i,[0,p],[n,i.shape[1]-p]);if(p===0)i=Ce(Y,at(at(Y,c),U));else{const q=Ce(Y,at(at(Y,c),U));i=Mt([st(i,[0,0],[n,p]),q],1)}return[c,o,i]}),qe([m,y,b])}return!t&&n>s&&(i=st(i,[0,0],[n,s]),o=st(o,[0,0],[s,s])),[i,o]})}const GB=P({qr_:zB});(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 VB(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 Ue(o);if(n===r.Reduction.MEAN){if(i==null)return zt(o);{const a=s.size/i.size,c=_e(Ue(o),Ue(i));return a>1?_e(c,Ne(a)):c}}if(n===r.Reduction.SUM_BY_NONZERO_WEIGHTS){if(i==null)return _e(Ue(o),Ne(s.size));{const a=X(i,si(s.shape)),c=ve(Ue(Pr(a,Ne(0))),"float32");return _e(Ue(o),c)}}throw Error(`Unknown reduction: ${n}`)}const nr=P({computeWeightedLoss_:VB});function HB(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")),dt(i.shape,o.shape,"Error in absoluteDifference: ");const c=rn(Ce(i,o));return nr(c,a,s)}const YB=P({absoluteDifference_:HB});function qB(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")),dt(o.shape,a.shape,"Error in cosineDistance: ");const u=Ne(1),p=Ce(u,Ue(X(o,a),n,!0));return nr(p,c,i)}const jB=P({cosineDistance_:qB});function KB(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")),dt(i.shape,o.shape,"Error in hingeLoss: ");const c=Ne(1);i=Ce(X(Ne(2),i),c);const u=Fi(Ce(c,X(i,o)));return nr(u,a,s)}const XB=P({hingeLoss_:KB});function JB(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")),dt(o.shape,a.shape,"Error in huberLoss: ");const u=Ne(s),p=rn(Ce(a,o)),m=ko(p,u),y=Ce(p,m),b=be(X(Ne(.5),Lt(m)),X(u,y));return nr(b,c,i)}const ZB=P({huberLoss_:JB});function QB(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")),dt(o.shape,a.shape,"Error in logLoss: ");const u=Ne(1),p=Ne(s),m=Pt(X(o,is(be(a,p)))),y=X(Ce(u,o),is(be(Ce(u,a),p))),b=Ce(m,y);return nr(b,c,i)}const eM=P({logLoss_:QB});function tM(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")),dt(i.shape,o.shape,"Error in meanSquaredError: ");const c=Sh(i,o);return nr(c,a,s)}const nM=P({meanSquaredError_:tM});function sM(e,t){const n=W(e,"labels","sigmoidCrossEntropyWithLogits"),s=W(t,"logits","sigmoidCrossEntropyWithLogits");dt(n.shape,s.shape,"Error in sigmoidCrossEntropyWithLogits: ");const i=Fi(s),o=X(s,n),a=Jd(xs(Pt(rn(s))));return be(Ce(i,o),a)}function iM(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")),dt(o.shape,a.shape,"Error in sigmoidCrossEntropy: "),s>0){const p=Ne(s),m=Ne(1),y=Ne(.5);o=be(X(o,Ce(m,p)),X(y,p))}const u=sM(o,a);return nr(u,c,i)}const rM=P({sigmoidCrossEntropy_:iM});function oM(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=Di((i,o,a)=>{const c=!0,u=vb(o,[n],c),p=Ce(ve(o,"float32"),u);a([i,p]);const m=Pt(X(p,i)),y=Ue(m,[n]),b=(w,I)=>{const[T,v]=I,N=En(w.shape,[n]);return[X(K(w,N),Ce(ve(T,"float32"),xs(v))),X(K(w,N),Ce(xs(v),ve(T,"float32")))]};return{value:y,gradFunc:b}});return s(e,t)}function aM(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")),dt(o.shape,a.shape,"Error in softmaxCrossEntropy: "),s>0){const p=Ne(s),m=Ne(1),y=Ne(o.shape[1]);o=be(X(o,Ce(m,p)),_e(p,y))}const u=oM(o,a);return nr(u,c,i)}const cM=P({softmaxCrossEntropy_:aM});const lM={fft:wh,ifft:ja,rfft:Lh,irfft:hp},hM={hammingWindow:aB,hannWindow:qA,frame:jA,stft:uB},Vr={flipLeftRight:fB,resizeNearestNeighbor:JA,resizeBilinear:XA,rotateWithOffset:yB,cropAndResize:pB,nonMaxSuppression:wB,nonMaxSuppressionAsync:NB,nonMaxSuppressionWithScore:RB,nonMaxSuppressionWithScoreAsync:EB,nonMaxSuppressionPadded:kB,nonMaxSuppressionPaddedAsync:_B},QA={bandPart:BB,gramSchmidt:PB,qr:GB},uM={absoluteDifference:YB,computeWeightedLoss:nr,cosineDistance:jB,hingeLoss:XB,huberLoss:ZB,logLoss:eM,meanSquaredError:nM,sigmoidCrossEntropy:rM,softmaxCrossEntropy:cM};class sr extends No{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 Ab(e,t)}dispose(){this.iterations_!=null&&qe(this.iterations_)}async saveIterations(){return this.iterations_==null&&(this.iterations_=0),{name:"iter",tensor:Ne(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(sr,Symbol.hasInstance,{value:e=>e.minimize!=null&&e.computeGradients!=null&&e.applyGradients!=null});class xh extends sr{constructor(e,t,n=null){super();this.learningRate=e,this.rho=t,this.epsilon=n,this.accumulatedGrads=[],this.accumulatedUpdates=[],n==null&&(this.epsilon=V.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);t.forEach((n,s)=>{const i=V.registeredVariables[n],o=!1;this.accumulatedGrads[s]==null&&(this.accumulatedGrads[s]={originalName:`${n}/accum_grad`,variable:ee(()=>et(i).variable(o))}),this.accumulatedUpdates[s]==null&&(this.accumulatedUpdates[s]={originalName:`${n}/accum_var`,variable:ee(()=>et(i).variable(o))});const a=Array.isArray(e)?e[s].tensor:e[n];if(a==null)return;const c=this.accumulatedGrads[s].variable,u=this.accumulatedUpdates[s].variable;ee(()=>{const p=be(X(c,this.rho),X(Lt(a),1-this.rho)),m=X(_e(Sn(be(u,this.epsilon)),Sn(be(c,this.epsilon))),a),y=be(X(u,this.rho),X(Lt(m),1-this.rho));c.assign(p),u.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)}}xh.className="Adadelta",ge(xh);class Th extends sr{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=V.registeredVariables[n];if(this.accumulatedGrads[s]==null){const c=!1;this.accumulatedGrads[s]={originalName:`${n}/accumulator`,variable:ee(()=>hh(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,Lt(o));a.assign(c);const u=be(X(_e(o,Sn(be(c,V.backend.epsilon()))),-this.learningRate),i);i.assign(u)})}),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)}}Th.className="Adagrad",ge(Th);class Ah extends sr{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=Ne(t).variable(),this.accBeta2=Ne(n).variable()}),s==null&&(this.epsilon=V.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);ee(()=>{const n=Ce(1,this.accBeta1),s=Ce(1,this.accBeta2);t.forEach((i,o)=>{const a=V.registeredVariables[i],c=!1;this.accumulatedFirstMoment[o]==null&&(this.accumulatedFirstMoment[o]={originalName:`${i}/m`,variable:ee(()=>et(a).variable(c))}),this.accumulatedSecondMoment[o]==null&&(this.accumulatedSecondMoment[o]={originalName:`${i}/v`,variable:ee(()=>et(a).variable(c))});const u=Array.isArray(e)?e[o].tensor:e[i];if(u==null)return;const p=this.accumulatedFirstMoment[o].variable,m=this.accumulatedSecondMoment[o].variable,y=be(X(p,this.beta1),X(u,1-this.beta1)),b=be(X(m,this.beta2),X(Lt(u),1-this.beta2)),w=_e(y,n),I=_e(b,s);p.assign(y),m.assign(b);const T=be(X(_e(w,be(Sn(I),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(ii(this.beta1,this.iterations_+1)),this.accBeta2.assign(ii(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)}}Ah.className="Adam",ge(Ah);class vh extends sr{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=Ne(0).variable(),this.accBeta1=Ne(t).variable()}),s==null&&(this.epsilon=V.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);ee(()=>{const n=Ce(1,this.accBeta1),s=_e(-this.learningRate,be(X(this.iteration,this.decay),1));t.forEach((i,o)=>{const a=V.registeredVariables[i],c=!1;this.accumulatedFirstMoment[o]==null&&(this.accumulatedFirstMoment[o]={originalName:`${i}/m`,variable:et(a).variable(c)}),this.accumulatedWeightedInfNorm[o]==null&&(this.accumulatedWeightedInfNorm[o]={originalName:`${i}/v`,variable:et(a).variable(c)});const u=Array.isArray(e)?e[o].tensor:e[i];if(u==null)return;const p=this.accumulatedFirstMoment[o].variable,m=this.accumulatedWeightedInfNorm[o].variable,y=be(X(p,this.beta1),X(u,1-this.beta1)),b=X(m,this.beta2),w=rn(u),I=Us(b,w);p.assign(y),m.assign(I);const T=be(X(_e(s,n),_e(y,be(I,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)}}vh.className="Adamax",ge(vh);class Za extends sr{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=V.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=Rn(Ne(-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)}}Za.className="SGD",ge(Za);class Nh extends Za{constructor(e,t,n=!1){super(e);this.learningRate=e,this.momentum=t,this.useNesterov=n,this.accumulations=[],this.m=Ne(this.momentum)}applyGradients(e){const t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);t.forEach((n,s)=>{const i=V.registeredVariables[n];if(this.accumulations[s]==null){const c=!1;this.accumulations[s]={originalName:`${n}/momentum`,variable:ee(()=>et(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 u=be(X(this.m,o),a);this.useNesterov?c=be(X(this.c,be(a,X(u,this.m))),i):c=be(X(this.c,u),i),o.assign(u),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)}}Nh.className="Momentum",ge(Nh);class Ch extends sr{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=V.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=V.registeredVariables[n],o=!1;this.accumulatedMeanSquares[s]==null&&(this.accumulatedMeanSquares[s]={originalName:`${n}/rms`,variable:ee(()=>et(i).variable(o))}),this.accumulatedMoments[s]==null&&(this.accumulatedMoments[s]={originalName:`${n}/momentum`,variable:ee(()=>et(i).variable(o))}),this.accumulatedMeanGrads[s]==null&&this.centered&&(this.accumulatedMeanGrads[s]={originalName:`${n}/mg`,variable:ee(()=>et(i).variable(o))});const a=Array.isArray(e)?e[s].tensor:e[n];if(a==null)return;const c=this.accumulatedMeanSquares[s].variable,u=this.accumulatedMoments[s].variable;ee(()=>{const p=be(X(c,this.decay),X(Lt(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=_e(X(a,this.learningRate),Sn(Ce(p,be(Lt(y),this.epsilon)))),w=be(X(u,this.momentum),b);c.assign(p),m.assign(y),u.assign(w);const I=Ce(i,w);i.assign(I)}else{const m=be(X(c,this.decay),X(Lt(a),1-this.decay)),y=be(X(u,this.momentum),_e(X(a,this.learningRate),Sn(be(m,this.epsilon))));c.assign(m),u.assign(y);const b=Ce(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)}}Ch.className="RMSProp",ge(Ch);class Bo{static sgd(e){return new Za(e)}static momentum(e,t,n=!1){return new Nh(e,t,n)}static rmsprop(e,t=.9,n=0,s=null,i=!1){return new Ch(e,t,n,s,i)}static adam(e=.001,t=.9,n=.999,s=null){return new Ah(e,t,n,s)}static adadelta(e=.001,t=.95,n=null){return new xh(e,t,n)}static adamax(e=.002,t=.9,n=.999,s=null,i=0){return new vh(e,t,n,s,i)}static adagrad(e,t=.1){return new Th(e,t)}}const Mo={sgd:Bo.sgd,momentum:Bo.momentum,adadelta:Bo.adadelta,adagrad:Bo.adagrad,rmsprop:Bo.rmsprop,adamax:Bo.adamax,adam:Bo.adam};const dM=(()=>typeof requestAnimationFrame!="undefined"?requestAnimationFrame:typeof setImmediate!="undefined"?setImmediate:e=>e())();function Ip(){return new Promise(e=>dM(()=>e()))}function qb(e,t,n){const s=n*(typeof e=="number"?e:e[0]),i=t*(typeof e=="number"?e:e[1]);return[s,i]}function Rh(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 Oh(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 Eh(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 jb(e,t){const n=[0];for(let s=0;s<t;++s)n.push(e[s][0]);return n}function Kb(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 xp=1.7580993408473768,Tp=1.0507009873554805;const Xb=.3275911,Jb=.254829592,Zb=-.284496736,Qb=1.421413741,ew=-1.453152027,tw=1.061405429;function Qa(...e){C().getBool("IS_TEST")||console.warn(...e)}function pM(...e){C().getBool("IS_TEST")||console.log(...e)}function ir(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 ev(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 tv(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 nv(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 nw(e,t){const n=e[t*2],s=e[t*2+1];return{real:n,imag:s}}function sv(e,t,n,s){e[s*2]=t,e[s*2+1]=n}function iv(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 rv(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 ov(e,t,n){if(t==="complex64"){if(e.dtype==="complex64")return e.clone();const s=ct(e.shape),i=ve(e,"float32"),o=n.complex(i,s);return s.dispose(),i.dispose(),o}if(!xy(e.dtype,t))return V.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=Ne(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 V.makeTensorFromDataId(e.dataId,t,e.dtype)}function sw(e,t,n){const s=(t-e)/(n-1),i=Ea(n,"float32");i[0]=e;for(let o=1;o<i.length;o++)i[o]=i[o-1]+s;return rs(i,"float32")}var iw=Object.freeze({__proto__:null,slice_util:KT,segment_util:oW,castTensor:ov,reshapeTensor:av,linspaceImpl:sw,upcastType:Cn,axesAreInnerMostDims:ib,combineLocations:tA,computeOutAndReduceShapes:On,expandShapeToKeepDim:En,assertAxesAreInnerMostDims:ss,getAxesPermutation:_n,getUndoAxesPermutation:eh,getInnerMostAxes:Is,getBroadcastDims:Eo,getReductionAxes:an,assertAndGetBroadcastShape:nt,assertParamsConsistent:mb,computeOutShape:Ur,computeDilation2DInfo:zd,computePool2DInfo:Wn,computePool3DInfo:sh,computeConv2DInfo:Oi,computeConv3DInfo:ih,computeDefaultPad:ub,tupleValuesAreOne:$r,eitherStridesOrDilationsAreOne:on,convertConv2DDataFormat:rh,getFusedDyActivation:mp,getFusedBiasGradient:fp,applyActivation:gp,shouldFuse:yp,PARALLELIZE_THRESHOLD:xb,computeOptimalWindowSize:uh,getImageCenter:qb,getReshaped:Rh,getPermuted:Oh,getReshapedPermuted:Eh,getSliceBeginCoords:jb,getSliceSize:Kb,prepareAndValidate:Fd,validateUpdateShape:qy,validateInput:jy,calculateShapes:Ua,SELU_SCALEALPHA:xp,SELU_SCALE:Tp,ERF_P:Xb,ERF_A1:Jb,ERF_A2:Zb,ERF_A3:Qb,ERF_A4:ew,ERF_A5:tw,warn:Qa,log:pM,mergeRealAndImagArrays:ir,splitRealAndImagArrays:ev,complexWithEvenIndex:tv,complexWithOddIndex:nv,getComplexWithIndex:nw,assignToTypedArray:sv,exponents:iv,exponent:rv,prepareSplitSize:IA});function rw(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=st(e,s,a);return s[n]+=o,c})}function ow(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=Qe(n,e.dtype);for(let i=0;i<s.values.length;++i){const o=s.indexToLoc(i),a=new Array(e.rank);for(let u=0;u<a.length;u++)a[u]=o[u]%e.shape[u];const c=e.locToIndex(a);s.values[i]=e.values[c]}return s.toTensor()}function aw(e,t,n,s,i){const o=t[t.length-1],[a,c]=[e.length/o,o],u=wn(n,a*s),p=wn("int32",a*s);for(let y=0;y<a;y++){const b=y*c,w=e.subarray(b,b+c),I=[];for(let E=0;E<w.length;E++)I.push({value:w[E],index:E});I.sort((E,D)=>D.value-E.value);const T=y*s,v=u.subarray(T,T+s),N=p.subarray(T,T+s);for(let E=0;E<s;E++)v[E]=I[E].value,N[E]=I[E].index}const m=t.slice();return m[m.length-1]=s,[en(u,m,n),en(p,m,"int32")]}var mM=Object.freeze({__proto__:null,nonMaxSuppressionV3Impl:wp,nonMaxSuppressionV4Impl:Lp,nonMaxSuppressionV5Impl:Sp,split:rw,tile:ow,topkImpl:aw,whereImpl:dp});const fM={kernelName:fe,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>X(e,Ka(ve(n,"float32"),-1))}}};const gM={kernelName:de,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const s=Lt(ve(n,"float32")),i=Sn(Ce(Ne(1),s));return Pt(_e(e,i))}}}};const yM={kernelName:Ae,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const s=Sn(Ce(Lt(ve(n,"float32")),1));return _e(e,s)}}}};const bM={kernelName:xe,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,i=nt(n.shape,s.shape),o=()=>{let c=e;const u=an(n.shape,i);return u.length>0&&(c=Ue(c,u)),K(c,n.shape)},a=()=>{let c=e;const u=an(s.shape,i);return u.length>0&&(c=Ue(c,u)),K(c,s.shape)};return{a:o,b:a}}};const wM={kernelName:Me,saveAllInputs:!0,gradFunc:(e,t)=>{const n={};return t.forEach((s,i)=>{n[i]=()=>e.clone()}),n}};const LM={kernelName:$t,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>et(n)}}};const SM={kernelName:Kt,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>et(n)}}};const IM={kernelName:Fn,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>_e(e,Sn(Ce(Ne(1),Lt(ve(n,"float32")))))}}};const xM={kernelName:vn,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const s=Sn(be(Ne(1),Lt(ve(n,"float32"))));return _e(e,s)}}}};const TM={kernelName:Ai,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,i=nt(n.shape,s.shape),o=()=>{const c=be(Lt(n),Lt(s));let u=X(e,_e(s,c));const p=an(n.shape,i);return p.length>0&&(u=Ue(u,p)),K(u,n.shape)},a=()=>{const c=be(Lt(n),Lt(s));let u=Pt(X(e,_e(n,c)));const p=an(s.shape,i);return p.length>0&&(u=Ue(u,p)),K(u,s.shape)};return{a:o,b:a}}};const AM={kernelName:Nn,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>_e(e,be(Lt(ve(n,"float32")),1))}}};const vM={kernelName:Qs,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>_e(e,Ce(Ne(1),Lt(ve(n,"float32"))))}}};function NM(e,t,n,s,i=[1,1,1],o,a){const c=W(e,"dy","avgPool3dBackprop"),u=W(t,"input","avgPool3dBackprop");let p=c,m=u,y=!1;u.rank===4&&(y=!0,p=K(c,[1,c.shape[0],c.shape[1],c.shape[2],c.shape[3]]),m=K(u,[1,u.shape[0],u.shape[1],u.shape[2],u.shape[3]])),k(p.rank===5,()=>`Error in avgPool3dBackprop: dy must be rank 5 but got rank ${p.rank}.`),k(m.rank===5,()=>`Error in avgPool3dBackprop: input must be rank 5 but got rank ${m.rank}.`),k(on(s,i),()=>`Error in avgPool3dBackprop: Either strides or dilations must be 1. Got strides ${s} and dilations '${i}'`),a!=null&&k(Ut(o),()=>`Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode ${a} but got pad ${o}.`);const b=v=>{const N=sh(m.shape,n,s,i,o,a);return v.avgPool3dBackprop(p,m,N)},w={dy:p,input:m},I={filterSize:n,strides:s,dilations:i,pad:o,dimRoundingMode:a},T=V.runKernelFunc(b,w,null,Cx,I);return y?K(T,[T.shape[1],T.shape[2],T.shape[3],T.shape[4]]):T}const CM=P({avgPool3dBackprop_:NM});const RM={kernelName:hl,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{filterSize:i,strides:o,dilations:a,pad:c,dimRoundingMode:u}=n,p=a==null?[1,1,1]:a;return{x:()=>CM(e,s,i,o,p,c,u)}}};function OM(e,t,n,s,i){const o=W(e,"dy","avgPoolBackprop"),a=W(t,"input","avgPoolBackprop");k(a.rank===o.rank,()=>`Rank of input (${a.rank}) does not match rank of dy (${o.rank})`);let c=a,u=o,p=!1;a.rank===3&&(p=!0,c=K(a,[1,a.shape[0],a.shape[1],a.shape[2]]),u=K(o,[1,o.shape[0],o.shape[1],o.shape[2]])),k(u.rank===4,()=>`Error in avgPoolBackprop: dy must be rank 4 but got rank ${u.rank}.`),k(c.rank===4,()=>`Error in avgPoolBackprop: input must be rank 4 but got rank ${c.rank}.`);const m=I=>{const T=Wn(c.shape,n,s,1,i);return I.avgPoolBackprop(u,c,T)},y={dy:u,input:c},b={filterSize:n,strides:s,pad:i},w=V.runKernelFunc(m,y,null,xa,b);return p?K(w,[w.shape[1],w.shape[2],w.shape[3]]):w}const EM=P({avgPoolBackprop_:OM});const DM={kernelName:ei,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{filterSize:i,strides:o,pad:a}=n;return{x:()=>EM(e,s,i,o,a)}}};const kM={kernelName:vg,inputsToSave:["a","b"],gradFunc:(e,t,n)=>{const[s,i]=t,{transposeA:o,transposeB:a}=n;return!o&&!a?{a:()=>at(e,i,!1,!0),b:()=>at(s,e,!0,!1)}:!o&&a?{a:()=>at(e,i,!1,!1),b:()=>at(e,s,!0,!1)}:o&&!a?{a:()=>at(i,e,!1,!0),b:()=>at(s,e,!1,!1)}:{a:()=>at(i,e,!0,!0),b:()=>at(e,s,!0,!0)}}};const FM={kernelName:Ng,gradFunc:(e,t,n)=>{const{blockShape:s,crops:i}=n;return{x:()=>fh(e,s,i)}}};const _M={kernelName:Cg,gradFunc:(e,t,n)=>{const s=n,i=s.inputShape,o=s.shape,a=Array.from(o);for(let u=i.length-1;u>=0;u--)if(i[u]===o[u])a[u]=1;else if(i[u]!==1)throw new Error(`broadcastTo(): [${i}] cannot be broadcast to [${o}].`);const c=[];for(let u=0;u<a.length;u++)a[u]>1&&c.push(u);return{x:()=>Ue(e,c,!0)}}};const WM={kernelName:ul,gradFunc:e=>({x:()=>e.clone()})};const $M={kernelName:dl,gradFunc:e=>({x:()=>et(e)})};const UM={kernelName:pl,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{clipValueMin:i,clipValueMax:o}=n;return{x:()=>$n(Bs(tr(s,i),Mr(s,o)),e,et(e))}}};const BM={kernelName:td,saveAllInputs:!0,gradFunc:(e,t,n)=>{const s=t.map(u=>u.shape),{axis:i}=n,o=ft(i,t[0].shape)[0],a=s.map(u=>u[o]),c=os(e,a,o);return c.map(u=>()=>u)}};const MM={kernelName:Og,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const[s,i]=t,{dilations:o,strides:a,pad:c,dataFormat:u}=n;return k($r(o),()=>`Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${o}'`),{x:()=>gb(s.shape,e,i,a,c,u),filter:()=>Vb(s,e,i.shape,a,c,u)}}};const PM={kernelName:Eg,inputsToSave:["dy","filter"],gradFunc:(e,t,n)=>{const[s,i]=t,{strides:o,pad:a,dataFormat:c,dimRoundingMode:u}=n;return{dy:()=>er(e,i,o,a,c,1,u),filter:()=>Vb(e,s,i.shape,o,a,c,u)}}};function zM(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]])),k(o.rank===5,()=>`Error in conv3dDerFilter: input must be rank 5, but got shape ${o.shape}.`),k(a.rank===5,()=>`Error in conv3dDerFilter: dy must be rank 5, but got shape ${a.shape}.`),k(n.length===5,()=>`Error in conv3dDerFilter: filterShape must be length 5, but got ${n}.`),k(o.shape[4]===n[3],()=>`Error in conv3dDerFilter: depth of input ${o.shape[4]}) must match input depth in filter (${n[3]}.`),k(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=ih(o.shape,n,s,y,i);return m.conv3dDerFilter(o,a,b)},u={x:o,y:a},p={strides:s,pad:i};return V.runKernelFunc(c,u,null,Ox,p)}const GM=P({conv3DBackpropFilter_:zM});const VM={kernelName:Dg,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const{dilations:s,strides:i,pad:o}=n;k($r(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:()=>lA(a.shape,e,c,i,o),filter:()=>GM(a,e,c.shape,i,o)}}};const HM={kernelName:Ta,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>X(Pt(op(ve(n,"float32"))),e)}}};const YM={kernelName:ml,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>X(ap(ve(n,"float32")),e)}}};const qM={kernelName:kg,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{axis:i,exclusive:o,reverse:a}=n;return{x:()=>{const c=_n([i],s.rank);let u=jd(e,i,o,!a);return c!=null&&(u=Pe(u,c)),u}}}};const jM={kernelName:Fg,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const{dilations:s,strides:i,pad:o,dimRoundingMode:a}=n,c=s==null?[1,1]:s;k($r(c),()=>`Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations '${c}'`);const[u,p]=t;k(u.rank===4,()=>`Error in gradient of depthwiseConv2dNative: input must be rank 4, but got rank ${u.rank}.`),k(p.rank===4,()=>`Error in gradient of depthwiseConv2dNative: filter must be rank 4, but got rank ${p.rank}.`),k(u.shape[3]===p.shape[2],()=>`Error in gradient of depthwiseConv2d: number of input channels (${u.shape[3]}) must match the inChannels dimension in filter ${p.shape[2]}.`),k(on(i,c),()=>`Error in gradient of depthwiseConv2d: Either strides or dilations must be 1. Got strides ${i} and dilations '${c}'.`),a!=null&&k(Ut(o),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${o}.`);const m=Oi(u.shape,p.shape,i,c,o,a,!0);return{x:()=>HA(u.shape,e,p,m),filter:()=>VA(u,e,p.shape,m)}}};const KM={kernelName:nd,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:()=>V.runKernel(sd,o,n),filter:()=>V.runKernel(id,a,n)}}};const XM={kernelName:Aa,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,i=nt(n.shape,s.shape),o=()=>{const c=_e(e,ve(s,"float32")),u=an(n.shape,i);return u.length>0?K(Ue(c,u),n.shape):c},a=()=>{let c=X(e,ve(n,"float32"));const u=an(s.shape,i);u.length>0&&(c=K(Ue(c,u),s.shape));const p=Lt(s);return Pt(_e(c,ve(p,"float32")))};return{a:o,b:a}}};const JM={kernelName:fl,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t,s=o=>o.eluDer(e,n),i={dy:e,y:n};return{x:()=>V.runKernelFunc(s,i,null,$x)}}};const ZM={kernelName:gl,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t,s=X(xs(Pt(Lt(n))),2/Math.sqrt(Math.PI));return{x:()=>X(e,s)}}};const QM={kernelName:yl,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>X(e,n)}}};const eP={kernelName:bl,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>X(e,xs(n))}}};const tP={kernelName:wl,gradFunc:e=>({x:()=>et(e)})};const nP={kernelName:Wg,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,i=nt(n.shape,s.shape),o=()=>{const c=_e(e,ve(s,"float32")),u=an(n.shape,i);return u.length>0?K(Ue(c,u),n.shape):c},a=()=>{let c=X(e,ve(n,"float32"));const u=an(s.shape,i);u.length>0&&(c=K(Ue(c,u),s.shape));const p=Lt(s);return Pt(_e(c,ve(p,"float32")))};return{a:o,b:a}}};const sP={kernelName:Ll,inputsToSave:["x","mean","variance","scale"],gradFunc:(e,t,n)=>{const{varianceEpsilon:s}=n,[i,o,a,c]=t,u=c==null?Ne(1):c,p=an(o.shape,i.shape),m=[];if(o.rank===1){for(let F=0;F<i.shape.length-1;++F)m.push(i.shape[F]);m.push(1)}const y=Ce(i,o),b=X(e,u),w=ip(be(a,Ne(s))),I=X(X(X(w,w),w),Ne(-.5)),T=()=>o.rank===1?K(X(X(e,Br(K(w,[1,1,1,o.shape[0]]),m)),u),i.shape):K(X(X(e,w),u),i.shape),v=()=>{let F=X(X(w,Ne(-1)),b);return o.rank===1&&(F=Ue(F,p)),K(F,o.shape)},N=()=>{let F=X(X(I,y),b);return o.rank===1&&(F=Ue(F,p)),K(F,o.shape)},E=()=>{const F=X(y,w);let _=X(e,F);return o.rank===1&&(_=Ue(_,p)),K(_,o.shape)},D=()=>{let F=e;return o.rank===1&&(F=Ue(F,p)),K(F,o.shape)};return{x:T,mean:v,variance:N,scale:E,offset:D}}};const iP={kernelName:$g,inputsToSave:["x","indices"],gradFunc:(e,t,n)=>{const[s,i]=t,{axis:o}=n,a=ft(o,s.shape)[0],c=()=>{const u=s.shape,p=i.size,m=u.slice(0,a),y=m.length,b=u.slice(o,u.length).slice(1),w=b.length,I=cv(0,y),T=cv(y+1,y+1+w),v=lv([m,[p],b]),N=K(e,v),E=K(i,[p]),D=lv([[y],I,T]),F=Pe(N,D);let _=Mb(F,E,s.shape[a]);const B=eh(D);return _=Pe(_,B),_};return{x:c,indices:()=>i}}};function cv(e,t){const n=[];for(let s=e;s<t;++s)n.push(s);return n}function lv(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 rP={kernelName:Ug,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t;return{a:()=>et(n),b:()=>et(s)}}};const oP={kernelName:Sl,gradFunc:e=>({x:()=>ve(e,"float32")})};const aP={kernelName:Il,gradFunc:e=>({x:()=>et(e)})};const cP={kernelName:xl,gradFunc:e=>({x:()=>et(e)})};const lP={kernelName:Tl,gradFunc:e=>({x:()=>et(e)})};const hP={kernelName:vl,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>_e(e,be(n,1))}}};const uP={kernelName:Al,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>_e(e,ve(n,"float32"))}}};const dP={kernelName:Pg,inputsToSave:[],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[s]=t,{axis:i}=n;return{logits:()=>{const o=!0,a=xs(s);return Ce(e,X(Ue(e,i,o),a))}}}};function pP(e,t,n,s=5,i=1,o=1,a=.5){const c=m=>m.LRNGrad(n,e,t,s,i,o,a),u={x:e,y:t,dy:n},p={depthRadius:s,bias:i,alpha:o,beta:a};return V.runKernelFunc(c,u,null,qx,p)}const mP=P({localResponseNormalizationBackprop_:pP});const fP={kernelName:zg,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[s,i]=t,{depthRadius:o,bias:a,alpha:c,beta:u}=n;return{x:()=>mP(s,i,e,o,a,c,u)}}};function hv(e,t,n,s,i){return t.rank<n.rank&&(t=K(t,En(t.shape,s))),e.rank<n.rank&&(e=K(e,En(e.shape,s))),{x:()=>{const o=X(e,ve(ni(n,t),e.dtype));return i==null?o:Pe(o,i)}}}const uv={kernelName:Nl,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const s=n,{reductionIndices:i}=s,[o,a]=t,c=ft(i,o.shape),u=_n(c,o.rank),p=hv(e,a,o,c,u);return{x:()=>{let m=p.x();return u!=null&&(m=Pe(m)),m}}}};const gP={kernelName:Gg,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,i=()=>X(e,ve(tr(n,s),"float32")),o=()=>X(e,ve(dh(n,s),"float32"));return{a:i,b:o}}};function yP(e,t,n,s,i,o=[1,1,1],a,c){const u=W(e,"dy","maxPool3dBackprop"),p=W(t,"input","maxPool3dBackprop"),m=W(n,"output","maxPool3dBackprop");let y=u,b=p,w=m,I=!1;p.rank===4&&(I=!0,y=K(u,[1,u.shape[0],u.shape[1],u.shape[2],u.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]])),k(y.rank===5,()=>`Error in maxPool3dBackprop: dy must be rank 5 but got rank ${y.rank}.`),k(b.rank===5,()=>`Error in maxPool3dBackprop: input must be rank 5 but got rank ${b.rank}.`),k(w.rank===5,()=>`Error in maxPool3dBackprop: output must be rank 5 but got rank ${w.rank}.`),k(on(i,o),()=>`Error in maxPool3dBackprop: Either strides or dilations must be 1. Got strides ${i} and dilations '${o}'`),c!=null&&k(Ut(a),()=>`Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode ${c} but got pad ${a}.`);const T=D=>{const F=sh(b.shape,s,i,o,a,c);return D.maxPool3dBackprop(y,b,w,F)},v={dy:y,input:b,output:w},N={filterSize:s,strides:i,dilations:o,pad:a,dimRoundingMode:c},E=V.runKernelFunc(T,v,null,jx,N);return I?K(E,[E.shape[1],E.shape[2],E.shape[3],E.shape[4]]):E}const bP=P({maxPool3dBackprop_:yP});const wP={kernelName:Vg,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[s,i]=t,{filterSize:o,strides:a,dilations:c,pad:u,dimRoundingMode:p}=n,m=c==null?[1,1,1]:c;return{x:()=>bP(e,s,i,o,a,m,u,p)}}};function LP(e,t,n,s,i,o,a){const c=W(e,"dy","maxPoolBackprop"),u=W(t,"input","maxPoolBackprop"),p=W(n,"output","maxPoolBackprop");k(u.rank===c.rank,()=>`Rank of input (${u.rank}) does not match rank of dy (${c.rank})`),k(c.rank===4,()=>`Error in maxPoolBackprop: dy must be rank 4 but got rank ${c.rank}.`),k(u.rank===4,()=>`Error in maxPoolBackprop: input must be rank 4 but got rank ${u.rank}.`),a!=null&&k(Ut(o),()=>`Error in maxPoolBackprop: pad must be an integer when using, dimRoundingMode ${a} but got pad ${o}.`);const m=w=>{const I=Wn(u.shape,s,i,1,o,a);return w.maxPoolBackprop(c,u,p,I)},y={dy:c,input:u,output:p},b={filterSize:s,strides:i,pad:o,dimRoundingMode:a};return V.runKernelFunc(m,y,null,ad,b)}const SP=P({maxPoolBackprop_:LP});const IP={kernelName:Cl,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[s,i]=t,{filterSize:o,strides:a,pad:c}=n;return{x:()=>SP(e,s,i,o,a,c)}}};const xP={kernelName:Hg,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const s=n,{axis:i}=s,[o,a]=t,c=ft(i,o.shape),u=_n(c,o.rank),p=hv(e,a,o,c,u);return{x:()=>{let m=p.x();return u!=null&&(m=Pe(m)),m}}}};const TP={kernelName:Yg,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,i=()=>X(e,ve(Mr(n,s),"float32")),o=()=>X(e,ve(Ts(n,s),"float32"));return{a:i,b:o}}};const AP={kernelName:qg,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,i=nt(n.shape,s.shape),o=()=>{const c=an(n.shape,i);return c.length>0?K(Ue(e,c),n.shape):e},a=()=>{const c=X(e,Pt(Pa(_e(n,s)))),u=an(s.shape,i);return u.length>0?K(Ue(c,u),s.shape):c};return{a:o,b:a}}};const vP={kernelName:Rl,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,i=nt(n.shape,s.shape),o=()=>{const c=X(e,ve(s,"float32")),u=an(n.shape,i);return u.length>0?K(Ue(c,u),n.shape):c},a=()=>{const c=X(e,ve(n,"float32")),u=an(s.shape,i);return u.length>0?K(Ue(c,u),s.shape):c};return{a:o,b:a}}};const NP={kernelName:jg,gradFunc:e=>({x:()=>Pt(e)})};const CP={kernelName:Jg,inputsToSave:["indices"],gradFunc:(e,t)=>{const n=t[0];return{indices:()=>ct(n.shape,"float32")}}};const RP={kernelName:Xg,gradFunc:e=>({x:()=>et(e)})};const dv={kernelName:dd,inputsToSave:["x"],gradFunc:(e,t,n)=>{const s=t[0],{paddings:i}=n,o=i.map(a=>a[0]);return{x:()=>st(e,o,s.shape)}}};const OP={kernelName:Zg,inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:(e,t)=>{const[n,s,i]=t,o=n,a=s,c=nt(o.shape,a.shape),u=()=>{const m=ve(a,"float32");let y=X(e,X(m,ii(o,Ce(m,Ne(1)))));const b=an(o.shape,c);return b.length>0&&(y=Ue(y,b)),K(y,o.shape)},p=()=>{const m=Ts(o,0),y=$n(m,is(o),et(o));let b=X(e,X(i,y));const w=an(a.shape,c);return w.length>0&&(b=Ue(b,w)),K(b,a.shape)};return{a:u,b:p}}};const EP={kernelName:Qg,inputsToSave:["x","alpha"],gradFunc:(e,t)=>{const[n,s]=t,i=Ts(n,0);return{x:()=>$n(i,e,X(e,s)),alpha:()=>{let o=$n(i,et(e),X(e,n));const a=an(s.shape,e.shape);return a.length>0&&(o=Ue(o,a)),K(o,s.shape)}}}};const DP={kernelName:Ol,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>_e(e,Pt(Lt(n)))}}};const kP={kernelName:iy,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t,s=X(Mr(n,6),Ka(n));return{x:()=>X(e,ve(s,"float32"))}}};const FP={kernelName:ty,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>X(e,ve(Ka(n),"float32"))}}};const _P={kernelName:El,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>K(e,n.shape)}}};const WP={kernelName:sy,inputsToSave:["images"],gradFunc:(e,t,n)=>{const[s]=t,i=c=>{const{alignCorners:u}=n;return c.resizeBilinearBackprop(e,s,u)},o={images:s},a=()=>V.runKernelFunc(i,o,null,Zx,n);return{images:a}}};const $P={kernelName:ny,inputsToSave:["images"],gradFunc:(e,t,n)=>{const[s]=t,i=c=>{const{alignCorners:u}=n;return c.resizeNearestNeighborBackprop(e,s,u)},o={images:s},a=()=>V.runKernelFunc(i,o,null,Jx,n);return{images:a}}};const UP={kernelName:ry,gradFunc:(e,t,n)=>{const{dims:s}=n,i=ft(s,e.shape);return{x:()=>As(e,i)}}};const BP={kernelName:Dl,gradFunc:e=>({x:()=>et(e)})};const MP={kernelName:kl,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Pt(_e(e,X(ii(n,1.5),2)))}}};const PP={kernelName:oy,inputsToSave:["condition"],gradFunc:(e,t)=>{const[n]=t;return{condition:()=>ve(et(n),"float32"),t:()=>X(e,ve(n,e.dtype)),e:()=>X(e,ve(ph(n),e.dtype))}}};const zP={kernelName:Fl,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const s=Ts(n,Ne(0)),i=Ne(xp),o=Ne(Tp),a=X(e,o),c=X(X(e,i),xs(ve(n,"float32")));return $n(s,a,c)}}}};const GP={kernelName:$l,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>X(e,X(n,Ce(Ne(1),n)))}}};const VP={kernelName:Wl,gradFunc:e=>({x:()=>et(e)})};const HP={kernelName:va,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>X(lh(ve(n,"float32")),e)}}};const YP={kernelName:_l,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>X(qd(ve(n,"float32")),e)}}};const qP={kernelName:pd,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{begin:i,size:o}=n,a=s.shape,[c,u]=$d(s,i,o),p=[];for(let m=0;m<e.rank;m++)p.push([c[m],a[m]-c[m]-u[m]]);return{x:()=>ki(e,p)}}};const jP={kernelName:ly,outputsToSave:[!0],gradFunc:(e,t,n)=>{const[s]=t,{dim:i}=n,o=!0,a=X(e,s);return{logits:()=>Ce(a,X(Ue(a,[i],o),s))}}};const KP={kernelName:Ul,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>X(e,Ei(n))}}};const pv={kernelName:md,gradFunc:(e,t,n)=>{const{blockShape:s,paddings:i}=n;return{x:()=>ah(e,s,i)}}};const mv={kernelName:cy,gradFunc:(e,t,n)=>{const{axis:s}=n;return{x:()=>Mt(e,s)}}};const XP={kernelName:Bl,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>_e(e,X(Sn(ve(n,"float32")),2))}}};const JP={kernelName:fd,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>X(e,X(ve(n,"float32"),2))}}};const ZP={kernelName:Na,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,i=Ne(2),o=()=>X(e,X(i,Ce(n,s))),a=()=>X(e,X(i,Ce(s,n)));return{a:o,b:a}}};const QP={kernelName:Gl,gradFunc:e=>({x:()=>et(e)})};const ez={kernelName:Ml,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,i=nt(n.shape,s.shape),o=()=>{let c=e;const u=an(n.shape,i);return u.length>0&&(c=Ue(c,u)),K(c,n.shape)},a=()=>{let c=e;const u=an(s.shape,i);return u.length>0&&(c=Ue(c,u)),K(Pt(c),s.shape)};return{a:o,b:a}}};const tz={kernelName:ay,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,i=s.shape.slice(),{axis:o}=n,a=ft(o,s.shape);a.forEach(p=>{i[p]=1});const c=K(e,i),u=X(c,si(s.shape,"float32"));return{x:()=>u}}};const nz={kernelName:Ca,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>_e(e,Lt(lh(n)))}}};const sz={kernelName:Pl,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>X(Ce(Ne(1),Lt(n)),e)}}};const iz={kernelName:hy,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{reps:i}=n,o=()=>{let a=et(s);if(s.rank===1)for(let c=0;c<i[0];++c)a=be(a,st(e,[c*s.shape[0]],[s.shape[0]]));else if(s.rank===2)for(let c=0;c<i[0];++c)for(let u=0;u<i[1];++u)a=be(a,st(e,[c*s.shape[0],u*s.shape[1]],[s.shape[0],s.shape[1]]));else if(s.rank===3)for(let c=0;c<i[0];++c)for(let u=0;u<i[1];++u)for(let p=0;p<i[2];++p)a=be(a,st(e,[c*s.shape[0],u*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 u=0;u<i[1];++u)for(let p=0;p<i[2];++p)for(let m=0;m<i[3];++m)a=be(a,st(e,[c*s.shape[0],u*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 rz={kernelName:zl,gradFunc:(e,t,n)=>{const s=n,{perm:i}=s,o=eh(i);return{x:()=>Pe(e,o)}}};const oz={kernelName:uy,gradFunc:(e,t,n)=>{const s=n,{axis:i}=s;return{value:()=>as(e,i)}}};const az={kernelName:dy,inputsToSave:["segmentIds"],gradFunc:(e,t)=>{const[n]=t,s=()=>cz(e,n);return{x:s}}};function cz(e,t){const n=Us(t,et(t)),s=za(e,n);let i=tr(t,Ne(0,"int32"));const o=s.rank-i.rank;for(let c=0;c<o;++c)i=Kn(i,c+1);i=Bs(i,si(s.shape,"bool"));const a=et(s);return $n(i,s,a)}const lz={kernelName:py,gradFunc:e=>({x:()=>et(e)})};const hz=[fM,gM,yM,bM,wM,LM,SM,IM,xM,TM,AM,vM,RM,DM,kM,FM,_M,WM,$M,UM,BM,PM,MM,VM,HM,YM,qM,jM,KM,XM,JM,ZM,QM,eP,nP,tP,sP,iP,rP,oP,aP,cP,lP,hP,uP,dP,fP,uv,uv,gP,wP,IP,xP,TP,AP,vP,NP,CP,RP,dv,dv,OP,EP,DP,kP,FP,_P,WP,$P,UP,BP,MP,PP,zP,GP,VP,HP,YP,qP,jP,KP,pv,pv,mv,mv,XP,ZP,JP,QP,ez,tz,nz,sz,iz,rz,oz,az,lz];for(const e of hz)sT(e);Q.prototype.abs=function(){return this.throwIfDisposed(),rn(this)};Q.prototype.acos=function(){return this.throwIfDisposed(),nb(this)};Q.prototype.acosh=function(){return this.throwIfDisposed(),sb(this)};Q.prototype.addStrict=function(e){return this.throwIfDisposed(),OA(this,e)};Q.prototype.add=function(e){return this.throwIfDisposed(),be(this,e)};Q.prototype.all=function(e,t){return this.throwIfDisposed(),Pd(this,e,t)};Q.prototype.any=function(e,t){return this.throwIfDisposed(),th(this,e,t)};Q.prototype.argMax=function(e){return this.throwIfDisposed(),nh(this,e)};Q.prototype.argMin=function(e){return this.throwIfDisposed(),rb(this,e)};Q.prototype.asScalar=function(){return this.throwIfDisposed(),k(this.size===1,()=>"The array must have only 1 element."),K(this,[])};Q.prototype.asType=function(e){return this.throwIfDisposed(),ve(this,e)};Q.prototype.as1D=function(){return this.throwIfDisposed(),K(this,[this.size])};Q.prototype.as2D=function(e,t){return this.throwIfDisposed(),K(this,[e,t])};Q.prototype.as3D=function(e,t,n){return this.throwIfDisposed(),K(this,[e,t,n])};Q.prototype.as4D=function(e,t,n,s){return this.throwIfDisposed(),K(this,[e,t,n,s])};Q.prototype.as5D=function(e,t,n,s,i){return this.throwIfDisposed(),K(this,[e,t,n,s,i])};Q.prototype.asin=function(){return this.throwIfDisposed(),ob(this)};Q.prototype.asinh=function(){return this.throwIfDisposed(),ab(this)};Q.prototype.atan=function(){return this.throwIfDisposed(),cb(this)};Q.prototype.atan2=function(e){return this.throwIfDisposed(),lb(this,e)};Q.prototype.atanh=function(){return this.throwIfDisposed(),hb(this)};Q.prototype.avgPool=function(e,t,n,s){return this.throwIfDisposed(),oh(this,e,t,n,s)};Q.prototype.batchToSpaceND=function(e,t){return this.throwIfDisposed(),ah(this,e,t)};Q.prototype.batchNorm=function(e,t,n,s,i){return this.throwIfDisposed(),Ro(this,e,t,n,s,i)};Q.prototype.broadcastTo=function(e){return this.throwIfDisposed(),ch(this,e)};Q.prototype.cast=function(e){return this.throwIfDisposed(),ve(this,e)};Q.prototype.ceil=function(){return this.throwIfDisposed(),fb(this)};Q.prototype.clipByValue=function(e,t){return this.throwIfDisposed(),jn(this,e,t)};Q.prototype.concat=function(e,t){return this.throwIfDisposed(),e instanceof Q&&(e=[e]),Mt([this,...e],t)};Q.prototype.conv1d=function(e,t,n,s,i,o){return this.throwIfDisposed(),Hd(this,e,t,n,s,i,o)};Q.prototype.conv2dTranspose=function(e,t,n,s,i){return this.throwIfDisposed(),Yd(this,e,t,n,s,i)};Q.prototype.conv2d=function(e,t,n,s,i,o){return this.throwIfDisposed(),er(this,e,t,n,s,i,o)};Q.prototype.cos=function(){return this.throwIfDisposed(),lh(this)};Q.prototype.cosh=function(){return this.throwIfDisposed(),qd(this)};Q.prototype.cumsum=function(e,t,n){return this.throwIfDisposed(),jd(this,e,t,n)};Q.prototype.depthToSpace=function(e,t){return this.throwIfDisposed(),bb(this,e,t)};Q.prototype.depthwiseConv2D=function(e,t,n,s,i,o){return sn("depthwiseConv2D is deprecated, use depthwiseConv2d instead"),this.throwIfDisposed(),Oo(this,e,t,n,s,i,o)};Q.prototype.depthwiseConv2d=function(e,t,n,s,i,o){return this.throwIfDisposed(),Oo(this,e,t,n,s,i,o)};Q.prototype.dilation2d=function(e,t,n,s,i){return this.throwIfDisposed(),wb(this,e,t,n,s,i)};Q.prototype.divNoNan=function(e){return this.throwIfDisposed(),Lb(this,e)};Q.prototype.divStrict=function(e){return this.throwIfDisposed(),EA(this,e)};Q.prototype.div=function(e){return this.throwIfDisposed(),_e(this,e)};Q.prototype.dot=function(e){return this.throwIfDisposed(),hA(this,e)};Q.prototype.elu=function(){return this.throwIfDisposed(),Do(this)};Q.prototype.equalStrict=function(e){return this.throwIfDisposed(),TA(this,e)};Q.prototype.equal=function(e){return this.throwIfDisposed(),ni(this,e)};Q.prototype.erf=function(){return this.throwIfDisposed(),Sb(this)};Q.prototype.exp=function(){return this.throwIfDisposed(),xs(this)};Q.prototype.expandDims=function(e){return this.throwIfDisposed(),Kn(this,e)};Q.prototype.expm1=function(){return this.throwIfDisposed(),Ib(this)};Q.prototype.fft=function(){return this.throwIfDisposed(),wh(this)};Q.prototype.flatten=function(){return this.throwIfDisposed(),K(this,[this.size])};Q.prototype.floor=function(){return this.throwIfDisposed(),Pa(this)};Q.prototype.floorDiv=function(e){return this.throwIfDisposed(),Md(this,e)};Q.prototype.gather=function(e,t){return this.throwIfDisposed(),za(this,e,t)};Q.prototype.greaterEqualStrict=function(e){return this.throwIfDisposed(),AA(this,e)};Q.prototype.greaterEqual=function(e){return this.throwIfDisposed(),tr(this,e)};Q.prototype.greaterStrict=function(e){return this.throwIfDisposed(),vA(this,e)};Q.prototype.greater=function(e){return this.throwIfDisposed(),Ts(this,e)};Q.prototype.ifft=function(){return this.throwIfDisposed(),ja(this)};Q.prototype.irfft=function(){return this.throwIfDisposed(),hp(this)};Q.prototype.isFinite=function(){return this.throwIfDisposed(),dA(this)};Q.prototype.isInf=function(){return this.throwIfDisposed(),pA(this)};Q.prototype.isNaN=function(){return this.throwIfDisposed(),mA(this)};Q.prototype.leakyRelu=function(e){return this.throwIfDisposed(),Xd(this,e)};Q.prototype.lessEqualStrict=function(e){return this.throwIfDisposed(),NA(this,e)};Q.prototype.lessEqual=function(e){return this.throwIfDisposed(),Mr(this,e)};Q.prototype.lessStrict=function(e){return this.throwIfDisposed(),CA(this,e)};Q.prototype.less=function(e){return this.throwIfDisposed(),dh(this,e)};Q.prototype.localResponseNormalization=function(e,t,n,s){return this.throwIfDisposed(),Tb(this,e,t,n,s)};Q.prototype.logSigmoid=function(){return this.throwIfDisposed(),gA(this)};Q.prototype.logSoftmax=function(e){return this.throwIfDisposed(),Qd(this,e)};Q.prototype.logSumExp=function(e,t){return this.throwIfDisposed(),vb(this,e,t)};Q.prototype.log=function(){return this.throwIfDisposed(),is(this)};Q.prototype.log1p=function(){return this.throwIfDisposed(),Jd(this)};Q.prototype.logicalAnd=function(e){return this.throwIfDisposed(),Bs(this,e)};Q.prototype.logicalNot=function(){return this.throwIfDisposed(),ph(this)};Q.prototype.logicalOr=function(e){return this.throwIfDisposed(),ep(this,e)};Q.prototype.logicalXor=function(e){return this.throwIfDisposed(),yA(this,e)};Q.prototype.matMul=function(e,t,n){return this.throwIfDisposed(),at(this,e,t,n)};Q.prototype.maxPool=function(e,t,n,s){return this.throwIfDisposed(),mh(this,e,t,n,s)};Q.prototype.max=function(e,t){return this.throwIfDisposed(),Xn(this,e,t)};Q.prototype.maximumStrict=function(e){return this.throwIfDisposed(),DA(this,e)};Q.prototype.maximum=function(e){return this.throwIfDisposed(),Us(this,e)};Q.prototype.mean=function(e,t){return this.throwIfDisposed(),zt(this,e,t)};Q.prototype.min=function(e,t){return this.throwIfDisposed(),Ha(this,e,t)};Q.prototype.minimumStrict=function(e){return this.throwIfDisposed(),kA(this,e)};Q.prototype.minimum=function(e){return this.throwIfDisposed(),ko(this,e)};Q.prototype.modStrict=function(e){return this.throwIfDisposed(),FA(this,e)};Q.prototype.mod=function(e){return this.throwIfDisposed(),tp(this,e)};Q.prototype.mulStrict=function(e){return this.throwIfDisposed(),_A(this,e)};Q.prototype.mul=function(e){return this.throwIfDisposed(),X(this,e)};Q.prototype.neg=function(){return this.throwIfDisposed(),Pt(this)};Q.prototype.norm=function(e,t,n){return this.throwIfDisposed(),pp(this,e,t,n)};Q.prototype.notEqualStrict=function(e){return this.throwIfDisposed(),RA(this,e)};Q.prototype.notEqual=function(e){return this.throwIfDisposed(),Pr(this,e)};Q.prototype.oneHot=function(e,t=1,n=0){return this.throwIfDisposed(),vo(this,e,t,n)};Q.prototype.onesLike=function(){return this.throwIfDisposed(),Dn(this)};Q.prototype.pad=function(e,t){return this.throwIfDisposed(),ki(this,e,t)};Q.prototype.pool=function(e,t,n,s,i){return this.throwIfDisposed(),LA(this,e,t,n,s,i)};Q.prototype.powStrict=function(e){return this.throwIfDisposed(),WA(this,e)};Q.prototype.pow=function(e){return this.throwIfDisposed(),ii(this,e)};Q.prototype.prelu=function(e){return this.throwIfDisposed(),gh(this,e)};Q.prototype.prod=function(e,t){return this.throwIfDisposed(),sp(this,e,t)};Q.prototype.reciprocal=function(){return this.throwIfDisposed(),Eb(this)};Q.prototype.relu=function(){return this.throwIfDisposed(),Fi(this)};Q.prototype.relu6=function(){return this.throwIfDisposed(),Db(this)};Q.prototype.reshapeAs=function(e){return this.throwIfDisposed(),K(this,e.shape)};Q.prototype.reshape=function(e){return this.throwIfDisposed(),K(this,e)};Q.prototype.resizeBilinear=function(e,t){return this.throwIfDisposed(),XA(this,e,t)};Q.prototype.resizeNearestNeighbor=function(e,t){return this.throwIfDisposed(),JA(this,e,t)};Q.prototype.reverse=function(e){return this.throwIfDisposed(),As(this,e)};Q.prototype.rfft=function(){return this.throwIfDisposed(),Lh(this)};Q.prototype.round=function(){return this.throwIfDisposed(),kb(this)};Q.prototype.rsqrt=function(){return this.throwIfDisposed(),ip(this)};Q.prototype.selu=function(){return this.throwIfDisposed(),rp(this)};Q.prototype.separableConv2d=function(e,t,n,s,i,o){return this.throwIfDisposed(),Fb(this,e,t,n,s,i,o)};Q.prototype.sigmoid=function(){return this.throwIfDisposed(),Ei(this)};Q.prototype.sign=function(){return this.throwIfDisposed(),_b(this)};Q.prototype.sin=function(){return this.throwIfDisposed(),op(this)};Q.prototype.sinh=function(){return this.throwIfDisposed(),ap(this)};Q.prototype.slice=function(e,t){return this.throwIfDisposed(),st(this,e,t)};Q.prototype.softmax=function(e){return this.throwIfDisposed(),Uo(this,e)};Q.prototype.softplus=function(){return this.throwIfDisposed(),Va(this)};Q.prototype.spaceToBatchND=function(e,t){return this.throwIfDisposed(),fh(this,e,t)};Q.prototype.split=function(e,t){return this.throwIfDisposed(),os(this,e,t)};Q.prototype.sqrt=function(){return this.throwIfDisposed(),Sn(this)};Q.prototype.square=function(){return this.throwIfDisposed(),Lt(this)};Q.prototype.squaredDifference=function(e){return this.throwIfDisposed(),Sh(this,e)};Q.prototype.squaredDifferenceStrict=function(e){return this.throwIfDisposed(),$A(this,e)};Q.prototype.squeeze=function(e){return this.throwIfDisposed(),zr(this,e)};Q.prototype.stack=function(e,t){this.throwIfDisposed();const n=e instanceof Q?[this,e]:[this,...e];return as(n,t)};Q.prototype.step=function(e){return this.throwIfDisposed(),Ka(this,e)};Q.prototype.stridedSlice=function(e,t,n,s,i,o,a,c){return this.throwIfDisposed(),$b(this,e,t,n,s,i,o,a,c)};Q.prototype.subStrict=function(e){return this.throwIfDisposed(),UA(this,e)};Q.prototype.sub=function(e){return this.throwIfDisposed(),Ce(this,e)};Q.prototype.sum=function(e,t){return this.throwIfDisposed(),Ue(this,e,t)};Q.prototype.tan=function(){return this.throwIfDisposed(),Ub(this)};Q.prototype.tanh=function(){return this.throwIfDisposed(),Ma(this)};Q.prototype.tile=function(e){return this.throwIfDisposed(),Br(this,e)};Q.prototype.toBool=function(){return this.throwIfDisposed(),ve(this,"bool")};Q.prototype.toFloat=function(){return this.throwIfDisposed(),ve(this,"float32")};Q.prototype.toInt=function(){return this.throwIfDisposed(),ve(this,"int32")};Q.prototype.topk=function(e,t){return this.throwIfDisposed(),Bb(this,e,t)};Q.prototype.transpose=function(e){return this.throwIfDisposed(),Pe(this,e)};Q.prototype.unique=function(e){return this.throwIfDisposed(),up(this,e)};Q.prototype.unsortedSegmentSum=function(e,t){return this.throwIfDisposed(),Mb(this,e,t)};Q.prototype.unstack=function(e){return this.throwIfDisposed(),_i(this,e)};Q.prototype.where=function(e,t){return this.throwIfDisposed(),$n(e,this,t)};Q.prototype.zerosLike=function(){return this.throwIfDisposed(),et(this)};let Ap;function cn(){return Ap==null&&(Ap=QT().epsilon()),Ap}function $Q(e){Ap=e}function ri(){return"channelsLast"}class rr extends Error{constructor(e){super(e);Object.setPrototypeOf(this,rr.prototype)}}class oi extends Error{constructor(e){super(e);Object.setPrototypeOf(this,oi.prototype)}}class j extends Error{constructor(e){super(e);Object.setPrototypeOf(this,j.prototype)}}class Ge extends Error{constructor(e){super(e);Object.setPrototypeOf(this,Ge.prototype)}}class fv extends Error{constructor(e){super(e);Object.setPrototypeOf(this,fv.prototype)}}class uz extends Error{constructor(e){super(e);Object.setPrototypeOf(this,uz.prototype)}}function Po(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 vs(e,t){if(!e)throw new fv(t)}function gv(e,t){let n=0;for(const s of e)s===t&&n++;return n}function Jn(e){return e.length===1?e[0]:e}function Nt(e){return Array.isArray(e)?e:[e]}function UQ(e){const t=Nt(e);let n="";for(const s of t){if(s.id==null)throw new j(`Object ${s} passed to objectListUid without an id`);n!==""&&(n=n+", "),n=`${n}${Math.abs(s.id)}`}return n}function or(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 zo(e){return e.length<=1||e.indexOf("_")===-1?e:e.replace(/[_]+(\w|$)/g,(t,n)=>n.toUpperCase())}let Ms={};function cw(e){if(e==null)return null;const t={};return t.className=e.getClassName(),t.config=e.getConfig(),t}function lw(e){if(e==null||typeof e!="object")return;if(Array.isArray(e))e.forEach(t=>lw(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:lw(s))}}}function Dh(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 Ms)a=Ms[o];else if(a=t[o],a==null)throw new j(`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 j(`${s}: Improper config format: ${JSON.stringify(o)}.
'className' and 'config' must set.`);const a=o.className;let c,u;if(a in n?[c,u]=n[a]:a in Ms?[c,u]=Ms.className:a in t&&([c,u]=t[a]),c==null)throw new j(`Unknown ${s}: ${a}. This may be due to one of the following reasons:
1. The ${s} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
2. The custom ${s} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);if(u!=null){const p={};for(const w of Object.keys(Ms))p[w]=Ms[w];for(const w of Object.keys(n))p[w]=n[w];const m=o.config;m.customObjects=p;const y=Object.assign({},Ms);for(const w of Object.keys(n))Ms[w]=n[w];lw(o.config);const b=u(c,o.config,n,i);return Ms=Object.assign({},y),b}else{const p=Object.assign({},Ms);for(const y of Object.keys(n))Ms[y]=n[y];const m=new c(o.config);return Ms=Object.assign({},p),m}}}function dz(e,t){return e<t?-1:e>t?1:0}function vp(e,t){return-1*dz(e,t)}function BQ(e){switch(e){case"float32":return"float32";default:throw new j(`Invalid dtype: ${e}`)}}function MQ(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 Hr(e){if(e==null)return e;const t=[];for(const n of e)t.indexOf(n)===-1&&t.push(n);return t}function pz(e){if(e==null)throw new j(`Invalid value in obj: ${JSON.stringify(e)}`);for(const t in e)if(e.hasOwnProperty(t))return!1;return!0}function ec(e,t,n){if(n==null)return;if(e.indexOf(n)<0)throw new j(`${n} is not a valid ${t}. Valid values are ${e} or null/undefined.`)}function hw(e,t,n=0,s=Infinity){return vs(n>=0),vs(s>=n),Array.isArray(e)&&e.length>=n&&e.length<=s&&e.every(i=>typeof i===t)}function mn(e,t){Array.isArray(e)?(k(e.length>0,()=>`${t} is unexpectedly an empty array.`),e.forEach((n,s)=>mn(n,`element ${s+1} of ${t}`))):k(Number.isInteger(e)&&e>0,()=>`Expected ${t} to be a positive integer, but got ${yv(e)}.`)}function yv(e){return e===null?"null":Array.isArray(e)?"["+e.map(t=>yv(t)).join(",")+"]":typeof e=="string"?`"${e}"`:`${e}`}function mz(e,t){let n=qn(),s;const i=(...o)=>{const a=qn();return a-n<t||(n=a,s=e(...o)),s};return i}function bv(e){return e==="relu"?"relu":e==="linear"?"linear":e==="elu"?"elu":null}function PQ(...e){vs(e.length>0,"arrayOfValues is empty");for(const t of e)vs(Array.isArray(t),"one of the values is not an array"),vs(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 uw(e,t){return ee(()=>Sn(Ue(X(e,e),t,!0)))}class kh extends No{getConfig(){return{}}}class dw extends kh{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=uw(e,this.axis),n=jn(t,0,this.maxValue);return X(e,_e(n,be(cn(),t)))})}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}}dw.className="MaxNorm",ge(dw);class pw extends kh{constructor(e){super();this.defaultAxis=0,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return ee(()=>_e(e,be(cn(),uw(e,this.axis))))}getConfig(){return{axis:this.axis}}}pw.className="UnitNorm",ge(pw);class mw extends kh{apply(e){return Fi(e)}}mw.className="NonNeg",ge(mw);class fw extends kh{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=uw(e,this.axis),n=be(X(this.rate,jn(t,this.minValue,this.maxValue)),X(1-this.rate,t));return X(e,_e(n,be(cn(),t)))})}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}}fw.className="MinMaxNorm",ge(fw);const wv={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function ln(e){return cw(e)}function Lv(e,t={}){return Dh(e,Ws.getMap().classNameMap,t,"constraint")}function hn(e){if(e==null)return null;if(typeof e=="string"){const t=e in wv?wv[e]:e,n={className:t,config:{}};return Lv(n)}else return e instanceof kh?e:Lv(e)}function fz(e){return new dw(e)}function gz(e){return new pw(e)}function yz(){return new mw}function bz(e){return new fw(e)}var wz=Object.freeze({__proto__:null,maxNorm:fz,unitNorm:gz,nonNeg:yz,minMaxNorm:bz});const Lz=["channelsFirst","channelsLast"],Sz=["valid","same","causal"],Iz=["max","avg"],xz=["sum","mul","concat","ave"],zQ=["temporal"];const tc=new Map;function Gt(e){ec(Lz,"DataFormat",e)}function Ns(e){ec(Sz,"PaddingMode",e)}function Sv(e){ec(Iz,"PoolMode",e)}const Fh=[],Iv="/";function Go(e,t){Fh.push(e);try{const n=t();return Fh.pop(),n}catch(n){throw Fh.pop(),n}}function Tz(){return Fh.length===0?"":Fh.join(Iv)+Iv}function xv(e){if(!Av(e))throw new Error("Not a valid tensor name: '"+e+"'");return Tz()+e}function Tv(e){if(!Av(e))throw new Error("Not a valid tensor name: '"+e+"'");tc.has(e)||tc.set(e,0);const t=tc.get(e);if(tc.set(e,tc.get(e)+1),t>0){const n=`${e}_${t}`;return tc.set(n,1),n}else return e}const Az=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function Av(e){return!!e.match(Az)}function vz(e){return e===parseInt(e.toString(),10)}function Yr(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 Np(e){return e=Array.isArray(e)?new Float32Array(e):e,rs(e)}function nc(e){return Ha(Np(e)).dataSync()[0]}function qr(e){return Xn(Np(e)).dataSync()[0]}function Nz(e){return Ue(Np(e)).dataSync()[0]}function Cz(e){return Nz(e)/e.length}function GQ(e){const t=Ce(Np(e),Ne(Cz(e))),n=Ue(X(t,t)).dataSync()[0];return n/e.length}function VQ(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 ai(e,t){if(t<e)throw new j(`end (${t}) < begin (${e}) is forbidden.`);const n=[];for(let s=e;s<t;++s)n.push(s);return n}let vv="webgl";function HQ(e){ZT(e),vv=e}function YQ(){return vv}function qQ(){return!1}function jQ(e){const t=e.shape;return t.length>0?t.reduce((n,s)=>n*s):1}function _h(e,t){return e.asType(t)}function Wh(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 Rz(e,t){return ee(()=>{if(e.shape.length!==2)throw new j(`repeat() expects a rank-2 tensor, but received a rank-${e.shape.length} tensor.`);const n=Wh(e,1);return bw(n,[1,t,1])})}function Oz(e){const t=[Yr(e.shape)];return e.reshape(t)}function Ez(e){if(e.rank<=1)throw new j(`batchFlatten requires a minimum rank of 2. Got rank: ${e.rank}.`);const t=[e.shape[0],Yr(e.shape,1)];return e.reshape(t)}function Vo(e,t,n){return ee(()=>{switch(e.rank){case 1:return cp(e,t,n);case 2:return Wb(e,[t,0],[n,e.shape[1]]);case 3:return lp(e,[t,0,0],[n,e.shape[1],e.shape[2]]);case 4:return bh(e,[t,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3]]);case 5:return st(e,[t,0,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3],e.shape[4]]);case 6:return st(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 j(`sliceAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}})}function gw(e,t,n){return ee(()=>{switch(e.rank){case 1:return cp(e,t,n);case 2:return Wb(e,[0,t],[e.shape[0],n]);case 3:return lp(e,[0,0,t],[e.shape[0],e.shape[1],n]);case 4:return bh(e,[0,0,0,t],[e.shape[0],e.shape[1],e.shape[2],n]);default:throw new j(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}})}function Cp(e,t,n,s){return ee(()=>{switch(e.rank){case 1:return cp(e,t,n);case 2:switch(s){case 1:return Vo(e,t,n);case 2:return gw(e,t,n);default:throw new j(`The axis is not within the rank of the tensor ${s}`)}case 3:switch(s){case 1:return Vo(e,t,n);case 2:return lp(e,[0,t,0],[e.shape[0],n,e.shape[2]]);case 3:return gw(e,t,n);default:throw new j(`The axis is not within the rank of the tensor ${s}`)}case 4:switch(s){case 1:return Vo(e,t,n);case 2:return bh(e,[0,t,0,0],[e.shape[0],n,e.shape[2],e.shape[3]]);case 3:return bh(e,[0,0,t,0],[e.shape[0],e.shape[1],n,e.shape[3]]);case 4:return gw(e,t,n);default:throw new j(`The axis is not within the rank of the tensor ${s}`)}default:throw new j(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}})}function yw(e,t=-1){let n;return t<0&&(n=e[0].rank,n!==0?t=n:t=0),t===e[0].rank&&(t=-1),Mt(e,t)}function Nv(e,t){switch(e.rank){case 1:return rA([e,t]);case 2:return oA([e,t],0);case 3:return aA([e,t],0);case 4:return cA([e,t],0);default:throw new j(`concatAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}}function bw(e,t){if(Array.isArray(t)||(t=[t]),e.rank!==t.length)throw new j(`The length of input n (${t.length}) does not match the number of dimensions in input x (${e.rank})`);return Br(e,t)}function Rp(e,t=0,n=1,s,i){return Ob(e,t,n,s,i)}function Wi(e,t,n,s){if(e.rank<2||t.rank<2)throw new Ge(`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 Ge(`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 bp({a:e,b:t,transposeA:i,transposeB:o,bias:s?ww(e.rank,s,ri()):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(),u=a.pop(),p=[...a,c],m=Array.from({length:t.rank},(I,T)=>T===0?t.rank-2:T<=t.rank-2?T-1:T);t=t.transpose(m).reshape([u,-1]);const y=[...i,...p],b=!1,w=!1;return bp({a:e,b:t,transposeA:b,transposeB:w,bias:s?ww(e.rank,s,ri()):null,activation:n}).reshape(y)}}function KQ(e){return ee(()=>{const t=et(e),n=Dn(e);return $n(ni(e,t),t,$n(Ts(e,et(e)),n,X(-1,n)))})}function XQ(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(),vo(e,t).toFloat()})}function Cv(e,t,n){return ee(()=>(Array.isArray(t)?t=rs(t,"int32"):t=t.toInt(),za(e,t,n)))}function $h(e){return X(e,e)}function JQ(e,t){return ee(()=>{if(typeof t=="number"&&(t=Ne(Math.round(t),"int32")),t.dtype!=="int32")throw new Ge(`Non-int32 dtype (${t.dtype}) is not supported by pow() yet`);return ii(e,t)})}function ww(e,t,n){const s=t.shape;if(t.rank!==1&&t.rank!==e)throw new j(`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 j(`Unsupported input rank by biasAdd: ${t.rank}`)}function $i(e,t,n){return ee(()=>(n==null&&(n=ri()),Gt(n),e.add(ww(e.rank,t,n))))}function Dz(e,t=1){if(t!==1)throw new Ge(`Support for alpha values other than 1 (${t}) is not implemented yet.`);return Do(e)}function kz(e){return ee(()=>_e(e,rn(e).add(1)))}function Rv(e,t,n,s){return ee(()=>zA(e,t,n,s))}function Fz(e){return ee(()=>{const t=be(.5,X(.2,e));return jn(t,0,1)})}function Uh(e,t,n=!1){return n?e():t()}const _z=["fanIn","fanOut","fanAvg"],Wz=["normal","uniform","truncatedNormal"],ZQ=["Zeros","Ones","Constant","RandomNormal","RandomUniform","TruncatedNormal","VarianceScaling","Orthogonal","Identity"];function $z(e){ec(_z,"FanMode",e)}function Uz(e){ec(Wz,"Distribution",e)}class Ps extends No{fromConfigUsesCustomObjects(){return!1}getConfig(){return{}}}class Lw extends Ps{apply(e,t){return ct(e,t)}}Lw.className="Zeros",ge(Lw);class Op extends Ps{apply(e,t){return si(e,t)}}Op.className="Ones",ge(Op);class Sw extends Ps{constructor(e){super();if(typeof e!="object")throw new j(`Expected argument of type ConstantConfig but got ${e}`);if(e.value===void 0)throw new j(`config must have value set but got ${e}`);this.value=e.value}apply(e,t){return ee(()=>X(Ne(this.value),si(e,t)))}getConfig(){return{value:this.value}}}Sw.className="Constant",ge(Sw);class Iw extends Ps{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 $o(e,this.minval,this.maxval,t)}getConfig(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}}}Iw.className="RandomUniform",ge(Iw);class xw extends Ps{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 Ge(`randomNormal does not support dType ${t}.`);return Rp(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}}xw.className="RandomNormal",ge(xw);class Tw extends Ps{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 Ge(`truncatedNormal does not support dType ${t}.`);return Ih(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}}Tw.className="TruncatedNormal",ge(Tw);class Aw extends Ps{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 j("Identity matrix initializer can only be used for 2D square matrices.");return X(this.gain,Kd(e[0]))})}getConfig(){return{gain:this.gain}}}Aw.className="Identity",ge(Aw);function Bz(e,t="channelsLast"){let n,s;if(Gt(t),e.length===2)n=e[0],s=e[1];else if([3,4,5].indexOf(e.length)!==-1){if(t==="channelsFirst"){const i=Yr(e,2);n=e[1]*i,s=e[0]*i}else if(t==="channelsLast"){const i=Yr(e,0,e.length-2);n=e[e.length-2]*i,s=e[e.length-1]*i}}else{const i=Yr(e);n=Math.sqrt(i),s=Math.sqrt(i)}return[n,s]}class Zn extends Ps{constructor(e){super();if(e.scale<0)throw new j(`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,$z(this.mode),this.distribution=e.distribution==null?"normal":e.distribution,Uz(this.distribution),this.seed=e.seed}apply(e,t){const n=Bz(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 Ge(`${this.getClassName()} does not support dType ${t}.`);return Ih(e,0,a,t,this.seed)}else{const a=Math.sqrt(3*o);return $o(e,-a,a,t)}}getConfig(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}}}Zn.className="VarianceScaling",ge(Zn);class Ep extends Zn{constructor(e){super({scale:1,mode:"fanAvg",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return Zn.className}}Ep.className="GlorotUniform",ge(Ep);class Dp extends Zn{constructor(e){super({scale:1,mode:"fanAvg",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return Zn.className}}Dp.className="GlorotNormal",ge(Dp);class kp extends Zn{constructor(e){super({scale:2,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return Zn.className}}kp.className="HeNormal",ge(kp);class Fp extends Zn{constructor(e){super({scale:2,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return Zn.className}}Fp.className="HeUniform",ge(Fp);class _p extends Zn{constructor(e){super({scale:1,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return Zn.className}}_p.className="LeCunNormal",ge(_p);class Wp extends Zn{constructor(e){super({scale:1,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return Zn.className}}Wp.className="LeCunNormal",ge(Wp);class vw extends Ps{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 Ge("Random seed is not implemented for Orthogonal Initializer yet.")}apply(e,t){return ee(()=>{if(e.length<2)throw new Ge("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=Rp(n,0,1,"float32");let i=QA.gramSchmidt(s);return e[0]>e[1]&&(i=i.transpose()),X(this.gain,i)})}getConfig(){return{gain:this.gain,seed:this.seed}}}vw.className="Orthogonal",ge(vw);const Ov={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 Ev(e,t={}){return Dh(e,Ws.getMap().classNameMap,t,"initializer")}function Vt(e){return cw(e)}function Ft(e){if(typeof e=="string"){const t=e in Ov?Ov[e]:e;if(t==="GlorotNormal")return new Dp;if(t==="GlorotUniform")return new Ep;if(t==="HeNormal")return new kp;if(t==="HeUniform")return new Fp;if(t==="LeCunNormal")return new _p;if(t==="LeCunUniform")return new Wp;{const n={};return n.className=t,n.config={},Ev(n)}}else return e instanceof Ps?e:Ev(e)}function Mz(){return new Lw}function Pz(){return new Op}function zz(e){return new Sw(e)}function Gz(e){return new Iw(e)}function Vz(e){return new xw(e)}function Hz(e){return new Tw(e)}function Yz(e){return new Aw(e)}function qz(e){return new Zn(e)}function jz(e){return new Ep(e)}function Kz(e){return new Dp(e)}function Xz(e){return new kp(e)}function Jz(e){return new Fp(e)}function Zz(e){return new _p(e)}function Qz(e){return new Wp(e)}function e3(e){return new vw(e)}var t3=Object.freeze({__proto__:null,zeros:Mz,ones:Pz,constant:zz,randomUniform:Gz,randomNormal:Vz,truncatedNormal:Hz,identity:Yz,varianceScaling:qz,glorotUniform:jz,glorotNormal:Kz,heNormal:Xz,heUniform:Jz,leCunNormal:Zz,leCunUniform:Qz,orthogonal:e3});let n3=0;function Dv(){return n3++}const $p={};function Up(e=""){return e in $p||($p[e]=0),$p[e]+=1,e+$p[e].toString()}function Nw(e){return Array.isArray(e)&&Array.isArray(e[0])}function Bp(e){return e.length===0?[]:Array.isArray(e[0])?e:[e]}function Xe(e){let t;if(Array.isArray(e)){if(e.length!==1)throw new j(`Expected Tensor length to be 1; got ${e.length}`);t=e[0]}else t=e;return t}function It(e){if(Array.isArray(e)&&Array.isArray(e[0])){if(e.length===1)return e=e,e[0];throw new j(`Expected exactly 1 Shape; got ${e.length}`)}else return e}function Mp(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 kv="Variable";class ci{constructor(e,t="float32",n=kv,s=!0,i=null){this.dtype=t==null?"float32":t,this.shape=e.shape,this.id=Dv(),n=n==null?kv:n,this.originalName=xv(n),this.name=Tv(this.originalName),this.trainable_=s,this.constraint=i,this.val=xA(e,this.trainable_,this.name,this.dtype)}read(){return this.assertNotDisposed(),this.val}write(e){return this.assertNotDisposed(),s3(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 s3(e,t){if(e.shape.toString()!==t.shape.toString())throw new Error("Shape mismatch: "+JSON.stringify(e.shape)+" vs. "+JSON.stringify(t.shape))}function QQ(e,t,n,s){return new ci(e,t,n,!0,s)}function eee(e,t,n){return new ci(ct(e),t,n)}function tee(e,t,n){return new ci(et(e),t,n)}function nee(e,t,n){const s=si(e);return new ci(s,t,n)}function see(e,t,n){const s=Dn(e);return new ci(s,t,n)}function iee(e,t,n){return new ci(Kd(e),t,n)}function ree(e,t,n,s,i,o="randomUniform"){return new ci($o(e,t,n,s),s,o)}function oee(e,t=0,n=1,s,i,o="truncatedNormal"){if(s=s||"float32",s!=="float32"&&s!=="int32")throw new Ge(`randomNormal does not support dType ${s}.`);return new ci(Ih(e,t,n,s,i),s,o)}function aee(e,t=0,n=1,s,i,o="randomNormal"){if(s=s||"float32",s!=="float32"&&s!=="int32")throw new Ge(`randomNormalVariable does not support dType ${s}.`);return new ci(Ob(e,t,n,s,i),s,o)}function cee(e,t){return e.write(t)}function lee(e,t){return e.write(be(e.read(),t))}function hee(e,t){return e.write(Ce(e.read(),t))}function Cw(e){return e.map(t=>t.read())}function Rw(e){e.forEach(t=>{const n=t[0];n.write(t[1])})}function uee(e,t){const n=t.map(i=>i.read()),s=Ab(e,n);return t.map(i=>s.grads[i.name])}class fn{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 li{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=Dv(),o!=null&&(this.originalName=xv(o),this.name=Tv(this.originalName)),this.rank=t.length}}let i3=0;class Pp{constructor(e,t){this.callArgs=t,this.id=i3++,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 r3=0;class lt extends No{constructor(e={}){super();this._callHook=null,this._addedWeightNames=[],this._stateful=!1,this.id=r3++,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=or(n)+"_"+Up(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 oi(`The layer has never been called and thus has no defined ${t}.`);if(this.inboundNodes.length<=e)throw new j(`Asked to get ${t} at node ${e}, but the layer has only ${this.inboundNodes.length} inbound nodes.`);return this.inboundNodes[e]}getInputAt(e){return Jn(this.getNodeAtIndex(e,"input").inputTensors)}getOutputAt(e){return Jn(this.getNodeAtIndex(e,"output").outputTensors)}get input(){if(this.inboundNodes.length>1)throw new rr(`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 rr(`Layer ${this.name} is not connected, no input to return.`);return Jn(this.getNodeAtIndex(0,"input").inputTensors)}get output(){if(this.inboundNodes.length===0)throw new rr(`Layer ${this.name} has no inbound nodes.`);if(this.inboundNodes.length>1)throw new rr(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use \`getOutputAt(nodeIndex)\` instead.`);return Jn(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=Nt(e),this.inputSpec==null||this.inputSpec.length===0)return;const t=Nt(this.inputSpec);if(e.length!==t.length)throw new j(`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 j(`Input ${n} is incompatible with layer ${this.name}: expected ndim=${i.ndim}, found ndim=${o}`);if(i.maxNDim!=null&&o>i.maxNDim)throw new j(`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 j(`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 j(`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 u=Number(c),p=i.axes[c],m=u>=0?a[u]:a[a.length+u];if(p!=null&&[p,null].indexOf(m)===-1)throw new j(`Input ${n} is incompatible with layer ${this.name}: expected axis ${u} 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],u=s.shape[a];if(c!=null&&u!=null&&c!==u)throw new j(`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=Nt(e);let s=!0;for(const o of n)if(!(o instanceof li)){s=!1;break}let i=!0;for(const o of n)if(o instanceof li){i=!1;break}if(s===i)throw new j("Arguments to apply() must be all SymbolicTensors or all Tensors");return Go(this.name,()=>{if(!this.built){this.assertInputCompatibility(e);const o=[];for(const a of Nt(e))o.push(a.shape);this.build(Jn(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=Nt(o),c=[];for(let u of a)n.indexOf(u)!==-1&&(u=u.clone()),c.push(u);if(o=Jn(c),this.activityRegularizer!=null)throw new Ge("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return o}else{const o=o3(e),a=this.computeOutputShape(o);let c;const u=a3(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 li(u,p,this,Nt(e),t,this.name,m)):c=new li(u,a,this,Nt(e),t,this.name),this.addInboundNode(e,c,null,null,o,a,t),this._refCount++,this.activityRegularizer!=null)throw new Ge("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 rr(`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 rr(`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 oi(`You tried to call countParams() on ${this.name}, but the layer is not built yet. Build it first by calling build(batchInputShape).`);return Mp(this.weights)}build(e){this.built=!0}getWeights(e=!1){return Cw(e?this.trainableWeights:this.weights)}setWeights(e){ee(()=>{const t=this.weights;if(t.length!==e.length)throw new j(`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=Cw(t);for(let i=0;i<s.length;++i){const o=s[i],a=t[i],c=e[i];if(!ot(o.shape,c.shape))throw new j(`Layer weight shape ${o.shape} not compatible with provided weight shape ${c.shape}`);n.push([a,c])}Rw(n)})}addWeight(e,t,n,s,i,o,a){if(this._addedWeightNames.indexOf(e)!==-1)throw new j(`Duplicate weight name ${e} for layer ${this.name}`);this._addedWeightNames.push(e),n==null&&(n="float32"),this.fastWeightInitDuringBuild&&(s=Ft("zeros"));const c=s.apply(t,n),u=new ci(c,n,e,o,a);return c.dispose(),i!=null&&this.addLoss(()=>i.apply(u.read())),o==null&&(o=!0),o?this._trainableWeights.push(u):this._nonTrainableWeights.push(u),u}setFastWeightInitDuringBuild(e){this.fastWeightInitDuringBuild=e}addLoss(e){if(e==null||Array.isArray(e)&&e.length===0)return;e=Nt(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=Nt(e);t=Nt(t),n=Nt(n),s=Nt(s),i=Bp(i),o=Bp(o);const u=[],p=[],m=[];for(const y of c)u.push(y.sourceLayer),p.push(y.nodeIndex),m.push(y.tensorIndex);new Pp({outboundLayer:this,inboundLayers:u,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 o3(e){e=Nt(e);const t=[];for(const n of e)t.push(n.shape);return Jn(t)}function a3(e){return"float32"}function Fv(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],u=s.nodeIndices[o],p=Fv(a,c,u);for(const m of p)i.indexOf(m)===-1&&i.push(m)}return i}}}class sc extends lt{constructor(e){super({dtype:e.dtype,name:e.name!=null?e.name:Up("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 j("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 j("An InputLayer should be passed either a `batchInputShape` or an `inputShape`.");t=[e.batchSize].concat(e.inputShape)}else if(e.batchSize!=null)throw new j("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 li(this.dtype,this.batchInputShape,this,[],{},this.name);s.nodeIndex=0,s.tensorIndex=0,new Pp({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:[s],outputTensors:[s],inputMasks:[null],outputMasks:[null],inputShapes:[t],outputShapes:[t]})}apply(e,t){throw new j(`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}}}sc.className="InputLayer",ge(sc);function _v(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 j("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 sc({batchInputShape:t,name:e.name,dtype:n,sparse:e.sparse}),i=s.inboundNodes[0].outputTensors;return i[0]}async function jr(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 Wv(e){if(e==null)return;for(const t in e){const n=e[t];typeof n!="number"&&n.dispose()}}var $v;(function(e){e[e.SILENT=0]="SILENT",e[e.VERBOSE=1]="VERBOSE"})($v||($v={}));const c3=125;class ic{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 Uv{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 l3 extends ic{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(_e(1,this.seen),this.totals[n]);t[n]=s,this.totals[n].dispose(),Rn(t[n])})}}}class Bv extends ic{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 Mv extends ic{constructor(e,t){super();if(this.currentEpoch=0,this.yieldEvery=t||"auto",this.yieldEvery==="auto"&&(this.yieldEvery=c3),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");xd(this.yieldEvery)&&(this.maybeWait=mz(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 jr(n),s.push(this.yield(e,t,n))),s.push(Ip()),await Promise.all(s)}async onEpochBegin(e,t){this.currentEpoch=e,this.epochBegin!=null&&(await jr(t),await this.epochBegin(e,t))}async onEpochEnd(e,t){const n=[];this.epochEnd!=null&&(await jr(t),n.push(this.epochEnd(e,t))),this.yieldEvery==="epoch"&&n.push(Ip()),await Promise.all(n)}async onBatchBegin(e,t){this.batchBegin!=null&&(await jr(t),await this.batchBegin(e,t))}async onBatchEnd(e,t){const n=[];this.batchEnd!=null&&(await jr(t),n.push(this.batchEnd(e,t))),this.yieldEvery==="batch"?n.push(Ip()):xd(this.yieldEvery)&&n.push(this.maybeWait(this.currentEpoch,e,t)),await Promise.all(n)}async onTrainBegin(e){this.trainBegin!=null&&(await jr(e),await this.trainBegin(e))}async onTrainEnd(e){this.trainEnd!=null&&(await jr(e),await this.trainEnd(e))}}function Pv(e,t){if(e==null&&(e={}),e instanceof ic)return[e];if(Array.isArray(e)&&e[0]instanceof ic)return e;const n=Nt(e);return n.map(s=>new Mv(s,t))}class zs{constructor(){}static registerCallbackConstructor(e,t){k(e>=0&&Number.isInteger(e),()=>`Verbosity level is expected to be an integer >= 0, but got ${e}`),zs.checkForDuplicate(t),zs.constructors[e]==null&&(zs.constructors[e]=[]),zs.constructors[e].push(t)}static checkForDuplicate(e){for(const t in zs.constructors){const n=zs.constructors[+t];n.forEach(s=>{if(s===e)throw new j("Duplicate callback constructor.")})}}static clear(){zs.constructors={}}static createCallbacks(e){const t=[];for(const n in zs.constructors){const s=+n;e>=s&&t.push(...zs.constructors[s])}return t.map(n=>new n)}}zs.constructors={};function zv(e,t,n,s,i,o,a,c,u){const p=new Bv,m=[new l3,...zs.createCallbacks(t)];e!=null&&m.push(...e),m.push(p);const y=new Uv(m);return y.setParams({epochs:n,initialEpoch:s,samples:i,steps:o,batchSize:a,verbose:t,doValidation:c,metrics:u}),{callbackList:y,history:p}}function hi(e,t={},n=!1){return Dh(e,Ws.getMap().classNameMap,t,"layer",n)}function zp(e,t){return ee(()=>{e.dtype!=="float32"&&(e=e.asType("float32"));const n=Ue($h(e),t,!0),s=hh(n.shape,cn()),i=Sn(Us(n,s));return _e(e,i)})}function ar(e,t){return ee(()=>zt($h(Ce(t,e)),-1))}function rc(e,t){return ee(()=>zt(rn(Ce(t,e)),-1))}function Kr(e,t){return ee(()=>{const n=Ce(e,t),s=jn(rn(e),cn(),Number.MAX_VALUE),i=rn(_e(n,s));return X(100,zt(i,-1))})}function Ow(e,t){return ee(()=>{const n=jn(t,cn(),Number.MAX_VALUE),s=is(be(1,n)),i=jn(e,cn(),Number.MAX_VALUE),o=is(be(1,i));return zt($h(Ce(s,o)),-1)})}function h3(e,t){return ee(()=>{const n=Us(0,Ce(1,X(e,t)));return zt($h(n),-1)})}function u3(e,t){return ee(()=>{const n=Us(0,Ce(1,X(e,t)));return zt(n,-1)})}function d3(e,t){return ee(()=>{const n=Ue(X(e,t),-1),s=Xn(X(Ce(1,e),t),-1);return Us(0,be(1,Ce(s,n)))})}function p3(e,t){return ee(()=>{const n=Math.log(2),s=Ce(t,e),i=Ce(be(s,Va(X(-2,s))),n);return zt(i,-1)})}function Bh(e,t,n=!1){return ee(()=>{if(n)t=Uo(t);else{const s=Ue(t,t.shape.length-1,!0);t=_e(t,s)}return t=jn(t,cn(),1-cn()),Pt(Ue(X(e.toFloat(),is(t)),t.shape.length-1))})}function Gp(e,t,n=!1){return ee(()=>{const s=Pa(Oz(e)).toInt();t=jn(t,cn(),1-cn());const i=t.shape,o=vo(s,i[i.length-1]).reshape(i);return Bh(o,t,n)})}function m3(e,t){if(!ot(e.shape,t.shape))throw new j(`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 Vp(e,t){return ee(()=>{let n;return n=jn(t,cn(),1-cn()),n=is(_e(n,Ce(1,n))),zt(m3(e,n),-1)})}function Ew(e,t){return ee(()=>{const n=jn(e,cn(),1),s=jn(t,cn(),1);return Ue(X(e,is(_e(n,s))),-1)})}function f3(e,t){return ee(()=>{const n=is(be(cn(),t));return zt(Ce(t,X(e,n)),-1)})}function Hp(e,t){return ee(()=>{const n=zp(e,-1),s=zp(t,-1),i=X(n,s);return Pt(Ue(i,-1))})}const dee=ar,pee=ar,mee=rc,fee=rc,gee=Kr,yee=Kr,bee=Ow,wee=Ow,Lee=Ew,See=Ew,Iee=Hp,Yp={meanSquaredError:ar,meanAbsoluteError:rc,meanAbsolutePercentageError:Kr,meanSquaredLogarithmicError:Ow,squaredHinge:h3,hinge:u3,categoricalHinge:d3,logcosh:p3,categoricalCrossentropy:Bh,sparseCategoricalCrossentropy:Gp,binaryCrossentropy:Vp,kullbackLeiblerDivergence:Ew,poisson:f3,cosineProximity:Hp};function Dw(e){if(typeof e=="string"){if(e in Yp)return Yp[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 j(t)}else return e}function kw(e,t){return ee(()=>{const n=X(.5,Dn(t)),s=_h(Ts(t,n),e.dtype);return zt(ni(e,s),-1)})}function Fw(e,t){return ee(()=>_h(ni(nh(e,-1),nh(t,-1)),"float32"))}function Gv(e,t){return ee(()=>Bs(e.equal(1),t.equal(1)).sum().cast("float32"))}function g3(e,t){return ee(()=>Bs(e.equal(1),t.equal(0)).sum().cast("float32"))}function y3(e,t){return ee(()=>Bs(e.equal(0),t.equal(1)).sum().cast("float32"))}function Vv(e,t){return ee(()=>{const n=Gv(e,t),s=y3(e,t),i=n.add(s);return $n(Ts(i,0),n.div(i),0).cast("float32")})}function b3(e,t){return ee(()=>{const n=Gv(e,t),s=g3(e,t),i=n.add(s);return $n(Ts(i,0),n.div(i),0).cast("float32")})}function Hv(e,t){return Vp(e,t)}function Yv(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)),ni(e,t).asType("float32")}function xee(e,t){throw new Ge}function Tee(e,t){throw new Ge}const w3=ar,L3=ar,S3=rc,I3=rc,x3=Kr,T3=Kr,_w=Bh,A3=Hp,qv=Gp,qp={binaryAccuracy:kw,categoricalAccuracy:Fw,precision:Vv,categoricalCrossentropy:_w,sparseCategoricalCrossentropy:qv,mse:w3,MSE:L3,mae:S3,MAE:I3,mape:x3,MAPE:T3,cosine:A3};function v3(e){if(typeof e=="string"&&e in qp)return qp[e];if(typeof e!="string"&&e!=null)return e;throw new j(`Unknown metric ${e}`)}function jp(e){if(vs(e!==null,`Unknown LossOrMetricFn ${e}`),typeof e=="string")return e;{let t;for(const n of Object.keys(Yp))if(Yp[n]===e){t=n;break}if(t!==void 0)return t;for(const n of Object.keys(qp))if(qp[n]===e){t=n;break}return t!==void 0?t:e.name}}function N3(e){const t={Adagrad:()=>Mo.adagrad(.01),Adadelta:()=>Mo.adadelta(1,.95,cn()),Adam:()=>Mo.adam(.001,.9,.999,cn()),Adamax:()=>Mo.adamax(.002,.9,.999,cn(),0),RMSProp:()=>Mo.rmsprop(.001,.9,0,cn()),SGD:()=>Mo.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 j(`Unknown Optimizer ${e}`)}const jv=1*1024*1024;function Kv(e,t,n=!1){if(e==null||typeof e!="object"||Object.getPrototypeOf(e)!==Object.prototype||!Ww(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>jv&&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 <= ${jv}.`)}}function Ww(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(!Ww(e[n]))return!1}return!0}else if(Array.isArray(e)){for(const t of e)if(!Ww(t))return!1;return!0}else return!1;else{const t=typeof e;return t==="string"||t==="number"||t==="boolean"}}function C3(e,t,n,s=console.log){const i=O3(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)),Kp(o,n,s),s("=".repeat(t));const c=e.layers;for(let m=0;m<c.length;++m)i?E3(c[m],n,s):D3(c[m],n,a,s),s((m===c.length-1?"=":"_").repeat(t));e.checkTrainableWeightsConsistency();const u=R3(e),p=Mp(e.nonTrainableWeights);s(`Total params: ${u+p}`),s(`Trainable params: ${u}`),s(`Non-trainable params: ${p}`),s("_".repeat(t))}function R3(e){let t;return e.collectedTrainableWeights!=null?t=Mp(e.collectedTrainableWeights):t=Mp(e.trainableWeights),t}function O3(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 Kp(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 E3(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()];Kp(a,t,n)}function D3(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],I=m.tensorIndices[y];o.push(`${b}[${w}][${I}]`)}}const a=e.name,c=e.getClassName(),u=o.length===0?"":o[0],p=[`${a} (${c})`,i,e.countParams().toString(),u];Kp(p,t,s);for(let m=1;m<o.length;++m)Kp(["","","",o[m]],t,s)}function Xv(e,t,n){return(e==="inboundNodes"||e==="outputLayers"||e==="inputLayers")&&t===0&&typeof n=="string"}function Mh(e,t){if(e===null)return null;if(typeof e=="string")return zo(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];Xv(t,i,o)?n.push(o):n.push(Mh(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=zo(s);n[o]=Mh(i,o)}}return n}}function $w(e,t){if(e==null)return null;if(typeof e=="string")return or(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];Xv(t,i,o)?n.push(o):n.push($w(o,t))}return n}else{const n={};for(const s of Object.keys(e)){const i=e[s],o=or(s);(s==="name"||s==="className")&&typeof i=="string"?n[o]=i:n[o]=$w(i,s)}return n}}const Xp="2.6.0";function k3(e,t){if(e.dtype==null||e.dtype===t.dtype)return t;try{return ve(t,e.dtype)}catch(n){throw new j(`The dtype of the feed (${t.dtype}) can not be cast to the dtype of the key '${e.name}' (${e.dtype}).`)}}class Ho{constructor(e){if(this.id2Value={},this.id2Mask={},this.name2Id={},e instanceof Ho)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]=k3(e,t),this.name2Id[e.name]=e.id,n!=null&&(this.id2Mask[e.id]=n);else throw new j(`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 li){if(this.id2Value[e.id]==null)throw new j(`Nonexistent key: ${e.name}`);return this.id2Value[e.id]}else{const t=this.name2Id[e];if(t==null)throw new j(`Feed dict has no SymbolicTensor name: ${e}`);return this.id2Value[t]}}getMask(e){if(e instanceof li){if(this.id2Value[e.id]==null)throw new j(`Nonexistent key: ${e.name}`);return this.id2Mask[e.id]}else{const t=this.name2Id[e];if(t==null)throw new j(`Feed dict has no SymbolicTensor name: ${e}`);return this.id2Mask[t]}}disposeMasks(){this.id2Mask!=null&&qe(this.id2Mask)}}const Uw={},Jv={};function Ph(e,t,n,s){const i=n==null?!1:n.training,o=Array.isArray(e),a=o?e:[e],c=a.map(I=>I.name),u=[],p=t.names();for(const I of c)p.indexOf(I)!==-1?u.push(t.getValue(I)):u.push(null);s!=null&&(s.maxNumTensors=-Infinity,s.minNumTensors=Infinity);const m=c.join(",")+"|"+t.names().join(",");let y,b;if(Uw[m]==null){const I=F3(a,t);y=I.sorted,b=I.recipientCounts,Uw[m]=y,Jv[m]=b}y=Uw[m],b={},i||Object.assign(b,Jv[m]);const w=new Ho(t);for(let I=0;I<y.length;++I){if(s!=null){const q=Bd().numTensors;q>s.maxNumTensors&&(s.maxNumTensors=q),q<s.minNumTensors&&(s.minNumTensors=q)}const T=y[I],v=T.sourceLayer;if(v instanceof sc)continue;const N=[],E=[],D=[];let F=!1;for(const q of T.inputs){const J=w.getValue(q),oe=w.getMask(q);N.push(J),E.push(oe),oe!=null&&(F=!0),i||(b[q.name]--,b[q.name]===0&&!t.hasKey(q)&&c.indexOf(q.name)===-1&&!J.isDisposed&&q.sourceLayer.stateful!==!0&&D.push(J))}F&&(n=n||{},n.mask=E[0]);const _=Nt(v.apply(N,n));let B=null;v.supportsMasking&&(B=v.computeMask(N,E));const U=W3(T),Y=Array.isArray(U)?U:[U];for(let q=0;q<Y.length;++q){w.hasKey(Y[q])||w.add(Y[q],_[q],Array.isArray(B)?B[0]:B);const J=c.indexOf(Y[q].name);J!==-1&&(u[J]=_[q])}i||qe(D)}return w.disposeMasks(),o?u:u[0]}function F3(e,t){k(e!=null&&e.length>0,()=>"Expected at least one fetch, got none");let n=[],s={};if(e.length===1){const i=Zv(e[0],t);n=i.sorted,s=i.recipientMap}else{const i=new Set;for(const o of e){const{sorted:a,recipientMap:c}=Zv(o,t);for(const u of a)i.has(u.name)||(n.push(u),i.add(u.name));for(const u in c)s[u]==null&&(s[u]=new Set),c[u].forEach(p=>s[u].add(p))}}return{sorted:n,recipientCounts:_3(s)}}function _3(e){const t={};for(const n in e)t[n]=e[n].size;return t}function Zv(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 u=a[a.length-1]===o.length-1;if(c.inputs.length===0||u)o.pop(),s.push(c),n.add(c.name),u&&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 W3(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 Ui extends lt{constructor(e){super({});if(this.containerNodes=new Set,this.name=e.name,this.name==null){const N=this.getClassName().toLowerCase();this.name=Up(N)}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],Hr(this.inputs).length!==this.inputs.length)throw new j(`The list of inputs passed to the model is redundant. All inputs should only appear once. Found: ${this.inputs.map(N=>N.name)}`);Hr(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(N=>N.name)}`),this.inputLayers=[],this.inputLayersNodeIndices=[],this.inputLayersTensorIndices=[],this.outputLayers=[],this.outputLayersNodeIndices=[],this.outputLayersTensorIndices=[],this.layers=[],this.internalContainerRefs=[];for(const N of this.outputs){const E=N.sourceLayer,D=N.nodeIndex,F=N.tensorIndex;this.outputLayers.push(E),this.outputLayersNodeIndices.push(D),this.outputLayersTensorIndices.push(F)}for(const N of this.inputs){const E=N.sourceLayer,D=N.nodeIndex,F=N.tensorIndex;vs(D===0,"input layer has >1 nodes"),vs(F===0,"input layer has >1 tensors"),this.inputLayers.push(E),this.inputLayersNodeIndices.push(D),this.inputLayersTensorIndices.push(F)}this.inputNames=[],this.outputNames=[],this.feedInputShapes=[],this.feedInputNames=[],this.feedOutputNames=[];for(let N=0;N<this.inputLayers.length;N++){const E=this.inputLayers[N];if(!(E instanceof sc))throw new TypeError(`Input layers to a LayersModel must be InputLayer objects. Received inputs: ${e.inputs}. Input ${N} (0-based) originates from layer type ${E.getClassName()}.`);this.inputNames.push(E.name),this.feedInputShapes.push(E.batchInputShape),this.feedInputNames.push(E.name)}for(const N of this.outputLayers)this.outputNames.push(N.name);this.internalInputShapes=this.inputs.map(N=>N.shape),this.internalOutputShapes=this.outputs.map(N=>N.shape);const t={},n={},s={},i={},o={},a=[],c=(N,E,D,F,_,B)=>{(F==null||_==null||B==null)&&(F=N.sourceLayer,_=N.nodeIndex,B=N.tensorIndex);const U=F.inboundNodes[_];if(D.indexOf(U)!==-1)throw new oi(`The tensor ${N.name} at layer "${F.name}" is part of a cycle.`);if(E.indexOf(U)!==-1)return;this.containerNodes.add(Ui.nodeKey(F,_)),F.id in o||(o[F.id]=Object.keys(o).length),D.indexOf(U)===-1&&D.push(U);const Y=U.inboundLayers.length;for(let q=0;q<Y;q++){const J=U.inputTensors[q],oe=U.inboundLayers[q],ce=U.nodeIndices[q],ue=U.tensorIndices[q];c(J,E,D,oe,ce,ue)}for(E.push(U);D.indexOf(U)>=0;)D.splice(D.indexOf(U),1);a.push(U)},u=[],p=[];for(const N of this.outputs)c(N,u,p);const m=a.slice().reverse();for(const N of m){n[N.id]=N,N.id in t||(t[N.id]=0);let E=t[N.id];const D=s[N.outboundLayer.id]==null?0:s[N.outboundLayer.id];E=Math.max(E,D),s[N.outboundLayer.id]=E,i[N.outboundLayer.id]=N.outboundLayer,t[N.id]=E;for(let F=0;F<N.inboundLayers.length;F++){const _=N.inboundLayers[F],B=N.nodeIndices[F],U=_.inboundNodes[B],Y=t[U.id]==null?0:t[U.id];t[U.id]=Math.max(E+1,Y),n[U.id]=U}}const y={};for(const N in t){const E=t[N];E in y||(y[E]=[]),y[E].push(n[N])}const b={};for(const N in s){const E=s[N];E in b||(b[E]=[]),b[E].push(i[N])}let w=Object.keys(b).map(N=>parseInt(N,10)).sort(vp);this.layers=[];for(const N of w){const E=b[N];E.sort((D,F)=>{const _=o[D.id],B=o[F.id];return _<B?-1:_>B?1:0});for(const D of E)D instanceof Ui&&this.internalContainerRefs.push(D),this.layers.push(D)}this.layersByDepth=b,w=Object.keys(y).map(N=>parseInt(N,10)).sort(vp);const I=this.inputs.slice(),T=[];for(const N of w)for(const E of y[N]){const D=E.outboundLayer;if(D!=null){for(const F of E.inputTensors)if(I.indexOf(F)===-1)throw new oi(`Graph disconnected: cannot obtain value for tensor ${F} at layer "${D.name}". The following previous layers were accessed without issue: ${T}`);for(const F of E.outputTensors)I.push(F);T.push(D.name)}}this.nodesByDepth=y;const v=this.layers.map(N=>N.name);for(const N of v){const E=v.filter(D=>D===N).length;if(E!==1)throw new oi(`The name "${N}" is used ${E} times in the model. All layer names should be unique. Layer names: `+JSON.stringify(v))}this.outboundNodes=[],this.inboundNodes=[],new Pp({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:this.inputs.map(N=>null),outputMasks:this.outputs.map(N=>null),inputShapes:this.inputs.map(N=>N.shape),outputShapes:this.outputs.map(N=>N.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 j("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 j(`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("/"),u=c.slice(0,-2).concat([c[c.length-1]]);a=u.join("/")}if(n[a]!=null)i.push([n[a],e[o]]);else if(t)throw new j(`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 j(`${o.length} of ${s} weights are not set: ${o}`)}Rw(i)}updatedConfig(){const e=this.getConfig(),t={};return t.className=this.getClassName(),t.config=e,t.kerasVersion=`tfjs-layers ${Xp}`,t.backend="TensorFlow.js",t}toJSON(e,t=!0){const n=$w(this.updatedConfig());return t?JSON.stringify(n):n}call(e,t){return ee(()=>{e=Nt(e);const n=new Ho;for(let s=0;s<this.inputs.length;++s)n.add(this.inputs[s],e[s]);return Ph(this.outputs,n,t)})}computeMask(e,t){return ee(()=>{e=Nt(e);let n;return t==null?n=Po(null,e.length):n=Nt(t),this.runInternalGraph(e,n)[1]})}computeOutputShape(e){const t=Bp(e);if(t.length!==this.inputLayers.length)throw new j(`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],u=t[a],p=c.name+"_0_0";n[p]=u}const s=Object.keys(this.nodesByDepth).map(a=>parseInt(a,10)).sort(vp);if(s.length>1)for(const a of s){const c=this.nodesByDepth[a];for(const u of c){const p=u.outboundLayer;if(this.inputLayers.map(I=>I.id).indexOf(p.id)!==-1)continue;const m=[];for(let I=0;I<u.inboundLayers.length;I++){const T=u.inboundLayers[I],v=u.nodeIndices[I],N=u.tensorIndices[I],E=`${T.name}_${v}_${N}`,D=n[E];m.push(D)}const y=p.computeOutputShape(Jn(m)),b=Bp(y),w=p.inboundNodes.indexOf(u);for(let I=0;I<b.length;I++){const T=`${p.name}_${w}_${I}`;n[T]=b[I]}}}const i=[],o=[];for(let a=0;a<this.outputLayers.length;a++){const c=this.outputLayers[a],u=this.outputLayersNodeIndices[a],p=this.outputLayersTensorIndices[a],m=`${c.name}_${u}_${p}`;o.push(m)}for(let a=0;a<o.length;a++){const c=o[a];vs(c in n),i.push(n[c])}return Jn(i)}runInternalGraph(e,t){t==null&&(t=Po(null,e.length));const n={};for(let c=0;c<this.inputs.length;++c){const u=this.inputs[c],p=e[c],m=t[c];n[u.id]=[p,m]}const s=Object.keys(this.nodesByDepth).map(c=>parseInt(c,10)).sort(vp);for(const c of s){const u=this.nodesByDepth[c];for(const p of u){const m=p.outboundLayer,y=p.inputTensors,b=p.outputTensors,w=new Array;for(const I of y)I.id in n&&w.push(n[I.id]);if(w.length===y.length){let I={},T,v,N,E;if(p.callArgs!=null&&(I=p.callArgs),w.length===1){const[D,F]=w[0];I.mask==null&&(I.mask=F),N=Nt(m.call(D,I)),E=Nt(m.computeMask(D,F)),T=[D],v=[F]}else T=w.map(D=>D[0]),v=w.map(D=>D[1]),I.mask==null&&(I.mask=v),N=Nt(m.call(T,I)),E=Nt(m.computeMask(T,v));if(m.activityRegularizer)throw new Ge("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 F=b[D],_=N[D],B=E[D];n[F.id]=[_,B]}}}}const i=[],o=[],a=[];for(const c of this.outputs){vs(c.id in n,`Could not compute output ${c.name} : ${c.id}`);const[u,p]=n[c.id];a.push(u.shape),i.push(u),o.push(p)}return[i,o,a]}buildNodeConversionMap(e){const t={};let n;for(const s of this.layers){n=s instanceof Ui?1:0;for(let i=0;i<s.inboundNodes.length;i++){const o=Ui.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 j(`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 j("Provide either a layer name or layer index");for(const n of this.layers)if(n.name===e)return n;throw new j(`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=Ui.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(),u=[];for(let m=0;m<o.inboundNodes.length;m++){const y=o.inboundNodes[m],b=Ui.nodeKey(o,m);let w={};if(this.containerNodes.has(b)){if(y.callArgs)try{JSON.stringify(y.callArgs),w=y.callArgs}catch(I){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 I=[];for(let T=0;T<y.inboundLayers.length;T++){const v=y.inboundLayers[T],N=y.nodeIndices[T],E=y.tensorIndices[T],D=Ui.nodeKey(v,N);let F=t[D];F==null&&(F=0),I.push([v.name,F,E,w])}u.push(I)}}}const p={};p.name=o.name,p.className=a,p.config=c,p.inboundNodes=u,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],u=Ui.nodeKey(a,c);if(!this.containerNodes.has(u))continue;let p=t[u];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],u=Ui.nodeKey(a,c);if(!this.containerNodes.has(u))continue;let p=t[u];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 N=[];let E;for(const D of v){const F=D[0],_=D[1],B=D[2];if(E=D[3]==null?{}:D[3],!(F in i)){a(T,v);return}const U=i[F];if(U.inboundNodes.length<=_){a(T,v);return}const Y=U.inboundNodes[_];N.push(Y.outputTensors[B])}N.length>0&&T.apply(Jn(N),E)}function u(T){const v=T.name,N=hi(T,t.customObjects!=null?t.customObjects:{});N.setFastWeightInitDuringBuild(s),i[v]=N;const E=T.inboundNodes;E.forEach(D=>{if(!(D instanceof Array))throw new j(`Corrupted configuration, expected array for nodeData: ${D}`);a(N,D)})}const p=t.name,m=t.layers;for(const T of m)u(T);for(;!pz(o);)for(const T of m){const v=i[T.name];if(v.name in o){const N=o[v.name];delete o[v.name];for(const E of N)c(v,E)}}const y=[],b=[],w=t.inputLayers;for(const T of w){const v=T[0],N=T[1],E=T[2];vs(v in i);const D=i[v],F=D.inboundNodes[N].outputTensors;y.push(F[E])}const I=t.outputLayers;for(const T of I){const v=T[0],N=T[1],E=T[2];vs(v in i);const D=i[v],F=D.inboundNodes[N].outputTensors;b.push(F[E])}return new e({inputs:y,outputs:b,name:p})}get stateful(){if(this._stateful)throw new j("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 Qv(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 eN(e,t){return Qv(e,t,"classWeight")}function Aee(e,t){return Qv(e,t,"sampleWeight")}async function tN(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])}),rs(a,"float32")}else return null}function $3(e,t){return X(e,t)}const U3=32;function nN(e,t){let n,s;const i=t;n=i.xs,s=i.ys,k(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];k(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)})`),k(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 u=0;u<o.length;u++)k(o[u].shape[0]===c,()=>`Batch size mismatch: input ${e.inputNames[u]} has ${o[u].shape[0]}; expected ${c} based on input ${e.inputNames[0]}.`);for(let u=0;u<a.length;u++)k(a[u].shape[0]===c,()=>`Batch size mismatch: output ${e.outputNames[u]} has ${a[u].shape[0]}; expected ${c} based on input ${e.inputNames[0]}.`);return{xs:o,ys:a}}function sN(e,t,n){if(n instanceof Q)return[n];if(Array.isArray(n))return k(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 j(`The feature data generated by the dataset lacks the required ${e} key '${i}'.`);s.push(n[i])}return s}}function B3(e){if(e.length===3)throw new Ge("Validation with sample weights is not implemented yet.");return{xs:e[0],ys:e[1]}}async function M3(e,t,n){const s=n.batchesPerEpoch!=null;if(k(e.optimizer!=null,()=>"You must compile a model before training/testing. Use LayersModel.compile(modelCompileConfig)."),k(n!=null,()=>"For fitDataset(), the 2nd argument (config) is required, but it is not provided in this call."),k(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}`),k(!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}`),k(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))k(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=B3(n.validationData);o=v.xs,a=v.ys}const c=e.makeTrainFunction(),u=e.getDedupedMetricsNames();let p;i?p=u.slice().concat(u.map(v=>"val_"+v)):p=u.slice();const m=Pv(n.callbacks,n.yieldEvery),y=n.verbose==null?1:n.verbose,{callbackList:b,history:w}=zv(m,y,n.epochs,null,null,P3(t,n),null,i,p);b.setModel(e),e.history=w,await b.onTrainBegin(),e.stopTraining_=!1;let I=n.initialEpoch==null?0:n.initialEpoch,T=await t.iterator();for(;I<n.epochs;){const v={};await b.onEpochBegin(I);let N=0,E=0;for(s||(T=await t.iterator());s?N<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 ${N} 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:F,ys:_}=nN(e,D.value),B={};B.batch=E,B.size=F[0].shape[0],await b.onBatchBegin(E,B);const U=[];if(n.classWeight!=null){const J=eN(n.classWeight,e.outputNames);for(let oe=0;oe<J.length;++oe)U.push(await tN(_[oe],null,J[oe]))}const Y=F.concat(_).concat(U),q=c(Y);qe(Y);for(let J=0;J<u.length;++J){const oe=u[J],ce=q[J];B[oe]=ce,Rn(ce)}await b.onBatchEnd(E,B),Wv(B),E++,N++}if(s?N>=n.batchesPerEpoch:D.done){if(i){let F;iN(n.validationData)?F=Nt(await e.evaluateDataset(n.validationData,{batches:n.validationBatches})):F=Nt(e.evaluate(o,a,{batchSize:n.validationBatchSize==null?U3:n.validationBatchSize,verbose:0}));for(let _=0;_<e.metricsNames.length;++_)v[`val_${e.metricsNames[_]}`]=F[_]}break}if(e.stopTraining_)break}if(await b.onEpochEnd(I,v),I++,e.stopTraining_)break}return await b.onTrainEnd(),await e.history.syncData(),e.history}finally{e.isTraining=!1}}function P3(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 z3(e){return typeof e.next=="function"}async function G3(e,t,n){n=n||{};const s=n.batches!=null,i=e.testFunction;let o=[];if(n.verbose>0)throw new Ge("Verbose mode is not implemented yet.");k(!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=z3(t)?t:await t.iterator();let c=0,u=0;for(;s?u<n.batches:!0;){const p=await a.next();if(o=ee(()=>{if(p.value){const{xs:m,ys:y}=nN(e,p.value),b=m.concat(y),w=ee(()=>i(b));if(qe(b),u===0)for(let T=0;T<w.length;++T)o.push(Ne(0));const I=b[0].shape[0];for(let T=0;T<w.length;++T){const v=w[T],N=o[T];o[T]=ee(()=>be(o[T],X(I,v))),u>0&&qe(N)}qe(w),c+=I,++u}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]=_e(o[p],c),qe(m)}return Jn(o)}function Bw(e){k(e>0&&Number.isInteger(e),()=>`batchSize is required to be a positive integer, but got ${e}`)}function zh(e,t,n){return e==null?[null]:Array.isArray(e)?e.map(s=>Vo(s,t,n-t)):Vo(e,t,n-t)}function Mw(e,t){return ee(()=>e==null?null:Array.isArray(e)?e.map(n=>Mw(n,t)):Cv(e,t.dtype==="int32"?t:t.toInt()))}function Pw(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 V3(e,t,n,s,i,o,a,c,u,p,m,y,b,w,I){i==null&&(i=32),o==null&&(o=1),m==null&&(m=!0),b==null&&(b=0);let T=!1;if(u!=null&&p!=null&&(T=!0),I!=null&&(T=!0,w==null))throw new j("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 N;v!=null&&(N=ai(0,v)),a==null&&(a=1);const{callbackList:E,history:D}=zv(c,a,o,b,v,w,i,T,y);E.setModel(e),e.history=D,await E.onTrainBegin(),e.stopTraining_=!1;for(let F=b;F<o;++F){await E.onEpochBegin(F);const _={};if(w!=null)throw new Ge("stepsPerEpoch mode is not implemented yet.");{if(m==="batch")throw new Ge("batch shuffling is not implemneted yet");m&&Ly(N);const B=rs(N),U=Pw(v,i);for(let Y=0;Y<U.length;++Y){const q={};if(await E.onBatchBegin(Y,q),ee(()=>{const J=U[Y][0],oe=U[Y][1],ce=Vo(B,J,oe-J);q.batch=Y,q.size=oe-J;const ue=Mw(n,ce),he=t(ue);for(let pe=0;pe<s.length;++pe){const le=s[pe],ye=he[pe];q[le]=ye,Rn(ye)}if(Y===U.length-1&&T){const pe=e.testLoop(u,p,i);for(let le=0;le<s.length;++le){const ye=s[le],me=pe[le];Rn(me),_["val_"+ye]=me}}}),await E.onBatchEnd(Y,q),Wv(q),e.stopTraining_)break}B.dispose()}if(await E.onEpochEnd(F,_),e.stopTraining_)break}return await E.onTrainEnd(),await e.history.syncData(),e.history}async function H3(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,u,p,m;try{const y=s.batchSize==null?32:s.batchSize;Bw(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 I=!1,T;if(s.validationData!=null&&s.validationData.length>0){if(I=!0,s.validationData.length===2)a=s.validationData[0],c=s.validationData[1];else throw s.validationData.length===3?new Ge("validationData including sample weights is not supported yet."):new j(`When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; ${s.validationData} is invalid.`);const U=!0,Y=await e.standardizeUserData(a,c,null,null,U,y);u=Y[0],p=Y[1],T=u.concat(p)}else if(s.validationSplit!=null&&s.validationSplit>0&&s.validationSplit<1){I=!0;const U=Math.floor(i[0].shape[0]*(1-s.validationSplit)),Y=i[0].shape[0];u=zh(i,U,Y),i=zh(i,0,U),p=zh(o,U,Y),o=zh(o,0,U),T=u.concat(p)}else s.validationSteps!=null&&(I=!0);const v=i.concat(o).concat(m);e.checkTrainableWeightsConsistency();const N=e.makeTrainFunction(),E=e.getDedupedMetricsNames();let D,F;I?(e.makeTestFunction(),D=e.testFunction,F=E.slice().concat(E.map(U=>"val_"+U))):(D=null,T=[],F=E.slice());const _=Pv(s.callbacks,s.yieldEvery),B=await V3(e,N,v,E,y,s.epochs,s.verbose,_,D,T,s.shuffle,F,s.initialEpoch,null,null);return B}finally{e.isTraining=!1,Yo(i,t),Yo(o,n),Yo(u,a),Yo(p,c),m!=null&&qe(m)}}function rN(e){const t=[];e instanceof Q&&(e=[e]);for(let n=0;n<e.length;++n){const s=e[n];if(s.rank===1)t.push(Wh(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 Yo(e,t){if(e==null)return;const n=[];if(t instanceof Q)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 Q)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 Y3(e){return e instanceof Q}function zw(e){return Array.isArray(e)}function oN(e){return!Y3(e)&&!zw(e)}function aN(e,t,n,s=!0,i=""){if(t==null||t.length===0){if(e!=null){let a=!1;if(zw(e)&&e.length>0)a=!0;else if(oN(e)){for(const c in e)if(e.hasOwnProperty(c)){a=!0;break}}else a=!0;if(a)throw new j(`Error when checking model ${i} expected no data, but got ${e}`)}return[]}if(e==null)return t.map(a=>null);let o;if(oN(e)){e=e,o=[];for(const a of t){if(e[a]==null)throw new j(`No data provided for "${a}". Need data for each key in: ${t}`);o.push(e[a])}}else if(zw(e)){if(e=e,e.length!==t.length)throw new j(`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 j(`The model ${i} expects ${t.length} Tensor(s), but only received one Tensor. Found: Tensor with shape ${e.shape}`);o=[e]}if(o=rN(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 j(`Error when checking ${i}: expected ${t[a]} to have ${n[a].length} dimension(s). but got array with shape ${c.shape}`);for(let u=0;u<n[a].length;++u){if(u===0&&!s)continue;const p=c.shape[u],m=n[a][u];if(m!=null&&m>=0&&p!==m)throw new j(`Error when checking ${i}: expected ${t[a]} to have shape [${n[a]}], but got array with shape [${c.shape}].`)}}return o}function q3(e,t,n){const s=Hr(e.map(o=>o.shape[0]));s.sort();const i=Hr(t.map(o=>o.shape[0]));if(i.sort(),s.length>1)throw new j(`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 j(`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&&!ot(s,i))throw new j(`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 j3(e,t,n){const s=[ar,Vp,Bh];for(let i=0;i<e.length;++i){const o=e[i],a=t[i],c=n[i];if(a==null)continue;if(a===Bh&&o.shape[o.shape.length-1]===1)throw new j(`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 u=o.shape.slice(1),p=c.slice(1);for(let m=0;m<u.length;++m){const y=u[m],b=p[m];if(b!=null&&y!==b)throw new j(`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 cN(e,t,n,s=!0,i=""){let o;if(Array.isArray(e)){if(e.length!==t.length)throw new j(`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 j(`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 j(`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 u=0;u<n[a].length;++u){if(u===0&&!s)continue;const p=c.shape[u],m=n[a][u];if(m!=null&&m!==p)throw new j(`Error when checking ${i}: expected ${t[a]} to have shape ${JSON.stringify(n[a])} but got array with shape ${JSON.stringify(c.shape)}.`)}}}function K3(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 X3="layers-model";class cr extends Ui{constructor(e){super(e);this.isTraining=!1}summary(e,t,n=console.log){if(!this.built)throw new j("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).");C3(this,e,t,n)}compile(e){if(e.loss==null&&(e.loss=[]),this.loss=e.loss,typeof e.optimizer=="string")this.optimizer_=N3(e.optimizer),this.isOptimizerOwned=!0;else{if(!(e.optimizer instanceof sr))throw new j("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 j(`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(Dw(e.loss[o]))}else if(Array.isArray(e.loss)){if(e.loss.length!==this.outputs.length)throw new j(`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=>Dw(a))}else{const o=Dw(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=[],Go("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=K3(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])};Go("metric",()=>{for(let o=0;o<this.outputs.length;++o){if(n.indexOf(o)!==-1)continue;const a=s[o],c=u=>{const p="";let m,y,b;for(const w of u){if(typeof w=="string"&&["accuracy","acc","crossentropy","ce"].indexOf(w)!==-1){const T=this.internalOutputShapes[o];T[T.length-1]===1||this.lossFunctions[o]===Vp?["accuracy","acc"].indexOf(w)!==-1?y=kw:["crossentropy","ce"].indexOf(w)!==-1&&(y=Hv):this.lossFunctions[o]===Gp?["accuracy","acc"].indexOf(w)!==-1?y=Yv:["crossentropy","ce"].indexOf(w)!==-1&&(y=qv):["accuracy","acc"].indexOf(w)!==-1?y=Fw:["crossentropy","ce"].indexOf(w)!==-1&&(y=_w);let v;["accuracy","acc"].indexOf(w)!==-1?v="acc":["crossentropy","ce"].indexOf(w)!==-1&&(v="ce"),b=y,m=p+v}else{const T=v3(w);b=T,m=p+jp(w)}let I;Go(m,()=>{I=b}),i(o,m,I)}};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;Bw(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,u=this.testLoop(c,a,s,n.verbose,n.steps);return Jn(u)}finally{Yo(o[0],e),Yo(o[1],t)}}async evaluateDataset(e,t){return this.makeTestFunction(),G3(this,e,t)}checkNumSamples(e,t,n,s="steps"){let i;if(n!=null){if(i=null,t!=null)throw new j(`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 j(`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 j("`outputs` is an empty Array, which is not allowed.");const n=Array.isArray(t),s=n?t:[t],i=this.retrieveSymbolicTensors(s),o=new Ho;if(e instanceof Q&&(e=[e]),Array.isArray(e)){if(e.length!==this.inputs.length)throw new j(`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 u=e[c.name];if(u==null)throw new j(`No value is provided for the model's input ${c.name}`);o.add(c,u)}const a=Ph(i,o);return n?a:a[0]}retrieveSymbolicTensors(e){const t=Po(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 j(`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 Ge("Verbose predictLoop() is not implemented yet.");const i=Pw(s,t),o=this.outputs.map(a=>[]);for(let a=0;a<i.length;++a){const c=ee(()=>{const u=i[a][0],p=i[a][1],m=zh(e,u,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 Ho(y);return Ph(this.outputs,b)});c.forEach((u,p)=>o[p].push(u))}return Jn(o.map(a=>Mt(a,0)))})}predict(e,t={}){const n=rN(e);cN(n,this.inputNames,this.feedInputShapes,!1);try{const s=t.batchSize==null?32:t.batchSize;return Bw(s),this.predictLoop(n,s)}finally{Yo(n,e)}}predictOnBatch(e){cN(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 oi("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===Gp?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"),q3(e,t,null),j3(t,this.feedLossFns,this.feedOutputShapes),this.stateful&&s!=null&&s>0&&e[0].shape[0]%s!==0)throw new j(`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 u=null;if(s!=null){const p=eN(s,this.outputNames);u=[];for(let m=0;m<p.length;++m)u.push(await tN(c[m],null,p[m]))}return[a,c,u]}testLoop(e,t,n,s=0,i){return ee(()=>{const o=this.checkNumSamples(t,n,i,"steps"),a=[];if(s>0)throw new Ge("Verbose mode is not implemented yet.");if(i!=null)throw new Ge("steps mode in testLoop() is not implemented yet");{const c=Pw(o,n),u=rs(ai(0,o));for(let p=0;p<c.length;++p){const m=c[p][0],y=c[p][1],b=Vo(u,m,y-m),w=Mw(t,b),I=e(w);if(p===0)for(let T=0;T<I.length;++T)a.push(Ne(0));for(let T=0;T<I.length;++T){const v=I[T];a[T]=be(a[T],X(y-m,v))}}for(let p=0;p<a.length;++p)a[p]=_e(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(gv(e,s)>1){const o=gv(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 I=0;I<this.inputs.length;++I)m.push({key:this.inputs[I],value:n[I]});const y=new Ho(m),b=Ph(this.outputs,y,{training:!0});let w;for(let I=0;I<this.lossFunctions.length;++I){const T=this.lossFunctions[I];let v=T(s[I],b[I]);i[I]!=null&&(v=$3(v,i[I]));const N=zt(v);t.push(N),I===0?w=v:w=be(w,v)}for(let I=0;I<this.metricsTensors.length;++I){let T;if(this.outputs.length>1&&I<this.outputs.length)T=t[I];else{const v=this.metricsTensors[I][0],N=this.metricsTensors[I][1];T=zt(v(s[N],b[N]))}Rn(T),o.push(T)}return w=zt(w),this.calculateLosses().forEach(I=>{w=be(w,I)}),w},c=this.collectedTrainableWeights.map(m=>m.read()),u=!0,p=this.optimizer_.minimize(a,u,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 u=0;u<this.inputs.length;++u)o.push({key:this.inputs[u],value:s[u]});const a=new Ho(o),c=Ph(this.outputs,a);for(let u=0;u<this.lossFunctions.length;++u){const p=this.lossFunctions[u],m=zt(p(i[u],c[u]));u===0?n=m:n=be(n,m),t.push(n)}for(let u=0;u<this.metricsTensors.length;++u){const p=this.metricsTensors[u][0],m=this.metricsTensors[u][1],y=zt(p(i[m],c[m]));t.push(y)}return t})}async fit(e,t,n={}){return H3(this,e,t,n)}async fitDataset(e,t){return M3(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 u of a){const p=await u.data();c.push(p[0])}return qe(a),Jn(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=Bd().numTensors;this.optimizer_.dispose(),e.numDisposedVariables+=t-Bd().numTensors}return e}getLossIdentifiers(){let e;if(typeof this.loss=="string")e=or(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=>or(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]=or(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[or(jp(this.metrics))];if(Array.isArray(this.metrics))return this.metrics.map(e=>or(jp(e)));{const e={};for(const t in this.metrics)e[t]=or(jp(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=Mh(e.optimizer_config),n=hi(t);let s;if(typeof e.loss=="string")s=zo(e.loss);else if(Array.isArray(e.loss))s=e.loss.map(o=>zo(o));else if(e.loss!=null){s={};for(const o in e.loss)s[o]=zo(e.loss[o])}let i;if(Array.isArray(e.metrics))i=e.metrics.map(o=>zo(o));else if(e.metrics!=null){i={};for(const o in e.metrics)i[o]=zo(e.metrics[o])}this.compile({loss:s,metrics:i,optimizer:n})}async save(e,t){if(typeof e=="string"){const u=Uy(e);if(u.length===0)throw new j(`Cannot find any save handlers for URL '${e}'`);if(u.length>1)throw new j(`Found more than one (${u.length}) save handlers for URL '${e}'`);e=u[0]}if(e.save==null)throw new j("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");const n=await Wy(this.getNamedWeights(t)),s=!1,i=null,o=this.toJSON(i,s),a={modelTopology:o,format:X3,generatedBy:`TensorFlow.js tfjs-layers v${Xp}`,convertedBy:null},c=t==null?!1:t.includeOptimizer;if(c&&this.optimizer!=null){a.trainingConfig=this.getTrainingConfig();const u="optimizer",{data:p,specs:m}=await Wy(await this.optimizer.getWeights(),u);n.specs.push(...m),n.data=Od([n.data,p])}if(this.userDefinedMetadata!=null){const u=!0;Kv(this.userDefinedMetadata,this.name,u),a.userDefinedMetadata=this.userDefinedMetadata}return a.weightData=n.data,a.weightSpecs=n.specs,e.save(a)}setUserDefinedMetadata(e){Kv(e,this.name),this.userDefinedMetadata=e}getUserDefinedMetadata(){return this.userDefinedMetadata}}cr.className="Model",ge(cr);class lN extends cr{}lN.className="Functional",ge(lN);async function J3(e,t){"modelTopology"in e||(e={modelTopology:e}),e=e;let n=e.modelTopology;n.model_config!=null&&(n=n.model_config);const s=Mh(n),i=hi(s,t);if(e.weightsManifest!=null){const o=await _T(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 Z3(e,t){if(t==null&&(t={}),typeof e=="string"){const n=By(e,t);if(n.length===0)n.push(kd(e,t));else if(n.length>1)throw new j(`Found more than one (${n.length}) load handlers for URL '${e}'`);e=n[0]}return Q3(e,void 0,t)}async function Q3(e,t,n){if(n==null&&(n={}),e.load==null)throw new j("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=hi(Mh(i),t,a),u=s.trainingConfig;if(u!=null&&c.loadTrainingConfig(u),s.userDefinedMetadata!=null&&c.setUserDefinedMetadata(s.userDefinedMetadata),s.weightData!=null){if(s.weightSpecs==null)throw new j("LayersModel artifacts contains weight data, but not weight specs. Therefore loading of weights cannot proceed.");const{modelWeights:p,optimizerWeights:m}=eG(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 eG(e,t){const n=Rd(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 oc extends cr{constructor(e){super({inputs:[],outputs:[]});if(e=e||{},this.trainable=!0,this.built=!1,this.name=e.name!=null?e.name:Up("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 j(`Negative dimension size caused by adding layer ${e.name} with input shape [${e.inboundNodes[0].inputTensors[0].shape}]`)}add(e){const t=e instanceof oc||e instanceof cr;let n;if(t){if(n=e,n.outputs.length!==1)throw new j("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 j("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 j("The first layer in a Sequential model must get an `inputShape` or `batchInputShape` argument.");const s=_v({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 j(`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 j("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=Fv(this.outputs[0])}this.inboundNodes=[],new Pp({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:Po(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(It(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 cr({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 oi("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 oi("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 oi("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 oi("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 j("Legacy serialization format not supported yet.");i=t}else k(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 oc))throw new Ge(`Sequential.fromConfig called on non-Sequential input: ${a}`);for(const c of i){const u=void 0,p=hi(c,u,s);s&&p.setFastWeightInitDuringBuild(!0),a.add(p)}return a}set stopTraining(e){if(this.model==null)throw new j("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 j("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}}}oc.className="Sequential",ge(oc);function tG(e){return new cr(e)}function nG(e){return new oc(e)}function sG(e,t){return t==null&&(t={}),Z3(e,t)}function hN(e){return _v(e)}function iG(e,t){zs.registerCallbackConstructor(e,t)}class cs extends No{getConfig(){return{}}}class uN extends cs{apply(e,t=1){return Dz(e,t)}}uN.className="elu",ge(uN);class dN extends cs{apply(e){return rp(e)}}dN.className="selu",ge(dN);class pN extends cs{apply(e){return Fi(e)}}pN.className="relu",ge(pN);class mN extends cs{apply(e){return ee(()=>ko(6,Fi(e)))}}mN.className="relu6",ge(mN);class fN extends cs{apply(e){return e}}fN.className="linear",ge(fN);class gN extends cs{apply(e){return Ei(e)}}gN.className="sigmoid",ge(gN);class yN extends cs{apply(e){return Fz(e)}}yN.className="hardSigmoid",ge(yN);class bN extends cs{apply(e){return Va(e)}}bN.className="softplus",ge(bN);class wN extends cs{apply(e){return kz(e)}}wN.className="softsign",ge(wN);class LN extends cs{apply(e){return Ma(e)}}LN.className="tanh",ge(LN);class Gw extends cs{apply(e,t=-1){return Uo(e,t)}}Gw.className="softmax",ge(Gw);class SN extends cs{apply(e,t=-1){return Qd(e,t)}}SN.className="logSoftmax",ge(SN);class IN extends cs{apply(e,t=1){return ee(()=>Ei(e.mul(t)).mul(e))}}IN.className="swish",ge(IN);function Xr(e){return e.getClassName()}function Vw(e,t={}){return Dh(e,Ws.getMap().classNameMap,t,"activation")}function Jr(e){if(e==null){const t={};return t.className="linear",t.config={},Vw(t)}if(typeof e=="string"){const t={};return t.className=e,t.config={},Vw(t)}else return e instanceof cs?e:Vw(e)}function Hw(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 xN extends No{}class Gh extends xN{constructor(e){super();Hw(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=ct([1]);return this.hasL1&&(t=be(t,Ue(X(this.l1,rn(e))))),this.hasL2&&(t=be(t,Ue(X(this.l2,$h(e))))),t.asScalar()})}getConfig(){return{l1:this.l1,l2:this.l2}}static fromConfig(e,t){return new e({l1:t.l1,l2:t.l2})}}Gh.className="L1L2",ge(Gh);function rG(e){return Hw(e),new Gh({l1:e!=null?e.l1:null,l2:0})}function oG(e){return Hw(e),new Gh({l2:e!=null?e.l2:null,l1:0})}const TN={l1l2:"L1L2"};function xt(e){return cw(e)}function AN(e,t={}){return Dh(e,Ws.getMap().classNameMap,t,"regularizer")}function _t(e){if(e==null)return null;if(typeof e=="string"){const t=e in TN?TN[e]:e,n={className:t,config:{}};return AN(n)}else return e instanceof xN?e:AN(e)}class Yw extends lt{constructor(e){super(e==null?{}:e);this.supportsMasking=!0,e!=null&&(this.maxValue=e.maxValue)}call(e,t){e=Xe(e);let n=Fi(e);return this.maxValue!=null&&(n=jn(n,0,this.maxValue)),n}computeOutputShape(e){return e}getConfig(){const e={maxValue:this.maxValue},t=super.getConfig();return Object.assign(e,t),e}}Yw.className="ReLU",ge(Yw);class qw extends lt{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=Xe(e);return Xd(n,this.alpha)}computeOutputShape(e){return e}getConfig(){const e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}}qw.className="LeakyReLU",ge(qw);class jw extends lt{constructor(e){super(e==null?{}:e);if(this.DEFAULT_ALPHA_INITIALIZER="zeros",e==null&&(e={}),this.supportsMasking=!0,this.alphaInitializer=Ft(e.alphaInitializer||this.DEFAULT_ALPHA_INITIALIZER),this.alphaRegularizer=_t(e.alphaRegularizer),this.alphaConstraint=hn(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 j(`Expected sharedAxes to be a number or an array of numbers, but got ${e.sharedAxes}`)}build(e){e=It(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 fn({ndim:e.length,axes:n})],this.built=!0}call(e,t){return e=Xe(e),gh(e,this.alpha.read())}getConfig(){const e={alphaInitializer:Vt(this.alphaInitializer),alphaRegularizer:xt(this.alphaRegularizer),alphaConstraint:ln(this.alphaConstraint),sharedAxes:this.sharedAxes},t=super.getConfig();return Object.assign(e,t),e}}jw.className="PReLU",ge(jw);class Kw extends lt{constructor(e){super(e==null?{}:e);if(this.DEFAULT_ALPHA=1,e==null&&(e={}),e.alpha!=null&&e.alpha!==this.DEFAULT_ALPHA)throw new Ge(`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=Xe(e);return Do(n)}computeOutputShape(e){return e}getConfig(){const e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}}Kw.className="ELU",ge(Kw);class Xw extends lt{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=Xe(e);return n.mul(_h(n.greater(this.theta),"float32"))}computeOutputShape(e){return e}getConfig(){const e={theta:this.theta},t=super.getConfig();return Object.assign(e,t),e}}Xw.className="ThresholdedReLU",ge(Xw);class Jw extends lt{constructor(e){super(e==null?{}:e);this.DEFAULT_AXIS=1,e==null&&(e={}),this.softmax=new Gw().apply,this.axis=e.axis==null?this.DEFAULT_AXIS:e.axis}call(e,t){const n=Xe(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}}Jw.className="Softmax",ge(Jw);function ac(e,t,n){if(typeof e=="number")return Po(e,t);if(e.length!==t)throw new j(`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(!vz(i))throw new j(`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 ui(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 Jp(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 j(`Unsupport padding mode: ${s}.`);return e}function Zw(e,t){return ee(()=>(Gt(t),t==="channelsFirst"?Pe(e,[0,2,3,1]):e))}function vN(e,t){return ee(()=>(Gt(t),t==="channelsFirst"?Pe(e,[0,2,3,4,1]):e))}function NN(e,t,n,s=1,i="valid",o,a=1){return ee(()=>{if(o==null&&(o=ri()),Gt(o),e.shape.length!==3)throw new j(`The input of a conv1dWithBias operation should be 3, but is ${e.shape.length} instead.`);if(t.shape.length!==3)throw new j(`The kernel for a conv1dWithBias operation should be 3, but is ${t.shape.length} instead`);if(n!=null&&n.shape.length!==1)throw new j(`The bias for a conv1dWithBias operation should be 1, but is ${t.shape.length} instead`);if(o==="channelsFirst"&&(e=Pe(e,[0,2,1])),i==="causal")throw new Ge("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");let c=Hd(e,t,s,i==="same"?"same":"valid","NWC",a);return n!=null&&(c=$i(c,n)),c})}function vee(e,t,n=1,s="valid",i,o=1){return ee(()=>(Gt(i),NN(e,t,null,n,s,i,o)))}function Nee(e,t,n=[1,1],s="valid",i,o){return ee(()=>(Gt(i),Qw(e,t,null,n,s,i,o)))}function Qw(e,t,n,s=[1,1],i="valid",o,a,c=null){return ee(()=>{if(o==null&&(o=ri()),Gt(o),e.rank!==3&&e.rank!==4)throw new j(`conv2dWithBiasActivation expects input to be of rank 3 or 4, but received ${e.rank}.`);if(t.rank!==3&&t.rank!==4)throw new j(`conv2dWithBiasActivation expects kernel to be of rank 3 or 4, but received ${e.rank}.`);let u=Zw(e,o);if(i==="causal")throw new Ge("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");return u=Hb({x:u,filter:t,strides:s,pad:i==="same"?"same":"valid",dilations:a,dataFormat:"NHWC",bias:n,activation:c}),o==="channelsFirst"&&(u=Pe(u,[0,3,1,2])),u})}function Cee(e,t,n=[1,1,1],s="valid",i,o){return ee(()=>(Gt(i),CN(e,t,null,n,s,i,o)))}function CN(e,t,n,s=[1,1,1],i="valid",o,a){return ee(()=>{if(o==null&&(o=ri()),Gt(o),e.rank!==4&&e.rank!==5)throw new j(`conv3dWithBias expects input to be of rank 4 or 5, but received ${e.rank}.`);if(t.rank!==4&&t.rank!==5)throw new j(`conv3dWithBias expects kernel to be of rank 4 or 5, but received ${e.rank}.`);let c=vN(e,o);if(i==="causal")throw new Ge("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");return c=yb(c,t,s,i==="same"?"same":"valid","NDHWC",a),n!=null&&(c=$i(c,n)),o==="channelsFirst"&&(c=Pe(c,[0,4,1,2,3])),c})}class eL extends lt{constructor(e,t){super(t);if(this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",eL.verifyArgs(t),this.rank=e,mn(this.rank,"rank"),this.rank!==1&&this.rank!==2&&this.rank!==3)throw new Ge(`Convolution layer for rank other than 1, 2, or 3 (${this.rank}) is not implemented yet.`);if(this.kernelSize=ac(t.kernelSize,e,"kernelSize"),this.strides=ac(t.strides==null?1:t.strides,e,"strides"),this.padding=t.padding==null?"valid":t.padding,Ns(this.padding),this.dataFormat=t.dataFormat==null?"channelsLast":t.dataFormat,Gt(this.dataFormat),this.activation=Jr(t.activation),this.useBias=t.useBias==null?!0:t.useBias,this.biasInitializer=Ft(t.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.biasConstraint=hn(t.biasConstraint),this.biasRegularizer=_t(t.biasRegularizer),this.activityRegularizer=_t(t.activityRegularizer),this.dilationRate=ac(t.dilationRate==null?1:t.dilationRate,e,"dilationRate"),this.rank===1&&Array.isArray(this.dilationRate)&&this.dilationRate.length!==1)throw new j(`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 j(`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 j(`dilationRate must be a number or array of three numbers for 3D convolution, but received ${JSON.stringify(this.dilationRate)}`)}}static verifyArgs(e){if(vs("kernelSize"in e,"required key 'kernelSize' not in config"),typeof e.kernelSize!="number"&&!hw(e.kernelSize,"number",1,3))throw new j(`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:Xr(this.activation),useBias:this.useBias,biasInitializer:Vt(this.biasInitializer),biasRegularizer:xt(this.biasRegularizer),activityRegularizer:xt(this.activityRegularizer),biasConstraint:ln(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}}class Vh extends eL{constructor(e,t){super(e,t);this.kernel=null,Vh.verifyArgs(t),this.filters=t.filters,mn(this.filters,"filters"),this.kernelInitializer=Ft(t.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.kernelConstraint=hn(t.kernelConstraint),this.kernelRegularizer=_t(t.kernelRegularizer)}build(e){e=It(e);const t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null)throw new j(`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=Xe(e);let n;const s=this.bias==null?null:this.bias.read(),i=bv(this.activation.getClassName());if(i!=null&&this.rank===2)n=Qw(e,this.kernel.read(),s,this.strides,this.padding,this.dataFormat,this.dilationRate,i);else{if(this.rank===1)n=NN(e,this.kernel.read(),s,this.strides[0],this.padding,this.dataFormat,this.dilationRate[0]);else if(this.rank===2)n=Qw(e,this.kernel.read(),s,this.strides,this.padding,this.dataFormat,this.dilationRate);else if(this.rank===3)n=CN(e,this.kernel.read(),s,this.strides,this.padding,this.dataFormat,this.dilationRate);else throw new Ge("convolutions greater than 3D are not implemented yet.");this.activation!=null&&(n=this.activation.apply(n))}return n})}computeOutputShape(e){e=It(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=ui(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:Vt(this.kernelInitializer),kernelRegularizer:xt(this.kernelRegularizer),kernelConstraint:ln(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 j(`Convolution layer expected config.filters to be a 'number' > 0 but got ${JSON.stringify(e.filters)}`)}}class Hh extends Vh{constructor(e){super(2,e);Hh.verifyArgs(e)}getConfig(){const e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if(typeof e.kernelSize!="number"&&!hw(e.kernelSize,"number",1,2))throw new j(`Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received ${JSON.stringify(e.kernelSize)}.`)}}Hh.className="Conv2D",ge(Hh);class Zp extends Vh{constructor(e){super(3,e);Zp.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 j(`Conv3D expects config.kernelSize to be number or [number, number, number], but received ${JSON.stringify(e.kernelSize)}.`)}}Zp.className="Conv3D",ge(Zp);class tL extends Hh{constructor(e){super(e);if(this.inputSpec=[new fn({ndim:4})],this.padding!=="same"&&this.padding!=="valid")throw new j(`Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(e=It(e),e.length!==4)throw new j("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 j("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 fn({ndim:4,axes:{[t]:n}})],this.built=!0}call(e,t){return ee(()=>{let n=Xe(e);if(n.shape.length!==4)throw new j(`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],u=s[a],p=this.kernelSize[0],m=this.kernelSize[1],y=this.strides[0],b=this.strides[1],w=Jp(c,y,p,this.padding),I=Jp(u,b,m,this.padding),T=[i,w,I,this.filters];this.dataFormat!=="channelsLast"&&(n=Pe(n,[0,2,3,1]));let v=Yd(n,this.kernel.read(),T,this.strides,this.padding);return this.dataFormat!=="channelsLast"&&(v=Pe(v,[0,3,1,2])),this.bias!=null&&(v=$i(v,this.bias.read(),this.dataFormat)),this.activation!=null&&(v=this.activation.apply(v)),v})}computeOutputShape(e){e=It(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],u=this.strides[1];return t[n]=this.filters,t[s]=Jp(t[s],c,o,this.padding),t[i]=Jp(t[i],u,a,this.padding),t}getConfig(){const e=super.getConfig();return delete e.dilationRate,e}}tL.className="Conv2DTranspose",ge(tL);class RN extends Vh{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 j("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(t.kernelInitializer!=null||t.kernelRegularizer!=null||t.kernelConstraint!=null)throw new j("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 j(`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=Ft(t.depthwiseInitializer||this.DEFAULT_DEPTHWISE_INITIALIZER),this.depthwiseRegularizer=_t(t.depthwiseRegularizer),this.depthwiseConstraint=hn(t.depthwiseConstraint),this.pointwiseInitializer=Ft(t.depthwiseInitializer||this.DEFAULT_POINTWISE_INITIALIZER),this.pointwiseRegularizer=_t(t.pointwiseRegularizer),this.pointwiseConstraint=hn(t.pointwiseConstraint)}build(e){if(e=It(e),e.length<this.rank+2)throw new j(`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 j(`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 fn({ndim:this.rank+2,axes:{[t]:n}})],this.built=!0}call(e,t){return ee(()=>{e=Xe(e);let n;if(this.rank===1)throw new Ge("1D separable convolution is not implemented yet.");return this.rank===2&&(this.dataFormat==="channelsFirst"&&(e=Pe(e,[0,2,3,1])),n=Fb(e,this.depthwiseKernel.read(),this.pointwiseKernel.read(),this.strides,this.padding,this.dilationRate,"NHWC")),this.useBias&&(n=$i(n,this.bias.read(),this.dataFormat)),this.activation!=null&&(n=this.activation.apply(n)),this.dataFormat==="channelsFirst"&&(n=Pe(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=Vt(this.depthwiseInitializer),e.pointwiseInitializer=Vt(this.pointwiseInitializer),e.depthwiseRegularizer=xt(this.depthwiseRegularizer),e.pointwiseRegularizer=xt(this.pointwiseRegularizer),e.depthwiseConstraint=ln(this.depthwiseConstraint),e.pointwiseConstraint=ln(this.pointwiseConstraint),e}}RN.className="SeparableConv";class nL extends RN{constructor(e){super(2,e)}}nL.className="SeparableConv2D",ge(nL);class Qp extends Vh{constructor(e){super(1,e);Qp.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"&&!hw(e.kernelSize,"number",1,1))throw new j(`Conv1D expects config.kernelSize to be number or number[] with length 1, but received ${JSON.stringify(e.kernelSize)}.`)}}Qp.className="Conv1D",ge(Qp);class sL extends lt{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=Xe(e),this.dataFormat==="channelsLast"){const n=Cp(e,this.cropping[0][0],e.shape[1]-this.cropping[0][0]-this.cropping[0][1],2);return Cp(n,this.cropping[1][0],e.shape[2]-this.cropping[1][1]-this.cropping[1][0],3)}else{const n=Cp(e,this.cropping[0][0],e.shape[2]-this.cropping[0][0]-this.cropping[0][1],3);return Cp(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}}sL.className="Cropping2D",ge(sL);class iL extends lt{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=Xe(e);const s=n.shape;if(this.dataFormat==="channelsFirst"){n=Pe(n,[0,2,3,1]);const i=this.size[0]*s[2],o=this.size[1]*s[3],a=n.resizeNearestNeighbor([i,o]);return Pe(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}}iL.className="UpSampling2D",ge(iL);function aG(e,t,n=[1,1],s="valid",i,o){return ee(()=>{i==null&&(i=ri()),Gt(i);let a=Zw(e,i);if(e.rank!==4)throw new j(`Input for depthwiseConv2d is required to be 4-D, but is instead ${e.rank}-D`);if(t.rank!==4)throw new j(`depthwiseKernel is required to be 4-D, but is instead ${t.rank}-D`);return a=Oo(a,t,n,s==="same"?"same":"valid","NHWC",o),i==="channelsFirst"&&(a=Pe(a,[0,3,1,2])),a})}class rL extends eL{constructor(e){super(2,e);this.depthwiseKernel=null,this.depthMultiplier=e.depthMultiplier==null?1:e.depthMultiplier,this.depthwiseInitializer=Ft(e.depthwiseInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.depthwiseConstraint=hn(e.depthwiseConstraint),this.depthwiseRegularizer=_t(e.depthwiseRegularizer)}build(e){if(e=It(e),e.length<4)throw new j(`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 j(`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=Xe(e);let n=aG(e,this.depthwiseKernel.read(),this.strides,this.padding,this.dataFormat,null);return this.useBias&&(n=$i(n,this.bias.read(),this.dataFormat)),this.activation!=null&&(n=this.activation.apply(n)),n})}computeOutputShape(e){e=It(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=ui(t,this.kernelSize[0],this.padding,this.strides[0]),o=ui(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=Vt(this.depthwiseInitializer),e.depthwiseRegularizer=xt(this.depthwiseRegularizer),e.depthwiseConstraint=ln(this.depthwiseRegularizer),e}}rL.className="DepthwiseConv2D",ge(rL);function ON(e,t,n,s){if(Array.isArray(e)){if(t!=null||n!=null)throw new j("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 EN(e,t,n,s=!1,i,o,a=!1,c=!1){return ee(()=>{const u=t.shape.length;if(u<3)throw new j(`Input should be at least 3D, but is ${u}D.`);const p=[1,0].concat(ai(2,u));if(t=Pe(t,p),o!=null)throw new Ge("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===u-1&&(i=Kn(i,-1)),i=Pe(i,p)),s&&(t=As(t,0),i!=null&&(i=As(i,0)));const m=[];let y,b=n;const w=t.shape[0],I=_i(t);let T;i!=null&&(T=_i(i));for(let N=0;N<w;++N){const E=I[N],D=ee(()=>e(E,b));if(i==null)y=D[0],b=D[1];else{const F=ee(()=>{const _=T[N],B=Dn(_).sub(_),U=D[0].mul(_).add(b[0].mul(B)),Y=b.map((q,J)=>D[1][J].mul(_).add(q.mul(B)));return{output:U,newStates:Y}});y=F.output,b=F.newStates}c&&m.push(y)}let v;if(c){const N=1;v=as(m,N)}return[y,v,b]})}class Bi extends lt{constructor(e){super(e);let t;if(e.cell==null)throw new j("cell property is missing for the constructor of RNN.");if(Array.isArray(e.cell)?t=new nm({cells:e.cell}):t=e.cell,t.stateSize==null)throw new j("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 fn({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 ai(0,e).map(t=>null)}else return this.states_}setStates(e){this.states_=e}computeOutputShape(e){Nw(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 Ge("Constants support is not implemented in RNN yet.");Nw(e)&&(e=e[0]),e=e;const n=this.stateful?e[0]:null,s=e.slice(2);this.inputSpec[0]=new fn({shape:[n,null,...s]});const i=[e[0]].concat(e.slice(2));if(t!=null)throw new Ge("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(!ot(this.stateSpec.map(a=>a.shape[a.shape.length-1]),o))throw new j(`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 fn({shape:[null,a]}));this.stateful&&this.resetStates()}resetStates(e,t=!1){ee(()=>{if(!this.stateful)throw new rr("Cannot call resetStates() on an RNN Layer that is not stateful.");const n=this.inputSpec[0].shape[0];if(n==null)throw new j("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=>ct([n,s])):this.states_=[ct([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=>ct([n,s])):this.states_[0]=ct([n,this.cell.stateSize]);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new j(`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(!ot(i.shape,a))throw new j(`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=>Rn(s.clone()))})}apply(e,t){let n=t==null?null:t.initialState,s=t==null?null:t.constants;t==null&&(t={});const i=ON(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 u of n)this.stateSpec.push(new fn({shape:u.shape}));a=a.concat(this.stateSpec)}s!=null&&(t.constants=s,o=o.concat(s),this.numConstants=s.length);const c=o[0]instanceof li;if(c){const u=[e].concat(o),p=this.inputSpec.concat(a),m=this.inputSpec;this.inputSpec=p;const y=super.apply(u,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=Xe(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 j(`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,I)=>{const T=this.cell.call([w].concat(I),a);return[T[0],T.slice(1)]},u=EN(c,e,i,this.goBackwards,n,null,this.unroll,this.returnSequences),p=u[0],m=u[1],y=u[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=ct(e.shape);return t=Ue(t,[1,2]),t=Wh(t),Array.isArray(this.cell.stateSize)?this.cell.stateSize.map(n=>n>1?bw(t,[1,n]):t):this.cell.stateSize>1?[bw(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()===Bi.className&&(t.cell={className:this.cell.getClassName(),config:n}),Object.assign({},n,e,t)}static fromConfig(e,t,n={}){const s=t.cell,i=hi(s,n);return new e(Object.assign(t,{cell:i}))}}Bi.className="RNN",ge(Bi);class cc extends lt{}class em extends cc{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,mn(this.units,"units"),this.activation=Jr(e.activation==null?this.DEFAULT_ACTIVATION:e.activation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=Ft(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Ft(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Ft(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=_t(e.kernelRegularizer),this.recurrentRegularizer=_t(e.recurrentRegularizer),this.biasRegularizer=_t(e.biasRegularizer),this.kernelConstraint=hn(e.kernelConstraint),this.recurrentConstraint=hn(e.recurrentConstraint),this.biasConstraint=hn(e.biasConstraint),this.dropout=nc([1,qr([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=nc([1,qr([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=It(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 j(`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=Zr({ones:()=>Dn(e),rate:this.dropout,training:s})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=Zr({ones:()=>Dn(n),rate:this.recurrentDropout,training:s}));let i;const o=this.dropoutMask,a=this.recurrentDropoutMask;o!=null?i=Wi(X(e,o),this.kernel.read()):i=Wi(e,this.kernel.read()),this.bias!=null&&(i=$i(i,this.bias.read())),a!=null&&(n=X(n,a));let c=be(i,Wi(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:Xr(this.activation),useBias:this.useBias,kernelInitializer:Vt(this.kernelInitializer),recurrentInitializer:Vt(this.recurrentInitializer),biasInitializer:Vt(this.biasInitializer),kernelRegularizer:xt(this.kernelRegularizer),recurrentRegularizer:xt(this.recurrentRegularizer),biasRegularizer:xt(this.biasRegularizer),activityRegularizer:xt(this.activityRegularizer),kernelConstraint:ln(this.kernelConstraint),recurrentConstraint:ln(this.recurrentConstraint),biasConstraint:ln(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout};return Object.assign({},e,t)}}em.className="SimpleRNNCell",ge(em);class oL extends Bi{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)}}oL.className="SimpleRNN",ge(oL);class tm extends cc{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 j("GRUCell does not support reset_after parameter set to true.");this.units=e.units,mn(this.units,"units"),this.activation=Jr(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=Jr(e.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=Ft(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Ft(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Ft(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=_t(e.kernelRegularizer),this.recurrentRegularizer=_t(e.recurrentRegularizer),this.biasRegularizer=_t(e.biasRegularizer),this.kernelConstraint=hn(e.kernelConstraint),this.recurrentConstraint=hn(e.recurrentConstraint),this.biasConstraint=hn(e.biasConstraint),this.dropout=nc([1,qr([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=nc([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=It(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 j(`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=Zr({ones:()=>Dn(e),rate:this.dropout,training:n,count:3})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=Zr({ones:()=>Dn(s),rate:this.recurrentDropout,training:n,count:3}));const i=this.dropoutMask,o=this.recurrentDropoutMask;let a,c,u;0<this.dropout&&this.dropout<1&&(e=X(e,i[0]));let p=Wi(e,this.kernel.read());this.useBias&&(p=$i(p,this.bias.read())),0<this.recurrentDropout&&this.recurrentDropout<1&&(s=X(s,o[0]));const m=this.recurrentKernel.read(),[y,b]=os(m,[2*this.units,this.units],m.rank-1),w=Wi(s,y),[I,T,v]=os(p,3,p.rank-1),[N,E]=os(w,2,w.rank-1);a=this.recurrentActivation.apply(be(I,N)),c=this.recurrentActivation.apply(be(T,E));const D=Wi(X(c,s),b);u=this.activation.apply(be(v,D));const F=be(X(a,s),X(be(1,Pt(a)),u));return[F,F]})}getConfig(){const e=super.getConfig(),t={units:this.units,activation:Xr(this.activation),recurrentActivation:Xr(this.recurrentActivation),useBias:this.useBias,kernelInitializer:Vt(this.kernelInitializer),recurrentInitializer:Vt(this.recurrentInitializer),biasInitializer:Vt(this.biasInitializer),kernelRegularizer:xt(this.kernelRegularizer),recurrentRegularizer:xt(this.recurrentRegularizer),biasRegularizer:xt(this.biasRegularizer),activityRegularizer:xt(this.activityRegularizer),kernelConstraint:ln(this.kernelConstraint),recurrentConstraint:ln(this.recurrentConstraint),biasConstraint:ln(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation,resetAfter:!1};return Object.assign({},e,t)}}tm.className="GRUCell",ge(tm);class aL extends Bi{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 tm(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)}}aL.className="GRU",ge(aL);class Yh extends cc{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,mn(this.units,"units"),this.activation=Jr(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=Jr(e.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=Ft(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Ft(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Ft(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.unitForgetBias=e.unitForgetBias,this.kernelRegularizer=_t(e.kernelRegularizer),this.recurrentRegularizer=_t(e.recurrentRegularizer),this.biasRegularizer=_t(e.biasRegularizer),this.kernelConstraint=hn(e.kernelConstraint),this.recurrentConstraint=hn(e.recurrentConstraint),this.biasConstraint=hn(e.biasConstraint),this.dropout=nc([1,qr([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=nc([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=It(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 Ps{apply(c,u){const p=i.apply([o]),m=new Op().apply([o]),y=i.apply([o*2]);return Nv(Nv(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 j(`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=Zr({ones:()=>Dn(e),rate:this.dropout,training:n,count:4})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=Zr({ones:()=>Dn(s),rate:this.recurrentDropout,training:n,count:4}));const o=this.dropoutMask,a=this.recurrentDropoutMask;let c,u,p,m;0<this.dropout&&this.dropout<1&&(e=X(e,o[0]));let y=Wi(e,this.kernel.read());0<this.recurrentDropout&&this.recurrentDropout<1&&(s=X(s,a[0])),y=be(y,Wi(s,this.recurrentKernel.read())),this.useBias&&(y=$i(y,this.bias.read()));const[b,w,I,T]=os(y,4,y.rank-1);c=this.recurrentActivation.apply(b),u=this.recurrentActivation.apply(w),p=be(X(u,i),X(c,this.activation.apply(I))),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:Xr(this.activation),recurrentActivation:Xr(this.recurrentActivation),useBias:this.useBias,kernelInitializer:Vt(this.kernelInitializer),recurrentInitializer:Vt(this.recurrentInitializer),biasInitializer:Vt(this.biasInitializer),unitForgetBias:this.unitForgetBias,kernelRegularizer:xt(this.kernelRegularizer),recurrentRegularizer:xt(this.recurrentRegularizer),biasRegularizer:xt(this.biasRegularizer),activityRegularizer:xt(this.activityRegularizer),kernelConstraint:ln(this.kernelConstraint),recurrentConstraint:ln(this.recurrentConstraint),biasConstraint:ln(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation};return Object.assign({},e,t)}}Yh.className="LSTMCell",ge(Yh);class cL extends Bi{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 Yh(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)}}cL.className="LSTM",ge(cL);class nm extends cc{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){Nw(e)&&(e=e[0]),e=e;let t;this.cells.forEach((n,s)=>{Go(`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(hi(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 Cw(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]])}Rw(t)}}nm.className="StackedRNNCells",ge(nm);function Zr(e){const{ones:t,rate:n,training:s=!1,count:i=1}=e,o=()=>Rv(t(),n),a=()=>Uh(o,t,s);if(!i||i<=1)return Rn(a().clone());const c=Array(i).fill(void 0).map(a);return c.map(u=>Rn(u.clone()))}var cG=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 Ree extends cc{}class DN extends Bi{constructor(e){if(e.unroll)throw new Ge("Unrolling is not possible with convolutional RNNs.");if(Array.isArray(e.cell))throw new Ge("It is not possible at the moment to stack convolutional cells.");super(e);this.inputSpec=[new fn({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 j("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=ct(i);return Array.isArray(t)?Array(t.length).fill(o):[o]})}resetStates(e,t=!1){ee(()=>{if(!this.stateful)throw new rr("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 j("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(()=>ct(i)):this.states_=[ct(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(()=>ct(i)):this.states_[0]=ct(i);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new j(`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],u=i;if(!ot(c.shape,u))throw new j(`State ${a} is incompatible with layer ${this.name}: expected shape=${u}, received shape=${c.shape}`);this.states_[a]=c}}this.states_=this.states_.map(a=>Rn(a.clone()))})}computeSingleOutputShape(e){const{dataFormat:t,filters:n,kernelSize:s,padding:i,strides:o,dilationRate:a}=this.cell,c=t==="channelsFirst",u=e[c?3:2],p=e[c?4:3],m=ui(u,s[0],i,o[0],a[0]),y=ui(p,s[1],i,o[1],a[1]),b=[...e.slice(0,2),...c?[n,m,y]:[m,y,n]];return b}}DN.className="ConvRNN2D";class sm extends Yh{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,mn(this.filters,"filters"),this.kernelSize=ac(n,2,"kernelSize"),this.kernelSize.forEach(c=>mn(c,"kernelSize")),this.strides=ac(s||1,2,"strides"),this.strides.forEach(c=>mn(c,"strides")),this.padding=i||"valid",Ns(this.padding),this.dataFormat=o||"channelsLast",Gt(this.dataFormat),this.dilationRate=ac(a||1,2,"dilationRate"),this.dilationRate.forEach(c=>mn(c,"dilationRate"))}build(e){var t;e=It(e);const n=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[n]==null)throw new j(`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 u=this.biasInitializer,p=this.filters;c=new(t=class extends Ps{apply(y,b){const w=u.apply([p]),I=si([p]),T=u.apply([p*2]);return yw([w,I,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 j(`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=Zr({ones:()=>Dn(s),rate:this.dropout,training:n,count:a}));const c=this.dropoutMask,u=(Ie,Se,Ee)=>!Se||!Se[Ee]?Ie:X(Se[Ee],Ie);let p=u(s,c,0),m=u(s,c,1),y=u(s,c,2),b=u(s,c,3);0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=Zr({ones:()=>Dn(i),rate:this.recurrentDropout,training:n,count:a}));const w=this.recurrentDropoutMask;let I=u(i,w,0),T=u(i,w,1),v=u(i,w,2),N=u(i,w,3);const E=3,[D,F,_,B]=os(this.kernel.read(),a,E),[U,Y,q,J]=this.useBias?os(this.bias.read(),a):[null,null,null,null];p=this.inputConv(p,D,U,this.padding),m=this.inputConv(m,F,Y,this.padding),y=this.inputConv(y,_,q,this.padding),b=this.inputConv(b,B,J,this.padding);const[oe,ce,ue,he]=os(this.recurrentKernel.read(),a,E);I=this.recurrentConv(I,oe),T=this.recurrentConv(T,ce),v=this.recurrentConv(v,ue),N=this.recurrentConv(N,he);const pe=this.recurrentActivation.apply(be(p,I)),le=this.recurrentActivation.apply(be(m,T)),ye=be(X(le,o),X(pe,this.activation.apply(be(y,v)))),me=X(this.recurrentActivation.apply(be(b,N)),this.activation.apply(ye));return[me,me,ye]})}getConfig(){const e=super.getConfig(),{units:t}=e,n=cG(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=er(e,t,this.strides,s||"valid",this.dataFormat==="channelsFirst"?"NCHW":"NHWC",this.dilationRate);return n?$i(i,n,this.dataFormat):i}recurrentConv(e,t){const n=1;return er(e,t,n,"same",this.dataFormat==="channelsFirst"?"NCHW":"NHWC")}}sm.className="ConvLSTM2DCell",ge(sm);class lL extends DN{constructor(e){const t=new sm(e);super(Object.assign({},e,{cell:t}))}static fromConfig(e,t){return new e(t)}}lL.className="ConvLSTM2D",ge(lL);class im extends lt{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=Xe(e);if(0<this.rate&&this.rate<1){const s=t.training==null?!1:t.training,i=this.getNoiseShape(n),o=Uh(()=>Rv(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()}}im.className="Dropout",ge(im);class hL extends im{constructor(e){super(e);this.inputSpec=[{ndim:3}]}getNoiseShape(e){const t=e.shape;return[t[0],1,t[2]]}}hL.className="SpatialDropout1D",ge(hL);class uL extends lt{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,mn(this.units,"units"),this.activation=Jr(e.activation),e.useBias!=null&&(this.useBias=e.useBias),this.kernelInitializer=Ft(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.biasInitializer=Ft(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelConstraint=hn(e.kernelConstraint),this.biasConstraint=hn(e.biasConstraint),this.kernelRegularizer=_t(e.kernelRegularizer),this.biasRegularizer=_t(e.biasRegularizer),this.activityRegularizer=_t(e.activityRegularizer),this.supportsMasking=!0,this.inputSpec=[{minNDim:2}]}build(e){e=It(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=It(e);const t=e.slice();return t[t.length-1]=this.units,t}call(e,t){return ee(()=>{this.invokeCallHook(e,t);const n=Xe(e),s=bv(this.activation.getClassName());let i;return s!=null?i=Wi(n,this.kernel.read(),s,this.bias?this.bias.read():null):(i=Wi(n,this.kernel.read()),this.bias!=null&&(i=$i(i,this.bias.read())),this.activation!=null&&(i=this.activation.apply(i))),i})}getConfig(){const e={units:this.units,activation:Xr(this.activation),useBias:this.useBias,kernelInitializer:Vt(this.kernelInitializer),biasInitializer:Vt(this.biasInitializer),kernelRegularizer:xt(this.kernelRegularizer),biasRegularizer:xt(this.biasRegularizer),activityRegularizer:xt(this.activityRegularizer),kernelConstraint:ln(this.kernelConstraint),biasConstraint:ln(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}}uL.className="Dense",ge(uL);class dL extends lt{constructor(e){e=e||{},super(e),this.inputSpec=[{minNDim:3}],this.dataFormat=e.dataFormat}computeOutputShape(e){e=It(e);for(const t of e.slice(1))if(t==null)throw new j(`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],Yr(e,1)]}call(e,t){return ee(()=>{this.invokeCallHook(e,t);let n=Xe(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 Ez(n)})}getConfig(){const e={};this.dataFormat!=null&&(e.dataFormat=this.dataFormat);const t=super.getConfig();return Object.assign(e,t),e}}dL.className="Flatten",ge(dL);class pL extends lt{constructor(e){super(e);this.supportsMasking=!0,this.activation=Jr(e.activation)}call(e,t){return ee(()=>{this.invokeCallHook(e,t);const n=Xe(e);return this.activation.apply(n)})}getConfig(){const e={activation:Xr(this.activation)},t=super.getConfig();return Object.assign(e,t),e}}pL.className="Activation",ge(pL);class mL extends lt{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=Xe(e),Rz(e,this.n)))}getConfig(){const e={n:this.n},t=super.getConfig();return Object.assign(e,t),e}}mL.className="RepeatVector",ge(mL);class fL extends lt{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 u=s[c];if(this.isUnknown(u))if(o===null)o=c;else throw new j("Can only specifiy one unknown dimension.");else i*=u}const a=Yr(e);if(o!==null){if(i===0||a%i!==0)throw new j(n);s[o]=a/i}else if(a!==i)throw new j(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=Xe(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}}fL.className="Reshape",ge(fL);class gL extends lt{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=ai(1,e.dims.length+1);if(!ot(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 fn({ndim:this.dims.length+1})]}computeOutputShape(e){e=It(e);const t=e.slice();return this.dims.forEach((n,s)=>{t[s+1]=e[n]}),t}call(e,t){return Pe(Xe(e),this.dimsIncludingBatch)}getConfig(){const e={dims:this.dims},t=super.getConfig();return Object.assign(e,t),e}}gL.className="Permute",ge(gL);class yL extends lt{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=Xe(e),s=-1;return th(Pr(n,this.maskValue),s)}call(e,t){return ee(()=>{this.invokeCallHook(e,t);const n=Xe(e),s=-1,i=!0,o=th(Pr(n,this.maskValue),s,i),a=n.mul(o.asType(n.dtype));return a})}}yL.className="Masking",ge(yL);class bL extends lt{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(Nt(e.inputLength))}this.inputDim=e.inputDim,mn(this.inputDim,"inputDim"),this.outputDim=e.outputDim,mn(this.outputDim,"outputDim"),this.embeddingsInitializer=Ft(e.embeddingsInitializer||this.DEFAULT_EMBEDDINGS_INITIALIZER),this.embeddingsRegularizer=_t(e.embeddingsRegularizer),this.activityRegularizer=_t(e.activityRegularizer),this.embeddingsConstraint=hn(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=Xe(e),Pr(e,et(e))):null)}computeOutputShape(e){if(e=It(e),this.inputLength==null)return[...e,this.outputDim];const t=Nt(this.inputLength);if(t.length!==e.length-1)throw new j(`"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 j(`"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=Xe(e);n.dtype!=="int32"&&(n=_h(n,"int32"));const s=Cv(this.embeddings.read(),n.as1D());return s.reshape(It(this.computeOutputShape(n.shape)))})}getConfig(){const e={inputDim:this.inputDim,outputDim:this.outputDim,embeddingsInitializer:Vt(this.embeddingsInitializer),embeddingsRegularizer:xt(this.embeddingsRegularizer),activityRegularizer:xt(this.activityRegularizer),embeddingsConstraint:ln(this.embeddingsConstraint),maskZero:this.maskZero,inputLength:this.inputLength},t=super.getConfig();return Object.assign(e,t),e}}bL.className="Embedding",ge(bL);class qo extends lt{constructor(e){super(e||{});this.supportsMasking=!0}mergeFunction(e){throw new Ge}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 j("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=[It(e)]),e=e,e.length<2)throw new j(`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=Hr(t),t.length>1)throw new j(`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&&Hr(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=Wh(o,1);n.push(o)}return this.mergeFunction(n)}else{let i=!1;for(const c of e){const u=c.rank;if(u==null){const p=c.shape,m=p[0],y=p.slice(1).concat([m]);let b=c.reshape([m].concat(Yr(p.slice(1))));b=Pe(b,[1,0]),b=b.reshape(y),n.push(b),i=!0}else if(u>1){const p=ai(1,u).concat([0]);n.push(Pe(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,u=c.length,p=c[u-1],m=[p].concat(c.slice(0,c.length-1));o=Pe(o.reshape([-1,p]),[1,0]).reshape(m)}else if(a>1){const c=[a-1].concat(ai(0,a-1));o=Pe(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=Hr(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 j("`mask` should be an Array");if(!Array.isArray(e))throw new j("`inputs` should be an Array");if(t.length!==e.length)throw new j(`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:Kn(s,0));let n=t[0];for(let s=1;s<t.length-1;++s)n=Bs(n,t[s]);return n})}}class qh extends qo{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})}}qh.className="Add",ge(qh);function Oee(e){if(Array.isArray(e)){const t=new qh({});return t.apply(e)}else return new qh(e)}class jh extends qo{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})}}jh.className="Multiply",ge(jh);function Eee(e){if(Array.isArray(e)){const t=new jh({});return t.apply(e)}else return new jh(e)}class Kh extends qo{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)})}}Kh.className="Average",ge(Kh);function Dee(e){if(Array.isArray(e)){const t=new Kh({});return t.apply(e)}else return new Kh(e)}class Xh extends qo{constructor(e){super(e)}mergeFunction(e){return ee(()=>{let t=e[0];for(let n=1;n<e.length;++n)t=Us(t,e[n]);return t})}}Xh.className="Maximum",ge(Xh);function kee(e){if(Array.isArray(e)){const t=new Xh({});return t.apply(e)}else return new Xh(e)}class Jh extends qo{constructor(e){super(e)}mergeFunction(e){return ee(()=>{let t=e[0];for(let n=1;n<e.length;++n)t=ko(t,e[n]);return t})}}Jh.className="Minimum",ge(Jh);function Fee(e){if(Array.isArray(e)){const t=new Jh({});return t.apply(e)}else return new Jh(e)}class Zh extends qo{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 j("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(ot(a,i)){o=!0;break}o||n.push(i)}if(n.length>1)throw new j("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(e))}mergeFunction(e){return ee(()=>yw(e,this.axis))}computeOutputShape(e){if(!(Array.isArray(e)&&Array.isArray(e[0])))throw new j("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 j("`mask` should be an array for Concatenate");if(!Array.isArray(e))throw new j("`inputs` should be an array for Concatenate");if(t.length!==e.length)throw new j(`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(Dn(e[o]).asType("bool")):t[o].rank<e[o].rank?s.push(Kn(t[o],-1)):s.push(t[o]);const i=Mt(s,this.axis);return Pd(i,-1,!1)})}getConfig(){const e={axis:this.axis},t=super.getConfig();return Object.assign(e,t),e}}Zh.className="Concatenate",ge(Zh);function _ee(e){if(Array.isArray(e)){const t=new Zh({});return t.apply(e)}else return new Zh(e)}function Qh(e,t){for(;e<0;)e+=t;return e}function lG(e,t,n){if(e.shape.length>3||t.shape.length>3)throw new Ge("batchDot is not implemented for tensors of 4D or higher rank yet");if(k(e.shape.length>=2,()=>`batchDot requires the rank of x to be >= 2, but got ${e.shape.length}`),k(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 Ge("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 u=[];for(let p=0;p<a;++p)u.push(1);t=t.reshape(t.shape.concat(u))}else if(i>s){a=i-s;const u=[];for(let p=0;p<a;++p)u.push(1);e=e.reshape(e.shape.concat(u))}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 u=o[0]!==e.shape.length-1,p=o[1]===t.shape.length-1;c=e.matMul(t,u,p)}if(a>0){let u;s>i?u=s+i-3:u=s-1;const p=[];for(let m=u;m<u+a;++m)p.push(m);c=c.squeeze(p)}return c.shape.length===1&&(c=c.expandDims(1)),c})}class wL extends qo{constructor(e){super(e);this.axes=e.axes,this.normalize=e.normalize==null?!1:e.normalize,this.supportsMasking=!0,this.reshapeRequired=!1}build(e){k(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 Ge("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 j(`Dimension incompatibility: ${t[s[0]]} !== ${n[s[1]]}`)}mergeFunction(e){if(e.length!==2)throw new j(`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)=>Qh(i,e[o].shape.length)):s=[Qh(this.axes,t.shape.length),Qh(this.axes,n.shape.length)],this.normalize&&(t=zp(t,s[0]),n=zp(n,s[1])),lG(t,n,s)}interpretAxes(e,t){let n;return Array.isArray(this.axes)?n=this.axes:n=[Qh(this.axes,e.length),Qh(this.axes,t.length)],n}computeOutputShape(e){k(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 Ge("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}}wL.className="Dot",ge(wL);class LL extends lt{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=Xe(e),s=()=>Rp(n.shape,0,this.stddev).add(n),i=Uh(s,()=>n,t.training||!1);return i})}}LL.className="GaussianNoise",ge(LL);class SL extends lt{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=Xe(e);if(this.rate>0&&this.rate<1){const s=()=>{const i=Math.sqrt(this.rate/(1-this.rate));return n.mul(Rp(n.shape,1,i))};return Uh(s,()=>n,t.training||!1)}return n})}}SL.className="GaussianDropout",ge(SL);class IL extends lt{constructor(e){super(e);this.supportsMasking=!0,this.rate=e.rate,this.noiseShape=e.noiseShape}_getNoiseShape(e){return this.noiseShape||Xe(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=Xe(e),o=1.6732632423543772,a=1.0507009873554805,c=-o*a;let u=tr($o(n),this.rate);u=_h(u,"float32");const p=((1-this.rate)*(1+this.rate*c**2))**-.5,m=-p*c*this.rate,y=i.mul(u).add(u.add(-1).mul(c));return y.mul(p).add(m)};return Uh(s,()=>Xe(e),t.training||!1)}return e})}}IL.className="AlphaDropout",ge(IL);function eu(e,t,n,s,i,o=.001){let a;if(e.rank===2)a=nA(e,t,n,s,i,o);else if(e.rank===3)a=sA(e,t,n,s,i,o);else if(e.rank===4)a=iA(e,t,n,s,i,o);else throw new Ge(`batchNormalization is not implemented for array of rank ${e.rank} yet`);return a}function hG(e,t,n,s,i=.001){return ee(()=>{const o=np(e,s),a=o.mean,c=o.variance,u=eu(e,a,c,n,t,i);return[u,a,c]})}function uG(e,t,n,s,i=.001){return ee(()=>{const o=np(e,s),a=o.mean,c=o.variance,u=[];for(const I of ai(0,e.rank))s.indexOf(I)!==-1?u.push(1):u.push(e.shape[I]);const p=a.reshape(u),m=c.reshape(u),y=t==null?null:t.reshape(u),b=n==null?null:n.reshape(u),w=eu(e,p,m,b,y,i);return[w,a,c]})}function dG(e,t,n,s,i=.001){return ot(s.slice().sort(),ai(0,e.rank-1))?hG(e,t,n,s,i):uG(e,t,n,s,i)}class xL extends lt{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=Ft(e.betaInitializer||"zeros"),this.gammaInitializer=Ft(e.gammaInitializer||"ones"),this.movingMeanInitializer=Ft(e.movingMeanInitializer||"zeros"),this.movingVarianceInitializer=Ft(e.movingVarianceInitializer||"ones"),this.betaConstraint=hn(e.betaConstraint),this.gammaConstraint=hn(e.gammaConstraint),this.betaRegularizer=_t(e.betaRegularizer),this.gammaRegularizer=_t(e.gammaRegularizer)}build(e){e=It(e);const t=this.axis>=0?this.axis:this.axis+e.length,n=e[t];if(n==null)throw new j(`Axis ${t} of input tensor should have a defined dimension but the layer received an input with shape ${JSON.stringify(e)}.`);this.inputSpec=[new fn({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=Xe(e),i=s.shape,o=i.length,a=ai(0,o),c=this.axis>=0?this.axis:this.axis+o;a.splice(c,1);const u=Po(1,o);u[c]=i[c];const p=a.slice();p.sort();const m=!ot(p,ai(0,o).slice(0,o-1)),y=()=>{if(m){const N=this.movingMean.read().reshape(u),E=this.movingVariance.read().reshape(u),D=this.center?this.beta.read().reshape(u):null,F=this.scale?this.gamma.read().reshape(u):null;return eu(s,N,E,D,F,this.epsilon)}else return eu(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,I]=dG(s,this.gamma.read(),this.beta.read(),a,this.epsilon),T=(N,E,D)=>{ee(()=>{const F=1-D,_=N.read(),B=_.sub(E).mul(F);N.write(_.sub(B))})},v=()=>{T(this.movingMean,w,this.momentum),T(this.movingVariance,I,this.momentum)};return v(),b})}getConfig(){const e={axis:this.axis,momentum:this.momentum,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:Vt(this.betaInitializer),gammaInitializer:Vt(this.gammaInitializer),movingMeanInitializer:Vt(this.movingMeanInitializer),movingVarianceInitializer:Vt(this.movingVarianceInitializer),betaRegularizer:xt(this.betaRegularizer),gammaRegularizer:xt(this.gammaRegularizer),betaConstraint:ln(this.betaConstraint),gammaConstraint:ln(this.gammaConstraint)},t=super.getConfig();return Object.assign(e,t),e}}xL.className="BatchNormalization",ge(xL);class TL extends lt{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=Ft(e.betaInitializer||"zeros"),this.gammaInitializer=Ft(e.gammaInitializer||"ones"),this.betaRegularizer=_t(e.betaRegularizer),this.gammaRegularizer=_t(e.gammaRegularizer),this.supportsMasking=!0}build(e){e=It(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!==Hr(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=Xe(e),s=n.shape,i=s.length;return ee(()=>{const o=!0;let{mean:a,variance:c}=np(n,this.axis,o);const u=Po(1,i);for(const I of this.axis)u[I]=s[I];const p=I=>I!=null&&I.shape.length!==i&&this.axis!==[i-1]?I.reshape(u):I;let m=p(this.gamma.read()),y=p(this.beta.read());const b=[],w=[];for(let I=0;I<i;++I)this.axis.indexOf(I)!==-1?(b.push(s[I]),w.push(1)):(b.push(1),w.push(s[I]));return a=a.tile(b),c=c.tile(b),m=m.tile(w),y=y.tile(w),eu(n,a,c,y,m,this.epsilon)})}getConfig(){const e={axis:this.axis,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:Vt(this.betaInitializer),gammaInitializer:Vt(this.gammaInitializer),betaRegularizer:xt(this.betaRegularizer),gammaRegularizer:xt(this.gammaRegularizer)},t=super.getConfig();return Object.assign(e,t),e}}TL.className="LayerNormalization",ge(TL);function Wee(e,t){return ee(()=>{if(e.rank!==3)throw new j(`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 j(`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 ki(e,n)})}function pG(e,t,n){return ee(()=>{if(e.rank!==4)throw new j(`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 j("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");if(n==null&&(n=ri()),n!=="channelsLast"&&n!=="channelsFirst")throw new j(`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]],ki(e,s)})}class AL extends lt{constructor(e){if(e==null&&(e={}),super(e),this.dataFormat=e.dataFormat==null?ri():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 j(`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 j(`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 j(`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 fn({ndim:4})]}computeOutputShape(e){e=It(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(()=>pG(Xe(e),this.padding,this.dataFormat))}getConfig(){const e={padding:this.padding,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}AL.className="ZeroPadding2D",ge(AL);function rm(e,t,n,s,i,o){return ee(()=>{Gt(i),Sv(o),Ns(s),n==null&&(n=[1,1]),s==null&&(s="valid"),i==null&&(i=ri()),o==null&&(o="max"),e=Zw(e,i);let a;const c=s==="same"?"same":"valid";return o==="max"?a=mh(e,t,n,c):a=oh(e,t,n,c),i==="channelsFirst"&&(a=Pe(a,[0,3,1,2])),a})}function kN(e,t,n,s,i,o){return ee(()=>{Gt(i),Sv(o),Ns(s),n==null&&(n=[1,1,1]),s==null&&(s="valid"),i==null&&(i=ri()),o==null&&(o="max"),e=vN(e,i);let a;const c=s==="same"?"same":"valid";return o==="max"?a=Nb(e,t,n,c):a=pb(e,t,n,c),i==="channelsFirst"&&(a=Pe(a,[0,4,1,2,3])),a})}class FN extends lt{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 j(`poolSize for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.poolSize)}`);if(mn(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 j(`strides for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.strides)}`);mn(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,Ns(this.padding),this.inputSpec=[new fn({ndim:3})]}computeOutputShape(e){e=It(e);const t=ui(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=Wh(Xe(e),2);const n=this.poolingFunction(Xe(e),[this.poolSize[0],1],[this.strides[0],1],this.padding,"channelsLast");return zr(n,[2])})}getConfig(){const e={poolSize:this.poolSize,padding:this.padding,strides:this.strides},t=super.getConfig();return Object.assign(e,t),e}}class vL extends FN{constructor(e){super(e)}poolingFunction(e,t,n,s,i){return Gt(i),Ns(s),rm(e,t,n,s,i,"max")}}vL.className="MaxPooling1D",ge(vL);class NL extends FN{constructor(e){super(e)}poolingFunction(e,t,n,s,i){return Gt(i),Ns(s),rm(e,t,n,s,i,"avg")}}NL.className="AveragePooling1D",ge(NL);class _N extends lt{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 j(`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];mn(this.poolSize,"poolSize"),mn(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Gt(this.dataFormat),Ns(this.padding),this.inputSpec=[new fn({ndim:4})]}computeOutputShape(e){e=It(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],n=this.dataFormat==="channelsFirst"?e[3]:e[2];return t=ui(t,this.poolSize[0],this.padding,this.strides[0]),n=ui(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(Xe(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 CL extends _N{constructor(e){super(e)}poolingFunction(e,t,n,s,i){return Gt(i),Ns(s),rm(e,t,n,s,i,"max")}}CL.className="MaxPooling2D",ge(CL);class RL extends _N{constructor(e){super(e)}poolingFunction(e,t,n,s,i){return Gt(i),Ns(s),rm(e,t,n,s,i,"avg")}}RL.className="AveragePooling2D",ge(RL);class WN extends lt{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 j(`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];mn(this.poolSize,"poolSize"),mn(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Gt(this.dataFormat),Ns(this.padding),this.inputSpec=[new fn({ndim:5})]}computeOutputShape(e){e=It(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=ui(t,this.poolSize[0],this.padding,this.strides[0]),n=ui(n,this.poolSize[1],this.padding,this.strides[1]),s=ui(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(Xe(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 OL extends WN{constructor(e){super(e)}poolingFunction(e,t,n,s,i){return Gt(i),Ns(s),kN(e,t,n,s,i,"max")}}OL.className="MaxPooling3D",ge(OL);class EL extends WN{constructor(e){super(e)}poolingFunction(e,t,n,s,i){return Gt(i),Ns(s),kN(e,t,n,s,i,"avg")}}EL.className="AveragePooling3D",ge(EL);class $N extends lt{constructor(e){super(e);this.inputSpec=[new fn({ndim:3})]}computeOutputShape(e){return[e[0],e[2]]}call(e,t){throw new Ge}}class DL extends $N{constructor(e){super(e||{})}call(e,t){return ee(()=>{const n=Xe(e);return zt(n,1)})}}DL.className="GlobalAveragePooling1D",ge(DL);class kL extends $N{constructor(e){super(e||{})}call(e,t){return ee(()=>{const n=Xe(e);return Xn(n,1)})}}kL.className="GlobalMaxPooling1D",ge(kL);class UN extends lt{constructor(e){super(e);this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Gt(this.dataFormat),this.inputSpec=[new fn({ndim:4})]}computeOutputShape(e){return e=e,this.dataFormat==="channelsLast"?[e[0],e[3]]:[e[0],e[1]]}call(e,t){throw new Ge}getConfig(){const e={dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}class FL extends UN{call(e,t){return ee(()=>{const n=Xe(e);return this.dataFormat==="channelsLast"?zt(n,[1,2]):zt(n,[2,3])})}}FL.className="GlobalAveragePooling2D",ge(FL);class _L extends UN{call(e,t){return ee(()=>{const n=Xe(e);return this.dataFormat==="channelsLast"?Xn(n,[1,2]):Xn(n,[2,3])})}}_L.className="GlobalMaxPooling2D",ge(_L);class BN extends lt{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=hi(s,n);delete t.layer;const o={layer:i};return Object.assign(o,t),new e(o)}}class WL extends BN{constructor(e){super(e);this.supportsMasking=!0}build(e){if(e=It(e),e.length<3)throw new j(`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=It(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=Xe(e);const n=(o,a)=>{const c=Xe(this.layer.call(o,t));return[c,[]]},s=EN(n,e,[],!1,null,null,!1,!0),i=s[1];return i})}}WL.className="TimeDistributed",ge(WL);function mG(e){ec(xz,"BidirectionalMergeMode",e)}const fG="concat";class $L extends BN{constructor(e){super(e);const t=e.layer.getConfig(),n={};n.className=e.layer.getClassName(),n.config=t,this.forwardLayer=hi(n),t.goBackwards=!(t.goBackwards===!0);const s={};if(s.className=e.layer.getClassName(),s.config=t,this.backwardLayer=hi(s),this.forwardLayer.name="forward_"+this.forwardLayer.name,this.backwardLayer.name="backward_"+this.backwardLayer.name,this.mergeMode=e.mergeMode===void 0?fG:e.mergeMode,mG(this.mergeMode),e.weights)throw new Ge("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()):Jn(s)}apply(e,t){let n=t==null?null:t.initialState,s=t==null?null:t.constants;t==null&&(t={});const i=ON(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 u=n.length;if(u%2>0)throw new j("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 fn({shape:m.shape}));this.forwardLayer.stateSpec=p.slice(0,u/2),this.backwardLayer.stateSpec=p.slice(u/2),a.push(...p)}if(s!=null)throw new Ge("Support for constants in Bidirectional layers is not implemented yet.");const c=o[0]instanceof li;for(const u of o)if(u instanceof li!==c)throw new j("The initial state of a Bidirectional layer cannot be specified as a mix of symbolic and non-symbolic tensors");if(c){const u=[e].concat(o),p=this.inputSpec.concat(a),m=this.inputSpec;this.inputSpec=p;const y=super.apply(u,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),u=n.slice(n.length/2);s=this.forwardLayer.call(e,Object.assign(t,{initialState:c})),i=this.backwardLayer.call(e,Object.assign(t,{initialState:u}))}let o;this.returnState&&(Array.isArray(s)&&(o=s.slice(1).concat(i.slice(1))),s=s[0],i=i[0]),this.returnSequences&&(i=As(i,1));let a;return this.mergeMode==="concat"?a=yw([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){Go(this.forwardLayer.name,()=>{this.forwardLayer.build(e)}),Go(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=hi(t.layer);if(delete t.layer,t.numConstants!=null)throw new Ge("Deserialization of a Bidirectional layer with numConstants present is not supported yet.");const s=t;return s.layer=n,new e(s)}}$L.className="Bidirectional",ge($L);function gG(e){return new sc(e)}function yG(e){return new Kw(e)}function bG(e){return new Yw(e)}function wG(e){return new qw(e)}function LG(e){return new jw(e)}function SG(e){return new Jw(e)}function IG(e){return new Xw(e)}function xG(e){return new Qp(e)}function TG(e){return new Hh(e)}function AG(e){return new tL(e)}function vG(e){return new Zp(e)}function NG(e){return new nL(e)}function CG(e){return new sL(e)}function RG(e){return new iL(e)}function OG(e){return new rL(e)}function EG(e){return new pL(e)}function DG(e){return new uL(e)}function kG(e){return new im(e)}function FG(e){return new hL(e)}function _G(e){return new dL(e)}function WG(e){return new mL(e)}function $G(e){return new fL(e)}function UG(e){return new gL(e)}function BG(e){return new bL(e)}function MG(e){return new qh(e)}function PG(e){return new Kh(e)}function zG(e){return new Zh(e)}function GG(e){return new Xh(e)}function VG(e){return new Jh(e)}function HG(e){return new jh(e)}function YG(e){return new wL(e)}function qG(e){return new xL(e)}function jG(e){return new TL(e)}function KG(e){return new AL(e)}function UL(e){return new NL(e)}function XG(e){return UL(e)}function JG(e){return UL(e)}function BL(e){return new RL(e)}function ZG(e){return BL(e)}function QG(e){return BL(e)}function ML(e){return new EL(e)}function eV(e){return ML(e)}function tV(e){return ML(e)}function nV(e){return new DL(e)}function sV(e){return new FL(e)}function MN(e){return new kL(e)}function PN(e){return new _L(e)}function zN(e){return new vL(e)}function GN(e){return new CL(e)}function iV(e){return new OL(e)}function rV(e){return new aL(e)}function oV(e){return new tm(e)}function aV(e){return new cL(e)}function cV(e){return new Yh(e)}function lV(e){return new oL(e)}function hV(e){return new em(e)}function uV(e){return new lL(e)}function dV(e){return new sm(e)}function pV(e){return new Bi(e)}function mV(e){return new nm(e)}function fV(e){return new $L(e)}function gV(e){return new WL(e)}const yV=MN,bV=PN,wV=zN,LV=GN;function SV(e){return new LL(e)}function IV(e){return new SL(e)}function xV(e){return new IL(e)}function TV(e){return new yL(e)}var AV=Object.freeze({__proto__:null,inputLayer:gG,elu:yG,reLU:bG,leakyReLU:wG,prelu:LG,softmax:SG,thresholdedReLU:IG,conv1d:xG,conv2d:TG,conv2dTranspose:AG,conv3d:vG,separableConv2d:NG,cropping2D:CG,upSampling2d:RG,depthwiseConv2d:OG,activation:EG,dense:DG,dropout:kG,spatialDropout1d:FG,flatten:_G,repeatVector:WG,reshape:$G,permute:UG,embedding:BG,add:MG,average:PG,concatenate:zG,maximum:GG,minimum:VG,multiply:HG,dot:YG,batchNormalization:qG,layerNormalization:jG,zeroPadding2d:KG,averagePooling1d:UL,avgPool1d:XG,avgPooling1d:JG,averagePooling2d:BL,avgPool2d:ZG,avgPooling2d:QG,averagePooling3d:ML,avgPool3d:eV,avgPooling3d:tV,globalAveragePooling1d:nV,globalAveragePooling2d:sV,globalMaxPooling1d:MN,globalMaxPooling2d:PN,maxPooling1d:zN,maxPooling2d:GN,maxPooling3d:iV,gru:rV,gruCell:oV,lstm:aV,lstmCell:cV,simpleRNN:lV,simpleRNNCell:hV,convLstm2d:uV,convLstm2dCell:dV,rnn:pV,stackedRNNCells:mV,bidirectional:fV,timeDistributed:gV,globalMaxPool1d:yV,globalMaxPool2d:bV,maxPool1d:wV,maxPool2d:LV,Layer:lt,RNN:Bi,RNNCell:cc,input:hN,gaussianNoise:SV,gaussianDropout:IV,alphaDropout:xV,masking:TV});function vV(e,t){return kw(e,t)}function NV(e,t){return Hv(e,t)}function CV(e,t){return Yv(e,t)}function RV(e,t){return Fw(e,t)}function OV(e,t){return _w(e,t)}function EV(e,t){return Vv(e,t)}function DV(e,t){return b3(e,t)}function kV(e,t){return Hp(e,t)}function FV(e,t){return rc(e,t)}function _V(e,t){return Kr(e,t)}function WV(e,t){return Kr(e,t)}function $V(e,t){return Kr(e,t)}function UV(e,t){return ar(e,t)}function BV(e,t){return ar(e,t)}function MV(e,t){return ar(e,t)}var PV=Object.freeze({__proto__:null,binaryAccuracy:vV,binaryCrossentropy:NV,sparseCategoricalAccuracy:CV,categoricalAccuracy:RV,categoricalCrossentropy:OV,precision:EV,recall:DV,cosineProximity:kV,meanAbsoluteError:FV,meanAbsolutePercentageError:_V,MAPE:WV,mape:$V,meanSquaredError:UV,MSE:BV,mse:MV});var zV=Object.freeze({__proto__:null,modelFromJSON:J3});function GV(e){return new Gh(e)}function VV(e){return rG(e)}function HV(e){return oG(e)}var YV=Object.freeze({__proto__:null,l1l2:GV,l1:VV,l2:HV});class VN extends ic{constructor(){super(...arguments);this.model=null}setModel(e){if(!(e instanceof cr))throw new Error("model must be a LayersModel, not some other Container");this.model=e}}function om(e,t){return e<t}function HN(e,t){return e>t}class YN extends VN{constructor(e){super();if(e==null&&(e={}),e.restoreBestWeights)throw new Ge("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=om:this.mode==="max"?this.monitorFunc=HN:this.monitor.indexOf("acc")!==-1?this.monitorFunc=HN:this.monitorFunc=om,this.monitorFunc===om&&(this.minDelta*=-1)}async onTrainBegin(e){this.wait=0,this.stoppedEpoch=0,this.baseline!=null?this.best=this.baseline:this.best=this.monitorFunc===om?Infinity:-Infinity}async onEpochEnd(e,t){await jr(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 qV(e){return new YN(e)}const jV={earlyStopping:qV};var di;(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"})(di||(di={}));var qN;(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={}))})(qN||(qN={}));const PL={};function KV(e,t){const n={tfOpName:e,category:"custom",inputs:[],attrs:[],customExecutor:t};PL[e]=n}function jN(e){return PL[e]}function XV(e){delete PL[e]}function R(e,t,n,s){const i=t.inputParams[e];if(i&&i.inputIndexStart!==void 0){const a=i.inputIndexStart,c=i.inputIndexEnd===0?void 0:i.inputIndexEnd===void 0?a+1:i.inputIndexEnd;if(i.type==="tensor")return Qn(t.inputNames[i.inputIndexStart],n,s);if(i.type==="tensors"){const m=t.inputNames.slice(a,c);return m.map(y=>Qn(y,n,s))}const u=Qn(t.inputNames.slice(a)[0],n,s),p=u.dataSync();return i.type==="number"?p[0]:Ls(u.shape,p)}const o=t.attrParams[e];return o&&o.value}function Qn(e,t,n){const[s,i]=ls(e),o=n.currentContextIds.find(a=>!!t[am(s,a)]);return o!==void 0?t[am(s,o)][i]:void 0}function JV(e,t,n){return t[am(e,n.currentContextId)]}function lr(e,t){const[n,s]=ls(e);return[am(n,t&&t.currentContextId),s]}function am(e,t){return t?`${e}-${t}`:e}function ls(e){const t=e.split(":");if(t.length===1)return[e,0];const n=t[0];return[n,Number(t[t.length-1])]}function $ee(e,t){const n=[];for(let s=0;s<e.length;s+=t)n.push(e.slice(s,s+t));return n}function cm(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 hr(e){return e.kept?e:Wr(e)}const ZV=[{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 QV=Object.freeze({__proto__:null,json:ZV});const eH=[{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 tH=Object.freeze({__proto__:null,json:eH});const nH=[{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 sH=Object.freeze({__proto__:null,json:nH});const iH=[{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 rH=Object.freeze({__proto__:null,json:iH});const oH=[{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 aH=Object.freeze({__proto__:null,json:oH});const cH=[{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 lH=Object.freeze({__proto__:null,json:cH});const hH=[{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 uH=Object.freeze({__proto__:null,json:hH});const dH=[{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 pH=Object.freeze({__proto__:null,json:dH});const mH=[{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 fH=Object.freeze({__proto__:null,json:mH});const gH=[{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 yH=Object.freeze({__proto__:null,json:gH});const bH=[{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 wH=Object.freeze({__proto__:null,json:bH});const LH=[{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 SH=Object.freeze({__proto__:null,json:LH});const IH=[{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 xH=Object.freeze({__proto__:null,json:IH});const TH=[{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 AH=Object.freeze({__proto__:null,json:TH});const vH=[{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 NH=Object.freeze({__proto__:null,json:vH});const CH=[{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:"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 RH=Object.freeze({__proto__:null,json:CH});class KN{static get Instance(){return this._instance||(this._instance=new this)}constructor(){const e=[QV,tH,sH,rH,aH,lH,uH,yH,fH,pH,wH,SH,xH,AH,NH,RH],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((I,T)=>(I[T.name]=this.mapNode(T),T.op.startsWith("Placeholder")?s.push(I[T.name]):T.op==="Const"?i.push(I[T.name]):(T.input==null||T.input.length===0)&&o.push(I[T.name]),I),{});let c=[];const u=[];let p={},m={};t!=null&&(p=this.mapSignatureEntries(t.inputs),m=this.mapSignatureEntries(t.outputs));const y=Object.keys(a);y.forEach(I=>{const T=a[I];T.inputNames.forEach(v=>{const[N]=lr(v);T.inputs.push(a[N]),a[N].children.push(T)})}),Object.keys(m).length===0?y.forEach(I=>{const T=a[I];T.children.length===0&&u.push(T)}):Object.keys(m).forEach(I=>{const[T]=lr(I),v=a[T];v!=null&&(v.signatureKey=m[I],u.push(v))}),Object.keys(p).length>0?Object.keys(p).forEach(I=>{const[T]=lr(I),v=a[T];v&&(v.signatureKey=p[I],c.push(v))}):c=s;let b={};e.library!=null&&e.library.function!=null&&(b=e.library.function.reduce((I,T)=>(I[T.signature.name]=this.mapFunction(T),I),{}));const w={nodes:a,inputs:c,outputs:u,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=jN(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=zL(e.attr,i.tfName,i.defaultValue),a===void 0&&!!i.tfDeprecatedName&&(a=zL(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"string[]":a=XL(e.attr,i.tfName,i.defaultValue),a===void 0&&!!i.tfDeprecatedName&&(a=XL(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"number":a=VL(e.attr,i.tfName,i.defaultValue||0),a===void 0&&!!i.tfDeprecatedName&&(a=VL(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"number[]":a=KL(e.attr,i.tfName,i.defaultValue),a===void 0&&!!i.tfDeprecatedName&&(a=KL(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"bool":a=GL(e.attr,i.tfName,i.defaultValue),a===void 0&&!!i.tfDeprecatedName&&(a=GL(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"bool[]":a=ZL(e.attr,i.tfName,i.defaultValue),a===void 0&&!!i.tfDeprecatedName&&(a=ZL(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"shape":a=jL(e.attr,i.tfName,i.defaultValue),a===void 0&&!!i.tfDeprecatedName&&(a=jL(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"shape[]":a=JL(e.attr,i.tfName,i.defaultValue),a===void 0&&!!i.tfDeprecatedName&&(a=JL(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"dtype":a=YL(e.attr,i.tfName,i.defaultValue),a===void 0&&!!i.tfDeprecatedName&&(a=YL(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"dtype[]":a=qL(e.attr,i.tfName,i.defaultValue),a===void 0&&!!i.tfDeprecatedName&&(a=qL(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"func":a=JN(e.attr,i.tfName,i.defaultValue),a===void 0&&!!i.tfDeprecatedName&&(a=JN(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]=lr(m.name),b={name:y,op:"Placeholder",inputs:[],inputNames:[],category:"graph",inputParams:{},attrParams:{dtype:{value:HL(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]=lr(b);y.inputs.push(i[w]),i[w].children.push(y)})});const u=e.ret;e.signature.outputArg.forEach(m=>{const[y,b]=lr(u[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 OH(e){const t=C().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 XN(e,t){const n=Array.isArray(e)?String.fromCharCode.apply(null,e):OH(e);return t?n:n.toLowerCase()}function zL(e,t,n,s=!1){const i=e[t];return i!=null?XN(i.s,s):n}function GL(e,t,n){const s=e[t];return s?s.b:n}function VL(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 HL(e){typeof e=="string"&&(e=di[e]);switch(e){case di.DT_FLOAT:return"float32";case di.DT_INT32:case di.DT_INT64:case di.DT_INT8:case di.DT_UINT8:return"int32";case di.DT_BOOL:return"bool";case di.DT_DOUBLE:return"float32";case di.DT_STRING:return"string";default:return null}}function JN(e,t,n){const s=e[t];return s&&s.func?s.func.name:n}function YL(e,t,n){const s=e[t];return s&&s.type?HL(s.type):n}function qL(e,t,n){const s=e[t];return s&&s.list&&s.list.type?s.list.type.map(i=>HL(i)):n}function ZN(e){return e.unknownRank?void 0:e.dim!=null?e.dim.map(t=>typeof t.size=="number"?t.size:parseInt(t.size,10)):[]}function jL(e,t,n){const s=e[t];return s&&s.shape?ZN(s.shape):n}function KL(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 XL(e,t,n,s=!1){const i=e[t];return i&&i.list&&i.list.s?i.list.s.map(o=>XN(o,s)):n}function JL(e,t,n){const s=e[t];return s&&s.list&&s.list.shape?s.list.shape.map(i=>ZN(i)):n}function ZL(e,t,n){const s=e[t];return s&&s.list&&s.list.b?s.list.b:n}class EH{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 Qn(e,this.tensorMap,this.context)}getAttr(e,t){const n=this.node.rawAttrs[e];if(n.tensor!=null)return Qn(e,this.tensorMap,this.context);if(n.i!=null||n.f!=null)return VL(this.node.rawAttrs,e,t);if(n.s!=null)return zL(this.node.rawAttrs,e,t);if(n.b!=null)return GL(this.node.rawAttrs,e,t);if(n.shape!=null)return jL(this.node.rawAttrs,e,t);if(n.type!=null)return YL(this.node.rawAttrs,e,t);if(n.list!=null){if(n.list.i!=null||n.list.f!=null)return KL(this.node.rawAttrs,e,t);if(n.list.s!=null)return XL(this.node.rawAttrs,e,t);if(n.list.shape!=null)return JL(this.node.rawAttrs,e,t);if(n.list.b!=null)return ZL(this.node.rawAttrs,e,t);if(n.list.type!=null)return qL(this.node.rawAttrs,e,t)}return t}}const DH=(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[eA(R("tensors",e,t,n))];case"FloorMod":case"Mod":return[tp(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[_e(R("a",e,t,n),R("b",e,t,n))];case"DivNoNan":return[Lb(R("a",e,t,n),R("b",e,t,n))];case"FloorDiv":return[Md(R("a",e,t,n),R("b",e,t,n))];case"Sub":return[Ce(R("a",e,t,n),R("b",e,t,n))];case"Minimum":return[ko(R("a",e,t,n),R("b",e,t,n))];case"Maximum":return[Us(R("a",e,t,n),R("b",e,t,n))];case"Pow":return[ii(R("a",e,t,n),R("b",e,t,n))];case"SquaredDifference":return[Sh(R("a",e,t,n),R("b",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},Uee="arithmetic";const kH=(e,t,n)=>{switch(e.op){case"Abs":case"ComplexAbs":return[rn(R("x",e,t,n))];case"Acos":return[nb(R("x",e,t,n))];case"Acosh":return[sb(R("x",e,t,n))];case"Asin":return[ob(R("x",e,t,n))];case"Asinh":return[ab(R("x",e,t,n))];case"Atan":return[cb(R("x",e,t,n))];case"Atan2":return[lb(R("x",e,t,n),R("y",e,t,n))];case"Atanh":return[hb(R("x",e,t,n))];case"Ceil":return[fb(R("x",e,t,n))];case"Complex":return[Ci(R("real",e,t,n),R("imag",e,t,n))];case"Cos":return[lh(R("x",e,t,n))];case"Cosh":return[qd(R("x",e,t,n))];case"Elu":return[Do(R("x",e,t,n))];case"Erf":return[Sb(R("x",e,t,n))];case"Exp":return[xs(R("x",e,t,n))];case"Expm1":return[Ib(R("x",e,t,n))];case"Floor":return[Pa(R("x",e,t,n))];case"Log":return[is(R("x",e,t,n))];case"Log1p":return[Jd(R("x",e,t,n))];case"Imag":return[Ga(R("x",e,t,n))];case"Neg":return[Pt(R("x",e,t,n))];case"Reciprocal":return[Eb(R("x",e,t,n))];case"Real":return[Fo(R("x",e,t,n))];case"Relu":return[Fi(R("x",e,t,n))];case"Round":return[kb(R("x",e,t,n))];case"Selu":return[rp(R("x",e,t,n))];case"Sigmoid":return[Ei(R("x",e,t,n))];case"Sin":return[op(R("x",e,t,n))];case"Sign":return[_b(R("x",e,t,n))];case"Sinh":return[ap(R("x",e,t,n))];case"Softplus":return[Va(R("x",e,t,n))];case"Sqrt":return[Sn(R("x",e,t,n))];case"Square":return[Lt(R("x",e,t,n))];case"Tanh":return[Ma(R("x",e,t,n))];case"Tan":return[Ub(R("x",e,t,n))];case"Relu6":case"ClipByValue":return[jn(R("x",e,t,n),R("clipValueMin",e,t,n),R("clipValueMax",e,t,n))];case"Rsqrt":return[ip(Qn(e.inputNames[0],t,n))];case"Prod":return[sp(R("x",e,t,n),R("axes",e,t,n))];case"LeakyRelu":return[Xd(R("x",e,t,n),R("alpha",e,t,n))];case"Prelu":return[gh(R("x",e,t,n),R("alpha",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},Bee="basic_math";function Gs(e,t,n=""){k(FH(e,t),()=>n+` Shapes ${e} and ${t} must match`)}function FH(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 _H{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=Ne(0),Rn(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),Gs(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,Rn(t),n.written=!0,this.tensors[e]=n}writeMany(e,t){if(e.length!==t.length)throw new Error(`TensorArray ${this.name}: could not write multiple tensors,because the index size: ${e.length} is not the same as tensors size: ${t.length}.`);e.forEach((n,s)=>this.write(n,t[s]))}gather(e,t){if(!!t&&t!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but gather requested dtype ${t}`);if(e)e=e.slice(0,this.size());else{e=[];for(let s=0;s<this.size();s++)e.push(s)}if(e.length===0)return en([],[0].concat(this.elementShape));const n=this.readMany(e);return Gs(this.elementShape,n[0].shape,"TensorArray shape mismatch: "),as(n,0)}concat(e){if(!!e&&e!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but concat requested dtype ${e}`);if(this.size()===0)return en([],[0].concat(this.elementShape));const t=[];for(let s=0;s<this.size();s++)t.push(s);const n=this.readMany(t);return Gs(this.elementShape,n[0].shape,`TensorArray shape mismatch: tensor array shape (${this.elementShape}) vs first tensor shape (${n[0].shape})`),Mt(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,_i(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 u=c===0?0:s[c-1],p=[0,u,0],m=[1,e[c],i];o[c]=K(st(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 tu{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}`);Gs(t,i.shape,"TensorList shape mismatch: "),Rn(i)}),this.idTensor=Ne(0),this.maxNumElements=s,Rn(this.idTensor)}get id(){return this.idTensor.id}copy(){return new tu([...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 Gs(e,this.elementShape,"TensorList shape mismatch: "),ee(()=>{const s=this.tensors.map(i=>K(i,e));return as(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 Gs(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(Gs(e.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");Rn(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 Gs(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.`);Gs(this.elementShape,t.shape,"TensorList shape mismatch: "),Rn(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 Gs(this.elementShape,n,"TensorList shape mismatch: "),e=e.slice(0,this.size()),e.length===0?en([],[0].concat(this.elementShape)):ee(()=>{const s=e.map(i=>K(this.tensors[i],n));return as(s,0)})}concat(e,t){if(!!e&&e!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${e}`);return Gs(this.elementShape,t,"TensorList shape mismatch: "),this.size()===0?en([],[0].concat(this.elementShape)):ee(()=>{const n=this.tensors.map(s=>K(s,t));return Mt(n,0)})}}function WH(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);Gs(i,t,"TensorList shape mismatch: ");const o=_i(e);return new tu(o,t,s)}function $H(e,t,n){return new tu([],e,t,n)}function UH(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 tu([],n,e.dtype,s),a=_i(e,0);return t.forEach((c,u)=>{o.setItem(c,a[u])}),o}function BH(e,t,n){let s=0;const i=t.map(u=>(s+=u,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 u=[];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];u[p]=K(st(e,y,b),n)}return e.dispose(),u}),c=new tu([],n,e.dtype,t.length);for(let u=0;u<a.length;u++)c.setItem(u,a[u]);return c}const MH=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 u=await a[0].data();a.forEach(m=>{!m.kept&&c.indexOf(m.id)===-1&&m.dispose()});let p=o;for(;u[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);u=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[hr(s)]}case"Switch":{const s=R("pred",e,t,n);let i=R("data",e,t,n);return i.kept||(i=hr(i)),(await s.data())[0]?[void 0,i]:[i,void 0]}case"Merge":{const s=e.inputNames.find(i=>Qn(i,t,n)!==void 0);if(s){const i=Qn(s,t,n);return[hr(i)]}return}case"Enter":{const s=R("frameName",e,t,n),i=R("tensor",e,t,n);return n.enterFrame(s),[hr(i)]}case"Exit":{const s=R("tensor",e,t,n);return n.exitFrame(),[hr(s)]}case"NextIteration":{const s=R("tensor",e,t,n);return n.nextIteration(),[hr(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),u=R("identicalElementShapes",e,t,n),p=R("name",e,t,n),m=new _H(p,i,s,o,u,a,c);return n.addTensorArray(m),[m.idTensor,Ne(1)]}case"TensorArrayWriteV3":{const s=R("tensorArrayId",e,t,n),i=R("index",e,t,n),o=R("tensor",e,t,n),a=n.getTensorArray(s.id);return a.write(i,o),[a.idTensor]}case"TensorArrayReadV3":{const s=R("tensorArrayId",e,t,n),i=R("index",e,t,n),o=n.getTensorArray(s.id);return[o.read(i)]}case"TensorArrayGatherV3":{const s=R("tensorArrayId",e,t,n),i=R("indices",e,t,n),o=R("dtype",e,t,n),a=n.getTensorArray(s.id);return[a.gather(i,o)]}case"TensorArrayScatterV3":{const s=R("tensorArrayId",e,t,n),i=R("indices",e,t,n),o=R("tensor",e,t,n),a=n.getTensorArray(s.id);return a.scatter(i,o),[a.idTensor]}case"TensorArrayConcatV3":{const s=R("tensorArrayId",e,t,n),i=n.getTensorArray(s.id),o=R("dtype",e,t,n);return[i.concat(o)]}case"TensorArraySplitV3":{const s=R("tensorArrayId",e,t,n),i=R("tensor",e,t,n),o=R("lengths",e,t,n),a=n.getTensorArray(s.id);return a.split(o,i),[a.idTensor]}case"TensorArraySizeV3":{const s=R("tensorArrayId",e,t,n),i=n.getTensorArray(s.id);return[Ne(i.size(),"int32")]}case"TensorArrayCloseV3":{const s=R("tensorArrayId",e,t,n),i=n.getTensorArray(s.id);return i.clearAndClose(),[i.idTensor]}case"TensorListSetItem":{const s=R("tensorListId",e,t,n),i=R("index",e,t,n),o=R("tensor",e,t,n),a=n.getTensorList(s.id);return a.setItem(i,o),[a.idTensor]}case"TensorListGetItem":{const s=R("tensorListId",e,t,n),i=R("index",e,t,n),o=R("elementShape",e,t,n),a=R("elementDType",e,t,n),c=n.getTensorList(s.id);return[c.getItem(i,o,a)]}case"TensorListScatterV2":case"TensorListScatter":{const s=R("indices",e,t,n),i=R("tensor",e,t,n),o=R("elementShape",e,t,n),a=R("numElements",e,t,n),c=UH(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=$H(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=WH(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=BH(s,o,i);return n.addTensorList(a),[a.idTensor]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},Mee="control";function QN(e,t,n){const[s,i]=R("fusedOps",e,t,n),o=s==="biasadd",a=i==="prelu",c=s==="fusedbatchnorm",u=R("numArgs",e,t,n);if(o){if(a&&u!==2)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!a&&u!==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=cm(e,t,n),y=R("dataFormat",e,t,n).toUpperCase(),b=R("dilations",e,t,n),[w,I]=R("args",e,t,n);return{stride:p,pad:m,dataFormat:y,dilations:b,biasArg:w,preluArg:I,activationFunc:i}}const PH=(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[Hd(R("x",e,t,n),R("filter",e,t,n),s,i,o,a)]}case"Conv2D":{const s=R("strides",e,t,n),i=cm(e,t,n),o=R("dataFormat",e,t,n).toUpperCase(),a=R("dilations",e,t,n);return[er(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:u,activationFunc:p}=QN(e,t,n);return[Hb({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:u})]}case"FusedDepthwiseConv2dNative":{const{stride:s,pad:i,dataFormat:o,dilations:a,biasArg:c,preluArg:u,activationFunc:p}=QN(e,t,n);return[YA({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:u})]}case"Conv2DBackpropInput":case"Conv2dTranspose":{const s=R("outputShape",e,t,n),i=R("strides",e,t,n),o=cm(e,t,n);return[Yd(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=cm(e,t,n),o=R("dilations",e,t,n),a=R("dataFormat",e,t,n).toUpperCase();return[Oo(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[yb(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[oh(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[mh(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:u}=bA(R("x",e,t,n),[o[1],o[2]],[s[1],s[2]],i,a);return[c,u]}case"AvgPool3D":{const s=R("strides",e,t,n),i=R("pad",e,t,n),o=R("kernelSize",e,t,n);return[pb(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[Nb(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],u=o[1],p=o[2];return[wb(R("x",e,t,n),R("filter",e,t,n),[a,c],i,[u,p],"NHWC")]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},Pee="convolution";const zH=(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[hh(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[wA(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[vo(s,i,o,a)]}case"Ones":return[si(R("shape",e,t,n),R("dtype",e,t,n))];case"OnesLike":return[Dn(R("x",e,t,n))];case"RandomUniform":return[$o(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[yh(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[Ih(s,i,o,R("dtype",e,t,n),a)]}case"Zeros":return[ct(R("shape",e,t,n),R("dtype",e,t,n))];case"ZerosLike":return[et(R("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},zee="creation";function QL(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),u=R("softNmsSigma",e,t,n);return{boxes:s,scores:i,maxOutputSize:o,iouThreshold:a,scoreThreshold:c,softNmsSigma:u}}const GH=async(e,t,n)=>{switch(e.op){case"NonMaxSuppressionV5":{const{boxes:s,scores:i,maxOutputSize:o,iouThreshold:a,scoreThreshold:c,softNmsSigma:u}=QL(e,t,n),p=await Vr.nonMaxSuppressionWithScoreAsync(s,i,o,a,c,u);return[p.selectedIndices,p.selectedScores]}case"NonMaxSuppressionV4":{const{boxes:s,scores:i,maxOutputSize:o,iouThreshold:a,scoreThreshold:c}=QL(e,t,n),u=R("padToMaxOutputSize",e,t,n),p=await Vr.nonMaxSuppressionPaddedAsync(s,i,o,a,c,u);return[p.selectedIndices,p.validOutputs]}case"NonMaxSuppressionV3":case"NonMaxSuppressionV2":{const{boxes:s,scores:i,maxOutputSize:o,iouThreshold:a,scoreThreshold:c}=QL(e,t,n);return[await Vr.nonMaxSuppressionAsync(s,i,o,a,c)]}case"Where":{const s=ve(R("condition",e,t,n),"bool"),i=[await Pb(s)];return s.dispose(),i}case"ListDiff":return SA(R("x",e,t,n),R("y",e,t,n));default:throw TypeError(`Node type ${e.op} is not implemented`)}},Gee="dynamic";const VH=(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=Bb(s,i,o);return[a.values,a.indices]}case"Unique":{const s=R("x",e,t,n),i=up(s);return[i.values,i.indices]}case"UniqueV2":{const s=R("x",e,t,n),i=R("axis",e,t,n),o=up(s,i);return[o.values,o.indices]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},Vee="evaluation";const HH=(e,t,n)=>{switch(e.op){case"Const":return t[e.name];case"PlaceholderWithDefault":const s=R("default",e,t,n);return[Qn(e.name,t,n)||s];case"Placeholder":return[Qn(e.name,t,n)];case"Identity":case"StopGradient":case"FakeQuantWithMinMaxVars":{const p=R("x",e,t,n);return[hr(p)]}case"IdentityN":return R("x",e,t,n).map(p=>hr(p));case"Snapshot":const i=R("x",e,t,n);return[hr(i)];case"Shape":return[rs(R("x",e,t,n).shape,"int32")];case"ShapeN":return R("x",e,t,n).map(p=>rs(p.shape));case"Size":return[Ne(R("x",e,t,n).size,"int32")];case"Rank":return[Ne(R("x",e,t,n).rank,"int32")];case"NoOp":return[Ne(1)];case"Print":const o=R("x",e,t,n),a=R("data",e,t,n),c=R("message",e,t,n),u=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,u));return[o];default:throw TypeError(`Node type ${e.op} is not implemented`)}},Hee="graph";const YH=(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[Vr.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[Vr.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),u=R("extrapolationValue",e,t,n);return[Vr.cropAndResize(s,i,o,a,c,u)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},Yee="image";const qH=(e,t,n)=>{switch(e.op){case"Equal":return[ni(R("a",e,t,n),R("b",e,t,n))];case"NotEqual":return[Pr(R("a",e,t,n),R("b",e,t,n))];case"Greater":return[Ts(R("a",e,t,n),R("b",e,t,n))];case"GreaterEqual":return[tr(R("a",e,t,n),R("b",e,t,n))];case"Less":return[dh(R("a",e,t,n),R("b",e,t,n))];case"LessEqual":return[Mr(R("a",e,t,n),R("b",e,t,n))];case"LogicalAnd":return[Bs(R("a",e,t,n),R("b",e,t,n))];case"LogicalNot":return[ph(R("a",e,t,n))];case"LogicalOr":return[ep(R("a",e,t,n),R("b",e,t,n))];case"Select":case"SelectV2":return[$n(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`)}},qee="logical";const jH=(e,t,n)=>{switch(e.op){case"BatchMatMul":case"BatchMatMulV2":case"MatMul":return[at(R("a",e,t,n),R("b",e,t,n),R("transposeA",e,t,n),R("transposeB",e,t,n))];case"Transpose":return[Pe(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[u,p]=R("args",e,t,n);return[bp({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:u,activation:i,preluActivationWeights:p})];default:throw TypeError(`Node type ${e.op} is not implemented`)}},jee="matrices";const KH=(e,t,n)=>{switch(e.op){case"FusedBatchNorm":case"FusedBatchNormV2":return[Ro(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[Ro(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[Tb(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[Uo(R("x",e,t,n))];case"LogSoftmax":return[Qd(R("x",e,t,n))];case"SparseToDense":return[zb(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`)}},Kee="normalization";const XH=(e,t,n)=>{switch(e.op){case"Max":{const s=R("axis",e,t,n),i=R("keepDims",e,t,n);return[Xn(R("x",e,t,n),s,i)]}case"Mean":{const s=R("axis",e,t,n),i=R("keepDims",e,t,n);return[zt(R("x",e,t,n),s,i)]}case"Min":{const s=R("axis",e,t,n),i=R("keepDims",e,t,n);return[Ha(R("x",e,t,n),s,i)]}case"Sum":{const s=R("axis",e,t,n),i=R("keepDims",e,t,n);return[Ue(R("x",e,t,n),s,i)]}case"All":{const s=R("axis",e,t,n),i=R("keepDims",e,t,n);return[Pd(R("x",e,t,n),s,i)]}case"Any":{const s=R("axis",e,t,n),i=R("keepDims",e,t,n);return[th(R("x",e,t,n),s,i)]}case"ArgMax":{const s=R("axis",e,t,n);return[nh(R("x",e,t,n),s)]}case"ArgMin":{const s=R("axis",e,t,n);return[rb(R("x",e,t,n),s)]}case"Prod":{const s=R("axis",e,t,n),i=R("keepDims",e,t,n);return[sp(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[jd(R("x",e,t,n),s,i,o)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},Xee="reduction";const JH=(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),[Mt(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[za(i,ve(o,"int32"),s)]}case"ReverseV2":case"Reverse":{const s=R("axis",e,t,n),i=R("x",e,t,n);return[As(i,s)]}case"Slice":{const s=R("begin",e,t,n),i=R("size",e,t,n);return[st(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),u=R("ellipsisMask",e,t,n),p=R("newAxisMask",e,t,n),m=R("shrinkAxisMask",e,t,n),y=R("x",e,t,n);return[$b(y,s,i,o,a,c,u,p,m)]}case"Pack":return ee(()=>{const s=R("axis",e,t,n),i=R("tensors",e,t,n),o=i[0].shape,a=zr(i[0]).shape,c=i.map(u=>{const p=ot(u.shape,o);if(!p&&!ot(zr(u).shape,a))throw new Error("the input tensors shape does not match");return p?u:K(u,o)});return[as(c,s)]});case"Unpack":{const s=R("axis",e,t,n),i=R("tensor",e,t,n);return _i(i,s)}case"Tile":{const s=R("reps",e,t,n);return[Br(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 os(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[MA(s,i,o)]}case"GatherNd":{const s=R("x",e,t,n),i=R("indices",e,t,n);return[PA(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[zb(s,o,i,o.dtype===a.dtype?a:ve(a,o.dtype))]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},Jee="slice_join";const ZH=(e,t,n)=>{switch(e.op){case"FFT":return[wh(R("x",e,t,n))];case"IFFT":return[ja(R("x",e,t,n))];case"RFFT":return[Lh(R("x",e,t,n))];case"IRFFT":return[hp(R("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},Zee="spectral";const QH=(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[Kn(R("x",e,t,n),s)]}case"Squeeze":{const s=R("axis",e,t,n);return[zr(R("x",e,t,n),s)]}case"Reshape":return[K(R("x",e,t,n),R("shape",e,t,n))];case"PadV2":case"Pad":return[ki(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[fh(R("x",e,t,n),s,i)]}case"BatchToSpaceND":{const s=R("blockShape",e,t,n),i=R("crops",e,t,n);return[ah(R("x",e,t,n),s,i)]}case"DepthToSpace":{const s=R("blockSize",e,t,n),i=R("dataFormat",e,t,n).toUpperCase();return[bb(R("x",e,t,n),s,i)]}case"BroadcastTo":return[ch(R("x",e,t,n),R("shape",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},Qee="transformation";function e0(e,t,n){const s=((i,o,a)=>{switch(i.category){case"arithmetic":return ee(()=>DH(i,o,a));case"basic_math":return ee(()=>kH(i,o,a));case"control":return MH(i,o,a);case"convolution":return ee(()=>PH(i,o,a));case"creation":return ee(()=>zH(i,o,a));case"dynamic":return GH(i,o,a);case"evaluation":return ee(()=>VH(i,o,a));case"image":return ee(()=>YH(i,o,a));case"graph":return ee(()=>HH(i,o,a));case"logical":return ee(()=>qH(i,o,a));case"matrices":return ee(()=>jH(i,o,a));case"normalization":return ee(()=>KH(i,o,a));case"reduction":return ee(()=>XH(i,o,a));case"slice_join":return ee(()=>JH(i,o,a));case"spectral":return ee(()=>ZH(i,o,a));case"transformation":return ee(()=>QH(i,o,a));case"custom":const c=jN(i.op);if(c&&c.customExecutor)return c.customExecutor(new EH(i,o,a));throw TypeError(`Custom op ${i.op} is not registered.`);default:throw TypeError(`Unknown op '${i.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 s instanceof Promise?s.then(i=>[].concat(i)):[].concat(s)}class t0{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 n0(e,t,n,s){const i=new Set,o=[];let a=null,c=null;const u=new Set,p=Object.keys(e).map(b=>ls(b)[0]);let m=[];s!=null&&(m=s.map(b=>ls(b.name)[0]));const y=[...t];for(;y.length>0;){const b=y.pop();if((s0(b)||sY(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(u.has(w.name))return;u.add(w.name),y.push(w)})}return{inputs:e,outputs:t,usedNodes:i,missingInputs:o,dynamicNode:a,syncInputs:c}}function eY(e,t,n){const{usedNodes:s,inputs:i}=n,o=[],a=Object.keys(i).map(m=>ls(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 u=new Set,p=[];for(;o.length>0;){const m=o.pop();u.add(m.name),t[m.name]||p.push(m),m.children.forEach(y=>{!u.has(y.name)&&s.has(y.name)&&y.inputs.every(b=>u.has(b.name))&&o.push(y)})}return p}const tY=["Switch","Merge","Enter","Exit","NextIteration","StatelessIf","StatelessWhile","if","While"],nY=["NonMaxSuppressionV2","NonMaxSuppressionV3","NonMaxSuppressionV5","Where"];function s0(e){return tY.indexOf(e.op)>=0}function sY(e){return nY.indexOf(e.op)>=0}class eS{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 eS(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}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=n0(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(u=>u.name),c=Object.keys(e);throw new Error(`Cannot compute the outputs [${a}] from the provided inputs [${c}]. Missing the following inputs: [${s}]`)}return eY(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[ls(m)[0]]),i=t.map(m=>ls(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 u={},p={};return ee(()=>{const m=new t0(this.weightMap,u,p,this.functionExecutorMap),y=Object.assign({},this.weightMap);Object.keys(e).forEach(I=>{const[T,v]=ls(I),N=[];N[v]=e[I],y[T]=N});const b=this.getFrozenTensorIds(y),w={};for(let I=0;I<c.length;I++){const T=c[I];if(!y[T.name]){const v=e0(T,y,m);if(v instanceof Promise)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(I=>Qn(I,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 u=JV(c.name,n,s);u!=null&&u.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 t0(this.weightMap,s,i,this.functionExecutorMap),a=await this.executeWithControlFlow(e,o,t,n),c=t.map(y=>Qn(y,a,o)),u=c.map(y=>y.id),p=Object.keys(e).map(y=>e[y].id),m=new Set([...u,...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(E=>this.graph.nodes[ls(E)[0]]),a=n.map(E=>ls(E)[0]),c=a.map(E=>this.graph.nodes[E]),{usedNodes:u,missingInputs:p,dynamicNode:m,syncInputs:y}=n0(e,c,this.weightMap),b=[...o,...this.graph.weights].map(E=>({node:E,contexts:t.currentContext})),w=Object.assign({},this.weightMap);Object.keys(e).forEach(E=>{const[D,F]=ls(E),_=[];_[F]=e[E],w[D]=_});const I={},T=this.getFrozenTensorIds(w),v={};for(;b.length>0;){const E=this.processStack(o,b,t,w,v,T,a,I,u);await Promise.all(E)}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 N=c.filter(E=>!s0(E)&&!Qn(E.name,w,t)).map(E=>E.name);if(N.length>0){let E="";throw m!=null&&(E=`Alternatively, to avoid the dynamic ops, use model.execute() and specify the inputs [${y}]`),new Error(`Cannot compute the outputs [${N}] from the provided inputs [${i}]. Consider providing the following inputs: [${p}]. ${E}`)}return w}processStack(e,t,n,s,i,o,a,c,u){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]=lr(m.node.name,n)),e.indexOf(m.node)===-1){const b=e0(m.node,s,n);y||([y]=lr(m.node.name,n));const w=n.currentContext;b instanceof Promise?p.push(b.then(I=>(s[y]=I,n.currentContext=w,this.checkTensorForDisposal(y,m.node,s,n,o,a,c),this.processChildNodes(m.node,t,n,s,i,u),I))):(s[y]=b,this.checkTensorForDisposal(y,m.node,s,n,o,a,c),this.processChildNodes(m.node,t,n,s,i,u))}else this.processChildNodes(m.node,t,n,s,i,u)}return p}processChildNodes(e,t,n,s,i,o){e.children.forEach(a=>{const[c]=lr(a.name,n);if(i[c]||!o.has(a.name))return;a.op==="Merge"?a.inputNames.some(u=>!!Qn(u,s,n))&&(i[c]=!0,t.push({contexts:n.currentContext,node:a})):a.inputNames.every(u=>!!Qn(u,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]=ls(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,u)=>o[u]===-1||o[u]===c);k(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&&k(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]=ls(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]=ls(t);if(!this.graph.nodes[n])throw new Error(`The output '${t}' is not found in the graph`)})}}const iY="?tfjs-format=file",rY="model.json";class i0{constructor(e,t={}){this.modelUrl=e,this.loadOptions=t,this.version="n/a",t==null&&(this.loadOptions={})}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=kd(e,this.loadOptions);else{const t=By(e,this.loadOptions);if(t.length===0)t.push(kd(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=Rd(this.artifacts.weightData,this.artifacts.weightSpecs);if(this.executor=new eS(KN.Instance.transformGraph(t,n)),this.executor.weightMap=this.convertTensorMapToTensorsMap(s),e.modelInitializer!=null){const i=KN.Instance.transformGraph(e.modelInitializer);this.initializer=new eS(i),this.initializer.weightMap=this.executor.weightMap,this.initializer.execute({},[])}return!0}async save(e,t){if(typeof e=="string"){const n=Uy(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 Q)&&!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()}}async function oY(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}${rY}${iY}`));const n=new i0(e,t);return await n.load(),n}const r0="2.6.0";function aY(e,t){return lm(e,t)}function lm(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],u=lm(c,t,n,s);o[a]=u}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 cY(e,t=a0){return o0(e,t)}function o0(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]),u=o0(c,t,n);o[a]=u}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 c0(e,t){const n=new Map;lm(e,t,n);for(const i of Array.from(n.keys())){const o=n.get(i);if(o instanceof Promise){const a=await o;n.set(i,a)}}const s=lm(e,t,n);return s}function lc(e){return e!=null&&!ArrayBuffer.isView(e)&&(Array.isArray(e)||typeof e=="object"&&!(e instanceof Q))}function lY(e){return e==null||hY(e)||Array.isArray(e)||typeof e=="object"&&e instanceof Q||Ln(e)}function hY(e){return e===null||typeof e!="object"&&typeof e!="function"}function uY(e){return aY(e,dY)}function dY(e){return e instanceof Q?{value:e.clone(),recurse:!1}:lc(e)?{value:null,recurse:!0}:{value:e,recurse:!1}}class l0{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 l0{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 h0(e){return new mY(e)}function ete(e){let t=e;return nu(()=>({value:t++,done:!1}))}function nu(e){return new fY(e)}function u0(e,t){return new p0(e,t)}function tte(e,t,n){return u0(nu(e).take(t),n)}function pY(e,t=Qr.FAIL){return new TY(e,t)}class gn{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 IY(this,e)}filter(e){return new LY(this,e)}map(e){return new SY(this,e)}mapAsync(e){return new d0(this,e)}serialMapAsync(e){return new d0(this,e).serial()}flatmap(e){return new xY(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 wY(this,e,t)}columnMajorBatch(e,t=!0,n=a0){const s=this.rowMajorBatch(e,t);return s.map(i=>cY(i,n))}concatenate(e,t){return new p0(h0([this,e]),t)}take(e){return e<0||e==null?this:new bY(this,e)}skip(e){return e<0||e==null?this:new yY(this,e)}prefetch(e){return new m0(this,e)}shuffle(e,t){return new AY(this,e,t)}serial(){return new gY(this)}}class mY extends gn{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:uY(e),done:!1}}}class fY extends gn{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 gY extends gn{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 yY extends gn{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 bY extends gn{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 wY extends gn{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 LY extends gn{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 SY extends gn{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)Nd(i,s)||i.dispose();return{value:n,done:!1}}}class IY extends gn{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 d0 extends gn{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)Nd(i,s)||i.dispose();return{value:n,done:!1}}}class nS extends gn{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 xY extends nS{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)Nd(i,s)||i.dispose();return!0}}class p0 extends gn{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 Qr;(function(e){e[e.FAIL=0]="FAIL",e[e.SHORTEST=1]="SHORTEST",e[e.LONGEST=2]="LONGEST"})(Qr||(Qr={}));class TY extends gn{constructor(e,t=Qr.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 gn){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 c0(this.iterators,s);if(t===n)return{value:null,done:!0};if(n>0)switch(this.mismatchMode){case Qr.FAIL:throw new Error(`Zipped streams should have the same length. Mismatched at element ${this.count}.`);case Qr.SHORTEST:return{value:null,done:!0};case Qr.LONGEST:default:}return this.count++,{value:i,done:!1}}async next(){return this.currentPromise=this.nextState(this.currentPromise),this.currentPromise}}class m0 extends gn{constructor(e,t){super();this.upstream=e,this.bufferSize=t,this.buffer=new l0(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 AY extends m0{constructor(e,t,n){super(e,t);this.upstream=e,this.windowSize=t,this.upstreamExhausted=!1,this.random=qa(n||qn().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 hc{constructor(){this.size=null}batch(e,t=!0){const n=this;k(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),hs(async()=>(await n.iterator()).columnMajorBatch(e,t,CY),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,hs(async()=>(await t.iterator()).concatenate(await e.iterator()),n)}filter(e){const t=this;let n;return this.size===Infinity?n=Infinity:n=null,hs(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 hs(async()=>(await t.iterator()).map(n=>ee(()=>e(n))),this.size)}mapAsync(e){const t=this;return hs(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 hs(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,hs(async()=>{const s=nu(async()=>({value:await t.iterator(),done:!1}));return u0(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,hs(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=qa(t||qn().toString());return hs(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,hs(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()}}hc.MAX_BUFFER_SIZE=1e4;function hs(e,t=null){return new class extends hc{constructor(){super(...arguments);this.size=t}async iterator(){return e()}}}function vY(e){return hs(async()=>h0(e),e.length)}function NY(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 hs(async()=>{const n=await c0(e,s=>{if(s instanceof hc)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 pY(n,Qr.SHORTEST)},t)}function CY(e){if(e===null)return null;const t=e[0];if(lY(t)){const n=RY(e);return{value:n,recurse:!1}}return{value:null,recurse:!0}}function RY(e){if(e.length===0)throw new Error("Can't make a batch of zero elements.");return e[0]instanceof Q?as(e):en(e)}class f0 extends hc{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 hm='"',su=Symbol("out"),g0=Symbol("field"),um=Symbol("quote"),sS=Symbol("quoteafterquote"),y0=Symbol("quoteinquote");class b0 extends hc{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 f0(e),t||(t={}),this.hasHeader=!(t.hasHeader===!1),this.fullColumnNames=t.columnNames,this.columnConfigs=t.columnConfigs,this.configuredColumnsOnly=t.configuredColumnsOnly,t.delimWhitespace?(k(t.delimiter==null,()=>"Delimiter should not be provided when delimWhitespace is true."),this.delimWhitespace=!0,this.delimiter=" "):this.delimiter=t.delimiter?t.delimiter:","}async columnNames(){return this.columnNamesValidated||await this.setColumnNames(),this.configuredColumnsOnly?Object.keys(this.columnConfigs):this.fullColumnNames}async setColumnNames(){const e=await this.maybeReadHeaderLine();if(!this.fullColumnNames&&!e)throw new Error("Column names must be provided if there is no header line.");this.fullColumnNames&&e&&k(e.length===this.fullColumnNames.length,()=>"The length of provided columnNames ("+this.fullColumnNames.length.toString()+") does not match the length of the header line read from file ("+e.length.toString()+")."),this.fullColumnNames||(this.fullColumnNames=e);const t=this.fullColumnNames.reduce((s,i)=>(s[i]=s[i]+1||1,s),{}),n=Object.keys(t).filter(s=>t[s]>1);if(k(n.length===0,()=>"Duplicate column names found: "+n.toString()),this.columnConfigs)for(const s of Object.keys(this.columnConfigs)){const i=this.fullColumnNames.indexOf(s);if(i===-1)throw new Error('The key "'+s+'" provided in columnConfigs does not match any of the column names ('+this.fullColumnNames.toString()+").")}this.columnNamesValidated=!0}async maybeReadHeaderLine(){if(this.hasHeader){const e=await this.base.iterator(),t=await e.next();if(t.done)throw new Error("No data was found for CSV parsing.");const n=t.value,s=this.parseRow(n,!1);return s}else return null}async iterator(){this.columnNamesValidated||await this.setColumnNames();let e=await this.base.iterator();return this.hasHeader&&(e=e.skip(1)),e.map(t=>this.makeDataElement(t))}makeDataElement(e){const t=this.parseRow(e),n={},s={};for(let i=0;i<this.fullColumnNames.length;i++){const o=this.fullColumnNames[i],a=this.columnConfigs?this.columnConfigs[o]:null;if(this.configuredColumnsOnly&&!a)continue;{const c=t[i];let u=null;if(c==="")if(a&&a.default!==void 0)u=a.default;else{if(a&&(a.required||a.isLabel))throw new Error(`Required column ${o} is empty in this line: ${e}`);u=void 0}else{const p=Number(c);if(isNaN(p))a&&a.dtype==="bool"?u=this.getBoolean(c):u=c;else if(!a||!a.dtype)u=p;else switch(a.dtype){case"float32":u=p;break;case"int32":u=Math.floor(p);break;case"bool":u=this.getBoolean(c);break;default:u=p}}a&&a.isLabel?s[o]=u:n[o]=u}}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=su;for(let a=0;a<i;a++)switch(o){case su:switch(e.charAt(a)){case hm:s=a+1,o=um;break;case this.delimiter:if(s=a+1,this.delimiter===" "&&this.delimWhitespace)break;n.push(""),o=su;break;default:o=g0,s=a;break}break;case g0:switch(e.charAt(a)){case this.delimiter:n.push(e.substring(s,a)),o=su,s=a+1;break;default:}break;case um:switch(e.charAt(a)){case hm:o=sS;break;default:}break;case sS:switch(e.charAt(a)){case this.delimiter:n.push(e.substring(s,a-1)),o=su,s=a+1;break;case hm:o=um;break;default:o=y0;break}break;case y0:switch(e.charAt(a)){case hm:o=um;break;default:}break;default:}if(o===sS?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 w0 extends gn{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(C().get("IS_NODE"))throw new Error("microphone API is only supported in browser environment.");const t=new w0(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(we(t));return n.set(e,n.length-e.length),en(n,t)}}class L0 extends gn{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=rs([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=Gr([o,i,c,a],[1,4])}else this.cropBox=Gr([0,0,1,1],[1,4])}summary(){return"webcam"}static async create(e,t={}){if(C().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 L0(e,t);return await n.start(),n}async start(){this.webcamConfig.facingMode&&k(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=BT(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=Vr.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 S0{}class I0 extends gn{split(e){return new OY(this,e)}}class OY extends I0{constructor(e,t){super();this.upstream=e,this.impl=new EY(e,t)}summary(){return this.impl.summary()}async next(){return this.impl.next()}}class EY extends nS{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 DY extends gn{decodeUTF8(){return new kY(this)}}class kY extends I0{constructor(e){super();this.upstream=e,this.impl=new FY(e)}summary(){return this.impl.summary()}async next(){return this.impl.next()}}class FY extends nS{constructor(e){super();if(this.upstream=e,C().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 C().get("IS_BROWSER")?n=this.decoder.decode(t,{stream:!0}):n=this.decoder.write(Buffer.from(t.buffer)),this.outputQueue.push(n),!0}}class x0 extends DY{constructor(e,t={}){super();this.file=e,this.options=t,k(e instanceof Uint8Array||(C().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 _Y(e,t={}){let n,s;typeof e=="string"?n=e:(n=e.url,s=WY(e));const i=await uT(n,s);if(i.ok){const o=new Uint8Array(await i.arrayBuffer());return new x0(o,t)}else throw new Error(i.statusText)}const WY=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 T0(e){return typeof e=="string"&&e.substr(0,7)==="file://"}class A0 extends S0{constructor(e,t={}){super();this.input=e,this.options=t}async iterator(){if(T0(this.input)&&C().get("IS_NODE")){const e=require("fs");this.input=e.readFileSync(this.input.substr(7))}return new x0(this.input,this.options)}}class v0 extends S0{constructor(e,t={}){super();this.url=e,this.fileOptions=t}async iterator(){return T0(this.url)?new A0(this.url,this.fileOptions).iterator():_Y(this.url,this.fileOptions)}}function $Y(e,t={}){return new b0(new v0(e),t)}function UY(e){const t=nu(e);return hs(async()=>t)}function BY(e){return hs(async()=>{const t=await e();return nu(()=>t.next())})}async function MY(e,t){return L0.create(e,t)}async function PY(e){return w0.create(e)}const N0="2.6.0";var zY=Object.freeze({__proto__:null,array:vY,Dataset:hc,zip:NY,CSVDataset:b0,TextLineDataset:f0,csv:$Y,func:UY,generator:BY,microphone:PY,webcam:MY,FileDataSource:A0,URLDataSource:v0,version_data:N0});function Te(e,t){Array.isArray(e)||(e=[e]),e.forEach(n=>{n!=null&&k(n.dtype!=="complex64",()=>`${t} does not support complex64 tensors in the CPU backend.`)})}const GY=wp,VY=rw,HY=ow,YY=aw,qY=dp;function iS(e,t,n,s){if(n==="linear")return e.linear(t);if(n==="relu")return e.relu(t);if(n==="elu")return Do(t);if(n==="relu6")return e.relu6(t);if(n==="prelu")return e.prelu(t,s);throw new Error(`Activation ${n} has not been implemented for the CPU backend.`)}class jY extends f{constructor(){super();this.blockSize=48,this.firstUse=!0,this.data=new d(this,$s())}write(e,t,n){this.firstUse&&(this.firstUse=!1,C().get("IS_NODE")&&Qa(`
============================
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){const s=this.write(n,e,t);return{dataId:s,shape:e,dtype:t}}incRef(e){const t=this.data.get(e);t.refCount++}decRef(e){if(this.data.has(e)){const t=this.data.get(e);t.refCount--}}move(e,t,n,s){this.data.set(e,{values:t,dtype:s,refCount:1})}numDataIds(){return this.data.numDataIds()}async read(e){return this.readSync(e)}readSync(e){const{dtype:t,complexTensorInfos:n}=this.data.get(e);if(t==="complex64"){const s=this.readSync(n.real.dataId),i=this.readSync(n.imag.dataId);return ir(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=>Yl(s))}catch(s){throw new Error("Failed to decode encoded string bytes into utf-8")}return Qe(e.shape,e.dtype,n)}makeOutput(e,t,n){const s=this.write(e,t,n);return $s().makeTensorFromDataId(s,t,n,this)}disposeData(e){if(this.data.has(e)){const{complexTensorInfos:t}=this.data.get(e);t!=null&&(this.disposeData(t.real.dataId),this.disposeData(t.imag.dataId)),this.data.delete(e)}}disposeIntermediateTensorInfo(e){const t=e.dataId;if(this.data.has(t)){const n=this.data.get(t);n.refCount--,n.refCount<1&&this.disposeData(t)}}async time(e){const t=qn();e();const n=qn()-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=Wd(t,n,s);if(i.some(c=>c===0))return en([],i);const o=Qe(i,e.dtype),a=this.bufferSync(e);for(let c=0;c<o.size;c++){const u=o.indexToLoc(c),p=new Array(u.length);for(let m=0;m<p.length;m++)p[m]=u[m]*s[m]+t[m];o.set(a.get(...p),...u)}return o.toTensor()}diag(e){const t=this.readSync(e.dataId),n=Qe([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 u=0;u<e.rank;u++)u!==t&&(s[i++]=e.shape[u]);const o=new Array(e.rank).fill(0),a=e.shape.slice();a[t]=1;const c=new Array(n);for(let u=0;u<c.length;u++)o[t]=u,c[u]=st(e,o,a).reshape(s);return c}reverse(e,t){Te(e,"reverse");const n=Qe(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(Ne(-1),e)}addN(e){Te(e,"addN");const t=e.map(i=>this.readSync(i.dataId)),n=Qe(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=ft([t],e.shape),s=Xn(e,n),i=En(s.shape,n),o=Ce(e,s.reshape(i)),a=xs(o),c=this.sum(a,n).reshape(i);return _e(a,c)}pow(e,t){return Te([e,t],"pow"),this.broadcastedBinaryOp(e,t,e.dtype,(n,s)=>Math.pow(n,s))}batchMatMul(e,t,n,s){Te([e,t],"matMul");const i=n?e.shape[1]:e.shape[2],o=n?e.shape[2]:e.shape[1],a=s?t.shape[1]:t.shape[2],c=e.shape[0],u=this.readSync(e.dataId),p=this.readSync(t.dataId),[m,y,b]=n?[e.strides[0],1,e.strides[1]]:[e.strides[0],e.strides[1],1],[w,I,T]=s?[1,t.strides[1],t.strides[0]]:[t.strides[1],1,t.strides[0]],v=o*a,N=Qe([c,o,a],e.dtype),E=N.values,D=this.blockSize;for(let F=0;F<c;F++)for(let _=0;_<o;_+=D)for(let B=0;B<a;B+=D)for(let U=0;U<i;U+=D){const Y=Math.min(_+D,o),q=Math.min(B+D,a),J=Math.min(U+D,i);for(let oe=_;oe<Y;oe++)for(let ce=B;ce<q;ce++){let ue=0;for(let he=U;he<J;he++)ue+=u[F*m+oe*y+he*b]*p[he*w+ce*I+F*T];E[F*v+(oe*a+ce)]+=ue}}return N.toTensor()}fusedBatchMatMul({a:e,b:t,transposeA:n,transposeB:s,bias:i,activation:o,preluActivationWeights:a}){let c=this.batchMatMul(e,t,n,s);return i&&(c=be(c,i)),o&&(c=iS(this,c,o,a)),c}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"),ss("sum",t,e.rank);const[n,s]=On(e.shape,t),i=Cn(e.dtype,"int32"),o=ct(n,i),a=we(s),c=this.readSync(o.dataId),u=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+=u[m+b];c[p]=y}return o}prod(e,t){Te(e,"sum");const[n,s]=On(e.shape,t),i=Cn(e.dtype,"int32"),o=ct(n,i),a=we(s),c=this.readSync(o.dataId),u=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*=u[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=Ne(o,"int32"),c=ni(a,t).asType("float32"),u=c.mul(e).sum(0);s.push(u)}return as(s)}argMin(e,t){Te(e,"argMin");const n=[t];ss("argMin",n,e.rank);const[s,i]=On(e.shape,n),o=ct(s,"int32"),a=we(i),c=this.readSync(o.dataId),u=this.readSync(e.dataId);for(let p=0;p<c.length;++p){const m=p*a;let y=u[m],b=0;for(let w=0;w<a;++w){const I=u[m+w];I<y&&(y=I,b=w)}c[p]=b}return o}argMax(e,t){Te(e,"argMax");const n=[t];ss("argMax",n,e.rank);const[s,i]=On(e.shape,n),o=ct(s,"int32"),a=we(i),c=this.readSync(o.dataId),u=this.readSync(e.dataId);for(let p=0;p<c.length;++p){const m=p*a;let y=u[m],b=0;for(let w=0;w<a;++w){const I=u[m+w];I>y&&(y=I,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=Cn(e.dtype,"int32"),o=ct(e.shape,i),a=this.readSync(o.dataId),c=this.readSync(e.dataId),u=e.shape[e.rank-1],p=s?(m,y)=>m+u-y-1:(m,y)=>m+y;for(let m=0;m<c.length;m+=u)for(let y=0;y<u;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=ct(t.shape,Cn(t.dtype,n.dtype)),c=this.readSync(a.dataId);let u=0;const p=e.rank===0||e.rank>1||t.rank===1?1:we(t.shape.slice(1));for(let m=0;m<s.length;m++)for(let y=0;y<p;y++)s[m]===1?c[u++]=i[m]:c[u++]=o[m];return a}where(e){Te([e],"where");const t=this.readSync(e.dataId);return qY(e.shape,t)}topk(e,t,n){Te(e,"topk");const s=this.readSync(e.dataId);return YY(s,e.shape,e.dtype,t,n)}min(e,t){Te(e,"min"),ss("min",t,e.rank);const[n,s]=On(e.shape,t),i=ct(n,e.dtype),o=we(s),a=this.readSync(i.dataId),c=this.readSync(e.dataId);for(let u=0;u<a.length;++u){const p=u*o;let m=c[p];for(let y=0;y<o;++y){const b=c[p+y];b<m&&(m=b)}a[u]=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"),ss("all",t,e.rank);const[n,s]=On(e.shape,t),i=ct(n,e.dtype),o=we(s),a=this.readSync(i.dataId),c=this.readSync(e.dataId);for(let u=0;u<a.length;++u){const p=u*o;let m=c[p];for(let y=0;y<o;++y){const b=c[p+y];m=m&&b}a[u]=m}return i}any(e,t){Te(e,"any"),ss("any",t,e.rank);const[n,s]=On(e.shape,t),i=ct(n,e.dtype),o=we(s),a=this.readSync(i.dataId),c=this.readSync(e.dataId);for(let u=0;u<a.length;++u){const p=u*o;let m=c[p];for(let y=0;y<o;++y){const b=c[p+y];m=m||b}a[u]=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})}linear(e){return e}relu(e){Te(e,"relu");const t=ct(e.shape,e.dtype),n=this.readSync(t.dataId),s=this.readSync(e.dataId);for(let i=0;i<s.length;++i)n[i]=Math.max(0,s[i]);return t}relu6(e){Te(e,"relu");const t=ct(e.shape,e.dtype),n=this.readSync(t.dataId),s=this.readSync(e.dataId);for(let i=0;i<s.length;++i)n[i]=Math.min(Math.max(0,s[i]),6);return t}prelu(e,t){return Te([e,t],"prelu"),this.broadcastedBinaryOp(e,t,e.dtype,(n,s)=>n<0?s*n:n)}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))}fusedConv2d({input:e,filter:t,convInfo:n,bias:s,activation:i,preluActivationWeights:o}){let a=this.conv2d(e,t,n);return s&&(a=be(a,s)),i&&(a=iS(this,a,i,o)),a}conv2d(e,t,n){Te([e,t],"conv2d");const s=n.filterHeight,i=n.filterWidth,o=n.dilationHeight,a=n.dilationWidth,c=n.padInfo.left,u=n.padInfo.top,p=n.dataFormat==="channelsLast",m=Qe(n.outShape,e.dtype),y=e.strides[0],b=p?e.strides[1]:e.strides[2],w=p?e.strides[2]:1,I=p?1:e.strides[1],T=m.strides[0],v=p?m.strides[1]:m.strides[2],N=p?m.strides[2]:1,E=p?1:m.strides[1],D=this.readSync(e.dataId),F=this.readSync(t.dataId),_=m.values;for(let B=0;B<n.batchSize;++B){const U=B*y,Y=B*T;for(let q=0;q<n.outHeight;++q){const J=Y+q*v,oe=q*n.strideHeight-u;for(let ce=0;ce<s;ce++){const ue=oe+ce*o;if(ue<0||ue>=n.inHeight)continue;const he=ce*t.strides[0],pe=U+ue*b;for(let le=0;le<n.outWidth;++le){const ye=J+le*N,me=le*n.strideWidth-c;for(let Ie=0;Ie<i;Ie++){const Se=me+Ie*a;if(Se<0||Se>=n.inWidth)continue;const Ee=he+Ie*t.strides[1],We=pe+Se*w;let Oe=Ee;for(let $e=0;$e<n.inChannels;++$e){const He=D[We+$e*I];for(let tt=0;tt<n.outChannels;++tt)_[ye+tt*E]+=He*F[Oe+tt];Oe+=n.outChannels}}}}}}return m.toTensor()}conv3d(e,t,n){const s=n.filterDepth,i=n.filterHeight,o=n.filterWidth,a=n.dilationDepth,c=n.dilationHeight,u=n.dilationWidth,p=n.padInfo.front,m=n.padInfo.left,y=n.padInfo.top,b=Qe(n.outShape,e.dtype),w=this.readSync(e.dataId),I=this.readSync(t.dataId),T=b.values;for(let v=0;v<n.batchSize;++v){const N=v*e.strides[0],E=v*b.strides[0];for(let D=0;D<n.outDepth;++D){const F=E+D*b.strides[1],_=D*n.strideDepth-p;for(let B=0;B<s;B++){const U=_+B*a;if(U<0||U>=n.inDepth)continue;const Y=B*t.strides[0],q=N+U*e.strides[1];for(let J=0;J<n.outHeight;++J){const oe=F+J*b.strides[2],ce=J*n.strideHeight-y;for(let ue=0;ue<i;ue++){const he=ce+ue*c;if(he<0||he>=n.inHeight)continue;const pe=Y+ue*t.strides[1],le=q+he*e.strides[2];for(let ye=0;ye<n.outWidth;++ye){const me=oe+ye*n.outChannels,Ie=ye*n.strideWidth-m;for(let Se=0;Se<o;Se++){const Ee=Ie+Se*u;if(Ee<0||Ee>=n.inWidth)continue;const We=pe+Se*t.strides[2],Oe=le+Ee*n.inChannels;let $e=We;for(let He=0;He<n.inChannels;++He){const tt=w[Oe+He];for(let bt=0;bt<n.outChannels;++bt)T[me+bt]+=tt*I[$e+bt];$e+=n.outChannels}}}}}}}}return b.toTensor()}conv2dDerInput(e,t,n){Te([e,t],"conv2dDerInput");const s=Qe(n.inShape,"float32"),i=s.values,o=this.readSync(e.dataId),a=this.readSync(t.dataId),[c,u,p]=t.strides,{batchSize:m,filterHeight:y,filterWidth:b,inChannels:w,inHeight:I,inWidth:T,outChannels:v,outHeight:N,outWidth:E,strideHeight:D,strideWidth:F,dataFormat:_}=n,B=y-1-n.padInfo.top,U=b-1-n.padInfo.left,Y=_==="channelsLast",q=s.strides[0],J=Y?s.strides[1]:s.strides[2],oe=Y?s.strides[2]:1,ce=Y?1:s.strides[1],ue=e.strides[0],he=Y?e.strides[1]:e.strides[2],pe=Y?e.strides[2]:1,le=Y?1:e.strides[1];for(let ye=0;ye<m;++ye)for(let me=0;me<w;++me)for(let Ie=0;Ie<I;++Ie){const Se=Ie-B,Ee=Math.max(0,Math.ceil(Se/D)),We=Math.min(N,(y+Se)/D);for(let Oe=0;Oe<T;++Oe){const $e=Oe-U,He=Math.max(0,Math.ceil($e/F)),tt=Math.min(E,(b+$e)/F);let bt=0;for(let dn=Ee;dn<We;++dn){const ds=dn*D-Se;for(let Ht=He;Ht<tt;++Ht){const Bn=Ht*F-$e,mi=ue*ye+he*dn+pe*Ht,Rs=c*(y-1-ds)+u*(b-1-Bn)+p*me;for(let ps=0;ps<v;++ps){const Hs=o[mi+le*ps],mu=a[Rs+ps];bt+=Hs*mu}}}const Jt=q*ye+J*Ie+oe*Oe+ce*me;i[Jt]=bt}}return s.toTensor()}conv3dDerInput(e,t,n){const s=Qe(n.inShape,"float32"),i=s.values,[o,a,c,u]=s.strides,p=this.readSync(e.dataId),[m,y,b,w]=e.strides,I=this.readSync(t.dataId),[T,v,N,E]=t.strides,{batchSize:D,filterDepth:F,filterHeight:_,filterWidth:B,inChannels:U,inDepth:Y,inHeight:q,inWidth:J,outChannels:oe,outDepth:ce,outHeight:ue,outWidth:he,strideDepth:pe,strideHeight:le,strideWidth:ye}=n,me=F-1-n.padInfo.front,Ie=_-1-n.padInfo.top,Se=B-1-n.padInfo.left;for(let Ee=0;Ee<D;++Ee)for(let We=0;We<U;++We)for(let Oe=0;Oe<Y;++Oe){const $e=Oe-me,He=Math.max(0,Math.ceil($e/pe)),tt=Math.min(ce,(F+$e)/pe);for(let bt=0;bt<q;++bt){const Jt=bt-Ie,dn=Math.max(0,Math.ceil(Jt/le)),ds=Math.min(ue,(_+Jt)/le);for(let Ht=0;Ht<J;++Ht){const Bn=Ht-Se,mi=Math.max(0,Math.ceil(Bn/ye)),Rs=Math.min(he,(B+Bn)/ye);let ps=0;for(let Hs=He;Hs<tt;++Hs){const mu=Hs*pe-$e;for(let xc=dn;xc<ds;++xc){const Tc=xc*le-Jt;for(let Ac=mi;Ac<Rs;++Ac){const vS=Ac*ye-Bn,NS=m*Ee+y*Hs+b*xc+w*Ac,pX=T*(F-1-mu)+v*(_-1-Tc)+N*(B-1-vS)+E*We;for(let vm=0;vm<oe;++vm){const mX=p[NS+vm],fX=I[pX+vm];ps+=mX*fX}}}}i[o*Ee+a*Oe+c*bt+u*Ht+We]=ps}}}return s.toTensor()}conv2dDerFilter(e,t,n){Te([e,t],"conv2dDerFilter");const s=n.strideHeight,i=n.strideWidth,o=n.filterHeight,a=n.filterWidth,c=n.dataFormat==="channelsLast",u=Qe(n.filterShape,"float32"),p=n.padInfo.left,m=n.padInfo.top,y=this.bufferSync(e),b=this.bufferSync(t);for(let w=0;w<o;++w){const I=Math.max(0,Math.ceil((m-w)/s)),T=Math.min(n.outHeight,(n.inHeight+m-w)/s);for(let v=0;v<a;++v){const N=Math.max(0,Math.ceil((p-v)/i)),E=Math.min(n.outWidth,(n.inWidth+p-v)/i);for(let D=0;D<n.inChannels;++D)for(let F=0;F<n.outChannels;++F){let _=0;for(let B=0;B<n.batchSize;++B)for(let U=I;U<T;++U){const Y=w+U*s-m;for(let q=N;q<E;++q){const J=v+q*i-p;c?_+=y.get(B,Y,J,D)*b.get(B,U,q,F):_+=y.get(B,D,Y,J)*b.get(B,F,U,q)}}u.set(_,w,v,D,F)}}}return u.toTensor()}conv3dDerFilter(e,t,n){const s=n.strideDepth,i=n.strideHeight,o=n.strideWidth,a=n.filterDepth,c=n.filterHeight,u=n.filterWidth,p=Qe(n.filterShape,"float32"),m=p.values,[y,b,w,I]=p.strides,T=this.readSync(t.dataId),[v,N,E,D]=t.strides,F=this.readSync(e.dataId),[_,B,U,Y]=e.strides,q=n.padInfo.front,J=n.padInfo.left,oe=n.padInfo.top;for(let ce=0;ce<a;++ce){const ue=Math.max(0,Math.ceil((q-ce)/s)),he=Math.min(n.outDepth,(n.inDepth+q-ce)/s),pe=ce*y;for(let le=0;le<c;++le){const ye=Math.max(0,Math.ceil((oe-le)/i)),me=Math.min(n.outHeight,(n.inHeight+oe-le)/i),Ie=le*b+pe;for(let Se=0;Se<u;++Se){const Ee=Math.max(0,Math.ceil((J-Se)/o)),We=Math.min(n.outWidth,(n.inWidth+J-Se)/o),Oe=Se*w+Ie;for(let $e=0;$e<n.inChannels;++$e){const He=$e*I+Oe;for(let tt=0;tt<n.outChannels;++tt){let bt=0;for(let Jt=0;Jt<n.batchSize;++Jt){const dn=Jt*_,ds=Jt*v;for(let Ht=ue;Ht<he;++Ht){const Bn=ce+Ht*s-q,mi=Bn*B+dn,Rs=Ht*N+ds;for(let ps=ye;ps<me;++ps){const Hs=le+ps*i-oe,mu=Hs*U+mi,xc=ps*E+Rs;for(let Tc=Ee;Tc<We;++Tc){const Ac=Se+Tc*o-J,vS=Ac*Y+mu,NS=Tc*D+xc;bt+=F[vS+$e]*T[NS+tt]}}}}m[He+tt]=bt}}}}}return p.toTensor()}fusedDepthwiseConv2D({input:e,filter:t,convInfo:n,bias:s,activation:i,preluActivationWeights:o}){let a=this.depthwiseConv2D(e,t,n);return s&&(a=be(a,s)),i&&(a=iS(this,a,i,o)),a}depthwiseConv2D(e,t,n){Te([e,t],"depthwiseConv2D");const s=n.filterHeight,i=n.filterWidth,o=n.dilationHeight,a=n.dilationWidth,c=n.padInfo.left,u=n.padInfo.top,p=n.outChannels/n.inChannels,m=Qe(n.outShape,e.dtype),y=this.readSync(e.dataId),b=this.readSync(t.dataId),w=m.values;for(let I=0;I<n.batchSize;++I){const T=I*e.strides[0],v=I*m.strides[0];for(let N=0;N<n.outHeight;++N){const E=v+N*m.strides[1],D=N*n.strideHeight-c;for(let F=0;F<s;++F){const _=D+F*o;if(_<0||_>=n.inHeight)continue;const B=F*t.strides[0],U=T+_*e.strides[1];for(let Y=0;Y<n.outWidth;++Y){const q=E+Y*m.strides[2],J=Y*n.strideWidth-u;for(let oe=0;oe<i;++oe){const ce=J+oe*a;if(ce<0||ce>=n.inWidth)continue;const ue=B+oe*t.strides[1],he=U+ce*n.inChannels;let pe=q,le=ue;for(let ye=0;ye<n.inChannels;++ye){const me=y[he+ye];for(let Ie=0;Ie<p;++Ie)w[pe+Ie]+=me*b[le+Ie];pe+=p,le+=p}}}}}}return m.toTensor()}depthwiseConv2DDerInput(e,t,n){Te([e,t],"depthwiseConv2DDerInput");const s=Qe(n.inShape,"float32"),i=s.values,[o,a,c]=s.strides,u=this.readSync(e.dataId),[p,m,y]=e.strides,b=this.readSync(t.dataId),[w,I,T]=t.strides,{batchSize:v,filterHeight:N,filterWidth:E,inChannels:D,inHeight:F,inWidth:_,outChannels:B,outHeight:U,outWidth:Y,strideHeight:q,strideWidth:J}=n,oe=N-1-n.padInfo.top,ce=E-1-n.padInfo.left,ue=B/D;for(let he=0;he<v;++he)for(let pe=0;pe<D;++pe)for(let le=0;le<F;++le){const ye=le-oe,me=Math.max(0,Math.ceil(ye/q)),Ie=Math.min(U,(N+ye)/q);for(let Se=0;Se<_;++Se){const Ee=Se-ce,We=Math.max(0,Math.ceil(Ee/J)),Oe=Math.min(Y,(E+Ee)/J);let $e=0;for(let He=me;He<Ie;++He){const tt=He*q-ye;for(let bt=We;bt<Oe;++bt){const Jt=bt*J-Ee,dn=p*he+m*He+y*bt,ds=w*(N-1-tt)+I*(E-1-Jt)+T*pe;for(let Ht=0;Ht<ue;++Ht){const Bn=pe*ue+Ht,mi=u[dn+Bn],Rs=b[ds+Ht];$e+=mi*Rs}}}i[o*he+a*le+c*Se+pe]=$e}}return s.toTensor()}depthwiseConv2DDerFilter(e,t,n){Te([e,t],"depthwiseConv2DDerFilter");const s=n.strideHeight,i=n.strideWidth,o=n.filterHeight,a=n.filterWidth,c=Qe(n.filterShape,"float32"),u=n.padInfo.left,p=n.padInfo.top,m=n.outChannels/n.inChannels,y=this.bufferSync(e),b=this.bufferSync(t);for(let w=0;w<o;++w){const I=Math.max(0,Math.ceil((p-w)/s)),T=Math.min(n.outHeight,(n.inHeight+p-w)/s);for(let v=0;v<a;++v){const N=Math.max(0,Math.ceil((u-v)/i)),E=Math.min(n.outWidth,(n.inWidth+u-v)/i);for(let D=0;D<n.outChannels;++D){const F=Math.trunc(D/m),_=D%m;let B=0;for(let U=0;U<n.batchSize;++U)for(let Y=I;Y<T;++Y){const q=w+Y*s-p;for(let J=N;J<E;++J){const oe=v+J*i-u;B+=y.get(U,q,oe,F)*b.get(U,Y,J,D)}}c.set(B,w,v,F,_)}}}return c.toTensor()}tile(e,t){return Te(e,"tile"),HY(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=Qe(s,e.dtype),a=this.bufferSync(e);for(let c=0;c<o.size;++c){const u=o.indexToLoc(c),p=u.slice();p[n]=i[u[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=Rh(e.shape,t,s),o=Oh(i.length,t.length),a=Eh(e.shape,t,s),c=jb(n,t.length),u=Kb(a,n,t.length);return Pe(e.reshape(i),o).reshape(a).slice(c,u)}pool3d(e,t,n){Te(e,"pool3d");const s=t.strideDepth,i=t.strideHeight,o=t.strideWidth,a=t.dilationDepth,c=t.dilationHeight,u=t.dilationWidth,p=t.effectiveFilterDepth,m=t.effectiveFilterHeight,y=t.effectiveFilterWidth,b=t.padInfo.front,w=t.padInfo.top,I=t.padInfo.left,T=n==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,v=this.readSync(e.dataId),N=Qe(t.outShape,e.dtype),E=N.values,D=t.outShape[1]*t.outShape[2]*t.outShape[3]*t.outShape[4],F=t.outShape[2]*t.outShape[3]*t.outShape[4],_=t.outShape[3]*t.outShape[4],B=t.outShape[4];for(let U=0;U<t.batchSize;++U){const Y=U*D,q=U*e.strides[0];for(let J=0;J<t.inChannels;++J)for(let oe=0;oe<t.outDepth;++oe){const ce=oe*s-b;let ue=ce;for(;ue<0;)ue+=a;const he=Math.min(t.inDepth,p+ce),pe=Y+oe*F;for(let le=0;le<t.outHeight;++le){const ye=le*i-w;let me=ye;for(;me<0;)me+=c;const Ie=Math.min(t.inHeight,m+ye),Se=pe+le*_;for(let Ee=0;Ee<t.outWidth;++Ee){const We=Ee*o-I;let Oe=We;for(;Oe<0;)Oe+=u;const $e=Math.min(t.inWidth,y+We),He=Se+Ee*B;let tt=T,bt=0,Jt=0;for(let ds=ue;ds<he;ds+=a){const Ht=q+ds*e.strides[1];for(let Bn=me;Bn<Ie;Bn+=c){const mi=Ht+Bn*e.strides[2];for(let Rs=Oe;Rs<$e;Rs+=u){const ps=mi+Rs*e.strides[3],Hs=v[ps+J];if(n==="max"&&Hs>tt?tt=Hs:n==="avg"&&(bt+=Hs,Jt++),isNaN(tt))break}if(isNaN(tt))break}if(isNaN(tt))break}const dn=He+J;E[dn]=n==="avg"?bt/Jt:tt}}}}return N.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,u=n.filterWidth,p=n.dilationDepth,m=n.dilationHeight,y=n.dilationWidth,b=n.effectiveFilterDepth,w=n.effectiveFilterHeight,I=n.effectiveFilterWidth,T=b-1-n.padInfo.front,v=I-1-n.padInfo.left,N=w-1-n.padInfo.top,E=Qe(t.shape,"float32"),D=1/(a*c*u),F=this.bufferSync(e);for(let _=0;_<n.batchSize;++_)for(let B=0;B<n.inChannels;++B)for(let U=0;U<n.inDepth;++U)for(let Y=0;Y<n.inHeight;++Y)for(let q=0;q<n.inWidth;++q){const J=U-T,oe=Y-N,ce=q-v;let ue=0;for(let he=0;he<b;he+=p){const pe=(J+he)/s;if(pe<0||pe>=n.outDepth||Math.floor(pe)!==pe)continue;for(let le=0;le<w;le+=m){const ye=(oe+le)/i;if(ye<0||ye>=n.outHeight||Math.floor(ye)!==ye)continue;for(let me=0;me<I;me+=y){const Ie=(ce+me)/o;if(Ie<0||Ie>=n.outWidth||Math.floor(Ie)!==Ie)continue;const Se=F.get(_,pe,ye,Ie,B);ue+=Se}}}E.set(ue*D,_,U,Y,q,B)}return E.toTensor()}maxPool3d(e,t){return Te(e,"maxPool3d"),this.pool3d(e,t,"max").toFloat()}maxPool3dPositions(e,t){const n=Qe(t.outShape,"int32"),s=t.strideDepth,i=t.strideHeight,o=t.strideWidth,a=t.dilationDepth,c=t.dilationHeight,u=t.dilationWidth,p=t.effectiveFilterDepth,m=t.effectiveFilterHeight,y=t.effectiveFilterWidth,b=t.padInfo.front,w=t.padInfo.top,I=t.padInfo.left,T=this.bufferSync(e);for(let v=0;v<t.batchSize;++v)for(let N=0;N<t.inChannels;++N)for(let E=0;E<t.outDepth;++E){const D=E*s-b;let F=D;for(;F<0;)F+=a;const _=Math.min(t.inDepth,p+D);for(let B=0;B<t.outHeight;++B){const U=B*i-w;let Y=U;for(;Y<0;)Y+=c;const q=Math.min(t.inHeight,m+U);for(let J=0;J<t.outWidth;++J){const oe=J*o-I;let ce=oe;for(;ce<0;)ce+=u;const ue=Math.min(t.inWidth,y+oe);let he=Number.NEGATIVE_INFINITY,pe=-1;for(let le=F;le<_;le+=a){const ye=le-D;for(let me=Y;me<q;me+=c){const Ie=me-U;for(let Se=ce;Se<ue;Se+=u){const Ee=Se-oe,We=T.get(v,le,me,Se,N);We>=he&&(he=We,pe=ye*m*y+Ie*m+Ee)}}}n.set(pe,v,E,B,J,N)}}}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,u=s.dilationDepth,p=s.dilationHeight,m=s.dilationWidth,y=s.effectiveFilterDepth,b=s.effectiveFilterHeight,w=s.effectiveFilterWidth,I=y-1-s.padInfo.front,T=w-1-s.padInfo.left,v=b-1-s.padInfo.top,N=Qe(t.shape,"float32"),E=this.bufferSync(i),D=this.bufferSync(e);for(let F=0;F<s.batchSize;++F)for(let _=0;_<s.inChannels;++_)for(let B=0;B<s.inDepth;++B)for(let U=0;U<s.inHeight;++U)for(let Y=0;Y<s.inWidth;++Y){const q=B-I,J=U-v,oe=Y-T;let ce=0;for(let ue=0;ue<y;ue+=u){const he=(q+ue)/o;if(he<0||he>=s.outDepth||Math.floor(he)!==he)continue;for(let pe=0;pe<b;pe+=p){const le=(J+pe)/a;if(le<0||le>=s.outHeight||Math.floor(le)!==le)continue;for(let ye=0;ye<w;ye+=m){const me=(oe+ye)/c;if(me<0||me>=s.outWidth||Math.floor(me)!==me)continue;const Ie=y*b*w-1-E.get(F,he,le,me,_),Se=ue*b*w+pe*w+ye,Ee=Ie===Se?1:0;if(Ee===0)continue;const We=D.get(F,he,le,me,_);ce+=We*Ee}}}N.set(ce,F,B,U,Y,_)}return N.toTensor()}resizeBilinear(e,t,n,s){Te(e,"resizeBilinear");const[i,o,a,c]=e.shape,u=this.readSync(e.dataId),p=new Float32Array(we([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],I=m[1]/y[1];for(let T=0;T<i;T++)for(let v=0;v<t;v++){const N=w*v,E=Math.floor(N),D=N-E,F=Math.min(o-1,Math.ceil(N)),_=T*e.strides[0]+E*e.strides[1],B=T*e.strides[0]+F*e.strides[1];for(let U=0;U<n;U++){const Y=I*U,q=Math.floor(Y),J=Y-q,oe=Math.min(a-1,Math.ceil(Y)),ce=_+q*e.strides[2],ue=B+q*e.strides[2],he=_+oe*e.strides[2],pe=B+oe*e.strides[2];for(let le=0;le<c;le++){const ye=u[ce+le],me=u[ue+le],Ie=u[he+le],Se=u[pe+le],Ee=ye+(Ie-ye)*J,We=me+(Se-me)*J,Oe=Ee+(We-Ee)*D;p[b++]=Oe}}}return en(p,[i,t,n,c])}resizeBilinearBackprop(e,t,n){Te([e,t],"resizeBilinearBackprop");const[s,i,o,a]=t.shape,[,c,u]=e.shape,p=new Float32Array(s*i*o*a),m=[n&&c>1?i-1:i,n&&u>1?o-1:o],y=[n&&c>1?c-1:c,n&&u>1?u-1:u],b=m[0]/y[0],w=m[1]/y[1],I=this.readSync(e.dataId);let T=0;for(let v=0;v<s;v++){const N=v*t.strides[0];for(let E=0;E<c;E++){const D=E*b,F=Math.floor(D),_=Math.min(Math.ceil(D),i-1),B=N+F*t.strides[1],U=N+_*t.strides[1],Y=D-F,q=1-Y;for(let J=0;J<u;J++){const oe=J*w,ce=Math.floor(oe),ue=Math.min(Math.ceil(oe),o-1),he=oe-ce,pe=1-he,le=B+ce*t.strides[2],ye=B+ue*t.strides[2],me=U+ce*t.strides[2],Ie=U+ue*t.strides[2],Se=q*pe,Ee=q*he,We=Y*pe,Oe=Y*he;for(let $e=0;$e<a;$e++){const He=I[T++];p[le+$e]+=He*Se,p[ye+$e]+=He*Ee,p[me+$e]+=He*We,p[Ie+$e]+=He*Oe}}}}return Xa(p,[s,o,i,a],t.dtype)}resizeNearestNeighbor(e,t,n,s){Te(e,"resizeNearestNeighbor");const[i,o,a,c]=e.shape,u=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 I=0;for(let T=0;T<i;T++){const v=T*e.strides[0];for(let N=0;N<t;N++){const E=b*N,D=Math.min(o-1,s?Math.round(E):Math.floor(E)),F=v+D*e.strides[1];for(let _=0;_<n;_++){const B=w*_,U=Math.min(a-1,s?Math.round(B):Math.floor(B)),Y=F+U*e.strides[2];for(let q=0;q<c;q++){const J=u[Y+q];p[I++]=J}}}}return en(p,[i,t,n,c],e.dtype)}resizeNearestNeighborBackprop(e,t,n){Te([e,t],"resizeNearestNeighborBackprop");const[s,i,o,a]=t.shape,[,c,u]=e.shape,p=new Float32Array(s*i*o*a),m=this.readSync(e.dataId),y=[n&&c>1?i-1:i,n&&u>1?o-1:o],b=[n&&c>1?c-1:c,n&&u>1?u-1:u],w=y[0]/b[0],I=y[1]/b[1],T=1/w,v=1/I,N=Math.ceil(T)*2+2,E=Math.ceil(v)*2+2;for(let D=0;D<s;D++){const F=D*t.strides[0];for(let _=0;_<i;_++){const B=F+_*t.strides[1],U=Math.floor(_*T),Y=Math.floor(U-N/2);for(let q=0;q<o;q++){const J=B+q*t.strides[2],oe=Math.floor(q*v),ce=Math.floor(oe-E/2);for(let ue=0;ue<a;ue++){let he=0;for(let pe=0;pe<N;pe++){const le=pe+Y;if(le<0||le>=c)continue;const ye=F+le*e.strides[1],me=le*w,Ie=Math.min(i-1,n?Math.round(me):Math.floor(me));if(_!==Ie)continue;for(let Se=0;Se<E;Se++){const Ee=Se+ce;if(Ee<0||Ee>=u)continue;const We=ye+Ee*e.strides[2],Oe=Ee*I,$e=Math.min(o-1,n?Math.round(Oe):Math.floor(Oe));q===$e&&(he+=m[We+ue])}}p[J+ue]=he}}}}return Xa(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),u=e.size,p=new Float32Array(u);function m(y){const b=y%o;let w=y-b+Math.max(0,b-t);const I=y-b+Math.min(b+t,a);let T=0;for(;w<=I;w++){const v=c[w];T+=v*v}return T}for(let y=0;y<u;y++){const b=m(y),w=c[y]*Math.pow(n+s*b,-i);p[y]=w}return Xa(p,e.shape)}LRNGrad(e,t,n,s,i,o,a){Te(e,"LRNGrad");const c=e.shape[3],u=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 I=w%c,T=w-I+Math.max(0,I-s),v=w-I+Math.min(c,I+s+1);let N=0;for(let E=T;E<v;E++)N+=Math.pow(p[E],2);N=o*N+i;for(let E=T;E<v;E++){let D=-2*o*a*p[E]*m[w]/N;w===E&&(D+=Math.pow(N,-a)),D*=u[w],y[E]+=D}}return Xa(y,e.shape)}multinomial(e,t,n,s){Te(e,"multinomial");const i=t?e:Uo(e),o=i.shape[0],a=i.shape[1],c=ct([o,n],"int32"),u=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=qa(s.toString()),I=m*n;for(let T=0;T<n;++T){const v=w();u[I+T]=b.length;for(let N=0;N<b.length;N++)if(v<b[N]){u[I+T]=N;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 Gr(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 GY(o,a,n,s,i)}depthToSpace(e,t,n){k(n==="NHWC",()=>`Only NHWC dataFormat supported on CPU for depthToSpace. Got ${n}`),k(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,u=o*t,p=a/(t*t),m=this.readSync(e.dataId),y=new Float32Array(s*c*u*p);let b=0;for(let w=0;w<s;++w)for(let I=0;I<c;++I){const T=Math.floor(I/t),v=I%t;for(let N=0;N<u;++N){const E=Math.floor(N/t),D=N%t,F=(v*t+D)*p;for(let _=0;_<p;++_){const B=_+F,U=B+a*(E+o*(T+i*w));y[b++]=m[U]}}}return Xa(y,[s,c,u,p])}broadcastedBinaryOp(e,t,n,s){const i=nt(e.shape,t.shape),o=Qe(i,n),a=this.readSync(e.dataId),c=this.readSync(t.dataId),u=Eo(e.shape,i),p=Eo(t.shape,i),m=o.values;if(u.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 I=o.indexToLoc(w),T=I.slice(-e.rank);u.forEach(D=>T[D]=0);const v=y.locToIndex(T),N=I.slice(-t.rank);p.forEach(D=>N[D]=0);const E=b.locToIndex(N);m[w]=s(a[v],c[E])}}return o.toTensor()}split(e,t,n){return VY(e,t,n)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}cropAndResize(e,t,n,s,i,o){const[a,c,u,p]=e.shape,m=t.shape[0],[y,b]=s,w=Qe([m,y,b,p],"float32"),I=this.readSync(t.dataId),T=this.readSync(n.dataId),v=this.readSync(e.dataId),N=e.strides,E=w.strides;for(let D=0;D<m;D++){const F=D*4,_=I[F],B=I[F+1],U=I[F+2],Y=I[F+3],q=T[D];if(q>=a)continue;const J=y>1?(U-_)*(c-1)/(y-1):0,oe=b>1?(Y-B)*(u-1)/(b-1):0;for(let ce=0;ce<y;ce++){const ue=y>1?_*(c-1)+ce*J:.5*(_+U)*(c-1);if(ue<0||ue>c-1){for(let he=0;he<b;he++)for(let pe=0;pe<p;pe++){const le=pe+he*E[2]+ce*E[1]+D*E[0];w.values[le]=o}continue}if(i==="bilinear"){const he=Math.floor(ue),pe=Math.ceil(ue),le=ue-he;for(let ye=0;ye<b;ye++){const me=b>1?B*(u-1)+ye*oe:.5*(B+Y)*(u-1);if(me<0||me>u-1){for(let We=0;We<p;We++){const Oe=We+ye*E[2]+ce*E[1]+D*E[0];w.values[Oe]=o}continue}const Ie=Math.floor(me),Se=Math.ceil(me),Ee=me-Ie;for(let We=0;We<p;We++){let Oe=We+Ie*N[2]+he*N[1]+q*N[0];const $e=v[Oe];Oe=We+Se*N[2]+he*N[1]+q*N[0];const He=v[Oe];Oe=We+Ie*N[2]+pe*N[1]+q*N[0];const tt=v[Oe];Oe=We+Se*N[2]+pe*N[1]+q*N[0];const bt=v[Oe],Jt=$e+(He-$e)*Ee,dn=tt+(bt-tt)*Ee;Oe=We+ye*E[2]+ce*E[1]+D*E[0],w.values[Oe]=Jt+(dn-Jt)*le}}}else for(let he=0;he<b;++he){const pe=b>1?B*(u-1)+he*oe:.5*(B+Y)*(u-1);if(pe<0||pe>u-1){for(let me=0;me<p;me++){const Ie=me+he*E[2]+ce*E[1]+D*E[0];w.values[Ie]=o}continue}const le=Math.round(pe),ye=Math.round(ue);for(let me=0;me<p;me++){const Ie=me+le*N[2]+ye*N[1]+q*N[0],Se=me+he*E[2]+ce*E[1]+D*E[0];w.values[Se]=v[Ie]}}}}return w.toTensor()}sparseToDense(e,t,n,s){const{sliceRank:i,numUpdates:o,sliceSize:a,strides:c,outputSize:u}=Ua(t,e,n),p=!1;return this.scatter(e,t,n,u,a,o,i,c,s,p)}gatherND(e,t){const n=t.shape,s=n[n.length-1],[i,o,a,c]=Fd(e,t);if(o===0)return en([],i,e.dtype);const u=new kr([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 I=0;I<s;I++){const T=p[y*s+I];w+=T*c[I],b.push(T)}if(w<0||w>=e.size/a)throw new Error(`Invalid indices: ${b} does not index into ${e.shape}`);for(let I=0;I<a;I++)u.values[y*a+I]=m[w*a+I]}return u.toTensor().reshape(i)}scatterND(e,t,n){const{sliceRank:s,numUpdates:i,sliceSize:o,strides:a,outputSize:c}=Ua(t,e,n),u=Ne(0),p=!0;return this.scatter(e,t,n,c,o,i,s,a,u,p)}fill(e,t,n){n=n||Oa(t);const s=So(n,we(e));return s.fill(t),$s().makeTensor(s,e,n,this)}onesLike(e){if(e.dtype==="string")throw new Error("onesLike is not supported for string tensors");return this.fill(e.shape,1,e.dtype)}zerosLike(e){const t=So(e.dtype,we(e.shape));return this.makeOutput(t,e.shape,e.dtype)}linspace(e,t,n){return sw(e,t,n)}scatter(e,t,n,s,i,o,a,c,u,p){const m=[s/i,i],y=this.readSync(e.dataId),b=this.readSync(t.dataId);if(s===0)return en([],n,t.dtype);const w=new kr(m,t.dtype);w.values.fill(this.readSync(u.dataId)[0]);for(let I=0;I<o;I++){const T=[];let v=0;for(let N=0;N<a;N++){const E=y[I*a+N];T.push(E),v+=E*c[N]}if(v<0||v>=s/i)throw new Error(`Invalid indices: ${T} does not index into ${n}`);for(let N=0;N<i;N++)p?w.values[v*i+N]+=b[I*i+N]:w.values[v*i+N]=t.rank===0?b[0]:b[I*i+N]}return w.toTensor().reshape(n)}}function C0(e){const t=new Float32Array(e.length);for(let n=0;n<e.length;++n)t[n]=Math.abs(e[n]);return t}const KY=e=>{const{x:t}=e.inputs,n=e.backend;let s=new Float32Array(we(t.shape));if(t.dtype!=="complex64"){const i=n.data.get(t.dataId).values;s=C0(i)}else{const i=n.data.get(t.dataId),o=i.complexTensorInfos.real,a=i.complexTensorInfos.imag,c=n.data.get(o.dataId).values,u=n.data.get(a.dataId).values;for(let p=0;p<c.length;p++){const m=c[p],y=u[p];s[p]=Math.hypot(m,y)}}return n.makeOutput(s,t.shape,"float32")},XY={kernelName:fe,backendName:"cpu",kernelFunc:KY};function jo(e){return(t,n,s,i,o)=>{const a=nt(t,n),c=a.length,u=Ot(a),p=we(a),m=wn(o,p),y=t.length,b=n.length,w=Ot(t),I=Ot(n),T=Eo(t,a),v=Eo(n,a);if(T.length+v.length===0)for(let N=0;N<m.length;++N)m[N]=e(s[N%s.length],i[N%i.length]);else for(let N=0;N<m.length;++N){const E=Da(N,c,u),D=E.slice(-y);T.forEach(U=>D[U]=0);const F=ti(D,y,w),_=E.slice(-b);v.forEach(U=>_[U]=0);const B=ti(_,b,I);m[N]=e(s[F],i[B])}return[m,a]}}function pi(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"),u=n.data.get(c.dataId);return u.complexTensorInfos={real:n.makeTensorInfo(s.shape,"float32",o),imag:n.makeTensorInfo(i.shape,"float32",a)},c}const JY={kernelName:Rg,backendName:"cpu",kernelFunc:pi};function uc(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 ZY={kernelName:Sl,backendName:"cpu",kernelFunc:uc};function iu(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 QY={kernelName:ey,backendName:"cpu",kernelFunc:iu};function ru(e){const{inputs:t,backend:n,attrs:s}=e,{x:i}=t,{dtype:o}=s;if(o==="complex64"){if(i.dtype==="complex64")return uc({inputs:{x:i},backend:n});const a=ct(i.shape),c=ru({inputs:{x:i},backend:n,attrs:{dtype:"float32"}}),u=pi({inputs:{real:c,imag:a},backend:n});return a.dispose(),n.disposeIntermediateTensorInfo(c),u}if(i.dtype==="complex64"){const a=iu({inputs:{input:i},backend:n}),c=ru({inputs:{x:a},backend:n,attrs:{dtype:o}});return n.disposeIntermediateTensorInfo(a),c}if(!xy(i.dtype,o)){const a=uc({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=Dr([0],i.dtype),[u,p]=jo((m,y)=>m!==y?1:0)(i.shape,[],a,c,"bool");return n.makeTensorInfo(p,"bool",u)}throw new Error(`Error in Cast: failed to cast ${i.dtype} to ${o}`)}const eq={kernelName:ul,backendName:"cpu",kernelFunc:ru};function dc(e,t,n,s){return n==null?({inputs:i,backend:o})=>{const{a,b:c}=i,u=o;Te([a,c],e);const p=u.data.get(a.dataId).values,m=u.data.get(c.dataId).values,y=s||a.dtype,[b,w]=t(a.shape,c.shape,p,m,y);return u.makeTensorInfo(w,y,b)}:({inputs:i,backend:o})=>{const{a,b:c}=i,u=o;if(a.dtype==="complex64"||c.dtype==="complex64"){const p=ru({inputs:{x:a},backend:u,attrs:{dtype:"complex64"}}),m=u.data.get(p.dataId),y=m.complexTensorInfos.real,b=m.complexTensorInfos.imag,w=u.data.get(y.dataId).values,I=u.data.get(b.dataId).values,T=ru({inputs:{x:c},backend:u,attrs:{dtype:"complex64"}}),v=u.data.get(T.dataId),N=v.complexTensorInfos.real,E=v.complexTensorInfos.imag,D=u.data.get(N.dataId).values,F=u.data.get(E.dataId).values,[_,B,U]=n(a.shape,c.shape,w,I,D,F),Y=u.makeTensorInfo(U,"float32",_),q=u.makeTensorInfo(U,"float32",B),J=pi({inputs:{real:Y,imag:q},backend:u});return u.disposeIntermediateTensorInfo(p),u.disposeIntermediateTensorInfo(T),u.disposeIntermediateTensorInfo(Y),u.disposeIntermediateTensorInfo(q),J}else{const p=u.data.get(a.dataId).values,m=u.data.get(c.dataId).values,y=s||a.dtype,[b,w]=t(a.shape,c.shape,p,m,y);return u.makeTensorInfo(w,y,b)}}}function rS(e){return(t,n,s,i,o,a)=>{const c=nt(t,n),u=we(c),p=c.length,m=Ot(c),y=wn("float32",u),b=wn("float32",u),w=Eo(t,c),I=Eo(n,c),T=ir(s,i),v=ir(o,a),N=t.length,E=Ot(t),D=n.length,F=Ot(n);if(w.length+I.length===0)for(let _=0;_<y.length;_++){const B=_%T.length,U=_%v.length,Y=e(T[B*2],T[B*2+1],v[U*2],v[U*2+1]);y[_]=Y.real,b[_]=Y.imag}else for(let _=0;_<y.length;_++){const B=Da(_,p,m),U=B.slice(-N);w.forEach(ce=>U[ce]=0);const Y=ti(U,N,E),q=B.slice(-D);I.forEach(ce=>q[ce]=0);const J=ti(q,D,F),oe=e(T[Y*2],T[Y*2+1],v[J*2],v[J*2+1]);y[_]=oe.real,b[_]=oe.imag}return[y,b,c]}}const R0=jo((e,t)=>e+t),tq=rS((e,t,n,s)=>({real:e+n,imag:t+s})),O0=dc(xe,R0,tq),nq={kernelName:xe,backendName:"cpu",kernelFunc:O0};function pc(e){return(t,n,s)=>{const i=wn(n,t.length);for(let o=0;o<t.length;++o)i[o]=e(t[o],s);return i}}function Tt(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,u=c.data.get(a.dataId).values,p=we(a.shape),m=n||a.dtype,y=So(m,p);for(let b=0;b<p;++b)y[b]=t(u[b],i);return c.makeTensorInfo(a.shape,m,y)}}function mc(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,u=c.data.get(a.dataId).values,p=n||a.dtype,m=t(u,p,i);return c.makeTensorInfo(a.shape,p,m)}}const E0=pc(e=>Math.ceil(e)),sq=mc(dl,E0),iq={kernelName:dl,backendName:"cpu",kernelFunc:sq};const D0=pc(e=>Math.exp(e)),rq=mc(yl,D0),oq={kernelName:yl,backendName:"cpu",kernelFunc:rq};const k0=pc(e=>Math.expm1(e)),aq=mc(bl,k0),cq={kernelName:bl,backendName:"cpu",kernelFunc:aq};const F0=pc(e=>Math.floor(e)),lq=mc(wl,F0),hq={kernelName:wl,backendName:"cpu",kernelFunc:lq};const _0=pc(e=>Math.log(e)),uq=mc(Al,_0),dq={kernelName:Al,backendName:"cpu",kernelFunc:uq};function W0(e,t,n,s){const i=wn(s,we(n));for(let o=0;o<i.length;++o){const a=o*t;let c=e[a];for(let u=0;u<t;++u){const p=e[a+u];p>c&&(c=p)}i[o]=c}return i}const $0=jo((e,t)=>e*t),pq=rS((e,t,n,s)=>({real:e*n-t*s,imag:e*s+t*n})),U0=dc(Rl,$0,pq),mq={kernelName:Rl,backendName:"cpu",kernelFunc:U0};const B0=pc(e=>1/Math.sqrt(e)),fq=mc(kl,B0),gq={kernelName:kl,backendName:"cpu",kernelFunc:fq};function M0(e,t,n,s,i){const o=Xy(s,t,n),a=we(n),c=Ot(s);if(o){const p=Jy(t,c);return e.subarray(p,p+a)}const u=wn(i,a);for(let p=0;p<a;++p){const m=n.length,y=Ot(n),b=Da(p,m,y),w=b.map((T,v)=>T+t[v]),I=ti(w,s.length,c);u[p]=e[I]}return u}function oS(e){const{inputs:t,backend:n,attrs:s}=e,{x:i}=t,{begin:o,size:a}=s;Te(i,"slice");const[c,u]=$d(i,o,a);Ky(i,c,u);const p=n.data.get(i.dataId).values,m=M0(p,c,u,i.shape,i.dtype);return n.makeTensorInfo(u,i.dtype,m)}const yq={kernelName:pd,backendName:"cpu",kernelFunc:oS};const P0=jo((e,t)=>e-t),bq=rS((e,t,n,s)=>({real:e-n,imag:t-s})),z0=dc(Ml,P0,bq),wq={kernelName:Ml,backendName:"cpu",kernelFunc:z0};function aS(e,t,n,s,i){const o=t.length,a=we(t),c=Ot(t),u=Ot(i),p=wn(n,we(i));for(let m=0;m<a;++m){const y=Da(m,o,c),b=new Array(y.length);for(let I=0;I<b.length;I++)b[I]=y[s[I]];const w=ti(b,o,u);p[w]=e[m]}return p}function G0(e,t,n,s){const i=ft(t,n)[0],o=[1,n[0],1];for(let I=0;I<i;I++)o[0]*=n[I];o[1]=n[i];for(let I=i+1;I<n.length;I++)o[2]*=n[I];const a={},c=new Int32Array(n[i]),u=new kr(o,s,e),p=[],m=o[0]===1&&o[2]===1;for(let I=0;I<n[i];I++){let T;if(m)T=e[I].toString();else{const v=[];for(let N=0;N<o[0];N++)for(let E=0;E<o[2];E++)v.push(u.get(N,I,E));T=v.join(",")}if(a[T]!==void 0)c[I]=a[T];else{const v=Object.keys(a).length;a[T]=v,c[I]=v,p.push(I)}}const y=o.slice();y[1]=Object.keys(a).length;const b=new kr(y,s);p.forEach((I,T)=>{for(let v=0;v<o[0];v++)for(let N=0;N<o[2];N++)b.set(u.get(v,I,N),v,T,N)});const w=n.slice();return w[i]=y[1],{outputValues:b.values,outputShape:w,indices:c}}var Lq=Object.freeze({__proto__:null,simpleAbsImpl:C0,addImpl:R0,ceilImpl:E0,expImpl:D0,expm1Impl:k0,floorImpl:F0,logImpl:_0,maxImpl:W0,multiplyImpl:$0,rsqrtImpl:B0,sliceImpl:M0,subImpl:P0,transposeImpl:aS,uniqueImpl:G0});const Sq="2.6.0";tb("cpu",()=>new jY,1);const Iq=Tt(de,e=>Math.acos(e)),xq={kernelName:de,backendName:"cpu",kernelFunc:Iq};const Tq=Tt(Ae,e=>Math.acosh(e)),Aq={kernelName:Ae,backendName:"cpu",kernelFunc:Tq};const vq=Tt(Fn,e=>Math.asin(e)),Nq={kernelName:Fn,backendName:"cpu",kernelFunc:vq};const Cq=Tt(vn,e=>Math.asinh(e)),Rq={kernelName:vn,backendName:"cpu",kernelFunc:Cq};const Oq=Tt(Nn,e=>Math.atan(e)),Eq={kernelName:Nn,backendName:"cpu",kernelFunc:Oq};const Dq=Tt(Qs,e=>Math.atanh(e)),kq={kernelName:Qs,backendName:"cpu",kernelFunc:Dq};function cS(e,t,n,s,i,o){const a=i.strideHeight,c=i.strideWidth,u=i.dilationHeight,p=i.dilationWidth,m=i.effectiveFilterHeight,y=i.effectiveFilterWidth,b=i.padInfo.top,w=i.padInfo.left,I=o==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,T=Qe(i.outShape,n),v=T.values,N=i.outShape[1]*i.outShape[2]*i.outShape[3],E=i.outShape[2]*i.outShape[3],D=i.outShape[3];for(let F=0;F<i.batchSize;++F){const _=F*N,B=F*s[0];for(let U=0;U<i.inChannels;++U)for(let Y=0;Y<i.outHeight;++Y){const q=Y*a-b,J=Math.max(0,q),oe=Math.min(i.inHeight,m+q),ce=_+Y*E;for(let ue=0;ue<i.outWidth;++ue){const he=ue*c-w,pe=Math.max(0,he),le=Math.min(i.inWidth,y+he);let ye=I,me=0,Ie=0;for(let Ee=J;Ee<oe;Ee+=u){const We=B+Ee*s[1];for(let Oe=pe;Oe<le;Oe+=p){const $e=We+Oe*s[2],He=e[$e+U];o==="max"&&He>ye?ye=He:o==="avg"&&(me+=He,Ie++)}if(isNaN(ye))break}const Se=ce+ue*D+U;v[Se]=o==="avg"?me/Ie:ye}}}return T}function V0(e,t,n,s,i=!1,o=!1){const a=Qe(s.outShape,"int32"),c=s.strideHeight,u=s.strideWidth,p=s.dilationHeight,m=s.dilationWidth,y=s.effectiveFilterHeight,b=s.effectiveFilterWidth,w=s.padInfo.top,I=s.padInfo.left,T=Qe(t,n,e);for(let v=0;v<s.batchSize;++v)for(let N=0;N<s.inChannels;++N)for(let E=0;E<s.outHeight;++E){const D=E*c-w;let F=D;for(;F<0;)F+=p;const _=Math.min(s.inHeight,y+D);for(let B=0;B<s.outWidth;++B){const U=B*u-I;let Y=U;for(;Y<0;)Y+=m;const q=Math.min(s.inWidth,b+U);let J=Number.NEGATIVE_INFINITY,oe=-1;for(let ce=F;ce<_;ce+=p){const ue=ce-D;for(let he=Y;he<q;he+=m){const pe=he-U,le=T.get(v,ce,he,N);le>J&&(J=le,i?oe=o?((v*s.inHeight+ce)*s.inWidth+he)*s.inChannels+N:(ce*s.inWidth+he)*s.inChannels+N:oe=ue*b+pe)}}a.set(oe,v,E,B,N)}}return a}function Fq(e){const{inputs:t,backend:n,attrs:s}=e,{x:i}=t;Te(i,"avgPool");const{filterSize:o,strides:a,pad:c,dimRoundingMode:u}=s,p=1;k(on(a,p),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${p}'`);const m=Wn(i.shape,o,a,p,c,u);let y;if(m.filterWidth===1&&m.filterHeight===1&&ot(m.inShape,m.outShape))y=uc({inputs:{x:i},backend:n});else{const b=n.data.get(i.dataId).values,w=Ot(i.shape),I=cS(b,i.shape,i.dtype,w,m,"avg");y=n.makeTensorInfo(m.outShape,i.dtype,I.values)}return y}const _q={kernelName:ei,backendName:"cpu",kernelFunc:Fq};function Wq(e){const{inputs:t,backend:n,attrs:s}=e,{dy:i,input:o}=t,a=o;Te([i,o],"avgPoolBackprop");const{filterSize:c,strides:u,pad:p}=s,m=Wn(a.shape,c,u,1,p),y=m.strideHeight,b=m.strideWidth,w=m.filterHeight,I=m.filterWidth,T=m.dilationHeight,v=m.dilationWidth,N=m.effectiveFilterHeight,E=m.effectiveFilterWidth,D=E-1-m.padInfo.left,F=N-1-m.padInfo.top,_=Qe(a.shape,"float32"),B=1/(w*I),U=n.data.get(i.dataId).values,Y=Qe(i.shape,"float32",U);for(let q=0;q<m.batchSize;++q)for(let J=0;J<m.inChannels;++J)for(let oe=0;oe<m.inHeight;++oe)for(let ce=0;ce<m.inWidth;++ce){const ue=oe-F,he=ce-D;let pe=0;for(let le=0;le<N;le+=T){const ye=(ue+le)/y;if(ye<0||ye>=m.outHeight||Math.floor(ye)!==ye)continue;for(let me=0;me<E;me+=v){const Ie=(he+me)/b;if(Ie<0||Ie>=m.outWidth||Math.floor(Ie)!==Ie)continue;const Se=Y.get(q,ye,Ie,J);pe+=Se}}_.set(pe*B,q,oe,ce,J)}return n.makeTensorInfo(_.shape,_.dtype,_.values)}const $q={kernelName:xa,backendName:"cpu",kernelFunc:Wq};function Uq(e){const{inputs:t,backend:n,attrs:s}=e,{x:i,scale:o,offset:a,mean:c,variance:u}=t;k(c.shape.length===u.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),k(a==null||c.shape.length===a.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),k(o==null||c.shape.length===o.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks."),Te([i,c,u,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(u.dataId).values,w=o?n.data.get(o.dataId).values:new Float32Array([1]),I=a?n.data.get(a.dataId).values:new Float32Array([0]),T=new Float32Array(m.length),v=I.length,N=w.length,E=b.length,D=y.length;let F=0,_=0,B=0,U=0;for(let Y=0;Y<m.length;++Y)T[Y]=I[F++]+(m[Y]-y[_++])*w[B++]/Math.sqrt(b[U++]+p),F>=v&&(F=0),_>=D&&(_=0),B>=N&&(B=0),U>=E&&(U=0);return n.makeTensorInfo(i.shape,i.dtype,T)}const Bq={kernelName:Ll,backendName:"cpu",kernelFunc:Uq};const Mq=Tt(pl,(e,t)=>{const n=t;return e>n.clipValueMax?n.clipValueMax:e<n.clipValueMin?n.clipValueMin:e}),Pq={kernelName:pl,backendName:"cpu",kernelFunc:Mq};function dm(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 zq={kernelName:Mg,backendName:"cpu",kernelFunc:dm};function eo(e){const{inputs:t,backend:n,attrs:s}=e,{x:i}=t,{shape:o}=s,a=we(i.shape),c=Id(o,a),u=we(c);k(a===u,()=>`The new shape (${c}) has ${u} 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 Gq={kernelName:El,backendName:"cpu",kernelFunc:eo};function ou(e){const{inputs:t,backend:n,attrs:s}=e,{axis:i}=s,o=ft(i,t[0].shape)[0];let a=Ur(t.map(w=>w.shape),o);if(we(a)===0)return n.makeTensorInfo(a,t[0].dtype,[]);const c=t.filter(w=>we(w.shape)>0);if(c.length===1)return c[0];const u=c.map(w=>w.shape);if(mb(u,o),c[0].dtype==="complex64"){const w=c.map(E=>iu({inputs:{input:E},backend:n})),I=c.map(E=>dm({inputs:{input:E},backend:n})),T=ou({inputs:w,backend:n,attrs:{axis:i}}),v=ou({inputs:I,backend:n,attrs:{axis:i}}),N=pi({inputs:{real:T,imag:v},backend:n});return w.forEach(E=>n.disposeIntermediateTensorInfo(E)),I.forEach(E=>n.disposeIntermediateTensorInfo(E)),n.disposeIntermediateTensorInfo(T),n.disposeIntermediateTensorInfo(v),N}const p=c.map(w=>{const I=we(w.shape.slice(o)),T=[-1,I];return eo({inputs:{x:w},backend:n,attrs:{shape:T}})});a=Ur(p.map(w=>w.shape),1);const m=wn(c[0].dtype,we(a));if(p[0].shape[0]===1){let w=0;p.forEach(I=>{const T=n.data.get(I.dataId).values,v=we(I.shape);m.set(T,w),w+=v})}else{let w=0;p.forEach(I=>{const T=n.data.get(I.dataId).values;let v=0;for(let N=0;N<I.shape[0];++N){const E=N*a[1]+w;for(let D=0;D<I.shape[1];++D)m[E+D]=T[v++]}w+=I.shape[1]})}const y=Ur(c.map(w=>w.shape),o),b=n.makeTensorInfo(y,t[0].dtype,m);return p.forEach(w=>n.disposeIntermediateTensorInfo(w)),b}const Vq={kernelName:td,backendName:"cpu",kernelFunc:ou};const Hq=Tt(Ta,e=>Math.cos(e)),Yq={kernelName:Ta,backendName:"cpu",kernelFunc:Hq};const qq=Tt(ml,e=>Math.cosh(e)),jq={kernelName:ml,backendName:"cpu",kernelFunc:qq};const Kq={kernelName:nd,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:s,filter:i}=e,{strides:o,pad:a,dilations:c}=n,u=t,p=u.data.get(s.dataId).values,m=s.shape.length,y=u.data.get(i.dataId).values,b=i.shape.length,{batchSize:w,inHeight:I,inWidth:T,inChannels:v,outHeight:N,outWidth:E,padInfo:D,strideHeight:F,strideWidth:_,filterHeight:B,filterWidth:U,dilationHeight:Y,dilationWidth:q,outShape:J}=zd(s.shape,i.shape,o,a,"NHWC",c),oe=we(J),ce=J.length,ue=So(s.dtype,oe);for(let pe=0;pe<w;++pe)for(let le=0;le<N;++le){const ye=le*F-D.top;for(let me=0;me<E;++me){const Ie=me*_-D.left;for(let Se=0;Se<v;++Se){let Ee=Number.MIN_SAFE_INTEGER;for(let Oe=0;Oe<B;++Oe){const $e=ye+Oe*Y;if($e>=0&&$e<I)for(let He=0;He<U;++He){const tt=Ie+He*q;if(tt>=0&&tt<T){const bt=ti([pe,$e,tt,Se],m,Ot(s.shape)),Jt=ti([Oe,He,Se],b,Ot(i.shape)),dn=p[bt]+y[Jt];dn>Ee&&(Ee=dn)}}}const We=ti([pe,le,me,Se],ce,Ot(J));ue[We]=Ee}}}const he=u.write(Dr(ue,s.dtype),J,s.dtype);return{dataId:he,shape:J,dtype:s.dtype}}};const Xq={kernelName:id,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:s,filter:i,dy:o}=e,{strides:a,pad:c,dilations:u}=n,p=t,m=Ls(s.shape,p.data.get(s.dataId).values),y=Ls(i.shape,p.data.get(i.dataId).values),{batchSize:b,inHeight:w,inWidth:I,inChannels:T,outHeight:v,outWidth:N,padInfo:E,strideHeight:D,strideWidth:F,filterHeight:_,filterWidth:B,dilationHeight:U,dilationWidth:Y,outShape:q}=zd(s.shape,i.shape,a,c,"NHWC",u);k(o.rank===q.length,()=>`Error in ${id}, dy must have the same rank as output ${q.length}, but got ${o.rank}`);const J=Ls(q,p.data.get(o.dataId).values),oe=vy(i.shape,i.dtype);for(let ue=0;ue<b;++ue)for(let he=0;he<v;++he){const pe=he*D-E.top;for(let le=0;le<N;++le){const ye=le*F-E.left;for(let me=0;me<T;++me){let Ie=Number.MIN_SAFE_INTEGER,Se=0,Ee=0;for(let We=0;We<_;++We){const Oe=pe+We*U;if(Oe>=0&&Oe<w)for(let $e=0;$e<B;++$e){const He=ye+$e*Y;if(He>=0&&He<I){const tt=m[ue][Oe][He][me]+y[We][$e][me];tt>Ie&&(Ie=tt,Se=We,Ee=$e)}}}oe[Se][Ee][me]+=J[ue][he][le][me]}}}const ce=p.write(Dr(oe,s.dtype),i.shape,i.dtype);return{dataId:ce,shape:i.shape,dtype:i.dtype}}};const Jq={kernelName:sd,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:s,filter:i,dy:o}=e,{strides:a,pad:c,dilations:u}=n,p=t,m=Ls(s.shape,p.data.get(s.dataId).values),y=Ls(i.shape,p.data.get(i.dataId).values),{batchSize:b,inHeight:w,inWidth:I,inChannels:T,outHeight:v,outWidth:N,padInfo:E,strideHeight:D,strideWidth:F,filterHeight:_,filterWidth:B,dilationHeight:U,dilationWidth:Y,outShape:q}=zd(s.shape,i.shape,a,c,"NHWC",u);k(o.rank===q.length,()=>`Error in ${sd}, dy must have the same rank as output ${q.length}, but got ${o.rank}`);const J=Ls(q,p.data.get(o.dataId).values),oe=vy(s.shape,s.dtype);for(let ue=0;ue<b;++ue)for(let he=0;he<v;++he){const pe=he*D-E.top;for(let le=0;le<N;++le){const ye=le*F-E.left;for(let me=0;me<T;++me){let Ie=Number.MIN_SAFE_INTEGER,Se=pe<0?0:pe,Ee=ye<0?0:ye;for(let We=0;We<_;++We){const Oe=pe+We*U;if(Oe>=0&&Oe<w)for(let $e=0;$e<B;++$e){const He=ye+$e*Y;if(He>=0&&He<I){const tt=m[ue][Oe][He][me]+y[We][$e][me];tt>Ie&&(Ie=tt,Se=Oe,Ee=He)}}}oe[ue][Se][Ee][me]+=J[ue][he][le][me]}}}const ce=p.write(Dr(oe,s.dtype),s.shape,s.dtype);return{dataId:ce,shape:s.shape,dtype:s.dtype}}};const Zq=jo((e,t)=>e/t),Qq=dc(Aa,Zq),lS={kernelName:Aa,backendName:"cpu",kernelFunc:Qq};const e4=Tt(fl,e=>e>=0?e:Math.exp(e)-1),t4={kernelName:fl,backendName:"cpu",kernelFunc:e4};const n4=Xb,s4=Jb,i4=Zb,r4=Qb,o4=ew,a4=tw,c4=Tt(gl,e=>{const t=Math.sign(e),n=Math.abs(e),s=1/(1+n4*n);return t*(1-((((a4*s+o4)*s+r4)*s+i4)*s+s4)*s*Math.exp(-n*n))}),l4={kernelName:gl,backendName:"cpu",kernelFunc:c4};function H0(e,t,n){const s=e.shape,i=s[0],o=s[1],a=n.data.get(e.dataId),c=a.complexTensorInfos.real,u=a.complexTensorInfos.imag,p=[i,o],m=we(p),y=wn("float32",m),b=wn("float32",m);for(let v=0;v<i;v++){const N=oS({inputs:{x:c},backend:n,attrs:{begin:[v,0],size:[1,o]}}),E=oS({inputs:{x:u},backend:n,attrs:{begin:[v,0],size:[1,o]}}),D=pi({inputs:{real:N,imag:E},backend:n}),{real:F,imag:_}=h4(D,t,n),B=ir(F,_);for(let U=0;U<o;U++){const Y=nw(B,U);y[v*o+U]=Y.real,b[v*o+U]=Y.imag}n.disposeIntermediateTensorInfo(N),n.disposeIntermediateTensorInfo(E),n.disposeIntermediateTensorInfo(D)}const w=n.makeTensorInfo(p,"float32",y),I=n.makeTensorInfo(p,"float32",b),T=pi({inputs:{real:w,imag:I},backend:n});return n.disposeIntermediateTensorInfo(w),n.disposeIntermediateTensorInfo(I),T}function h4(e,t,n){const s=we(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(u4(s)){const c=hS(o,a,s,t,n),u=[e.shape[0],e.shape[1]];if(t){const p=n.makeTensorInfo(u,"float32",c.real),m=n.makeTensorInfo(u,"float32",c.imag),y=n.makeTensorInfo([],"float32",lT(s,"float32")),b=uc({inputs:{x:y},backend:n}),w=lS.kernelFunc({inputs:{a:p,b:y},backend:n}),I=lS.kernelFunc({inputs:{a:m,b},backend:n}),T=n.data.get(w.dataId).values,v=n.data.get(I.dataId).values;return n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(y),n.disposeIntermediateTensorInfo(b),n.disposeIntermediateTensorInfo(w),n.disposeIntermediateTensorInfo(I),{real:T,imag:v}}return c}else{const c=ir(o,a),u=d4(c,s,t);return ev(u)}}function u4(e){return(e&e-1)===0}function hS(e,t,n,s,i){if(n===1)return{real:e,imag:t};const o=ir(e,t),a=n/2,c=tv(o),u=c.real,p=c.imag,m=[u.length],y=i.makeTensorInfo(m,"float32",u),b=i.makeTensorInfo(m,"float32",p),w=pi({inputs:{real:y,imag:b},backend:i}),I=nv(o),T=I.real,v=I.imag,N=[T.length],E=i.makeTensorInfo(N,"float32",T),D=i.makeTensorInfo(N,"float32",v),F=pi({inputs:{real:E,imag:D},backend:i}),_=hS(u,p,a,s,i),B=_.real,U=_.imag,Y=[B.length],q=i.makeTensorInfo(Y,"float32",B),J=i.makeTensorInfo(Y,"float32",U),oe=pi({inputs:{real:q,imag:J},backend:i}),ce=hS(T,v,a,s,i),ue=ce.real,he=ce.imag,pe=[ue.length],le=i.makeTensorInfo(pe,"float32",ue),ye=i.makeTensorInfo(pe,"float32",he),me=pi({inputs:{real:le,imag:ye},backend:i}),Ie=iv(n,s),Se=[Ie.real.length],Ee=i.makeTensorInfo(Se,"float32",Ie.real),We=i.makeTensorInfo(Se,"float32",Ie.imag),Oe=pi({inputs:{real:Ee,imag:We},backend:i}),$e=U0({inputs:{a:Oe,b:me},backend:i}),He=O0({inputs:{a:oe,b:$e},backend:i}),tt=z0({inputs:{a:oe,b:$e},backend:i}),bt=iu({inputs:{input:He},backend:i}),Jt=iu({inputs:{input:tt},backend:i}),dn=dm({inputs:{input:He},backend:i}),ds=dm({inputs:{input:tt},backend:i}),Ht=ou({inputs:[bt,Jt],backend:i,attrs:{axis:0}}),Bn=ou({inputs:[dn,ds],backend:i,attrs:{axis:0}}),mi=i.data.get(Ht.dataId).values,Rs=i.data.get(Bn.dataId).values;return i.disposeIntermediateTensorInfo(y),i.disposeIntermediateTensorInfo(b),i.disposeIntermediateTensorInfo(w),i.disposeIntermediateTensorInfo(E),i.disposeIntermediateTensorInfo(D),i.disposeIntermediateTensorInfo(F),i.disposeIntermediateTensorInfo(q),i.disposeIntermediateTensorInfo(J),i.disposeIntermediateTensorInfo(oe),i.disposeIntermediateTensorInfo(le),i.disposeIntermediateTensorInfo(ye),i.disposeIntermediateTensorInfo(me),i.disposeIntermediateTensorInfo(Ee),i.disposeIntermediateTensorInfo(We),i.disposeIntermediateTensorInfo(Oe),i.disposeIntermediateTensorInfo($e),i.disposeIntermediateTensorInfo(He),i.disposeIntermediateTensorInfo(tt),i.disposeIntermediateTensorInfo(bt),i.disposeIntermediateTensorInfo(dn),i.disposeIntermediateTensorInfo(Jt),i.disposeIntermediateTensorInfo(ds),i.disposeIntermediateTensorInfo(Ht),i.disposeIntermediateTensorInfo(Bn),{real:mi,imag:Rs}}function d4(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 u=rv(i*c,t,n),p=nw(e,c);o+=p.real*u.real-p.imag*u.imag,a+=p.real*u.imag+p.imag*u.real}n&&(o/=t,a/=t),sv(s,o,a,i)}return s}function p4(e){const{inputs:t,backend:n}=e,{input:s}=t,i=we(s.shape),o=s.shape[s.shape.length-1],a=i/o,c=eo({inputs:{x:s},backend:n,attrs:{shape:[a,o]}}),u=H0(c,!1,n),p=eo({inputs:{x:u},backend:n,attrs:{shape:s.shape}});return n.disposeIntermediateTensorInfo(c),n.disposeIntermediateTensorInfo(u),p}const m4={kernelName:_g,backendName:"cpu",kernelFunc:p4};const f4={kernelName:rd,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{image:s}=e,i=n,o=wn(s.dtype,we(s.shape)),[a,c,u,p]=s.shape,m=i.data.get(s.dataId).values;for(let b=0;b<a;b++){const w=b*u*c*p;for(let I=0;I<c;I++){const T=I*(u*p);for(let v=0;v<u;v++){const N=v*p;for(let E=0;E<p;E++){const D=[a,I,v,E],F=D[2],_=Math.round(u-F),B=w+T+N+E;let U=m[B];if(_>=0&&_<u){const Y=_*p,q=w+T+Y+E;U=m[q]}o[B]=U}}}}const y=i.write(o,s.shape,s.dtype);return{dataId:y,shape:s.shape,dtype:s.dtype}}};function g4(e){const{inputs:t,backend:n}=e,{input:s}=t,i=we(s.shape),o=s.shape[s.shape.length-1],a=i/o,c=eo({inputs:{x:s},backend:n,attrs:{shape:[a,o]}}),u=H0(c,!0,n),p=eo({inputs:{x:u},backend:n,attrs:{shape:s.shape}});return n.disposeIntermediateTensorInfo(c),n.disposeIntermediateTensorInfo(u),p}const y4={kernelName:Bg,backendName:"cpu",kernelFunc:g4};const b4=Tt(Il,e=>Number.isFinite(e)?1:0,"bool"),w4={kernelName:Il,backendName:"cpu",kernelFunc:b4};const L4=Tt(xl,e=>Math.abs(e)===Infinity?1:0,"bool"),S4={kernelName:xl,backendName:"cpu",kernelFunc:L4};const I4=Tt(Tl,e=>Number.isNaN(e)?1:0,"bool"),x4={kernelName:Tl,backendName:"cpu",kernelFunc:I4};const T4=Tt(vl,e=>Math.log1p(e)),A4={kernelName:vl,backendName:"cpu",kernelFunc:T4};const v4=Tt(od,e=>e?0:1,"bool"),N4={kernelName:od,backendName:"cpu",kernelFunc:v4};const C4={kernelName:Nl,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 u=c.length,p=ft(i,c);let m=p;const y=_n(m,u);let b=a.data.get(s.dataId).values;if(y!=null){const D=new Array(u);for(let F=0;F<D.length;F++)D[F]=c[y[F]];b=aS(b,c,s.dtype,y,D),m=Is(m.length,u),c=D}Te(s,"max"),ss("max",m,u);const[w,I]=On(c,m),T=we(I),v=W0(b,T,w,s.dtype),N=a.write(v,w,s.dtype);let E=w;if(o){const D=En(w,p);E=D}return{dataId:N,shape:E,dtype:s.dtype}}};function R4(e){const{inputs:t,backend:n,attrs:s}=e,{x:i}=t;Te(i,"maxPool");const{filterSize:o,strides:a,pad:c,dimRoundingMode:u}=s,p=1;k(on(a,p),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${p}'`);const m=Wn(i.shape,o,a,p,c,u);let y;if(m.filterWidth===1&&m.filterHeight===1&&ot(m.inShape,m.outShape))y=uc({inputs:{x:i},backend:n});else{const b=n.data.get(i.dataId).values,w=Ot(i.shape),I=cS(b,i.shape,i.dtype,w,m,"max");y=n.makeTensorInfo(m.outShape,i.dtype,I.values)}return y}const O4={kernelName:Cl,backendName:"cpu",kernelFunc:R4};function E4(e){const{inputs:t,backend:n,attrs:s}=e,{dy:i,input:o,output:a}=t,c=o;Te([o,a],"maxPoolBackprop");const{filterSize:u,strides:p,pad:m,dimRoundingMode:y}=s,b=Wn(c.shape,u,p,1,m,y),w=n.data.get(c.dataId).values,I=Qe(b.outShape,c.dtype,V0(w,c.shape,c.dtype,b).values),T=b.strideHeight,v=b.strideWidth,N=b.dilationHeight,E=b.dilationWidth,D=b.effectiveFilterHeight,F=b.effectiveFilterWidth,_=F-1-b.padInfo.left,B=D-1-b.padInfo.top,U=Qe(c.shape,"float32"),Y=n.data.get(i.dataId).values,q=Qe(i.shape,"float32",Y);for(let J=0;J<b.batchSize;++J)for(let oe=0;oe<b.inChannels;++oe)for(let ce=0;ce<b.inHeight;++ce)for(let ue=0;ue<b.inWidth;++ue){const he=ce-B,pe=ue-_;let le=0;for(let ye=0;ye<D;ye+=N){const me=(he+ye)/T;if(me<0||me>=b.outHeight||Math.floor(me)!==me)continue;for(let Ie=0;Ie<F;Ie+=E){const Se=(pe+Ie)/v;if(Se<0||Se>=b.outWidth||Math.floor(Se)!==Se)continue;const Ee=D*F-1-I.get(J,me,Se,oe),We=ye*F+Ie,Oe=Ee===We?1:0;if(Oe===0)continue;const $e=q.get(J,me,Se,oe);le+=$e*Oe}}U.set(le,J,ce,ue,oe)}return n.makeTensorInfo(U.shape,U.dtype,U.values)}const D4={kernelName:ad,backendName:"cpu",kernelFunc:E4};function k4(e,t,n,s,i){const o=Ot(t),a=cS(e,t,n,o,i,"max"),c=V0(e,t,n,i,!0,s);return[a.values,c.values]}const F4={kernelName:cd,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:s}=e,{filterSize:i,strides:o,pad:a,includeBatchInIndex:c}=t,u=n;Te(s,"MaxPoolWithArgmax");const p=u.data.get(s.dataId).values,m=Wn(s.shape,i,o,[1,1],a),[y,b]=k4(p,s.shape,s.dtype,c,m),w=u.write(y,m.outShape,s.dtype),I=u.write(b,m.outShape,s.dtype);return[{dataId:w,shape:m.outShape,dtype:s.dtype},{dataId:I,shape:m.outShape,dtype:"int32"}]}};const _4=Lp,W4={kernelName:hd,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{boxes:s,scores:i}=e,{maxOutputSize:o,iouThreshold:a,scoreThreshold:c,padToMaxOutputSize:u}=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}=_4(m,y,o,a,c,u);return[b,w]}};const $4=Sp,U4={kernelName:ud,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{boxes:s,scores:i}=e,{maxOutputSize:o,iouThreshold:a,scoreThreshold:c,softNmsSigma:u}=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,I=c,T=u,{selectedIndices:v,selectedScores:N}=$4(m,y,b,w,I,T);return[v,N]}};const B4=jo((e,t)=>e!==t?1:0),M4=dc(ld,B4,null,"bool"),P4={kernelName:ld,backendName:"cpu",kernelFunc:M4};function z4(e){const{inputs:t,backend:n,attrs:s}=e,{x:i}=t,{paddings:o,constantValue:a}=s;Te(i,"pad");const c=o.map((E,D)=>E[0]+i.shape[D]+E[1]),u=o.map(E=>E[0]),p=n.data.get(i.dataId).values,m=we(i.shape),y=i.shape.length,b=Ot(i.shape),w=we(c),I=c.length,T=Ot(c),v=wn(i.dtype,w);a!==0&&v.fill(a);for(let E=0;E<m;E++){const D=Da(E,y,b),F=D.map((B,U)=>B+u[U]),_=ti(F,I,T);v[_]=p[E]}const N=n.write(v,c,i.dtype);return{dataId:N,shape:c,dtype:i.dtype}}const Y0={kernelName:dd,backendName:"cpu",kernelFunc:z4};const G4=Tt(Ol,e=>1/e),V4={kernelName:Ol,backendName:"cpu",kernelFunc:G4};const H4={kernelName:bd,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{image:s}=e,{radians:i,fillValue:o,center:a}=t,c=n,u=wn(s.dtype,we(s.shape)),[p,m,y,b]=s.shape,[w,I]=qb(a,m,y),T=255,v=Math.sin(i),N=Math.cos(i),E=c.data.get(s.dataId).values;for(let F=0;F<p;F++){const _=F*y*m*b;for(let B=0;B<m;B++){const U=B*(y*b);for(let Y=0;Y<y;Y++){const q=Y*b;for(let J=0;J<b;J++){const oe=[p,B,Y,J],ce=oe[2],ue=oe[1];let he=(ce-w)*N-(ue-I)*v,pe=(ce-w)*v+(ue-I)*N;he=Math.round(he+w),pe=Math.round(pe+I);let le=o;if(typeof o!="number"&&(J===3?le=T:le=o[J]),he>=0&&he<y&&pe>=0&&pe<m){const me=pe*(y*b),Ie=he*b,Se=_+me+Ie+J;le=E[Se]}const ye=_+U+q+J;u[ye]=le}}}}const D=c.write(u,s.shape,s.dtype);return{dataId:D,shape:s.shape,dtype:s.dtype}}};const Y4=Tt(Dl,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}),q4={kernelName:Dl,backendName:"cpu",kernelFunc:Y4};const j4=xp,K4=Tp,X4=Tt(Fl,e=>e>=0?K4*e:j4*(Math.exp(e)-1)),J4={kernelName:Fl,backendName:"cpu",kernelFunc:X4};const Z4=Tt($l,e=>1/(1+Math.exp(-e))),Q4={kernelName:$l,backendName:"cpu",kernelFunc:Z4};const ej=Tt(Wl,e=>e<0?-1:e>0?1:0),tj={kernelName:Wl,backendName:"cpu",kernelFunc:ej};const nj=Tt(va,e=>Math.sin(e)),sj={kernelName:va,backendName:"cpu",kernelFunc:nj};const ij=Tt(_l,e=>Math.sinh(e)),rj={kernelName:_l,backendName:"cpu",kernelFunc:ij};const oj=11920928955078125e-23,q0=Math.log(oj)+2,aj=Tt(Ul,e=>{const t=e>-q0,n=e<q0,s=Math.exp(e);let i;return n?i=s:t?i=e:i=Math.log(1+s),i}),cj={kernelName:Ul,backendName:"cpu",kernelFunc:aj};function j0(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 u=s.data.get(i.dataId).values,p=aS(u,i.shape,i.dtype,o,c),m=s.write(p,c,i.dtype);return{dataId:m,shape:c,dtype:i.dtype}}const lj={kernelName:zl,backendName:"cpu",kernelFunc:j0};function hj(e){const{inputs:t,backend:n,attrs:s}=e,{x:i}=t,{blockShape:o,paddings:a}=s;Te([i],"spaceToBatchND");const c=we(o),u=[[0,0]];u.push(...a);for(let B=1+o.length;B<i.shape.length;++B)u.push([0,0]);const p=Y0.kernelFunc({inputs:{x:i},backend:n,attrs:{paddings:u,constantValue:0}}),m=Rh(p.shape,o,c,!1),y=Oh(m.length,o.length,!1),b=Eh(p.shape,o,c,!1),w={x:p},I={shape:m},T=eo({inputs:w,backend:n,attrs:I}),v={x:T},N={perm:y},E=j0({inputs:v,backend:n,attrs:N}),D={x:E},F={shape:b},_=eo({inputs:D,backend:n,attrs:F});return n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(T),n.disposeIntermediateTensorInfo(E),_}const uj={kernelName:md,backendName:"cpu",kernelFunc:hj};const dj=Tt(Bl,e=>Math.sqrt(e)),pj={kernelName:Bl,backendName:"cpu",kernelFunc:dj};const mj={kernelName:fd,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 u=i[c];o[c]=u*u}const a=s.write(o,n.shape,n.dtype);return{dataId:a,shape:n.shape,dtype:n.dtype}}};const fj=jo((e,t)=>{const n=e-t;return n*n}),gj=dc(Na,fj),yj={kernelName:Na,backendName:"cpu",kernelFunc:gj};const bj=Tt(Gl,(e,t)=>{const n=t;return isNaN(e)?NaN:e>0?1:n.alpha}),wj={kernelName:Gl,backendName:"cpu",kernelFunc:bj};const Lj=Tt(Ca,e=>Math.tan(e)),Sj={kernelName:Ca,backendName:"cpu",kernelFunc:Lj};const Ij=Tt(Pl,e=>Math.tanh(e)),xj={kernelName:Pl,backendName:"cpu",kernelFunc:Ij};function Tj(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:u,indices:p}=G0(a,i,o.shape,o.dtype);return[s.makeTensorInfo(u,o.dtype,c),s.makeTensorInfo([p.length],"int32",p)]}const Aj={kernelName:gd,backendName:"cpu",kernelFunc:Tj};const vj=[XY,xq,Aq,nq,Nq,Rq,Eq,kq,_q,$q,Bq,eq,iq,Pq,JY,Vq,Yq,jq,Kq,Jq,Xq,lS,t4,l4,oq,cq,m4,f4,hq,ZY,y4,zq,w4,S4,x4,dq,A4,N4,O4,D4,F4,C4,mq,W4,U4,P4,Y0,QY,V4,Gq,H4,q4,gq,J4,Q4,tj,sj,rj,yq,cj,uj,pj,mj,yj,wj,wq,Sj,xj,lj,Aj];for(const e of vj)Ld(e);const Ko={},uS={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function Nj(e,t){Ko[e]=t}function Mi(e){if(!(e in Ko)){const n=Rj(e);if(n!==null)Ko[e]=n;else return console.log("Could not get context for WebGL version",e),null}const t=Ko[e];return t.isContextLost()?(delete Ko[e],Mi(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),Ko[e])}function Cj(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 Rj(e){if(e!==1&&e!==2)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");const t=Cj(e);return t.addEventListener("webglcontextlost",n=>{n.preventDefault(),delete Ko[e]},!1),e===1?t.getContext("webgl",uS)||t.getContext("experimental-webgl",uS):t.getContext("webgl2",uS)}var au;(function(e){e[e.DENSE=0]="DENSE",e[e.SHARED_BATCH=1]="SHARED_BATCH"})(au||(au={}));var Cs;(function(e){e[e.RENDER=0]="RENDER",e[e.UPLOAD=1]="UPLOAD",e[e.PIXELS=2]="PIXELS",e[e.DOWNLOAD=3]="DOWNLOAD"})(Cs||(Cs={}));var In;(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"})(In||(In={}));function cu(e,t){return[t,e]}function Oj(e,t){return e*t}function nte(e,t){return[t*4,e]}function lu(e){const t=we(e),n=Math.ceil(t/4);return Sd(n)}function ste(e,t){if(e%t!==0)throw new Error(`unpackedSize (${e}) must be a multiple of ${t}`);return e/t}function ite(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 fc(e,t){return[Math.max(1,Math.ceil(t/2)),Math.max(1,Math.ceil(e/2))]}function Ej(e,t){const[n,s]=fc(e,t);return n*s*4}function dS(e,t){const n=e;let s,i,o,a,c,u,p,m,y,b;return C().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),u=e.RGBA,{internalFormatFloat:s,internalFormatHalfFloat:i,internalFormatPackedHalfFloat:o,internalFormatPackedFloat:a,textureFormatFloat:c,downloadTextureFormat:u,downloadUnpackNumChannels:p,defaultNumChannels:m,textureTypeHalfFloat:y,textureTypeFloat:b}}function Re(e,t){const n=t();return C().getBool("DEBUG")&&Dj(e),n}function Dj(e){const t=e.getError();if(t!==e.NO_ERROR)throw new Error("WebGL Error: "+Wj(e,t))}const kj=596e-10,Fj=65504;function _j(e){return!!(C().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||e===0||kj<Math.abs(e)&&Math.abs(e)<Fj)}function Wj(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 pm(e,t){return ur(e,()=>e.getExtension(t),'Extension "'+t+'" not supported on this browser.')}function $j(e,t){const n=ur(e,()=>e.createShader(e.VERTEX_SHADER),"Unable to create vertex WebGLShader.");if(Re(e,()=>e.shaderSource(n,t)),Re(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 Uj(e,t){const n=ur(e,()=>e.createShader(e.FRAGMENT_SHADER),"Unable to create fragment WebGLShader.");if(Re(e,()=>e.shaderSource(n,t)),Re(e,()=>e.compileShader(n)),e.getShaderParameter(n,e.COMPILE_STATUS)===!1)throw Mj(t,e.getShaderInfoLog(n)),new Error("Failed to compile fragment shader.");return n}const Bj=/ERROR: [0-9]+:([0-9]+):/g;function Mj(e,t){const n=Bj.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)=>Lo((b+1).toString(),o)+y);let c=0;for(let y=0;y<a.length;y++)c=Math.max(a[y].length,c);const u=a.slice(0,s-1),p=a.slice(s-1,s),m=a.slice(s);console.log(u.join(`
`)),console.log(t.split(`
`)[0]),console.log(`%c ${Lo(p[0],c)}`,"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(m.join(`
`))}function Pj(e){return ur(e,()=>e.createProgram(),"Unable to create WebGLProgram.")}function zj(e,t){if(Re(e,()=>e.linkProgram(t)),e.getProgramParameter(t,e.LINK_STATUS)===!1)throw console.log(e.getProgramInfoLog(t)),new Error("Failed to link vertex and fragment shaders.")}function pS(e,t){if(Re(e,()=>e.validateProgram(t)),e.getProgramParameter(t,e.VALIDATE_STATUS)===!1)throw console.log(e.getProgramInfoLog(t)),new Error("Shader program validation failed.")}function Gj(e,t){const n=ur(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return Re(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n)),Re(e,()=>e.bufferData(e.ARRAY_BUFFER,t,e.STATIC_DRAW)),n}function Vj(e,t){const n=ur(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return Re(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,n)),Re(e,()=>e.bufferData(e.ELEMENT_ARRAY_BUFFER,t,e.STATIC_DRAW)),n}function rte(){return C().getNumber("WEBGL_VERSION")===2?1:4}function Hj(e){return ur(e,()=>e.createTexture(),"Unable to create WebGLTexture.")}function Yj(e,t){const n=C().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(e<=0||t<=0){const s=`[${e}x${t}]`;throw new Error("Requested texture size "+s+" is invalid.")}if(e>n||t>n){const s=`[${e}x${t}]`,i=`[${n}x${n}]`;throw new Error("Requested texture size "+s+" greater than WebGL maximum on this browser / GPU "+i+".")}}function qj(e){return ur(e,()=>e.createFramebuffer(),"Unable to create WebGLFramebuffer.")}function K0(e,t,n,s,i,o,a){const c=e.getAttribLocation(t,n);return c===-1?!1:(Re(e,()=>e.bindBuffer(e.ARRAY_BUFFER,s)),Re(e,()=>e.vertexAttribPointer(c,i,e.FLOAT,!1,o,a)),Re(e,()=>e.enableVertexAttribArray(c)),!0)}function jj(e,t,n){J0(e,n),Re(e,()=>e.activeTexture(e.TEXTURE0+n)),Re(e,()=>e.bindTexture(e.TEXTURE_2D,t))}function ote(e,t){J0(e,t),Re(e,()=>e.activeTexture(e.TEXTURE0+t)),Re(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function Kj(e,t,n){return ur(e,()=>e.getUniformLocation(t,n),'uniform "'+n+'" not present in program.')}function Xj(e,t,n){return e.getUniformLocation(t,n)}function Jj(e,t,n,s){Re(e,()=>jj(e,t,s)),Re(e,()=>e.uniform1i(n,s))}function ate(e){Re(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,null)),Re(e,()=>e.viewport(0,0,e.canvas.width,e.canvas.height)),Re(e,()=>e.scissor(0,0,e.canvas.width,e.canvas.height))}function mS(e,t,n){Re(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,n)),Re(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0))}function X0(e,t){Re(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,t)),Re(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0))}function mm(e){const t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+Zj(e,t))}function Zj(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 ur(e,t,n){const s=Re(e,()=>t());if(s==null)throw new Error(n);return s}function J0(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 gc(e,t=2){return we(e.slice(0,e.length-t))}function yc(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 fS(e){let t=[1,1,1];const n=e.length===0||e.length===1&&e[0]===1;return n||(t=[gc(e),...yc(e)]),t}function Qj(e,t=!1){let n=C().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(t&&(n=n*2,e=e.map((i,o)=>o>=e.length-2?Sy(e[o]):e[o]),e.length===1&&(e=[2,e[0]])),e.length!==2){const i=Rr(e);e=i.newShape}let s=we(e);if(e.length<=1&&s<=n)return[1,s];if(e.length===2&&e[0]<=n&&e[1]<=n)return e;if(e.length===3&&e[0]*e[1]<=n&&e[2]<=n)return[e[0]*e[1],e[2]];if(e.length===3&&e[0]<=n&&e[1]*e[2]<=n)return[e[0],e[1]*e[2]];if(e.length===4&&e[0]*e[1]*e[2]<=n&&e[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=gc(e);let o=2,a=2;return e.length&&([o,a]=yc(e)),s=i*(o/2)*(a/2),Sd(s).map(c=>c*2)}return Sd(s)}function fm(e){return e%2===0}function gm(e,t){if(e=e.slice(-2),t=t.slice(-2),ot(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(fm(n)&&fm(s)&&(e[0]===1||t[0]===1))return!0}return e[1]===t[1]&&fm(e[0])&&fm(t[0])}let ym,bm;function eK(e){if(ym==null){const t=Mi(e);ym=t.getParameter(t.MAX_TEXTURE_SIZE)}return ym}function cte(){ym=null}function lte(){bm=null}function tK(e){if(bm==null){const t=Mi(e);bm=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,bm)}function nK(e){if(e===0)return 0;let t;const n=Mi(e);return Vs(n,"EXT_disjoint_timer_query_webgl2")&&e===2?t=2:Vs(n,"EXT_disjoint_timer_query")?t=1:t=0,t}function Vs(e,t){const n=e.getExtension(t);return n!=null}function Z0(e){try{const t=Mi(e);if(t!=null)return!0}catch(t){return console.log("Error when getting WebGL context: ",t),!1}return!1}function sK(e){if(e===0)return!1;const t=Mi(e);if(e===1){if(!Vs(t,"OES_texture_float"))return!1}else if(!Vs(t,"EXT_color_buffer_float"))return!1;const n=gS(t);return n}function iK(e){if(e===0)return!1;const t=Mi(e);if(e===1){if(!Vs(t,"OES_texture_float"))return!1;if(!Vs(t,"WEBGL_color_buffer_float"))return!1}else{if(Vs(t,"EXT_color_buffer_float"))return gS(t);const s="EXT_color_buffer_half_float";if(Vs(t,s)){const i=t.getExtension(s);return rK(t,i)}return!1}const n=gS(t);return n}function gS(e){const t=dS(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 rK(e,t){const n=dS(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 oK(e){if(e!==2)return!1;const t=Mi(e),n=t.fenceSync!=null;return n}function hu(e,t){Array.isArray(e)||(e=[e]),e.forEach(n=>{n!=null&&k(n.dtype!=="complex64",()=>`${t} does not support complex64 tensors in the WebGL backend.`)})}const Ve=C();Ve.registerFlag("HAS_WEBGL",()=>Ve.getNumber("WEBGL_VERSION")>0),Ve.registerFlag("WEBGL_VERSION",()=>Z0(2)?2:Z0(1)?1:0),Ve.registerFlag("WEBGL_CHECK_NUMERICAL_PROBLEMS",()=>!1),Ve.registerFlag("WEBGL_BUFFER_SUPPORTED",()=>Ve.get("WEBGL_VERSION")===2),Ve.registerFlag("WEBGL_CPU_FORWARD",()=>!0),Ve.registerFlag("WEBGL_FORCE_F16_TEXTURES",()=>!1),Ve.registerFlag("WEBGL_PACK",()=>Ve.getBool("HAS_WEBGL")),Ve.registerFlag("WEBGL_PACK_NORMALIZATION",()=>Ve.getBool("WEBGL_PACK")),Ve.registerFlag("WEBGL_PACK_CLIP",()=>Ve.getBool("WEBGL_PACK")),Ve.registerFlag("WEBGL_PACK_DEPTHWISECONV",()=>!1),Ve.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",()=>Ve.getBool("WEBGL_PACK")),Ve.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",()=>Ve.getBool("WEBGL_PACK")),Ve.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",()=>Ve.getBool("WEBGL_PACK")),Ve.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",()=>Ve.getBool("WEBGL_PACK")),Ve.registerFlag("WEBGL_PACK_REDUCE",()=>Ve.getBool("WEBGL_PACK")),Ve.registerFlag("WEBGL_LAZILY_UNPACK",()=>Ve.getBool("WEBGL_PACK")),Ve.registerFlag("WEBGL_CONV_IM2COL",()=>Ve.getBool("WEBGL_PACK")),Ve.registerFlag("WEBGL_MAX_TEXTURE_SIZE",()=>eK(Ve.getNumber("WEBGL_VERSION"))),Ve.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",()=>tK(Ve.getNumber("WEBGL_VERSION"))),Ve.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",()=>{const e=Ve.getNumber("WEBGL_VERSION");return e===0?0:nK(e)}),Ve.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",()=>Ve.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!wT()),Ve.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",()=>sK(Ve.getNumber("WEBGL_VERSION"))),Ve.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",()=>Ve.getBool("WEBGL_FORCE_F16_TEXTURES")?!1:Ve.getBool("WEBGL_RENDER_FLOAT32_CAPABLE")),Ve.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",()=>iK(Ve.getNumber("WEBGL_VERSION"))),Ve.registerFlag("WEBGL_FENCE_API_ENABLED",()=>oK(Ve.getNumber("WEBGL_VERSION"))),Ve.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",()=>{const e=Ve.getBool("WEBGL_RENDER_FLOAT32_ENABLED");return e?4:0}),Ve.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:aK,addImpl:cK,ceilImpl:lK,expImpl:hK,expm1Impl:uK,floorImpl:dK,logImpl:pK,maxImpl:mK,multiplyImpl:fK,rsqrtImpl:gK,sliceImpl:yK,subImpl:bK,transposeImpl:Q0,uniqueImpl:wK}=Lq;class LK{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 SK{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 IK{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 eC(e,t){return["x","y","z","w","u","v"].slice(0,t).map(n=>`${e}.${n}`)}function us(e,t){return t===1?[e]:eC(e,t)}function xK(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 Un(){let e,t,n,s,i,o,a,c,u,p;return C().getNumber("WEBGL_VERSION")===2?(e="#version 300 es",t="in",n="out",s="in",i="texture",o="outputColor",a="out vec4 outputColor;",c=`
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)
`,u="",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));
}
`,u=`
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:u,defineRound:p}}function Xo(e,t,n="index"){const s=Ot(t);return s.map((i,o)=>{const a=`int ${e[o]} = ${n} / ${i}`,c=o===s.length-1?`int ${e[o+1]} = ${n} - ${e[o]} * ${i}`:`index -= ${e[o]} * ${i}`;return`${a}; ${c};`}).join("")}function wm(e){return e.length===1?`${e[0]}`:`vec${e.length}(${e.join(",")})`}function hte(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(`${wm(a)}, ${wm(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(`${wm(o)}, ${wm(a)}`)}return n.map((o,a)=>`dot(${o})`).join("+")}function yS(e){const t=Ot(e).map(n=>n.toString());return`
int getFlatIndex(ivec3 coords) {
return coords.x * ${t[0]} + coords.y * ${t[1]} + coords.z;
}
`}const tC=`
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}=iw;function TK(e,t,n,s){const i=[];e.forEach(I=>{const T=we(I.shapeInfo.logicalShape);I.shapeInfo.isUniform?i.push(`uniform float ${I.name}${T>1?`[${T}]`:""};`):(i.push(`uniform sampler2D ${I.name};`),i.push(`uniform int offset${I.name};`))});const o=i.join(`
`),a=e.map(I=>AK(I,t,s)).join(`
`),c=t.texShape,u=Un(),p=CK(u);let m,y,b=EK(u);t.isPacked?(m=vK(t.logicalShape,c),y=OK(u)):(m=NK(t.logicalShape,c),y=RK(u)),s&&(b+=_K);const w=[b,p,y,o,m,a,n].join(`
`);return w}function bc(e){const t=e.shapeInfo.logicalShape;switch(t.length){case 0:return qK(e);case 1:return KK(e);case 2:return JK(e);case 3:return QK(e);case 4:return t5(e);case 5:return n5(e);case 6:return s5(e);default:throw new Error(`${t.length}-D input sampling is not yet supported`)}}function sC(e){const t=e.shapeInfo.logicalShape;switch(t.length){case 0:return YK(e);case 1:return jK(e);case 2:return XK(e);case 3:return ZK(e);default:return e5(e)}}function AK(e,t,n=!1){let s="";n?s+=sC(e):s+=bc(e);const i=e.shapeInfo.logicalShape,o=t.logicalShape;return i.length<=o.length&&(n?s+=i5(e,t):s+=r5(e,t)),s}function vK(e,t){switch(e.length){case 0:return iC();case 1:return WK(e,t);case 2:return VK(e,t);case 3:return UK(e,t);default:return MK(e,t)}}function NK(e,t){switch(e.length){case 0:return iC();case 1:return $K(e,t);case 2:return HK(e,t);case 3:return BK(e,t);case 4:return PK(e,t);case 5:return zK(e,t);case 6:return GK(e,t);default:throw new Error(`${e.length}-D output sampling is not yet supported`)}}function CK(e){return`
float sampleTexture(sampler2D textureSampler, vec2 uv) {
return ${e.texture2D}(textureSampler, uv).r;
}
`}function RK(e){return`
void setOutput(float val) {
${e.output} = vec4(val, 0, 0, 0);
}
`}function OK(e){return`
void setOutput(vec4 val) {
${e.output} = val;
}
`}function EK(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);
}
${DK}
${kK}
${FK}
`;return t}const DK=`
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);
}
`,kK=`
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);
}
`,FK=`
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);
}
`,_K=`
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 iC(){return`
int getOutputCoords() {
return 0;
}
`}function WK(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 $K(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 UK(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 BK(e,t){const n=Xo(["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 MK(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 u=2;u<e.length-1;u++)o*=e[e.length-u-1],a=`
int b${u} = index / ${o};
index -= b${u} * ${o};
`+a,c=`b${u}, `+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 PK(e,t){const n=Xo(["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 zK(e,t){const n=Xo(["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 GK(e,t){const n=Xo(["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 VK(e,t){const n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(ot(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 HK(e,t){return ot(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 Jo(e){return`offset${e}`}function YK(e){const t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1),s=Un();return`
vec4 ${n}() {
return ${s.texture2D}(${t}, halfCR);
}
`}function qK(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=Jo(t);return`
float ${n}() {
vec2 uv = uvFromFlat(${o}, ${a}, ${c});
return sampleTexture(${t}, uv);
}
`}function jK(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=Un();return`
vec4 ${n}(int index) {
vec2 uv = packedUVfrom1D(
${i[0]}, ${i[1]}, index);
return ${o.texture2D}(${t}, uv);
}
`}function KK(e){const t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1);if(e.shapeInfo.isUniform)return`
float ${n}(int index) {
${wc(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=Jo(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 XK(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=Un();if(i!=null&&ot(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 u=[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}, ${u[0]}, ${u[1]}, row, col);
return ${c.texture2D}(${n}, uv);
}
`}function JK(e){const t=e.shapeInfo.logicalShape,n=e.name,s="get"+n.charAt(0).toUpperCase()+n.slice(1),i=e.shapeInfo.texShape;if(i!=null&&ot(t,i)){const y=i[0],b=i[1];return`
float ${s}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${b}.0, ${y}.0);
return sampleTexture(${n}, uv);
}
`}const{newShape:o,keptDims:a}=Rr(t),c=o;if(c.length<t.length){const y=Lc(e,c),b=["row","col"];return`
${bc(y)}
float ${s}(int row, int col) {
return ${s}(${Sc(b,a)});
}
`}if(e.shapeInfo.isUniform)return`
float ${s}(int row, int col) {
int index = round(dot(vec2(row, col), vec2(${t[1]}, 1)));
${wc(e)}
}
`;const u=i[0],p=i[1],m=Jo(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) / ${u}.0);
return sampleTexture(${n}, uv);
}
`:u===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(${u}, ${p}, index);
return sampleTexture(${n}, uv);
}
`}function ZK(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=Lc(e,y),I=["b","row","col"];return`
${sC(w)}
vec4 ${s}(int b, int row, int col) {
return ${s}(${Sc(I,b)});
}
`}const a=o[0],c=o[1],u=Math.ceil(t[2]/2),p=u*Math.ceil(t[1]/2),m=Un();return`
vec4 ${s}(int b, int row, int col) {
vec2 uv = packedUVfrom3D(
${a}, ${c}, ${p}, ${u}, b, row, col);
return ${m.texture2D}(${n}, uv);
}
`}function QK(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}=Rr(t),u=a;if(u.length<t.length){const I=Lc(e,u),T=["row","col","depth"];return`
${bc(I)}
float ${s}(int row, int col, int depth) {
return ${s}(${Sc(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)));
${wc(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=Jo(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 e5(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],u=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 I=2;I<n-1;I++)y=`int b${I}, `+y,m*=t[n-I-1],b=`b${I} * ${m} + `+b;const w=Un();return`
vec4 ${i}(${y}) {
int index = ${b};
int texR = index / ${u};
int texC = index - texR * ${u};
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${u}, ${c});
return ${w.texture2D}(${s}, uv);
}
`}function t5(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:u}=Rr(t);if(c.length<t.length){const I=Lc(e,c),T=["row","col","depth","depth2"];return`
${bc(I)}
float ${s}(int row, int col, int depth, int depth2) {
return ${s}(${Sc(T,u)});
}
`}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)));
${wc(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=Jo(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 n5(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:u,keptDims:p}=Rr(t);if(u.length<t.length){const T=Lc(e,u),v=["row","col","depth","depth2","depth3"];return`
${bc(T)}
float ${s}(int row, int col, int depth, int depth2, int depth3) {
return ${s}(${Sc(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;
${wc(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 I=Jo(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 + ${I};
vec2 uv = uvFromFlat(${b}, ${w}, index);
return sampleTexture(${n}, uv);
}
`}function s5(e){const t=e.shapeInfo.logicalShape,n=e.name,s="get"+n.charAt(0).toUpperCase()+n.slice(1),{newShape:i,keptDims:o}=Rr(t);if(i.length<t.length){const v=Lc(e,i),N=["row","col","depth","depth2","depth3","depth4"];return`
${bc(v)}
float ${s}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
return ${s}(${Sc(N,o)});
}
`}const a=t[5],c=t[4]*a,u=t[3]*c,p=t[2]*u,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}, ${u}, ${c})) +
dot(
vec2(depth3, depth4),
vec2(${a}, 1)));
${wc(e)}
}
`;const y=e.shapeInfo.flatOffset,b=e.shapeInfo.texShape,w=b[0],I=b[1];if(I===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}, ${u}, ${c}, ${a})) +
float(depth4);
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${I}.0, ${w}.0);
return sampleTexture(${n}, uv);
}
`;if(I===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(${I}.0, ${w}.0);
return sampleTexture(${n}, uv);
}
`;const T=Jo(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 * ${u} +
depth2 * ${c} + depth3 * ${a} + depth4 + ${T};
vec2 uv = uvFromFlat(${w}, ${I}, index);
return sampleTexture(${n}, uv);
}
`}function wc(e){const t=e.name,n=we(e.shapeInfo.logicalShape);return n<2?`return ${t};`:`
for (int i = 0; i < ${n}; i++) {
if (i == index) {
return ${t}[i];
}
}
`}function i5(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),u=Et(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(E=>`coords.${y[E+p]} = 0;`).join(`
`);let b="";a<2&&o>0?b="coords":b=e.shapeInfo.logicalShape.map((E,D)=>`coords.${y[D+p]}`).join(", ");let w="return outputValue;";const I=we(e.shapeInfo.logicalShape),T=I===1,v=we(t.logicalShape),N=v===1;if(o===1&&!T&&!N)w=`
return vec4(outputValue.xy, outputValue.xy);
`;else if(T&&!N)a===1?w=`
return vec4(outputValue.x, outputValue.x, 0., 0.);
`:w=`
return vec4(outputValue.x);
`;else if(c.length){const E=o-2,D=o-1;c.indexOf(E)>-1&&c.indexOf(D)>-1?w="return vec4(outputValue.x);":c.indexOf(E)>-1?w="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":c.indexOf(D)>-1&&(w="return vec4(outputValue.xx, outputValue.zz);")}return`
vec4 ${i}() {
${u} coords = getOutputCoords();
${m}
vec4 outputValue = get${s}(${b});
${w}
}
`}function r5(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,u=t.logicalShape.length;if(!e.shapeInfo.isUniform&&c===u&&e.shapeInfo.flatOffset==null&&ot(a,o))return`
float ${i}() {
return sampleTexture(${n}, resultUV);
}
`;const p=Et(u),m=nC(e.shapeInfo.logicalShape,t.logicalShape),y=u-c;let b;const w=["x","y","z","w","u","v"];c===0?b="":u<2&&m.length>=1?b="coords = 0;":b=m.map(T=>`coords.${w[T+y]} = 0;`).join(`
`);let I="";return u<2&&c>0?I="coords":I=e.shapeInfo.logicalShape.map((T,v)=>`coords.${w[v+y]}`).join(", "),`
float ${i}() {
${p} coords = getOutputCoords();
${b}
return get${s}(${I});
}
`}function Et(e){if(e<=1)return"int";if(e===2)return"ivec2";if(e===3)return"ivec3";if(e===4)return"ivec4";if(e===5)return"ivec5";if(e===6)return"ivec6";throw Error(`GPU for rank ${e} is not yet supported`)}function Lc(e,t){const n=JSON.parse(JSON.stringify(e));return n.shapeInfo.logicalShape=t,n}function Sc(e,t){return t.map(n=>e[n]).join(", ")}class o5{constructor(e,t,n,s){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,k(e.length>2,()=>`Packed arg${n.charAt(0).toUpperCase()+n.slice(1)} supports only inputs with rank above 2.`);const i=e[e.length-1],o=Math.ceil(i/t);this.outputShape=e.slice(0,-1),o>1&&this.outputShape.push(o),s||this.variableNames.push("bestIndicesA");const a=this.outputShape,c=a.length,u=Et(c),p=us("coords",c);let m,y;if(o===1){y=c+1;const U=Et(y);m=`
${U} sourceLocR = ${U}(${p.join()}, 0);
++${p[c-1]};
${U} sourceLocG = ${U}(${p.join()}, 0);
++${p[c-2]};
${U} sourceLocA = ${U}(${p.join()}, 0);
--${p[c-1]};
${U} sourceLocB = ${U}(${p.join()}, 0);
--${p[c-2]};`}else y=c,m=`
${u} sourceLocR = coords;
++${p[c-1]};
${u} sourceLocG = coords;
++${p[c-2]};
${u} sourceLocA = coords;
--${p[c-1]};
${u} sourceLocB = coords;
--${p[c-2]};`;const b=["x","y","z","w","u","v"].slice(0,y),w="."+b[y-1],I=b.map(U=>"int "+U),T=us("sourceLocR",y-1).concat("inIdx.r"),v=us("sourceLocG",y-1).concat("inIdx.g"),N=us("sourceLocB",y-1).concat("inIdx.b"),E=us("sourceLocA",y-1).concat("inIdx.a"),D=n==="max"?"greaterThan":"lessThan",F=s?"":`
inIdx = round(vec4(getBestIndicesAChannel(${T.join()}),
getBestIndicesAChannel(${v.join()}),
getBestIndicesAChannel(${N.join()}),
getBestIndicesAChannel(${E.join()})));`,_=`vec4(
getAChannel(${T.join()}),
hasNextCol ? getAChannel(${v.join()}) : 0.,
hasNextRow ? getAChannel(${N.join()}) : 0.,
hasNextRow && hasNextCol ? getAChannel(${E.join()}) : 0.)`,B=s?"":`
float getBestIndicesAChannel(${I.join()}) {
return getChannel(getBestIndicesA(${b.join()}),
vec2(${b.slice(-2).join()}));
}`;this.userCode=`
float getAChannel(${I.join()}) {
return getChannel(getA(${b.join()}),
vec2(${b.slice(-2).join()}));
}
${B}
void main() {
${u} 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 = ${_};
for (int i = 0; i < ${t}; i++) {
inIdx = srcIdx;
${F}
vec4 candidate = ${_};
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 a5{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,u=e.effectiveFilterWidth,p=c-1-e.padInfo.top,m=u-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 < ${u};
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 c5{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,u=e.dilationHeight,p=e.dilationWidth,m=e.effectiveFilterDepth,y=e.effectiveFilterHeight,b=e.effectiveFilterWidth,w=m-1-e.padInfo.front,I=y-1-e.padInfo.top,T=b-1-e.padInfo.left,v=1/(t*n*s);this.userCode=`
const ivec3 pads = ivec3(${w}, ${I}, ${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 += ${u}) {
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 rC={REAL:"return areal * breal - aimag * bimag;",IMAG:"return areal * bimag + aimag * breal;"};class oC{constructor(e,t,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=nt(t,n),this.userCode=`
float binaryOpComplex(
float areal, float aimag, float breal, float bimag) {
${e}
}
void main() {
float areal = getARealAtOutCoords();
float aimag = getAImagAtOutCoords();
float breal = getBRealAtOutCoords();
float bimag = getBImagAtOutCoords();
setOutput(binaryOpComplex(areal, aimag, breal, bimag));
}
`}}const aC=`
if (isnan(a)) return a;
if (isnan(b)) return b;
`,bS="return a + b;",wS="return a - b;",cC="return a * b;",l5=`
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;
}
`,h5=`
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);
`,ute="return (a - b) * (a - b);",u5="return float(a == b);",d5="return float(a != b);",p5="return float(a < b);",m5="return float(a <= b);",f5="return float(a > b);",g5="return float(a >= b);",y5="return float(a >= 1.0 && b >= 1.0);",b5="return float(a >= 1.0 || b >= 1.0);",w5=aC+`
return max(a, b);
`,L5=aC+`
return min(a, b);
`,S5=`if (b == 0.0) return NAN;
return mod(a, b);`,I5="return (b >= 1.0) ? a : a * (b + 1.0);",lC="return (a < 0.) ? b * a : a;";class un{constructor(e,t,n){this.variableNames=["A","B"],this.outputShape=nt(t,n),this.userCode=`
float binaryOperation(float a, float b) {
${e}
}
void main() {
float a = getAAtOutCoords();
float b = getBAtOutCoords();
setOutput(binaryOperation(a, b));
}
`}}const Lm=`
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;
`,x5=`
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);
`,T5=`
// 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));
`+Lm+`
return result;
`,hC=`
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
`,A5=`
vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));
return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));
`,v5=`
return vec4(equal(a, b));
`,N5=`
return vec4(notEqual(a, b));
`,C5=`
return vec4(lessThan(a, b));
`,R5=`
return vec4(lessThanEqual(a, b));
`,O5=`
return vec4(greaterThan(a, b));
`,E5=`
return vec4(greaterThanEqual(a, b));
`,D5=`
return vec4(
vec4(greaterThanEqual(a, vec4(1.0))) *
vec4(greaterThanEqual(b, vec4(1.0))));
`,k5=`
return min(
vec4(greaterThanEqual(a, vec4(1.0))) +
vec4(greaterThanEqual(b, vec4(1.0))),
vec4(1.0));
`,F5=`
vec4 result = vec4(max(a, b));
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
`+Lm+`
return result;
`,_5=`
vec4 result = vec4(min(a, b));
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
`+Lm+`
return result;
`,W5=`
vec4 result = mod(a, b);
vec4 isNaN = vec4(equal(b, vec4(0.0)));
`+Lm+`
return result;
`;class to{constructor(e,t,n,s=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=nt(t,n);const i=this.outputShape.length;let o="";if(s)if(i===0||we(this.outputShape)===1)o=`
result.y = 0.;
result.z = 0.;
result.w = 0.;
`;else{const a=Et(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=us("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 $5{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 U5{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 B5{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 M5{constructor(e){this.outputShape=[],this.outputShape=Ur(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 P5{constructor(e,t){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=Ur(e,t);const n=this.outputShape,s=n.length,i=Et(s),o=us("coords",s),a=["x","y","z","w","u","v"].slice(0,s);this.variableNames=e.map((I,T)=>`T${T}`);const c=new Array(e.length-1);c[0]=e[0][t];for(let I=1;I<c.length;I++)c[I]=c[I-1]+e[I][t];const u=a[t],p=a.slice(-2),m=a.join();let y=`if (${u} < ${c[0]}) {
return getChannel(
getT0(${m}), vec2(${p.join()}));
}`;for(let I=1;I<c.length;I++){const T=c[I-1];y+=`
if (${u} < ${c[I]} && ${u} >= ${c[I-1]}) {
return getChannel(
getT${I}(${Sm(a,u,T)}),
vec2(${Sm(p,u,T)}));
}`}const b=c.length,w=c[c.length-1];y+=`
return getChannel(
getT${b}(${Sm(a,u,w)}),
vec2(${Sm(p,u,w)}));`,this.userCode=`
float getValue(${a.map(I=>"int "+I)}) {
${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 Sm(e,t,n){const s=e.indexOf(t),i=e.map((o,a)=>a===s?`${o} - ${n}`:o);return i.join()}class z5{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 G5{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,u=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[${u}], 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 V5{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 H5{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterDepth,n=e.filterHeight,s=e.filterWidth,i=e.strideDepth,o=e.strideHeight,a=e.strideWidth,c=t-1-e.padInfo.front,u=n-1-e.padInfo.top,p=s-1-e.padInfo.left;this.userCode=`
const ivec3 pads = ivec3(${c}, ${u}, ${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 Y5{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 q5{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 uC{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,u=e.dilationHeight,p=e.dilationWidth,m=e.filterHeight,y=e.filterWidth,b=Math.floor(e.inChannels/4)*4,w=e.inChannels%4,I=e.dataFormat==="channelsLast",T=I?1:2,v=I?2:3,N=I?3:1;let E="",D="";n&&(s?E=`float activation(float a) {
float b = getPreluActivationWeightsAtOutCoords();
${n}
}`:E=`
float activation(float x) {
${n}
}
`,D="result = activation(result);");const F=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),s&&this.variableNames.push("preluActivationWeights"),this.userCode=`
${E}
const ivec2 strides = ivec2(${a}, ${c});
const ivec2 pads = ivec2(${i}, ${o});
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d2 = coords[${N}];
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 * ${u};
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 (${I}) {
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 (${I}) {
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 (${I}) {
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 (${I}) {
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;
${F}
${D}
setOutput(result);
}
`}}class j5{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,u=e.dilationHeight,p=e.dilationWidth,m=e.filterDepth,y=e.filterHeight,b=e.filterWidth,w=Math.floor(e.inChannels/4)*4,I=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 * ${u};
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 (${I===1}) {
dotProd +=
getX(batch, xF, xR, xC, ${w}) *
getW(wF, wR, wC, ${w}, d2);
} else if (${I===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 (${I===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 dC{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,u=e.strideHeight,p=e.strideWidth,m=e.dilationHeight,y=e.dilationWidth,b=e.filterHeight,w=e.filterWidth,I=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 N=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),s&&this.variableNames.push("preluActivationWeights"),this.userCode=`
${T}
const ivec2 strides = ivec2(${u}, ${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 / ${I};
int q = d2 - d1 * ${I};
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;
${N}
${v}
setOutput(result);
}
`}}class pC{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,u=e.strideHeight,p=e.strideWidth,m=e.dilationHeight,y=e.dilationWidth,b=e.filterHeight,w=e.filterWidth,I=w;let T="int xR; int xC; int xCOffset;";for(let D=0;D<b;D++)for(let F=0;F<w;F++)T+=`
vec4 xTexelR${D}C${F*2} = vec4(0.);
vec4 wR${D}C${F} = vec4(0.);
vec4 xR${D}C${F} = vec4(0.);`;for(let D=0;D<b;D++)for(let F=0;F<I;F++){const _=F*2;if(T+=`
xR = xRCorner + ${D*m};
xC = xCCorner + ${_*y};
`,p===1){if(_<w&&(c%2===1?T+=`
xCOffset = xC + 1;
if(xR >= 0 && xR < ${i} && xCOffset >= 0 && xCOffset < ${o}) {
xTexelR${D}C${_} = 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${_}.zw = vec2(0.);
}
} else {
xTexelR${D}C${_} = 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${_} = vec4(previous.zw, xTexelR${D}C${_}.xy);
} else {
xR${D}C${_} = vec4(0, 0, xTexelR${D}C${_}.xy);
}
`:T+=`
if(xR >= 0 && xR < ${i} && xC >= 0 && xC < ${o}) {
xTexelR${D}C${_} = getX(batch, xR, xC, d1);
} else {
xTexelR${D}C${_} = vec4(0.);
}
xR${D}C${_} = xTexelR${D}C${_};
`,_+1<w)){const B=c%2===0?Sy(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${_+2} = getX(batch, xR, xCOffset, d1);
}
`,y>1&&(T+=`
xCOffset -= 2;
if(xR >= 0 && xR < ${i} &&
xCOffset >= 0 && xCOffset < ${o}) {
xTexelR${D}C${_} = getX(batch, xR, xCOffset, d1);
} else {
xTexelR${D}C${_} = vec4(0.);
}
`),T+=`
xR${D}C${_+1} = vec4(
xTexelR${D}C${_}.zw, xTexelR${D}C${_+2}.xy);
`):T+=`
xCOffset = xC + ${B};
if(xR >= 0 && xR < ${i} &&
xCOffset >= 0 && xCOffset < ${o}) {
xTexelR${D}C${_+2} = getX(batch, xR, xCOffset, d1);
}
xR${D}C${_+1} = xTexelR${D}C${_+2};
`}}else _<w&&(T+=`
if(xR >= 0 && xR < ${i}) {
`,c%2===1?(T+=`
xCOffset = xC + 1 - ${p};
if(xCOffset >= 0 && xCOffset < ${o}) {
xTexelR${D}C${_} = getX(batch, xR, xCOffset, d1);
} else {
xTexelR${D}C${_} = vec4(0.);
}
if(xC + 1 >= 0 && xC + 1 < ${o}) {
xTexelR${D}C${_+2} = getX(batch, xR, xC + 1, d1);
} else {
xTexelR${D}C${_+2} = vec4(0.);
}
xR${D}C${_} = vec4(
xTexelR${D}C${_}.zw, xTexelR${D}C${_+2}.zw);
`,_+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${_+1} = vec4(xTexelR${D}C${_+2}.xy, final.xy);
`)):(T+=`
if(xC >= 0 && xC < ${o}) {
xTexelR${D}C${_} = getX(batch, xR, xC, d1);
} else {
xTexelR${D}C${_} = vec4(0.);
}
xCOffset = xC + ${p};
if(xCOffset >= 0 && xCOffset < ${o}) {
xTexelR${D}C${_+2} = getX(batch, xR, xCOffset, d1);
} else {
xTexelR${D}C${_+2} = vec4(0.);
}
xR${D}C${_} = vec4(
xTexelR${D}C${_}.xy, xTexelR${D}C${_+2}.xy);
`,_+1<w&&(T+=`
xR${D}C${_+1} = vec4(
xTexelR${D}C${_}.zw, xTexelR${D}C${_+2}.zw);
`)),T+="}");_<w&&(T+=`
vec4 wTexelR${D}C${_} = getW(${D}, ${_}, d1, q);
wR${D}C${_} = vec4(wTexelR${D}C${_}.xz, wTexelR${D}C${_}.xz);
`,_+1<w&&(T+=`
vec4 wTexelR${D}C${_+1} = getW(${D}, ${_+1}, d1, q);
wR${D}C${_+1} =
vec4(wTexelR${D}C${_+1}.xz, wTexelR${D}C${_+1}.xz);`))}for(let D=0;D<b;D++)for(let F=0;F<w;F++)T+=`dotProd += xR${D}C${F} * wR${D}C${F};`;let v="",N="";n&&(s?v=`vec4 activation(vec4 a) {
vec4 b = getPreluActivationWeightsAtOutCoords();
${n}
}`:v=`vec4 activation(vec4 x) {
${n}
}`,N="result = activation(result);");const E=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),s&&this.variableNames.push("preluActivationWeights"),this.userCode=`
${v}
const ivec2 strides = ivec2(${u}, ${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;
${E}
${N}
setOutput(result);
}
`}}class K5{constructor(e,t,n,s,i){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];const[o,a,c,u]=e,[p]=t,[m,y]=n;this.outputShape=[p,m,y,u];const b=s==="bilinear"?1:0,[w,I]=[`${a-1}.0`,`${c-1}.0`],[T,v,N]=m>1?[`${(a-1)/(m-1)}`,"(y2-y1) * height_ratio",`y1*${w} + float(y)*(height_scale)`]:["0.0","0.0",`0.5 * (y1+y2) * ${w}`],[E,D,F]=y>1?[`${(c-1)/(y-1)}`,"(x2-x1) * width_ratio",`x1*${I} + float(x)*(width_scale)`]:["0.0","0.0",`0.5 * (x1+x2) * ${I}`];this.userCode=`
const float height_ratio = float(${T});
const float width_ratio = float(${E});
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 = ${N};
if( in_y < 0.0 || in_y > ${w} ) {
setOutput(float(${i}));
return;
}
float in_x = ${F};
if( in_x < 0.0 || in_x > ${I} ) {
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 mC{constructor(e,t,n){this.variableNames=["x"],this.outputShape=e;const s=e.length,i=t?"0.0":`getX(${fC(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() {
${Et(s)} coords = getOutputCoords();
int end = ${gC(s,"coords")};
float val = ${i};
int pow2 = int(pow(2.0, index));
if (${a}) {
int idx = ${c};
${gC(s,"coords")} = idx;
val += getX(${fC(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 fC(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 gC(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 X5{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=au.DENSE;const t=lu(e),n=Un();this.outputShape=e,this.userCode=`
ivec3 outCoordsFromFlatIndex(int index) {
${Xo(["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 J5{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=au.DENSE;const t=lu(e),n=Un();this.outputShape=e,this.userCode=`
ivec3 outCoordsFromFlatIndex(int index) {
${Xo(["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 Z5{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 Q5{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 e8{constructor(e){this.variableNames=["A"],this.outTexUsage=Cs.DOWNLOAD;const t=Un();this.outputShape=e,this.userCode=`
${tC}
void main() {
float x = getAAtOutCoords();
${t.output} = encode_float(x);
}
`}}class t8{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=Cs.DOWNLOAD;const t=Un();this.outputShape=e,this.userCode=`
${tC}
void main() {
ivec3 coords = getOutputCoords();
float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));
${t.output} = encode_float(x);
}
`}}class n8{constructor(e,t,n=!1){this.variableNames=["A"];const s=Un(),[i,o]=t;this.outputShape=e;let a="result";n&&(a="floor(result * 255. + 0.5)"),this.userCode=`
${yS(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 s8{constructor(e,t,n=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;const s=Un(),[i,o]=t;this.outputShape=e;let a="",c="result";n&&(c="floor(result * 255. + 0.5)");for(let u=0;u<=1;u++)for(let p=0;p<=1;p++){const m=u*2+p;a+=`
localCoords = coords;
if(localCoords[2] + ${p} < ${e[2]}) {
localCoords[2] += ${p};
if(localCoords[1] + ${u} < ${e[1]}) {
localCoords[1] += ${u};
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=`
${yS(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};
}
`}}const yC={REAL:"return real * expR - imag * expI;",IMAG:"return real * expI + imag * expR;"};class bC{constructor(e,t,n){this.variableNames=["real","imag"];const s=t[1];this.outputShape=t;const i=n?`2.0 * ${Math.PI}`:`-2.0 * ${Math.PI}`,o=n?`${s}.0`:"1.0";this.userCode=`
const float exponentMultiplier = ${i};
float unaryOpComplex(float real, float expR, float imag, float expI) {
${e}
}
float mulMatDFT(int batch, int index) {
float indexRatio = float(index) / float(${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]));
}
`}}class i8{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 r8{constructor(e,t,n){this.variableNames=["A","indices"];const s=e.slice();s[n]=t,this.outputShape=s,this.rank=s.length;const i=Et(this.rank),o=o8(e,n);this.userCode=`
void main() {
${i} resRC = getOutputCoords();
setOutput(getA(${o}));
}
`}}function o8(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 a8{constructor(e,t,n){this.sliceDim=e,this.strides=t,this.variableNames=["x","indices"],this.outputShape=n;const s=Et(t.length),i=Et(n.length),o=this.sliceDim>1?"strides[j]":"strides";this.userCode=`
${s} strides = ${s}(${this.strides});
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 c8(e){const t=Un(),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 $j(e,n)}function l8(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 Gj(e,t)}function h8(e){const t=new Uint16Array([0,1,2,2,1,3]);return Vj(e,t)}function uu(e,t,n,s,i,o){Yj(t,n);const a=Hj(e),c=e.TEXTURE_2D;return Re(e,()=>e.bindTexture(c,a)),Re(e,()=>e.texParameteri(c,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE)),Re(e,()=>e.texParameteri(c,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)),Re(e,()=>e.texParameteri(c,e.TEXTURE_MIN_FILTER,e.NEAREST)),Re(e,()=>e.texParameteri(c,e.TEXTURE_MAG_FILTER,e.NEAREST)),Re(e,()=>e.texImage2D(c,0,s,t,n,0,i,o,null)),Re(e,()=>e.bindTexture(e.TEXTURE_2D,null)),a}function wC(e){return e.internalFormatFloat}function u8(e,t,n,s){const[i,o]=cu(t,n);return uu(e,i,o,wC(s),s.textureFormatFloat,e.FLOAT)}function LC(e){return e.internalFormatHalfFloat}function d8(e,t,n,s){const[i,o]=cu(t,n);return uu(e,i,o,LC(s),s.textureFormatFloat,s.textureTypeHalfFloat)}function SC(e){return e.downloadTextureFormat}function p8(e,t,n,s){const[i,o]=cu(t,n);return uu(e,i,o,SC(s),e.RGBA,e.UNSIGNED_BYTE)}function IC(e){return e.internalFormatPackedFloat}function m8(e,t,n,s){const[i,o]=fc(t,n);return uu(e,i,o,IC(s),e.RGBA,e.FLOAT)}function xC(e){return e.internalFormatPackedHalfFloat}function f8(e,t,n,s){const[i,o]=fc(t,n);return uu(e,i,o,xC(s),e.RGBA,s.textureTypeHalfFloat)}function g8(e,t,n){const s=0,i=3*4,o=3*4+2*4;Re(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n));const a=K0(e,t,"clipSpacePos",n,3,o,s);return a&&K0(e,t,"uv",n,2,o,i)}function y8(e,t,n,s,i,o){Re(e,()=>e.bindTexture(e.TEXTURE_2D,t));let a,c,u;i instanceof Uint8Array?(a=new Uint8Array(n*s*4),c=e.UNSIGNED_BYTE,u=e.RGBA):(a=new Float32Array(n*s*4),c=e.FLOAT,u=o.internalFormatPackedFloat),a.set(i),Re(e,()=>e.texImage2D(e.TEXTURE_2D,0,u,n,s,0,e.RGBA,c,a)),Re(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function b8(e,t,n){Re(e,()=>e.bindTexture(e.TEXTURE_2D,t)),n.data instanceof Uint8Array?Re(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,n.width,n.height,0,e.RGBA,e.UNSIGNED_BYTE,n.data)):Re(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,n)),Re(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function w8(e,t,n,s){const i=e.createBuffer();Re(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,i));const o=4,a=4,c=o*a*t*n;return Re(e,()=>e.bufferData(e.PIXEL_PACK_BUFFER,c,e.STREAM_READ)),Re(e,()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,0)),Re(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,null)),i}function L8(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 S8(e,t,n,s){const[i,o]=cu(t,n),a=4,c=new Uint8Array(Oj(t*n,a));return Re(e,()=>e.readPixels(0,0,i,o,s.downloadTextureFormat,e.UNSIGNED_BYTE,c)),new Float32Array(c.buffer)}function I8(e,t,n,s,i,o,a,c){const u=e,p=new Float32Array(Ej(o,a));return u.bindBuffer(u.PIXEL_PACK_BUFFER,t),u.getBufferSubData(u.PIXEL_PACK_BUFFER,0,p),u.bindBuffer(u.PIXEL_PACK_BUFFER,null),p}function x8(e,t,n){const s=new Float32Array(t*n*4);return Re(e,()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,s)),s}class T8{constructor(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];const t=C().getNumber("WEBGL_VERSION");e!=null?(this.gl=e,Nj(t,e)):this.gl=Mi(t);let n="WEBGL_color_buffer_float";const s="EXT_color_buffer_half_float";if(C().getNumber("WEBGL_VERSION")===1){const i="OES_texture_float",o="OES_texture_half_float";if(this.textureFloatExtension=pm(this.gl,i),Vs(this.gl,o))this.textureHalfFloatExtension=pm(this.gl,o);else if(C().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support half float textures, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.");if(this.colorBufferFloatExtension=this.gl.getExtension(n),Vs(this.gl,s))this.colorBufferHalfFloatExtension=pm(this.gl,s);else if(C().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support color renderable half floats, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.")}else if(n="EXT_color_buffer_float",Vs(this.gl,n))this.colorBufferFloatExtension=this.gl.getExtension(n);else if(Vs(this.gl,s))this.colorBufferHalfFloatExtension=this.gl.getExtension(s);else throw new Error("GL context does not support color renderable floats");this.vertexBuffer=l8(this.gl),this.indexBuffer=h8(this.gl),this.framebuffer=qj(this.gl),this.textureConfig=dS(this.gl,this.textureHalfFloatExtension)}get debug(){return C().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;Re(e,()=>e.finish()),Re(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,null)),Re(e,()=>e.deleteFramebuffer(this.framebuffer)),Re(e,()=>e.bindBuffer(e.ARRAY_BUFFER,null)),Re(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)),Re(e,()=>e.deleteBuffer(this.indexBuffer)),this.disposed=!0}createFloat32MatrixTexture(e,t){return this.throwIfDisposed(),u8(this.gl,e,t,this.textureConfig)}createFloat16MatrixTexture(e,t){return this.throwIfDisposed(),d8(this.gl,e,t,this.textureConfig)}createUnsignedBytesMatrixTexture(e,t){return this.throwIfDisposed(),p8(this.gl,e,t,this.textureConfig)}uploadPixelDataToTexture(e,t){this.throwIfDisposed(),b8(this.gl,e,t)}uploadDenseMatrixToTexture(e,t,n,s){this.throwIfDisposed(),y8(this.gl,e,t,n,s,this.textureConfig)}createFloat16PackedMatrixTexture(e,t){return this.throwIfDisposed(),f8(this.gl,e,t,this.textureConfig)}createPackedMatrixTexture(e,t){return this.throwIfDisposed(),m8(this.gl,e,t,this.textureConfig)}deleteMatrixTexture(e){this.throwIfDisposed(),this.outputTexture===e&&(X0(this.gl,this.framebuffer),this.outputTexture=null),Re(this.gl,()=>this.gl.deleteTexture(e))}downloadByteEncodedFloatMatrixFromOutputTexture(e,t,n){return this.downloadMatrixDriver(e,()=>S8(this.gl,t,n,this.textureConfig))}downloadPackedMatrixFromBuffer(e,t,n,s,i,o){return I8(this.gl,e,t,n,s,i,o,this.textureConfig)}downloadFloat32MatrixFromBuffer(e,t){return L8(this.gl,e,t)}createBufferFromTexture(e,t,n){this.bindTextureToFrameBuffer(e);const s=w8(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(C().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 C().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(t=this.beginQuery(),this.endQuery(),n=()=>this.isQueryAvailable(t,C().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))):n=()=>!0;return{query:t,isFencePassed:n}}downloadMatrixFromPackedTexture(e,t,n){return this.downloadMatrixDriver(e,()=>x8(this.gl,t,n))}createProgram(e){this.throwIfDisposed();const t=this.gl,n=Uj(t,e),s=c8(t),i=Pj(t);return Re(t,()=>t.attachShader(i,s)),Re(t,()=>t.attachShader(i,n)),zj(t,i),this.debug&&pS(t,i),this.vertexAttrsAreBound||(this.setProgram(i),this.vertexAttrsAreBound=g8(t,this.program,this.vertexBuffer)),i}deleteProgram(e){this.throwIfDisposed(),e===this.program&&(this.program=null),e!=null&&Re(this.gl,()=>this.gl.deleteProgram(e))}setProgram(e){this.throwIfDisposed(),this.program=e,this.program!=null&&this.debug&&pS(this.gl,this.program),Re(this.gl,()=>this.gl.useProgram(e))}getUniformLocation(e,t,n=!0){return this.throwIfDisposed(),n?Kj(this.gl,e,t):Xj(this.gl,e,t)}getAttributeLocation(e,t){return this.throwIfDisposed(),Re(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(),Jj(this.gl,e,t,n)}setOutputMatrixTexture(e,t,n){this.setOutputMatrixTextureDriver(e,n,t)}setOutputPackedMatrixTexture(e,t,n){this.throwIfDisposed();const[s,i]=fc(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&&pS(this.gl,this.program),mm(this.gl)}executeProgram(){this.throwIfDisposed(),this.throwIfNoProgram();const e=this.gl;this.debug&&this.debugValidate(),Re(e,()=>e.drawElements(e.TRIANGLES,6,e.UNSIGNED_SHORT,0))}blockUntilAllProgramsCompleted(){this.throwIfDisposed(),Re(this.gl,()=>this.gl.finish())}getQueryTimerExtension(){return this.disjointQueryTimerExtension==null&&(this.disjointQueryTimerExtension=pm(this.gl,C().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(C().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(C().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 Iy(()=>this.disposed||this.isQueryAvailable(e,C().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))),this.getQueryTime(e,C().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=A8(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;Iy(()=>(this.pollItems(),this.itemsToPoll.length===0))}bindTextureToFrameBuffer(e){this.throwIfDisposed(),mS(this.gl,e,this.framebuffer),this.debug&&mm(this.gl)}unbindTextureToFrameBuffer(){this.outputTexture!=null?(mS(this.gl,this.outputTexture,this.framebuffer),this.debug&&mm(this.gl)):X0(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;mS(s,e,this.framebuffer),this.debug&&mm(s),this.outputTexture=e,Re(s,()=>s.viewport(0,0,t,n)),Re(s,()=>s.scissor(0,0,t,n))}setOutputMatrixWriteRegionDriver(e,t,n,s){this.throwIfDisposed(),Re(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 A8(e){let t=0;for(;t<e.length;++t){const n=e[t]();if(!n)break}return t-1}function v8(e,t,n,s){const i=t.userCode,o=n.map((w,I)=>{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[I],shapeInfo:T}}),a=o.map(w=>w.shapeInfo),c={logicalShape:s.shape,texShape:s.texData.texShape,isUniform:!1,isPacked:s.texData.isPacked,flatOffset:null},u=TK(o,c,i,t.packedInputs),p=e.createProgram(u);let m=null;const y=e.getUniformLocation(p,"NAN",!1);C().getNumber("WEBGL_VERSION")===1&&(m=e.getUniformLocation(p,"INFINITY",!1));const b={};for(let w=0;w<t.variableNames.length;w++){const I=t.variableNames[w],T=!1;b[I]=e.getUniformLocation(p,I,T),b[`offset${I}`]=e.getUniformLocation(p,`offset${I}`,T)}return{program:t,source:u,webGLProgram:p,uniformLocations:b,inShapeInfos:a,outShapeInfo:c,infLoc:m,nanLoc:y}}function TC(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(!ot(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,u=o.isUniform?null:o.texData.texShape;if(!ot(c,u))throw Error(`Binary was compiled with different texture shapes than the current args. Shape ${c} and ${u} must match`)})}function N8(e,t,n,s,i){TC(t.inShapeInfos,n),TC([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),C().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,u)=>{const p=t.program.variableNames[u],m=t.uniformLocations[p],y=t.uniformLocations[`offset${p}`];if(m==null)return;if(c.isUniform){if(we(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,u)}),i!=null&&i(e,t.webGLProgram),e.executeProgram()}function C8(e,t,n){let s="";t.concat(n).forEach(a=>{const c=a.texData!=null&&a.texData.slice!=null&&a.texData.slice.flatOffset>0,u=a.isUniform?"uniform":a.texData.texShape;s+=`${a.shape}_${u}_${c}`});const i=e.userCode;let o=e.constructor.name;return o+="_"+s+"_"+i,o}class R8{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:u,dilationWidth:p,dilationHeight:m,dataFormat:y}=n,{left:b,top:w}=c,I=i*s,T=Un(),v=y==="channelsLast",N=v?0:1,E=v?1:2;let D="";for(let F=0;F<=1;F++)for(let _=0;_<=1;_++)D+=`
blockIndex = rc.y + ${_};
pos = rc.x + ${F};
if(blockIndex < ${e[1]} && pos < ${e[0]}) {
offsetY = int(blockIndex / (${u})) * ${a} - ${w};
d0 = offsetY + ${m} * (pos / ${I});
if(d0 < ${t[N]} && d0 >= 0) {
offsetX = int(mod(float(blockIndex), ${u}.) * ${o}. - ${b}.);
d1 = offsetX + ${p} * (int(mod(float(pos), ${I}.) / ${i}.));
if(d1 < ${t[E]} && d1 >= 0) {
ch = int(mod(float(pos), ${i}.));
if (${v}) {
innerDims = vec2(d1, ch);
result[${F*2+_}] = getChannel(
getA(d0, int(innerDims.x),
int(innerDims.y)), innerDims);
} else {
innerDims = vec2(d0, d1);
result[${F*2+_}] = 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 O8{constructor(e,t,n,s,i){this.variableNames=["x"],this.outputShape=[];const o=t,a=e[3]-1;this.outputShape=e;let c;const u=`float(${n}) + float(${s}) * sum`;i===.5?c=`inversesqrt(${u})`:i===1?c=`1.0/(${u})`:c=`exp(log(${u}) * 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 E8{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 D8{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 u=`float(${n}) + float(${s}) * sum`;i===.5?c=`inversesqrt(${u})`:i===1?c=`1.0/(${u})`:c=`exp(log(${u}) * 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 k8{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,u=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 = ${u} - 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 F8{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,u=e.effectiveFilterHeight,p=e.effectiveFilterWidth,m=c-1-e.padInfo.front,y=u-1-e.padInfo.top,b=p-1-e.padInfo.left,w=c*u*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 < ${u};
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 * ${u} * ${p} +
wR * ${p} + wC;
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
dotProd += dyValue * mask;
}
}
}
setOutput(dotProd);
}
`}}class LS{constructor(e,t,n=!1,s=!1,i=!1,o=null,a=!1){this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t;const c=n?e[1]:e[2],u=Math.ceil(c/2),p=n?"i * 2, rc.y":"rc.y, i * 2",m=s?"rc.z, i * 2":"i * 2, rc.z",y=n?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],b=s?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"];let w="",I="";o&&(a?w=`vec4 activation(vec4 a) {
vec4 b = getPreluActivationWeightsAtOutCoords();
${o}
}`:w=`vec4 activation(vec4 x) {
${o}
}`,I="result = activation(result);");const T=i?"result += getBiasAtOutCoords();":"";i&&this.variableNames.push("bias"),a&&this.variableNames.push("preluActivationWeights"),this.userCode=`
${w}
const float sharedDimension = ${u}.0;
vec4 dot2x2ARowBCol(ivec3 rc) {
vec4 result = vec4(0);
for (int i = 0; i < ${u}; i++) {
vec4 a = getMatrixA(rc.x, ${p});
vec4 b = getMatrixB(rc.x, ${m});
// These swizzled products need to be separately added.
// See: https://github.com/tensorflow/tfjs/issues/1735
result += (${y[0]} * ${b[0]});
result += (${y[1]} * ${b[1]});
}
return result;
}
void main() {
ivec3 rc = getOutputCoords();
vec4 result = dot2x2ARowBCol(rc);
${T}
${I}
setOutput(result);
}
`}}class _8{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 W8{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 $8{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=us("rc",t),s=Et(t),i=B8(t,e,n),o=M8(t,e[e.length-1],e[e.length-2],n),a=P8(e,n);this.userCode=`
void main() {
${s} rc = getOutputCoords();
if(${i}) {
setOutput(vec4(0));
} else {
${o}
setOutput(vec4(${a}));
}
}
`}}}function U8(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 B8(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 M8(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 P8(e,t){const n=e.length,s=U8(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 z8{constructor(e,t,n){this.variableNames=["x"],this.outputShape=t.map((u,p)=>u[0]+e[p]+u[1]);const s=e.length,i=Et(s),o=t.map(u=>u[0]).join(","),a=t.map((u,p)=>u[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 G8{constructor(e,t,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.map((I,T)=>I[0]+e[T]+I[1]);const s=e.length,i=Et(s),o=t.map(I=>I[0]).join(","),a=t.map((I,T)=>I[0]+e[T]).join(","),c=us("rc",s),u=us("source",s),p=`${c[s-1]} < ${this.outputShape[s-1]}`,m=s===1?"source":`vec2(${u.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 I=0,T=s===1?2:4;I<T;I++)w+=`
${y[I]}
if (${b}) {
result[${I}] = float(${n});
} else {
${i} source = rc - start;
result[${I}] = getChannel(getX(${u.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 du{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,u=e.dilationHeight,p=e.dilationWidth,m=e.effectiveFilterHeight,y=e.effectiveFilterWidth,b=e.padInfo.top,w=e.padInfo.left;this.outputShape=e.outShape;const I=t==="avg",T=`((batch * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + d`,v=`(xR * ${e.inWidth} + xC) * ${e.inChannels} + d`;let N="0.0";if(I||(N="-1.0 / 1e-20"),n){const U=">=";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 += ${u}) {
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 ${U} currMinMaxValue) {
minMaxValue = value;
minMaxValueFound = 1.0;
minMaxPosition = ${s?i?T:v:`wR * ${y} + wC`};
}
}
}
setOutput(float(minMaxPosition));
}
`;return}const E="max";let D=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(D="avgValue / count");const F=Math.floor(o/4)*4,_=o%4,B=`
if (${I}) {
avgValue += dot(values, ones);
} else {
minMaxValue = ${E}(values, minMaxValue);
}
`;this.userCode=`
const ivec2 strides = ivec2(${a}, ${c});
const ivec2 pads = ivec2(${b}, ${w});
const float initializationValue = ${N};
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(${N});
float avgValue = 0.0;
count = 0.0;
for (int wR = 0; wR < ${m};
wR += ${u}) {
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int wC = 0; wC < ${F}; 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 + ${F};
if (${_===1}) {
vec4 values = vec4(
getValue(batch, xR, xC, d),
initializationValue,
initializationValue,
initializationValue
);
${B}
} else if (${_===2}) {
vec4 values = vec4(
getValue(batch, xR, xC, d),
getValue(batch, xR, xC + ${p}, d),
initializationValue,
initializationValue
);
${B}
} else if (${_===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 SS{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,u=e.strideWidth,p=e.dilationDepth,m=e.dilationHeight,y=e.dilationWidth,b=e.effectiveFilterDepth,w=e.effectiveFilterHeight,I=e.effectiveFilterWidth,T=e.padInfo.front,v=e.padInfo.top,N=e.padInfo.left;this.outputShape=e.outShape;const E=t==="avg";let D="0.0";if(E||(D="-1.0 / 1e-20"),n){const q=">=";this.userCode=`
const ivec3 strides =
ivec3(${a}, ${c}, ${u});
const ivec3 pads = ivec3(${T}, ${v}, ${N});
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 < ${I};
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 ${q} 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} * ${I} +
wR * ${I} + wC`};
}
}
}
}
setOutput(float(minMaxPosition));
}
`;return}const F="max";let _=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(_="avgValue / count");const B=Math.floor(o/4)*4,U=o%4,Y=`
if (${E}) {
avgValue += dot(values, ones);
} else {
minMaxValue = ${F}(values, minMaxValue);
}
`;this.userCode=`
const ivec3 strides =
ivec3(${a}, ${c}, ${u});
const ivec3 pads = ivec3(${T}, ${v}, ${N});
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 (${U===1}) {
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
initializationValue,
initializationValue,
initializationValue
);
${Y}
} else if (${U===2}) {
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
getValue(batch, xD, xR, xC + ${y}, ch),
initializationValue,
initializationValue
);
${Y}
} else if (${U===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(${_});
}
}
`}}class AC{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 u=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="sum"?u="sumValue":t==="prod"?u="prodValue":t==="all"?u="allValue":t==="any"&&(u="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(${u});
}
`}}class vC{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=`
${V8(t)}
${yS(e)}
void main() {
ivec3 rc = getOutputCoords();
vec4 result = vec4(0.);
ivec3 thisRC;
int rows = ${e[1]};
int cols = ${e[2]};
${n}
setOutput(result);
}
`}}function V8(e){const t=Xo(["r","c","d"],e);return`
ivec3 inputCoordsFromReshapedOutCoords(int index) {
${t}
return ivec3(r, c, d);
}
`}class H8{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t.shape;const[,s,i]=t.shape,[,o,a]=e.shape,c=[n&&o>1?s-1:s,n&&a>1?i-1:i],u=[n&&o>1?o-1:o,n&&a>1?a-1:a],p=c[0]/u[0],m=c[1]/u[1],y=1/p,b=1/m,w=Math.ceil(y)*2+2,I=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(${I});
// 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 Y8{constructor(e,t,n,s){this.variableNames=["A"],this.outputShape=[];const[i,o,a,c]=e;this.outputShape=[i,t,n,c];const u=[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(
${u[0]/p[0]},
${u[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 q8{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 u=[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(
${u[0]/p[0]},
${u[1]/p[1]},
${u[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 j8{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],u=[n&&o>1?o-1:o,n&&a>1?a-1:a],p=c[0]/u[0],m=c[1]/u[1],y=1/p,b=1/m,w=Math.ceil(y)*2+2,I=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(${I});
// 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(${u[0]}));
float sourceFracCol =
float(${c[1]}) *
(float(dyC) / float(${u[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 K8{constructor(e,t,n,s){this.variableNames=["A"],this.outputShape=[];const[i,o,a,c]=e;this.outputShape=[i,t,n,c];const u=[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(
${u[0]/p[0]},
${u[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 X8{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=Et(n);this.userCode=`
void main() {
${o} coords = getOutputCoords();
setOutput(getX(${i}));
}
`}}class J8{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=us("rc",n),i=`${s[n-1]} + 1 < ${this.outputShape[n-1]}`,o=`${s[n-2]} + 1 < ${this.outputShape[n-2]}`,a=Et(n);n===1?this.userCode=`
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 = ${u(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 u(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 I=e.map((N,E)=>b(E,w)),T=I.join(","),v=I.slice(-2).join(",");return`getChannel(getX(${T}), vec2(${v}))`}function b(w,I){return t.indexOf(w)!==-1&&e[w]!==1?`${e[w]} - ${I[w]} - 1`:`${I[w]}`}}}class NC{constructor(e,t,n,s,i,o,a=!0){this.variableNames=["updates","indices","defaultValue"],this.outputShape=o;const c=Et(i.length),u=Et(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() {
${u} 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 Z8{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",u="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(${u});
}
`}}class Q8{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=[],u=[];for(let p=0;p<t.length;p++)u.push(`${a[p]}`),p<e&&c.push(`${a[p]}`);s=c.join(),i=u.join()}const o=Et(n);this.userCode=`
void main() {
${o} resRC = getOutputCoords();
float cVal = getC(${s});
if (cVal >= 1.0) {
setOutput(getA(${i}));
} else {
setOutput(getB(${i}));
}
}
`}}class e6{constructor(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;const t=Et(this.rank),n=`uniform int start[${this.rank}];`,s=t6(this.rank);let i;const o=e.map((a,c)=>`sourceLoc.${IS[c]} = start[${c}] + coords.${IS[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 IS=["x","y","z","w","u","v"];function t6(e){if(e===1)return"sourceLoc";if(e<=6)return IS.slice(0,e).map(t=>"sourceLoc."+t).join(",");throw Error(`Slicing for rank ${e} is not yet supported`)}class n6{constructor(e){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.rank=e.length;const t=Et(this.rank),n=us("coords",this.rank),s=us("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};
}
}
`,u=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;
${u}
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 s6{constructor(e,t,n){this.variableNames=["x"],this.outputShape=n;const s=n.length,i=Et(n.length),o=Et(n.length);let a="";if(s===1)a="coords * strides + begin";else{let c=0;a=n.map((u,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 i6{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=RC(t,n),i=OC(e,s,n);i in this.freeTextures||(this.freeTextures[i]=[]),i in this.usedTextures||(this.usedTextures[i]=[]);const o=CC(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===In.PACKED_2X2_FLOAT32?a=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):s===In.PACKED_2X2_FLOAT16?a=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):s===In.UNPACKED_FLOAT32?a=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):s===In.UNPACKED_FLOAT16?a=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):s===In.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=RC(n,s),o=OC(t,i,s);o in this.freeTextures||(this.freeTextures[o]=[]);const a=CC(t,i,this.gpgpu.gl,this.gpgpu.textureConfig,s),c=C().get("WEBGL_DELETE_TEXTURE_THRESHOLD");c!==-1&&this._numBytesAllocated>c?(this.gpgpu.deleteMatrixTexture(e),this._numBytesAllocated-=a):(this.freeTextures[o].push(e),this.numFreeTextures++,this._numBytesFree+=a),this.numUsedTextures--;const u=this.usedTextures[o],p=u.indexOf(e);if(p<0)throw new Error("Cannot release a texture that was never provided by this texture manager");u.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 r6(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 CC(e,t,n,s,i){const o=o6(t,s);let a;if(i){const[u,p]=fc(e[0],e[1]);a=u*p}else{const[u,p]=cu(e[0],e[1]);a=u*p}const c=r6(n,o);return a*c}function o6(e,t){switch(e){case In.PACKED_2X2_FLOAT32:return IC(t);case In.PACKED_2X2_FLOAT16:return xC(t);case In.UNPACKED_FLOAT32:return wC(t);case In.UNPACKED_FLOAT16:return LC(t);case In.PACKED_4X1_UNSIGNED_BYTE:return SC(t);default:throw new Error(`Unknown physical texture type ${e}`)}}function a6(e){return C().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?In.PACKED_2X2_FLOAT32:In.UNPACKED_FLOAT32:e?In.PACKED_2X2_FLOAT16:In.UNPACKED_FLOAT16}function RC(e,t){if(e===Cs.UPLOAD)return In.PACKED_2X2_FLOAT32;if(e===Cs.RENDER||e==null)return a6(t);if(e===Cs.DOWNLOAD||e===Cs.PIXELS)return In.PACKED_4X1_UNSIGNED_BYTE;throw new Error(`Unknown logical texture type ${e}`)}function OC(e,t,n){return`${e[0]}_${e[1]}_${t}_${n}`}class c6{constructor(e,t){this.variableNames=["A"];const n=new Array(e.length);for(let o=0;o<n.length;o++)n[o]=e[o]*t[o];this.outputShape=n,this.rank=n.length;const s=Et(this.rank),i=l6(e);this.userCode=`
void main() {
${s} resRC = getOutputCoords();
setOutput(getA(${i}));
}
`}}function l6(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 dr="if (isnan(x)) return x;",h6="return x;",EC="return abs(x);",DC=dr+`
return (x < 0.0) ? 0.0 : x;
`,kC=dr+`
return (x < 0.0) ? 0.0 : min(6.0, x);
`,FC="return (x >= 0.0) ? x : (exp(x) - 1.0);",u6=`
// Stable and Attracting Fixed Point (0, 1) for Normalized Weights.
// see: https://arxiv.org/abs/1706.02515
float scaleAlpha = ${xp};
float scale = ${Tp};
return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);
`;function d6(e=0){return dr+`
return x > 0.0 ? 1.0 : float(${e});
`}const _C="return -x;",WC="return ceil(x);",$C="return floor(x);",p6=`
if (isnan(x)) { return 0.0; }
return sign(x);
`,m6="return float(isnan(x));",f6="return float(isinf(x));",g6="return float(!isnan(x) && !isinf(x));",y6=`
// 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;
}
}
`,UC="return exp(x);",BC="return exp(x) - 1.0;",b6=`if (x < 0.0) return NAN;
return log(x);`,w6="return log(1.0 + x);",L6="return sqrt(x);",S6="return inversesqrt(x);",I6="return 1.0 / (1.0 + exp(-1.0 * x));",x6=`
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;
`,T6=dr+`
if (abs(x) > 1.) {
return NAN;
}
return asin(x);
`,A6=dr+`
if (abs(x) > 1.) {
return NAN;
}
return acos(x);
`,v6=dr+`
return atan(x);
`,N6=`
float e2x = exp(x);
return (e2x - 1.0 / e2x) / 2.0;
`,C6=`
float e2x = exp(-x);
return (e2x + 1.0 / e2x) / 2.0;
`,R6=`
float e2x = exp(-2.0 * abs(x));
return sign(x) * (1.0 - e2x) / (1.0 + e2x);
`,O6=dr+"return log(x + sqrt(x * x + 1.0));",E6=dr+`
if (x < 1.0) return NAN;
return log(x + sqrt(x * x - 1.0));`,D6=dr+`
if ((x < -1.0) || (x > 1.0)) return NAN;
return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,k6=`
// Error function is calculated approximately with elementary function.
// See "Handbook of Mathematical Functions with Formulas,
// Graphs, and Mathematical Tables", Abramowitz and Stegun.
float p = ${Xb};
float a1 = ${Jb};
float a2 = ${Zb};
float a3 = ${Qb};
float a4 = ${ew};
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));
`,F6="return 1.0 / x;",_6="return float(!(x >= 1.0));",W6="return float(int(x));",Im="return x;";const $6="return x;",U6=`
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;
`,MC=`
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;
`,PC=`
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;
`,zC=`
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 pu{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 B6{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e;const t=e.length,n=us("rc",t),s=Et(t),i=xK(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:GC}=iw,M6=rw,P6=ow,z6=aw,G6=dp,V6=1e-7,H6=1e-4,xm={};function Y6(e){return e in xm||(xm[e]={}),xm[e]}function Tm(e,t=!1){if(e==="linear")return t?$6:h6;if(e==="relu")return t?MC:DC;if(e==="elu")return t?zC:FC;if(e==="relu6")return t?PC:kC;if(e==="prelu")return t?hC:lC;throw new Error(`Activation ${e} has not been implemented for the WebGL backend.`)}const q6=128,j6=600;function K6(){return C().global.screen==null?1024:C().global.screen.height*C().global.screen.width*window.devicePixelRatio*j6/1024/1024}const VC=1e3;class X6 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,!C().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");if(e==null){const t=Mi(C().getNumber("WEBGL_VERSION"));this.binaryCache=Y6(C().getNumber("WEBGL_VERSION")),this.gpgpu=new T8(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 i6(this.gpgpu),this.numMBBeforeWarning=K6(),this.texData=new d(this,$s())}numDataIds(){return this.texData.numDataIds()+(this.cpuBackend?this.cpuBackend.numDataIds():0)-this.pendingDeletes}write(e,t,n){if((C().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||C().getBool("DEBUG"))&&this.checkNumericalProblems(e),n==="complex64"&&e!=null)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");const s={};return this.texData.set(s,{shape:t,dtype:n,values:e,usage:Cs.UPLOAD,refCount:1}),s}incRef(e){const t=this.texData.get(e);t.refCount++}decRef(e){if(this.texData.has(e)){const t=this.texData.get(e);t.refCount--}}move(e,t,n,s){if(C().getBool("DEBUG")&&this.checkNumericalProblems(t),s==="complex64")throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(e,{shape:n,dtype:s,values:t,usage:Cs.UPLOAD,refCount:1})}disposeIntermediateTensorInfo(e){const t=e.dataId;if(this.texData.has(t)){const n=this.texData.get(t);n.refCount--,n.refCount<1&&this.disposeData(t)}}readSync(e){const t=this.texData.get(e),{values:n,dtype:s,complexTensors:i,slice:o,shape:a,isPacked:c}=t;if(o!=null){let y;c?y=new pu(a,Im):y=new it(a,Im);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 u=this.activeTimers!=null;let p;u&&(p=qn());let m;if(s==="complex64"){const y=i.real.dataSync(),b=i.imag.dataSync();m=ir(y,b)}else m=this.getValuesFromTexture(e);return u&&(this.downloadWaitMs+=qn()-p),this.convertAndCacheOnCPU(e,m)}async read(e){if(this.pendingRead.has(e)){const w=this.pendingRead.get(e);return new Promise(I=>w.push(I))}const t=this.texData.get(e),{values:n,shape:s,slice:i,dtype:o,complexTensors:a,isPacked:c}=t;if(i!=null){let w;c?w=new pu(s,Im):w=new it(s,Im);const I=this.runWebGLProgram(w,[{dataId:e,shape:s,dtype:o}],o),T=this.read(I.dataId);return this.disposeIntermediateTensorInfo(I),T}if(n!=null)return this.convertAndCacheOnCPU(e);if(!C().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&C().getNumber("WEBGL_VERSION")===2)throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");let u=null,p;if(o!=="complex64"&&C().get("WEBGL_BUFFER_SUPPORTED")){p=this.decode(e);const w=this.texData.get(p.dataId);u=this.gpgpu.createBufferFromTexture(w.texture,...lu(s))}this.pendingRead.set(e,[]),o!=="complex64"&&await this.gpgpu.createAndWaitForFence();let m;if(o==="complex64"){const w=await Promise.all([a.real.data(),a.imag.data()]),I=w[0],T=w[1];m=ir(I,T)}else if(u==null)m=this.getValuesFromTexture(e);else{const w=we(s);m=this.gpgpu.downloadFloat32MatrixFromBuffer(u,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(!_j(n))throw C().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=we(t);if(C().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")){const y=this.decode(e),b=this.texData.get(y.dataId),w=this.gpgpu.downloadMatrixFromPackedTexture(b.texture,...lu(t)).subarray(0,i);return this.disposeIntermediateTensorInfo(y),w}const o=C().getBool("WEBGL_PACK")&&s===!0,a=o?fS(t):t,c=o?new t8(a):new e8(a),u=this.runWebGLProgram(c,[{shape:a,dtype:n,dataId:e}],"float32"),p=this.texData.get(u.dataId),m=this.gpgpu.downloadByteEncodedFloatMatrixFromOutputTexture(p.texture,p.texShape[0],p.texShape[1]).subarray(0,i);return this.disposeIntermediateTensorInfo(u),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=Ji(this.activeTimers.map(c=>c.query)).filter(c=>c!=null),o=Ji(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(C().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0){const c=await Promise.all(i);a.kernelMs=iT(c),a.getExtraProfileInfo=()=>c.map((u,p)=>({name:o[p],ms:u})).map(u=>`${u.name}: ${u.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 C().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:qn(),endMs:null}}endTimer(e){return C().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),e):(e.endMs=qn(),e)}async getQueryTime(e){if(C().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;this.releaseGPUData(e);const{complexTensors:t}=this.texData.get(e);t!=null&&(t.real.dispose(),t.imag.dispose()),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,u=this.dataRefCount.get(c);u>1?this.dataRefCount.set(c,u-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 C().getBool("WEBGL_CPU_FORWARD")?(this.cpuBackend==null&&(this.cpuBackend=$s().findBackend("cpu")),this.cpuBackend):null}shouldExecuteOnCPU(e,t=q6){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&&we(s.shape)<t)}getGPGPUContext(){return this.gpgpu}complex(e,t){const n=this.makeOutput(e.shape,"complex64"),s=this.texData.get(n.dataId);return s.complexTensors={real:$s().keep(e.clone()),imag:$s().keep(t.clone())},n}real(e){const t=this.texData.get(e.dataId);return t.complexTensors.real.clone()}imag(e){const t=this.texData.get(e.dataId);return t.complexTensors.imag.clone()}slice(e,t,n){if(this.shouldExecuteOnCPU([e])){const o=yK(this.texData.get(e.dataId).values,t,n,e.shape,e.dtype);return this.makeOutput(n,e.dtype,o)}if(we(n)===0)return en([],n,e.dtype);const{isPacked:s}=this.texData.get(e.dataId),i=Xy(e.shape,t,n);if(s||!i){const o=C().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new n6(n):new e6(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=Jy(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=Wd(t,n,s);if(o.some(c=>c===0))return en([],o);const a=new s6(t,s,o);return this.compileAndRun(a,[e])}reverse(e,t){const n=C().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new J8(e.shape,t):new X8(e.shape,t);return this.compileAndRun(n,[e])}concat(e,t){if(e[0].dtype==="complex64"){const a=e.map(u=>Fo(u)),c=e.map(u=>Ga(u));return Ci(this.concat(a,t),this.concat(c,t))}if(e.length===1)return e[0];if(e.length>C().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){const a=Math.floor(e.length/2),c=this.concat(e.slice(0,a),t),u=this.concat(e.slice(a),t);return this.concat([c,u],t)}if(C().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&e[0].rank>1){const a=new P5(e.map(c=>c.shape),t);return this.compileAndRun(a,e)}const n=Ur(e.map(a=>a.shape),t),s=e.map(a=>a.as2D(-1,we(a.shape.slice(t)))),i=new M5(s.map(a=>a.shape)),o=this.compileAndRun(i,s);return o.reshape(n)}neg(e){const t=this.tryRunOnCpuOrThrow([e],()=>this.cpuBackend.neg(e));if(t)return t;if(C().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,_C,e.dtype);const n=new it(e.shape,_C);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,,]=e.shape;if((i===1||o===1)&&a>VC){n&&(e=Pe(e,[0,2,1])),s&&(t=Pe(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;return this.multiply(m,b).sum(y,!0)}const u=Cn(e.dtype,t.dtype),p=new LS(e.shape,[c,i,o],n,s);return this.compileAndRun(p,[e,t],u)}fusedBatchMatMul({a:e,b:t,transposeA:n,transposeB:s,bias:i,activation:o,preluActivationWeights:a}){const c=n?e.shape[2]:e.shape[1],u=s?t.shape[1]:t.shape[2],[p,,]=e.shape,m=Cn(e.dtype,t.dtype),y=i!=null,b=a!=null,w=o?Tm(o,!0):null,I=new LS(e.shape,[p,c,u],n,s,y,w,b),T=[e,t];return i&&T.push(i),a&&T.push(a),this.compileAndRun(I,T,m)}multiply(e,t){if(e.dtype==="complex64"){const i=this.texData.get(e.dataId),o=this.texData.get(t.dataId),a=new oC(rC.REAL,e.shape,t.shape),c=new oC(rC.IMAG,e.shape,t.shape),u=[this.makeComplexComponentTensorInfo(e,i.complexTensors.real),this.makeComplexComponentTensorInfo(e,i.complexTensors.imag),this.makeComplexComponentTensorInfo(t,o.complexTensors.real),this.makeComplexComponentTensorInfo(t,o.complexTensors.imag)],p=this.compileAndRun(a,u),m=this.compileAndRun(c,u),y=this.complex(p,m);return p.dispose(),m.dispose(),y}const n=Cn(e.dtype,t.dtype);if(this.shouldExecuteOnCPU([e,t])){const i=this.texData.get(e.dataId),o=this.texData.get(t.dataId),[a,c]=fK(e.shape,t.shape,i.values,o.values,n);return this.makeOutput(c,n,a)}if(C().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,cC,e.dtype);const s=new un(cC,e.shape,t.shape);return this.compileAndRun(s,[e,t],e.dtype)}localResponseNormalization4D(e,t,n,s,i){const o=C().getBool("WEBGL_PACK_NORMALIZATION")?new D8(e.shape,t,n,s,i):new O8(e.shape,t,n,s,i);return this.compileAndRun(o,[e])}LRNGrad(e,t,n,s,i,o,a){const c=new E8(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=>Yl(a)),o=Qe(e.shape,e.dtype,i);return P6(o,t)}const n=new c6(e.shape,t);return this.compileAndRun(n,[e])}pad(e,t,n){const s=C().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new G8(e.shape,t,n):new z8(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 r8(e.shape,t.size,n);return this.compileAndRun(i,[e,t])}batchToSpaceND(e,t,n){k(e.rank<=4,()=>"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet");const s=t.reduce((p,m)=>p*m),i=Rh(e.shape,t,s),o=Oh(i.length,t.length),a=Eh(e.shape,t,s),c=jb(n,t.length),u=Kb(a,n,t.length);return Pe(e.reshape(i),o).reshape(a).slice(c,u)}spaceToBatchND(e,t,n){k(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=Rh(o.shape,t,s,!1),c=Oh(a.length,t.length,!1),u=Eh(o.shape,t,s,!1),p=Pe(o.reshape(a),c);return K(p,u)}reduce(e,t,n){const s=e.shape[0],i=e.shape[1],o=uh(i),a=Math.ceil(i/o),c={windowSize:o,inSize:i,batchSize:s,outSize:a},u=new AC(c,t),p=this.compileAndRun(u,[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=uh(i),a={windowSize:o,inSize:i,batchSize:s,outSize:Math.ceil(i/o)},c=new IK(a,t,n==null),u=[e];n!=null&&u.push(n);const p=this.compileAndRun(c,u,"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=uh(i),a=new o5(s,o,t,n==null),c=n==null?[e]:[e,n],u=this.compileAndRun(a,c,"int32");return u.rank===e.rank?this.argReducePacked(e,t,u):u}sum(e,t){ss("sum",t,e.rank);const[n,s]=On(e.shape,t),i=we(s),o=e.as2D(-1,i),a=vd(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]=On(e.shape,t),o=we(i),a=e.as2D(-1,o),c=vd(e.dtype);return this.reduce(a,"prod",c).reshape(s)}unsortedSegmentSum(e,t,n){let s=0;const i=_n([s],e.rank);let o=e;i!=null&&(o=Pe(e,i),s=Is(1,e.rank)[0]);const a=GC.computeOutShape(o.shape,s,n),c=we([o.shape[s]]),u=o.as2D(-1,c),p=vd(e.dtype);let m=this.segOpCompute(u,"unsortedSegmentSum",t,p,n).reshape(a);return i!=null&&(m=Pe(m,eh(i))),m}segOpCompute(e,t,n,s,i){const o=e.shape[0],a=e.shape[1],c=GC.segOpComputeOptimalWindowSize(a,i),u={windowSize:c,inSize:a,batchSize:o,numSegments:i},p=new Z8(u,t),m=this.compileAndRun(p,[e,n],s);return m.shape[1]===i?m:(n=yh(0,i).tile([a/c]),this.segOpCompute(m,t,n,s,i))}argMinMaxReduce(e,t,n){const s=[t];if(ss("arg"+n.charAt(0).toUpperCase()+n.slice(1),s,e.rank),!C().getBool("WEBGL_PACK_REDUCE")||e.rank<=2){const[i,o]=On(e.shape,s),a=we(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 mC(e.shape,!1,s),u=c.getCustomSetupFunc(a),p=o;o=this.compileAndRun(c,[o],o.dtype,u),p.dispose()}if(n){const a=new mC(e.shape,n,s),c=o;o=this.compileAndRun(a,[o]),c.dispose()}return o}equal(e,t){if(C().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,v5,"bool");const n=new un(u5,e.shape,t.shape);return this.compileAndRun(n,[e,t],"bool")}notEqual(e,t){if(C().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,N5,"bool");const n=new un(d5,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(C().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,C5,"bool");const s=new un(p5,e.shape,t.shape);return this.compileAndRun(s,[e,t],"bool")}lessEqual(e,t){if(C().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,R5,"bool");const n=new un(m5,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(C().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,O5,"bool");const s=new un(f5,e.shape,t.shape);return this.compileAndRun(s,[e,t],"bool")}greaterEqual(e,t){if(C().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,E5,"bool");const n=new un(g5,e.shape,t.shape);return this.compileAndRun(n,[e,t],"bool")}logicalNot(e){const t=new it(e.shape,_6);return this.compileAndRun(t,[e])}logicalAnd(e,t){if(C().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,D5,"bool");const n=new un(y5,e.shape,t.shape);return this.compileAndRun(n,[e,t],"bool")}logicalOr(e,t){if(C().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,k5,"bool");const n=new un(b5,e.shape,t.shape);return this.compileAndRun(n,[e,t],"bool")}select(e,t,n){const s=new Q8(e.rank,t.shape,t.rank);return this.compileAndRun(s,[e,t,n],Cn(t.dtype,n.dtype))}where(e){Qa("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");const t=e.dataSync();return G6(e.shape,t)}topk(e,t,n){const s=e.dataSync();return z6(s,e.shape,e.dtype,t,n)}min(e,t){ss("min",t,e.rank);const[n,s]=On(e.shape,t),i=we(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=C().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new to(_5,e.shape,t.shape):new un(L5,e.shape,t.shape);return this.compileAndRun(s,[e,t])}mod(e,t){const n=C().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new to(W5,e.shape,t.shape):new un(S5,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=C().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new to(F5,e.shape,t.shape):new un(w5,e.shape,t.shape);return this.compileAndRun(s,[e,t])}all(e,t){ss("all",t,e.rank);const[n,s]=On(e.shape,t),i=we(s),o=e.as2D(-1,i);return this.reduce(o,"all",o.dtype).reshape(n)}any(e,t){ss("any",t,e.rank);const[n,s]=On(e.shape,t),i=we(s),o=e.as2D(-1,i);return this.reduce(o,"any",o.dtype).reshape(n)}floorDiv(e,t){const n=l5,s="int32";if(C().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,x5,s);const i=new un(n,e.shape,t.shape);return this.compileAndRun(i,[e,t],s)}add(e,t){if(e.dtype==="complex64"&&t.dtype==="complex64")return this.complexSeparableBinaryOp(e,t,bS);const n=Cn(e.dtype,t.dtype);if(this.shouldExecuteOnCPU([e,t])){const i=this.texData.get(e.dataId),o=this.texData.get(t.dataId),[a,c]=cK(e.shape,t.shape,i.values,o.values,n);return this.makeOutput(c,n,a)}if(C().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,bS,n);const s=new un(bS,e.shape,t.shape);return this.compileAndRun(s,[e,t],n)}packedUnaryOp(e,t,n){const s=new pu(e.shape,t);return this.compileAndRun(s,[e],n)}packedBinaryOp(e,t,n,s,i=!1){const o=new to(n,e.shape,t.shape,i);return this.compileAndRun(o,[e,t],s)}complexSeparableBinaryOp(e,t,n){const s=this.texData.get(e.dataId),i=this.texData.get(t.dataId),[o,a]=[[s.complexTensors.real,i.complexTensors.real],[s.complexTensors.imag,i.complexTensors.imag]].map(u=>{const[p,m]=u,y=this.makeComplexComponentTensorInfo(e,p),b=this.makeComplexComponentTensorInfo(t,m),w=new un(n,e.shape,t.shape);return this.compileAndRun(w,[y,b],Cn(p.dtype,m.dtype))}),c=this.complex(o,a);return o.dispose(),a.dispose(),c}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>C().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)=>Cn(o,a)),n=e.map(o=>o.shape),s=C().getBool("WEBGL_PACK"),i=s?new SK(e[0].shape,n):new LK(e[0].shape,n);return this.compileAndRun(i,e,t)}subtract(e,t){if(e.dtype==="complex64"&&t.dtype==="complex64")return this.complexSeparableBinaryOp(e,t,wS);const n=Cn(e.dtype,t.dtype);if(this.shouldExecuteOnCPU([e,t])){const i=this.texData.get(e.dataId),o=this.texData.get(t.dataId),[a,c]=bK(e.shape,t.shape,i.values,o.values,n);return this.makeOutput(c,n,a)}if(C().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,wS,e.dtype);const s=new un(wS,e.shape,t.shape);return this.compileAndRun(s,[e,t],n)}pow(e,t){const n=C().getBool("WEBGL_PACK_BINARY_OPERATIONS"),s=n?new to(T5,e.shape,t.shape):new un(h5,e.shape,t.shape),i=Cn(e.dtype,t.dtype);return this.compileAndRun(s,[e,t],i)}ceil(e){if(this.shouldExecuteOnCPU([e])){const n=lK(this.texData.get(e.dataId).values,e.dtype);return this.makeOutput(e.shape,e.dtype,n)}if(C().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,WC,e.dtype);const t=new it(e.shape,WC);return this.compileAndRun(t,[e])}floor(e){if(this.shouldExecuteOnCPU([e])){const n=dK(this.texData.get(e.dataId).values,e.dtype);return this.makeOutput(e.shape,e.dtype,n)}if(C().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,$C,e.dtype);const t=new it(e.shape,$C);return this.compileAndRun(t,[e])}sign(e){const t=new it(e.shape,p6);return this.compileAndRun(t,[e])}isNaN(e){const t=new it(e.shape,m6);return this.compileAndRun(t,[e],"bool")}isInf(e){const t=new it(e.shape,f6);return this.compileAndRun(t,[e],"bool")}isFinite(e){const t=new it(e.shape,g6);return this.compileAndRun(t,[e],"bool")}round(e){const t=new it(e.shape,y6);return this.compileAndRun(t,[e])}exp(e){if(this.shouldExecuteOnCPU([e])){const n=hK(this.texData.get(e.dataId).values,e.dtype);return this.makeOutput(e.shape,e.dtype,n)}if(C().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,UC,e.dtype);const t=new it(e.shape,UC);return this.compileAndRun(t,[e])}expm1(e){if(this.shouldExecuteOnCPU([e])){const n=uK(this.texData.get(e.dataId).values,e.dtype);return this.makeOutput(e.shape,e.dtype,n)}if(C().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,BC,e.dtype);const t=new it(e.shape,BC);return this.compileAndRun(t,[e])}softmax(e,t){const n=ft([t],e.shape),s=Xn(e,n),i=En(s.shape,n),o=this.subtract(e,s.reshape(i)),a=this.exp(o),c=this.sum(a,n).reshape(i);return _e(a,c)}log(e){if(this.shouldExecuteOnCPU([e])){const n=pK(this.texData.get(e.dataId).values,e.dtype);return this.makeOutput(e.shape,e.dtype,n)}if(C().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,U6,e.dtype);const t=new it(e.shape,b6);return this.compileAndRun(t,[e])}log1p(e){const t=new it(e.shape,w6);return this.compileAndRun(t,[e])}sqrt(e){const t=new it(e.shape,L6);return this.compileAndRun(t,[e])}rsqrt(e){if(this.shouldExecuteOnCPU([e])){const n=gK(this.texData.get(e.dataId).values,e.dtype);return this.makeOutput(e.shape,e.dtype,n)}const t=new it(e.shape,S6);return this.compileAndRun(t,[e])}reciprocal(e){const t=new it(e.shape,F6);return this.compileAndRun(t,[e])}relu(e){let t;return C().getBool("WEBGL_PACK")?t=new pu(e.shape,MC):t=new it(e.shape,DC),this.compileAndRun(t,[e])}relu6(e){let t;return C().getBool("WEBGL_PACK")?t=new pu(e.shape,PC):t=new it(e.shape,kC),this.compileAndRun(t,[e])}prelu(e,t){const n=C().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new to(hC,e.shape,t.shape):new un(lC,e.shape,t.shape);return this.compileAndRun(n,[e,t])}elu(e){if(C().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,zC,e.dtype);const t=new it(e.shape,FC);return this.compileAndRun(t,[e])}eluDer(e,t){const n=C().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new to(A5,e.shape,t.shape):new un(I5,e.shape,t.shape);return this.compileAndRun(n,[e,t])}selu(e){const t=new it(e.shape,u6);return this.compileAndRun(t,[e])}int(e){const t=new it(e.shape,W6);return this.compileAndRun(t,[e],"int32")}clip(e,t,n){let s;C().getBool("WEBGL_PACK_CLIP")?s=new U5(e.shape):s=new $5(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=aK(this.texData.get(e.dataId).values);return this.makeOutput(e.shape,e.dtype,n)}if(C().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,EC,e.dtype);const t=new it(e.shape,EC);return this.compileAndRun(t,[e])}complexAbs(e){const t=this.texData.get(e.dataId),n=new B5(e.shape),s=[this.makeComplexComponentTensorInfo(e,t.complexTensors.real),this.makeComplexComponentTensorInfo(e,t.complexTensors.imag)];return this.compileAndRun(n,s)}sigmoid(e){const t=new it(e.shape,I6);return this.compileAndRun(t,[e])}softplus(e){const t=new it(e.shape,x6);return this.compileAndRun(t,[e])}asin(e){const t=new it(e.shape,T6);return this.compileAndRun(t,[e])}acos(e){const t=new it(e.shape,A6);return this.compileAndRun(t,[e])}atan(e){const t=new it(e.shape,v6);return this.compileAndRun(t,[e])}sinh(e){const t=new it(e.shape,N6);return this.compileAndRun(t,[e])}cosh(e){const t=new it(e.shape,C6);return this.compileAndRun(t,[e])}tanh(e){const t=new it(e.shape,R6);return this.compileAndRun(t,[e])}asinh(e){const t=new it(e.shape,O6);return this.compileAndRun(t,[e])}acosh(e){const t=new it(e.shape,E6);return this.compileAndRun(t,[e])}atanh(e){const t=new it(e.shape,D6);return this.compileAndRun(t,[e])}erf(e){const t=new it(e.shape,k6);return this.compileAndRun(t,[e])}step(e,t){const n=new it(e.shape,d6(t));return this.compileAndRun(n,[e])}conv2dByMatMul(e,t,n,s,i,o){const a=e.shape,c=this.texData.get(e.dataId),u=n.inChannels,p=a[0]*a[1]*a[2],m=n.outChannels,y=n.dataFormat==="channelsLast",b=!1,w=!1,I=(p===1||m===1)&&u>VC,T=a[2]%2!==0&&!!c.isPacked;if(I||!C().getBool("WEBGL_LAZILY_UNPACK")||!C().getBool("WEBGL_PACK_BINARY_OPERATIONS")||!T){const B=y?a[0]*a[1]*a[2]:a[0]*a[2]*a[3],U=K(e,[1,B,n.inChannels]),Y=K(t,[1,n.inChannels,n.outChannels]),q=this.fusedBatchMatMul({a:U,b:Y,transposeA:b,transposeB:w,bias:s,activation:i,preluActivationWeights:o});return K(q,n.outShape)}const v=y?a[0]*a[1]*(a[2]+1):a[0]*a[2]*(a[3]+1),N={dataId:e.dataId,shape:[1,v,n.inChannels],dtype:e.dtype},E=c.shape;c.shape=c.shape.slice(),c.shape[c.shape.length-2]++,k(gm(c.shape,N.shape),()=>`packed reshape ${c.shape} to ${N.shape} isn't free`);const D=K(t,[1,n.inChannels,n.outChannels]),F=this.fusedBatchMatMul({a:N,b:D,transposeA:b,transposeB:w,bias:s,activation:i,preluActivationWeights:o}),_=this.texData.get(F.dataId);return k(_.isPacked,()=>"batchMatMul result is expected to be packed"),c.shape=E,_.shape=n.outShape,$s().makeTensorFromDataId(F.dataId,n.outShape,F.dtype)}conv2dWithIm2Row(e,t,n,s,i,o){const{filterWidth:a,filterHeight:c,inChannels:u,outWidth:p,outHeight:m,dataFormat:y}=n,b=y==="channelsLast",w=a*c*u,I=m*p,T=[w,I],v=!0,N=!1,E=e.squeeze([0]),D=t.reshape([1,w,-1]),F=new R8(T,E.shape,n),_=this.compileAndRun(F,[E]).reshape([1,T[0],T[1]]),B=s!=null,U=o!=null,Y=i?Tm(i,!0):null,q=new LS(_.shape,[1,I,n.outChannels],v,N,B,Y,U),J=[_,D];s&&J.push(s),U&&J.push(o);const oe=this.compileAndRun(q,J);return b?oe.reshape([1,m,p,n.outChannels]):oe.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(C().getBool("WEBGL_CONV_IM2COL")&&e.shape[0]===1)return this.conv2dWithIm2Row(e,t,n,s,i,o);const a=s!=null,c=o!=null,u=i?Tm(i,!1):null,p=new uC(n,a,u,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(C().getBool("WEBGL_CONV_IM2COL")&&e.shape[0]===1)return this.conv2dWithIm2Row(e,t,n);const s=new uC(n);return this.compileAndRun(s,[e,t])}conv2dDerInput(e,t,n){const s=new G5(n);return this.compileAndRun(s,[e,t])}conv2dDerFilter(e,t,n){const s=new z5(n);return this.compileAndRun(s,[e,t])}fusedDepthwiseConv2D({input:e,filter:t,convInfo:n,bias:s,activation:i,preluActivationWeights:o}){const a=C().getBool("WEBGL_PACK_DEPTHWISECONV")&&n.strideWidth<=2&&n.outChannels/n.inChannels===1,c=i?Tm(i,a):null,u=[e,t],p=s!=null,m=o!=null;p&&u.push(s),m&&u.push(o);let y;return a?(y=new pC(n,p,c,m),this.compileAndRun(y,u)):(y=new dC(n,p,c,m),this.compileAndRun(y,u))}depthwiseConv2D(e,t,n){let s;return C().getBool("WEBGL_PACK_DEPTHWISECONV")&&n.strideWidth<=2&&n.outChannels/n.inChannels===1?(s=new pC(n),this.compileAndRun(s,[e,t])):(s=new dC(n),this.compileAndRun(s,[e,t]))}depthwiseConv2DDerInput(e,t,n){const s=new q5(n);return this.compileAndRun(s,[e,t])}depthwiseConv2DDerFilter(e,t,n){const s=new Y5(n);return this.compileAndRun(s,[e,t])}conv3d(e,t,n){const s=new j5(n);return this.compileAndRun(s,[e,t])}conv3dDerInput(e,t,n){const s=new H5(n);return this.compileAndRun(s,[e,t])}conv3dDerFilter(e,t,n){const s=new V5(n);return this.compileAndRun(s,[e,t])}cast(e,t){return ov(e,t,this)}unstack(e,t){const n=e.shape[t],s=new Array(e.rank-1);let i=0;for(let u=0;u<e.rank;u++)u!==t&&(s[i++]=e.shape[u]);const o=new Array(e.rank).fill(0),a=e.shape.slice();a[t]=1;const c=new Array(n);for(let u=0;u<c.length;u++)o[t]=u,c[u]=this.slice(e,o,a).reshape(s);return c}avgPool3d(e,t){const n=new SS(t,"avg",!1);return this.compileAndRun(n,[e],"float32")}avgPool3dBackprop(e,t,n){const s=new c5(n);return this.compileAndRun(s,[e],t.dtype)}maxPool3d(e,t){const n=new SS(t,"max",!1);return this.compileAndRun(n,[e],"float32")}maxPool3dBackprop(e,t,n,s){const i=!0,o=new SS(s,"max",i),a=this.compileAndRun(o,[t]),c=new F8(s),u=this.compileAndRun(c,[e,a],t.dtype);return a.dispose(),u}resizeBilinear(e,t,n,s){const i=C().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new q8(e.shape,t,n,s):new Y8(e.shape,t,n,s);return this.compileAndRun(i,[e],"float32")}resizeBilinearBackprop(e,t,n){const s=new H8(e,t,n);return this.compileAndRun(s,[e])}resizeNearestNeighbor(e,t,n,s){const i=new K8(e.shape,t,n,s);return this.compileAndRun(i,[e])}resizeNearestNeighborBackprop(e,t,n){const s=new j8(e,t,n);return this.compileAndRun(s,[e])}multinomial(e,t,n,s){const i=t?e:Uo(e),o=i.shape[0],a=i.shape[1],c=new _8(o,a,n),u=c.getCustomSetupFunc(s);return this.compileAndRun(c,[i],"int32",u)}oneHot(e,t,n,s){const i=new W8(e.size,t,n,s);return this.compileAndRun(i,[e])}diag(e){const t=new Q5(e.size);return this.compileAndRun(t,[e])}cropAndResize(e,t,n,s,i,o){const a=new K5(e.shape,t.shape,s,i,o);return this.compileAndRun(a,[e,t,n],"float32")}depthToSpace(e,t,n){k(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,u=o*t,p=a/(t*t),m=n==="NHWC"?[s,c,u,p]:[s,p,c,u],y=new Z5(m,t,n);return this.compileAndRun(y,[e])}split(e,t,n){return M6(e,t,n)}scatterND(e,t,n){const{sliceRank:s,numUpdates:i,sliceSize:o,strides:a,outputSize:c}=Ua(t,e,n),u=[c/o,o],p=e.reshape([i,s]),m=t.reshape([i,o]);if(c===0)return av(en([]),n);const y=Ne(0),b=new NC(i,s,p.rank,m.rank,a,u),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}=Ua(t,e,n),u=!1,p=new NC(o,i,e.rank,t.rank,a,[c,1],u),m=this.compileAndRun(p,[t,e,s]);return m.reshape(n)}fft(e){const t=!1;return this.fftImpl(e,t)}ifft(e){const t=!0;return this.fftImpl(e,t)}fftImpl(e,t){const n=this.texData.get(e.dataId),s=new bC(yC.REAL,e.shape,t),i=new bC(yC.IMAG,e.shape,t),o=[this.makeComplexComponentTensorInfo(e,n.complexTensors.real),this.makeComplexComponentTensorInfo(e,n.complexTensors.imag)],a=this.compileAndRun(s,o),c=this.compileAndRun(i,o),u=this.complex(a,c).as2D(e.shape[0],e.shape[1]);return a.dispose(),c.dispose(),u}gatherND(e,t){const n=t.shape,s=n[n.length-1],[i,o,a,c]=Fd(e,t),u=t.reshape([o,s]),p=e.reshape([e.size/a,a]),m=new a8(s,c,[o,a]),y=this.compileAndRun(m,[p,u]);return y.reshape(i)}fill(e,t,n){if(n=n||Oa(t),n==="string"){const s=So(n,we(e));return s.fill(t),$s().makeTensor(s,e,n,this)}else{const s=new i8(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 sw(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 $s().makeTensorFromDataId(s,e,t,this)}unpackTensor(e){const t=new B6(e.shape);return this.runWebGLProgram(t,[e],e.dtype)}packTensor(e){const t=new $8(e.shape),n=!0;return this.runWebGLProgram(t,[e],e.dtype,null,n)}packedReshape(e,t){const n=[gc(e.shape),...yc(e.shape)],s={dtype:e.dtype,shape:n,dataId:e.dataId},i=[gc(t),...yc(t)],o=new vC(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=fS(s);let a;n?a=new J5(o):a=new X5(o);const c=!0,u=this.runWebGLProgram(a,[{shape:o,dtype:i,dataId:e}],i,null,c);return{dtype:i,shape:s,dataId:u.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===au.DENSE){const I=lu(e.outputShape);a.texShape=I.map(T=>T*2)}if(e.outTexUsage!=null&&(a.usage=e.outTexUsage),we(o.shape)===0)return a.values=wn(o.dtype,0),o;const c=[],u=t.map(I=>{if(I.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(I.dataId);if(T.texture==null){if(!e.packedInputs&&we(I.shape)<=C().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:I.shape,texData:null,isUniform:!0,uniformValues:T.values};e.packedInputs&&(T.isPacked=!0,T.shape=I.shape)}else if(!!T.isPacked!==!!e.packedInputs)I=T.isPacked?this.unpackTensor(I):this.packTensor(I),c.push(I),T=this.texData.get(I.dataId);else if(T.isPacked&&!gm(T.shape,I.shape)){const v=I,N=I.shape;I.shape=T.shape,I=this.packedReshape(I,N),c.push(I),T=this.texData.get(I.dataId),v.shape=N}return this.uploadToGPU(I.dataId),{shape:I.shape,texData:T,isUniform:!1}});this.uploadToGPU(o.dataId);const p={shape:o.shape,texData:a,isUniform:!1},m=C8(e,u,p),y=this.getAndSaveBinary(m,()=>v8(this.gpgpu,e,u,p)),b=this.activeTimers!=null;let w;if(b&&(w=this.startTimer()),N8(this.gpgpu,y,u,p,s),c.forEach(I=>this.disposeIntermediateTensorInfo(I)),b&&(w=this.endTimer(w),this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(w)})),!C().getBool("WEBGL_LAZILY_UNPACK")&&a.isPacked&&i===!1){const I=this.unpackTensor(o);return this.disposeIntermediateTensorInfo(o),I}return o}compileAndRun(e,t,n,s,i=!1){n=n||t[0].dtype;const o=this.runWebGLProgram(e,t,n,s,i);return $s().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(!C().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(!C().get("WEBGL_RENDER_FLOAT32_ENABLED")){const e=C().getBool("DEBUG");C().set("DEBUG",!1);const t=this.abs(Ne(1e-8)).dataSync()[0];if(C().set("DEBUG",e),t>0)return 32}return 16})),this.floatPrecisionValue}epsilon(){return this.floatPrecision()===32?V6:H6}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 u=this.activeTimers!=null;let p;u&&(p=qn());let m=t.texShape;if(m==null&&(m=Qj(n,c),t.texShape=m),i!=null){const y=fS(n);let b,w=m[1],I=m[0];const T=i instanceof Uint8Array;c?([w,I]=fc(m[0],m[1]),b=new s8(y,[I,w],T)):b=new n8(y,[I,w],T);const v=this.makeTensorInfo([I,w],s);T?this.texData.get(v.dataId).usage=Cs.PIXELS:this.texData.get(v.dataId).usage=Cs.UPLOAD,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(v.dataId),w,I,i);const N=!0,E=this.runWebGLProgram(b,[v],s,null,N),D=this.texData.get(E.dataId);t.texture=D.texture,t.texShape=D.texShape,t.isPacked=D.isPacked,t.usage=D.usage,this.disposeIntermediateTensorInfo(v),this.texData.delete(E.dataId),t.values=null,u&&(this.uploadWaitMs+=qn()-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=J6(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]*Ty(t)}tryRunOnCpuOrThrow(e,t){if(this.shouldExecuteOnCPU(e))try{return t()}catch(n){if(C().getBool("IS_TEST"))throw new Error("CPU forwarding failed")}return null}}function J6(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 Z6="2.6.0";function Q6(){C().set("WEBGL_FORCE_F16_TEXTURES",!0)}Fy()&&tb("webgl",()=>new X6,2);const dte={forceHalfFloat:Q6},HC="if (isnan(x)) return x;",e7=`
if (isnan(a)) return a;
if (isnan(b)) return b;
`,t7=`
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 Am(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 xS(e,t,n,s){return({inputs:i,backend:o})=>{const{a,b:c}=i,u=o,p=C().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new to(t,a.shape,c.shape,!!n):new un(e,a.shape,c.shape),m=s||a.dtype,y=u.runWebGLProgram(p,[a,c],m);return y}}const n7=e7+`
return atan(a, b);
`,s7=`
vec4 result = atan(a, b);
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
`+t7+`
return result;
`,i7=xS(n7,s7),r7={kernelName:Ai,backendName:"webgl",kernelFunc:i7};function TS(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 o7={kernelName:Sl,backendName:"webgl",kernelFunc:TS};function a7(e){const{inputs:t,backend:n,attrs:s}=e,{x:i}=t;hu(i,"avgPool");const{filterSize:o,strides:a,pad:c,dimRoundingMode:u}=s,p=1;k(on(a,p),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${p}'`);const m=Wn(i.shape,o,a,p,c,u);if(m.filterWidth===1&&m.filterHeight===1&&ot(m.inShape,m.outShape))return TS({inputs:{x:i},backend:n});const y=new du(m,"avg",!1);return n.runWebGLProgram(y,[i],"float32")}const c7={kernelName:ei,backendName:"webgl",kernelFunc:a7};function l7(e){const{inputs:t,backend:n,attrs:s}=e,{dy:i,input:o}=t,a=o;hu([i,o],"avgPoolBackprop");const{filterSize:c,strides:u,pad:p}=s,m=Wn(a.shape,c,u,1,p),y=new a5(m);return n.runWebGLProgram(y,[i],a.dtype)}const h7={kernelName:xa,backendName:"webgl",kernelFunc:l7};class u7{constructor(e,t,n,s,i,o){this.outputShape=[],this.variableNames=["x","mean","variance"],nt(e,t),nt(e,n);let a="0.0";s!=null&&(nt(e,s),this.variableNames.push("offset"),a="getOffsetAtOutCoords()");let c="1.0";i!=null&&(nt(e,i),this.variableNames.push("scale"),c="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`
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 d7{constructor(e,t,n,s,i,o){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],nt(e,t),nt(e,n);let a="vec4(0.0)";s!=null&&(nt(e,s),this.variableNames.push("offset"),a="getOffsetAtOutCoords()");let c="vec4(1.0)";i!=null&&(nt(e,i),this.variableNames.push("scale"),c="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`
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 p7=({inputs:e,backend:t,attrs:n})=>{const{x:s,mean:i,variance:o,offset:a,scale:c}=e;k(i.shape.length===o.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),k(a==null||i.shape.length===a.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),k(c==null||i.shape.length===c.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let{varianceEpsilon:u}=n;u==null&&(u=.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=C().getBool("WEBGL_PACK_NORMALIZATION")?new d7(s.shape,i.shape,o.shape,m,y,u):new u7(s.shape,i.shape,o.shape,m,y,u),w=t.runWebGLProgram(b,p,p[0].dtype);return w},m7={kernelName:Ll,backendName:"webgl",kernelFunc:p7};const f7=HC+`
return cos(x);
`,g7=Am(f7),y7={kernelName:Ta,backendName:"webgl",kernelFunc:g7};const b7=`
if (a == b) {
return 1.0;
};
return a / b;`,w7=`
// 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;
`,L7=xS(b7,w7,!0),S7={kernelName:Aa,backendName:"webgl",kernelFunc:L7};class I7{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 x7={kernelName:rd,backendName:"webgl",kernelFunc:({inputs:e,backend:t})=>{const{image:n}=e,s=t,i=new I7(n.shape),o=s.runWebGLProgram(i,[n],n.dtype);return o}};class T7{constructor(e){this.variableNames=["A"];const t=Un(),[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 A7{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;const t=Un(),[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 v7={kernelName:yd,backendName:"webgl",kernelFunc:N7};let Ic;function N7(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,[u,p]=a?[i.videoWidth,i.videoHeight]:[i.width,i.height],m=[p,u],y=[p,u,o];(c||a)&&(Ic==null&&(Ic=document.createElement("canvas").getContext("2d")),Ic.canvas.width=u,Ic.canvas.height=p,Ic.drawImage(i,0,0,u,p),i=Ic.canvas);const b=n.makeTensorInfo(m,"int32");n.texData.get(b.dataId).usage=Cs.PIXELS,n.gpgpu.uploadPixelDataToTexture(n.getTexture(b.dataId),i);const w=C().getBool("WEBGL_PACK")?new A7(y):new T7(y),I=n.runWebGLProgram(w,[b],"int32");return n.disposeData(b.dataId),I}function C7(e){const t=[];for(;t.length===0||t[t.length-1].outSize!==1;){const n=t.length?t[t.length-1].outSize:e[1],s=uh(n);t.push({inSize:n,windowSize:s,outSize:Math.ceil(n/s)})}return t}function R7(e,t,n,s){const i=C7(e.shape);let o=e;for(let a=0;a<i.length;a++){const{inSize:c,windowSize:u,outSize:p}=i[a],m=new AC({windowSize:u,inSize:c,batchSize:e.shape[0],outSize:p},n),y=o;o=s.runWebGLProgram(m,[o],t),y.dataId!==e.dataId&&s.disposeData(y.dataId)}return o}function O7(e,t,n){const s=[gc(e.shape),...yc(e.shape)],i={dtype:e.dtype,shape:s,dataId:e.dataId},o=[gc(t),...yc(t)],a=new vC(o,s),c=!0,u=n.runWebGLProgram(a,[i],e.dtype,null,c);return{dataId:u.dataId,shape:t,dtype:u.dtype}}function AS(e){const{inputs:t,backend:n,attrs:s}=e,{x:i}=t,{shape:o}=s,a=n,c=we(i.shape),u=Id(o,c),p=we(u);k(c===p,()=>`The new shape (${u}) 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&&!gm(i.shape,u)&&!(m.texture!==null&&gm(m.shape,u))?O7(i,u,a):(a.incRef(i.dataId),{dataId:i.dataId,shape:u,dtype:i.dtype})}const E7={kernelName:El,backendName:"webgl",kernelFunc:AS};function D7(e,t,n,s){const i=we(t),o=we(e.shape),a=o/i,c=AS({inputs:{x:e},attrs:{shape:[a,i]},backend:s}),u=R7(c,e.dtype,"max",s),p=AS({inputs:{x:u},attrs:{shape:n},backend:s});return s.disposeIntermediateTensorInfo(c),s.disposeIntermediateTensorInfo(u),p}class k7{constructor(e,t){this.variableNames=["A"];const n=new Array(e.length);for(let o=0;o<n.length;o++)n[o]=e[t[o]];this.outputShape=n,this.rank=n.length;const s=Et(this.rank),i=F7(t);this.userCode=`
void main() {
${s} resRC = getOutputCoords();
setOutput(getA(${i}));
}
`}}function F7(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 _7{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=Et(this.rank),i=eC("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]}`,u=`getChannel(getA(${o.join()}), ${a})`;this.userCode=`
void main() {
${s} rc = getOutputCoords();
vec4 result = vec4(0.);
result[0] = ${u};
if(${c}) {
result[1] = ${u};
}
--${i[this.rank-1]};
if(++${i[this.rank-2]} < ${n[this.rank-2]}) {
result[2] = ${u};
if(${c}) {
result[3] = ${u};
}
}
setOutput(result);
}
`}}function YC(e,t,n){const s=C().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new _7(e.shape,t):new k7(e.shape,t);return n.runWebGLProgram(s,[e],e.dtype)}const W7={kernelName:Nl,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:s}=e,{reductionIndices:i,keepDims:o}=t,a=n,c=s.shape.length,u=ft(i,s.shape);let p=u;const m=_n(p,c),y=m!=null,b=a.shouldExecuteOnCPU([s]);let w=s;if(y){if(b){const E=a.texData.get(w.dataId),D=E.values,F=new Array(c);for(let U=0;U<F.length;U++)F[U]=s.shape[m[U]];const _=Q0(D,s.shape,s.dtype,m,F);w=a.makeTensorInfo(F,s.dtype);const B=a.texData.get(w.dataId);B.values=_}else w=YC(s,m,a);p=Is(p.length,c)}ss("max",p,c);const[I,T]=On(w.shape,p);let v=I;o&&(v=En(I,u));let N;if(b){const E=a.texData.get(w.dataId),D=E.values,F=mK(D,we(T),v,s.dtype);N=a.makeTensorInfo(v,s.dtype);const _=a.texData.get(N.dataId);_.values=F}else N=D7(w,T,v,a);return y&&a.disposeIntermediateTensorInfo(w),N}};function $7(e){const{inputs:t,backend:n,attrs:s}=e,{x:i}=t;hu(i,"maxPool");const{filterSize:o,strides:a,pad:c,dimRoundingMode:u}=s,p=1;k(on(a,p),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${p}'`);const m=Wn(i.shape,o,a,p,c,u);if(m.filterWidth===1&&m.filterHeight===1&&ot(m.inShape,m.outShape))return TS({inputs:{x:i},backend:n});const y=new du(m,"max",!1);return n.runWebGLProgram(y,[i],i.dtype)}const U7={kernelName:Cl,backendName:"webgl",kernelFunc:$7};function B7(e){const{inputs:t,backend:n,attrs:s}=e,{dy:i,input:o,output:a}=t,c=o;hu([o,a],"maxPoolBackprop");const{filterSize:u,strides:p,pad:m,dimRoundingMode:y}=s,b=Wn(c.shape,u,p,1,m,y),w=!0,I=new du(b,"max",w),T=n.runWebGLProgram(I,[c],c.dtype),v=new k8(b),N=n.runWebGLProgram(v,[i,T],c.dtype);return n.disposeIntermediateTensorInfo(T),N}const M7={kernelName:ad,backendName:"webgl",kernelFunc:B7};function P7(e,t,n,s){let i=new du(n,"max",!1);const o=s.runWebGLProgram(i,[e],"float32");i=new du(n,"max",!0,!0,t);const a=s.runWebGLProgram(i,[e],"float32");return[o,a]}const z7={kernelName:cd,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:s}=e,{filterSize:i,strides:o,pad:a,includeBatchInIndex:c}=t,u=n;k(s.shape.length===4,()=>`Error in maxPool: input must be rank 4 but got rank ${s.shape.length}.`);const p=[1,1];k(on(o,p),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${o} and dilations '${p}'`);const m=Wn(s.shape,i,o,p,a),[y,b]=P7(s,c,m,u);return[y,b]}};const G7={kernelName:Kg,backendName:"webgl",kernelFunc:({inputs:e,backend:t,attrs:n})=>{Qa("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,u=t,p=u.readSync(s.dataId),m=u.readSync(i.dataId),y=o,b=a,w=c;return wp(p,m,y,b,w)}};const V7=Lp,H7={kernelName:hd,backendName:"webgl",kernelFunc:({inputs:e,backend:t,attrs:n})=>{Qa("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:u}=n,p=t,m=p.readSync(s.dataId),y=p.readSync(i.dataId),{selectedIndices:b,validOutputs:w}=V7(m,y,o,a,c,u);return[b,w]}};const Y7=Sp,q7={kernelName:ud,backendName:"webgl",kernelFunc:({inputs:e,backend:t,attrs:n})=>{Qa("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:u}=n,p=t,m=p.readSync(s.dataId),y=p.readSync(i.dataId),b=o,w=a,I=c,T=u,{selectedIndices:v,selectedScores:N}=Y7(m,y,b,w,I,T);return[v,N]}};class j7{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[u,p]=qb(s,i,o),m=u.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 K7={kernelName:bd,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{image:s}=e,{radians:i,fillValue:o,center:a}=t,c=n,u=new j7(s.shape,i,o,a),p=c.runWebGLProgram(u,[s],s.dtype);return p}};const X7=HC+`
return sin(x);
`,J7=Am(X7),Z7={kernelName:va,backendName:"webgl",kernelFunc:J7};const Q7="return x * x;",eX=Am(Q7),tX={kernelName:fd,backendName:"webgl",kernelFunc:eX};const qC="return (a - b) * (a - b);",nX=xS(qC,qC),sX={kernelName:Na,backendName:"webgl",kernelFunc:nX};const iX="return tan(x);",rX=Am(iX),oX={kernelName:Ca,backendName:"webgl",kernelFunc:rX};const aX={kernelName:zl,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 u;if(o.shouldExecuteOnCPU([s])){const p=o.texData.get(s.dataId),m=p.values,y=Q0(m,s.shape,s.dtype,i,c);u=o.makeTensorInfo(c,s.dtype);const b=o.texData.get(u.dataId);b.values=y}else u=YC(s,i,o);return u}};function cX(e){const{inputs:t,attrs:n,backend:s}=e,{axis:i}=n,{x:o}=t;hu(o,"unique"),console.warn("WARNING: ","UI might be locked temporarily as data is being downloaded");const a=s.readSync(o.dataId),{outputValues:c,outputShape:u,indices:p}=wK(a,i,o.shape,o.dtype);return[s.makeTensorInfo(u,o.dtype,c),s.makeTensorInfo([p.length],"int32",p)]}const lX={kernelName:gd,backendName:"webgl",kernelFunc:cX};const hX=[r7,c7,h7,m7,y7,S7,x7,v7,o7,W7,U7,M7,z7,G7,H7,q7,E7,K7,Z7,tX,sX,oX,aX,lX];for(const e of hX)Ld(e);const uX="2.6.0";const dX={"tfjs-core":JT,"tfjs-backend-cpu":Sq,"tfjs-backend-webgl":Z6,"tfjs-data":N0,"tfjs-layers":Xp,"tfjs-converter":r0,tfjs:uX};r.Abs=fe,r.Acos=de,r.Acosh=Ae,r.AdadeltaOptimizer=xh,r.AdagradOptimizer=Th,r.AdamOptimizer=Ah,r.AdamaxOptimizer=vh,r.Add=xe,r.AddN=Me,r.All=Ke,r.Any=wt,r.ArgMax=$t,r.ArgMin=Kt,r.Asin=Fn,r.Asinh=vn,r.Atan=Nn,r.Atan2=Ai,r.Atanh=Qs,r.AvgPool=ei,r.AvgPool3D=hl,r.AvgPool3DBackprop=Cx,r.AvgPoolBackprop=xa,r.BatchMatMul=vg,r.BatchToSpaceND=Ng,r.BroadcastTo=Cg,r.Callback=VN,r.CallbackList=Uv,r.Cast=ul,r.Ceil=dl,r.ClipByValue=pl,r.Complex=Rg,r.Concat=td,r.Conv2D=Og,r.Conv2DBackpropFilter=Rx,r.Conv2DBackpropInput=Eg,r.Conv3D=Dg,r.Conv3DBackpropFilterV2=Ox,r.Conv3DBackpropInputV2=Ex,r.Cos=Ta,r.Cosh=ml,r.CropAndResize=Dx,r.Cumsum=kg,r.CustomCallback=Mv,r.DataStorage=d,r.DepthToSpace=kx,r.DepthwiseConv2dNative=Fg,r.DepthwiseConv2dNativeBackpropFilter=Fx,r.DepthwiseConv2dNativeBackpropInput=_x,r.Diag=Wx,r.Dilation2D=nd,r.Dilation2DBackpropFilter=id,r.Dilation2DBackpropInput=sd,r.Div=Aa,r.EarlyStopping=YN,r.Elu=fl,r.EluGrad=$x,r.Environment=L,r.Equal=Ux,r.Erf=gl,r.Exp=yl,r.Expm1=bl,r.FFT=_g,r.Fill=Bx,r.FlipLeftRight=rd,r.Floor=wl,r.FloorDiv=Wg,r.FromPixels=yd,r.FusedBatchNorm=Ll,r.FusedConv2D=fy,r.FusedDepthwiseConv2D=gy,r.GatherNd=Mx,r.GatherV2=$g,r.GraphModel=i0,r.Greater=Px,r.GreaterEqual=Ug,r.History=Bv,r.IFFT=Bg,r.Identity=Sl,r.Imag=Mg,r.InputSpec=fn,r.IsFinite=Il,r.IsInf=xl,r.IsNan=Tl,r.KernelBackend=f,r.LRN=zg,r.LRNBackprop=qx,r.LayerVariable=ci,r.LayersModel=cr,r.Less=zx,r.LessEqual=Gx,r.LinSpace=Vx,r.Log=Al,r.Log1p=vl,r.LogSoftmax=Pg,r.LogicalAnd=Hx,r.LogicalNot=od,r.LogicalOr=Yx,r.Max=Nl,r.MaxPool=Cl,r.MaxPool3D=Vg,r.MaxPool3DBackprop=jx,r.MaxPoolBackprop=ad,r.MaxPoolWithArgmax=cd,r.Maximum=Gg,r.Mean=VD,r.Min=Hg,r.Minimum=Yg,r.Mod=qg,r.MomentumOptimizer=Nh,r.Multiply=Rl,r.Negate=jg,r.NonMaxSuppressionV3=Kg,r.NonMaxSuppressionV4=hd,r.NonMaxSuppressionV5=ud,r.NotEqual=ld,r.OP_SCOPE_SUFFIX=IT,r.OneHot=Jg,r.OnesLike=Xg,r.Optimizer=sr,r.PadV2=dd,r.Pool=HD,r.Pow=Zg,r.Prelu=Qg,r.Prod=Kx,r.RMSPropOptimizer=Ch,r.RNN=Bi,r.Range=Xx,r.Real=ey,r.Reciprocal=Ol,r.Relu=ty,r.Relu6=iy,r.Reshape=El,r.ResizeBilinear=sy,r.ResizeBilinearGrad=Zx,r.ResizeNearestNeighbor=ny,r.ResizeNearestNeighborGrad=Jx,r.Reverse=ry,r.RotateWithOffset=bd,r.Round=Dl,r.Rsqrt=kl,r.SGDOptimizer=Za,r.ScatterNd=Qx,r.SelectV2=oy,r.Selu=Fl,r.Sequential=oc,r.Sigmoid=$l,r.Sign=Wl,r.Sin=va,r.Sinh=_l,r.Slice=pd,r.Softmax=ly,r.Softplus=Ul,r.SpaceToBatchND=md,r.SparseToDense=eT,r.SplitV=cy,r.Sqrt=Bl,r.Square=fd,r.SquaredDifference=Na,r.Step=Gl,r.StridedSlice=tT,r.Sub=Ml,r.Sum=ay,r.SymbolicTensor=li,r.Tan=Ca,r.Tanh=Pl,r.Tensor=Q,r.TensorBuffer=kr,r.Tile=hy,r.TopK=nT,r.Transpose=zl,r.Unique=gd,r.Unpack=uy,r.UnsortedSegmentSum=dy,r.Variable=Xl,r.ZerosLike=py,r._FusedMatMul=my,r.abs=rn,r.acos=nb,r.acosh=sb,r.add=be,r.addN=eA,r.addStrict=OA,r.all=Pd,r.any=th,r.argMax=nh,r.argMin=rb,r.asin=ob,r.asinh=ab,r.atan=cb,r.atan2=lb,r.atanh=hb,r.avgPool=oh,r.avgPool3d=pb,r.backend=QT,r.backend_util=iw,r.basicLSTMCell=f_,r.batchNorm=Ro,r.batchNorm2d=nA,r.batchNorm3d=sA,r.batchNorm4d=iA,r.batchToSpaceND=ah,r.booleanMaskAsync=vU,r.broadcastTo=ch,r.browser=bF,r.buffer=Qe,r.callbacks=jV,r.cast=ve,r.ceil=fb,r.clipByValue=jn,r.clone=Wr,r.complex=Ci,r.concat=Mt,r.concat1d=rA,r.concat2d=oA,r.concat3d=aA,r.concat4d=cA,r.constraints=wz,r.conv1d=Hd,r.conv2d=er,r.conv2dTranspose=Yd,r.conv3d=yb,r.conv3dTranspose=W_,r.copyRegisteredKernels=jD,r.cos=lh,r.cosh=qd,r.cosineWindow=Gb,r.cumsum=jd,r.customGrad=Di,r.data=zY,r.deprecationWarn=sn,r.depthToSpace=bb,r.depthwiseConv2d=Oo,r.deregisterOp=XV,r.device_util=bk,r.diag=G_,r.dilation2d=wb,r.disableDeprecationWarnings=EF,r.dispose=qe,r.disposeVariables=DF,r.div=_e,r.divNoNan=Lb,r.divStrict=EA,r.dot=hA,r.dropout=zA,r.elu=Do,r.enableDebugMode=OF,r.enableProdMode=RF,r.enclosingPowerOfTwo=GA,r.engine=$s,r.env=C,r.equal=ni,r.equalStrict=TA,r.erf=Sb,r.exp=xs,r.expandDims=Kn,r.expm1=Ib,r.eye=Kd,r.fft=wh,r.fill=hh,r.findBackend=UF,r.findBackendFactory=BF,r.floor=Pa,r.floorDiv=Md,r.fused=rB,r.gather=za,r.gatherND=PA,r.gather_util=wF,r.getBackend=WF,r.getGradient=by,r.getKernel=yy,r.getKernelsForBackend=wd,r.grad=SW,r.grads=IW,r.greater=Ts,r.greaterEqual=tr,r.greaterEqualStrict=AA,r.greaterStrict=vA,r.ifft=ja,r.imag=Ga,r.image=Vr,r.inTopKAsync=ZU,r.initializers=t3,r.input=hN,r.io=cF,r.irfft=hp,r.isFinite=dA,r.isInf=pA,r.isNaN=mA,r.keep=Rn,r.kernel_impls=mM,r.layers=AV,r.leakyRelu=Xd,r.less=dh,r.lessEqual=Mr,r.lessEqualStrict=NA,r.lessStrict=CA,r.linalg=QA,r.linspace=fA,r.loadGraphModel=oY,r.loadLayersModel=sG,r.localResponseNormalization=Tb,r.log=is,r.log1p=Jd,r.logSigmoid=gA,r.logSoftmax=Qd,r.logSumExp=vb,r.logicalAnd=Bs,r.logicalNot=ph,r.logicalOr=ep,r.logicalXor=yA,r.losses=uM,r.matMul=at,r.math=fF,r.max=Xn,r.maxPool=mh,r.maxPool3d=Nb,r.maxPoolWithArgmax=bA,r.maximum=Us,r.maximumStrict=DA,r.mean=zt,r.memory=Bd,r.metrics=PV,r.min=Ha,r.minimum=ko,r.minimumStrict=kA,r.mod=tp,r.modStrict=FA,r.model=tG,r.models=zV,r.moments=np,r.movingAverage=VU,r.mul=X,r.mulStrict=_A,r.multiRNNCell=qW,r.multinomial=wA,r.neg=Pt,r.nextFrame=Ip,r.norm=pp,r.notEqual=Pr,r.notEqualStrict=RA,r.oneHot=vo,r.ones=si,r.onesLike=Dn,r.op=P,r.outerProduct=QW,r.pad=ki,r.pad1d=n$,r.pad2d=i$,r.pad3d=o$,r.pad4d=c$,r.pool=LA,r.pow=ii,r.powStrict=WA,r.prelu=gh,r.print=ET,r.prod=sp,r.profile=kF,r.rand=y$,r.randomGamma=E$,r.randomNormal=Ob,r.randomUniform=$o,r.range=yh,r.ready=_F,r.real=Fo,r.reciprocal=Eb,r.registerBackend=tb,r.registerCallbackConstructor=iG,r.registerGradient=sT,r.registerKernel=Ld,r.registerOp=KV,r.regularizers=YV,r.relu=Fi,r.relu6=Db,r.removeBackend=$F,r.reshape=K,r.reverse=As,r.reverse1d=B$,r.reverse2d=P$,r.reverse3d=G$,r.reverse4d=H$,r.rfft=Lh,r.round=kb,r.rsqrt=ip,r.scalar=Ne,r.scatterND=MA,r.scatter_util=LF,r.selu=rp,r.separableConv2d=Fb,r.sequential=nG,r.serialization=SF,r.setBackend=ZT,r.setPlatform=MF,r.setdiff1dAsync=SA,r.sigmoid=Ei,r.sign=_b,r.signal=hM,r.sin=op,r.sinh=ap,r.slice=st,r.slice1d=cp,r.slice2d=Wb,r.slice3d=lp,r.slice4d=bh,r.slice_util=KT,r.softmax=Uo,r.softplus=Va,r.spaceToBatchND=fh,r.sparseToDense=zb,r.spectral=lM,r.split=os,r.sqrt=Sn,r.square=Lt,r.squaredDifference=Sh,r.squaredDifferenceStrict=$A,r.squeeze=zr,r.stack=as,r.step=Ka,r.stridedSlice=$b,r.sub=Ce,r.subStrict=UA,r.sum=Ue,r.sumOutType=vd,r.tan=Ub,r.tanh=Ma,r.tensor=en,r.tensor1d=rs,r.tensor2d=Gr,r.tensor3d=UT,r.tensor4d=Xa,r.tensor5d=yU,r.tensor6d=bU,r.tensor_util=mk,r.test_util=CF,r.tidy=ee,r.tile=Br,r.time=FF,r.topk=Bb,r.train=Mo,r.transpose=Pe,r.truncatedNormal=Ih,r.unique=up,r.unregisterGradient=qD,r.unregisterKernel=YD,r.unsortedSegmentSum=Mb,r.unstack=_i,r.upcastType=Cn,r.util=tk,r.valueAndGrad=xW,r.valueAndGrads=TW,r.variable=xA,r.variableGrads=Ab,r.version=dX,r.version_converter=r0,r.version_core=JT,r.version_layers=Xp,r.where=$n,r.whereAsync=Pb,r.zeros=ct,r.zerosLike=et,Object.defineProperty(r,"__esModule",{value:!0})})});var a2=CS((EX,o2)=>{vc(EX,{isNodejs:()=>DX});function DX(){return typeof global=="object"&&!0&&typeof o2!="undefined"&&typeof process!="undefined"&&!!process.version}});function gr(r,l,h=!1){if(r.beginPath(),l.slice(1).forEach(({x:d,y:f},g)=>{const S=l[g];r.moveTo(S.x,S.y),r.lineTo(d,f)}),h){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 ms{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 ms(1/this.width,1/this.height)}}const US={};vc(US,{computeReshapedDimensions:()=>PS,getCenterPoint:()=>ta,isDimensions:()=>Dm,isEven:()=>Em,isFloat:()=>MS,isTensor:()=>Qo,isTensor1D:()=>kX,isTensor2D:()=>BS,isTensor3D:()=>yr,isTensor4D:()=>Os,isValidNumber:()=>gi,isValidProbablitiy:()=>Rc,range:()=>zi,round:()=>ea});const c2=Ye(Je());function Qo(r,l){return r instanceof c2.Tensor&&r.shape.length===l}function kX(r){return Qo(r,1)}function BS(r){return Qo(r,2)}function yr(r){return Qo(r,3)}function Os(r){return Qo(r,4)}function MS(r){return r%1!==0}function Em(r){return r%2===0}function ea(r,l=2){const h=Math.pow(10,l);return Math.floor(r*h)/h}function Dm(r){return r&&r.width&&r.height}function PS({width:r,height:l},h){const d=h/Math.max(l,r);return new ms(Math.round(r*d),Math.round(l*d))}function ta(r){return r.reduce((l,h)=>l.add(h),new Ze(0,0)).div(new Ze(r.length,r.length))}function zi(r,l,h){return Array(r).fill(0).map((d,f)=>l+f*h)}function gi(r){return!!r&&r!==Infinity&&r!==-Infinity&&!isNaN(r)||r===0}function Rc(r){return gi(r)&&0<=r&&r<=1}class Ze{constructor(r,l){this._x=r,this._y=l}get x(){return this._x}get y(){return this._y}add(r){return new Ze(this.x+r.x,this.y+r.y)}sub(r){return new Ze(this.x-r.x,this.y-r.y)}mul(r){return new Ze(this.x*r.x,this.y*r.y)}div(r){return new Ze(this.x/r.x,this.y/r.y)}abs(){return new Ze(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 Ze(Math.floor(this.x),Math.floor(this.y))}}class Ct{static isRect(r){return!!r&&[r.x,r.y,r.width,r.height].every(gi)}static assertIsValidBox(r,l,h=!1){if(!Ct.isRect(r))throw new Error(`${l} - invalid box: ${JSON.stringify(r)}, expected object with properties x, y, width, height`);if(!h&&(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 h=r||{},d=[h.left,h.top,h.right,h.bottom].every(gi),f=[h.x,h.y,h.width,h.height].every(gi);if(!f&&!d)throw new Error(`Box.constructor - expected box to be IBoundingBox | IRect, instead have ${JSON.stringify(h)}`);const[g,S,L,x]=f?[h.x,h.y,h.width,h.height]:[h.left,h.top,h.right-h.left,h.bottom-h.top];Ct.assertIsValidBox({x:g,y:S,width:L,height:x},"Box.constructor",l),this._x=g,this._y=S,this._width=L,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 Ze(this.left,this.top)}get topRight(){return new Ze(this.right,this.top)}get bottomLeft(){return new Ze(this.left,this.bottom)}get bottomRight(){return new Ze(this.right,this.bottom)}round(){const[r,l,h,d]=[this.x,this.y,this.width,this.height].map(f=>Math.round(f));return new Ct({x:r,y:l,width:h,height:d})}floor(){const[r,l,h,d]=[this.x,this.y,this.width,this.height].map(f=>Math.floor(f));return new Ct({x:r,y:l,width:h,height:d})}toSquare(){let{x:r,y:l,width:h,height:d}=this;const f=Math.abs(h-d);return h<d&&(r-=f/2,h+=f),d<h&&(l-=f/2,d+=f),new Ct({x:r,y:l,width:h,height:d})}rescale(r){const l=Dm(r)?r.width:r,h=Dm(r)?r.height:r;return new Ct({x:this.x*l,y:this.y*h,width:this.width*l,height:this.height*h})}pad(r,l){let[h,d,f,g]=[this.x-r/2,this.y-l/2,this.width+r,this.height+l];return new Ct({x:h,y:d,width:f,height:g})}clipAtImageBorders(r,l){const{x:h,y:d,right:f,bottom:g}=this,S=Math.max(h,0),L=Math.max(d,0),x=f-S,A=g-L,O=Math.min(x,r-S),C=Math.min(A,l-L);return new Ct({x:S,y:L,width:O,height:C}).floor()}shift(r,l){const{width:h,height:d}=this,f=this.x+r,g=this.y+l;return new Ct({x:f,y:g,width:h,height:d})}padAtBorders(r,l){const h=this.width+1,d=this.height+1;let f=1,g=1,S=h,L=d,x=this.left,A=this.top,O=this.right,C=this.bottom;return O>l&&(S=-O+l+h,O=l),C>r&&(L=-C+r+d,C=r),x<1&&(L=2-x,x=1),A<1&&(L=2-A,A=1),{dy:g,edy:L,dx:f,edx:S,y:A,ey:C,x,ex:O,w:h,h:d}}calibrate(r){return new Ct({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 wu extends Ct{constructor(r,l,h,d,f=!1){super({left:r,top:l,right:h,bottom:d},f)}}class Oc{constructor(r,l,h,d,f){this._imageDims=new ms(f.width,f.height),this._score=r,this._classScore=l,this._className=h,this._box=new Ct(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 Ct(this._box).rescale(this.imageDims.reverse())}forSize(r,l){return new Oc(this.score,this.classScore,this.className,this.relativeBox,{width:r,height:l})}}class Yt extends Oc{constructor(r,l,h){super(r,r,"",l,h)}forSize(r,l){const{score:h,relativeBox:d,imageDims:f}=super.forSize(r,l);return new Yt(h,d,f)}}function zS(r,l,h=!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 h?g/(r.area+l.area-g):g/Math.min(r.area,l.area)}function GS(r){const l=r.map(L=>L.x),h=r.map(L=>L.y),d=l.reduce((L,x)=>x<L?x:L,Infinity),f=h.reduce((L,x)=>x<L?x:L,Infinity),g=l.reduce((L,x)=>L<x?x:L,0),S=h.reduce((L,x)=>L<x?x:L,0);return new wu(d,f,g,S)}function VS(r,l,h,d=!0){let f=l.map((S,L)=>({score:S,boxIndex:L})).sort((S,L)=>S.score-L.score).map(S=>S.boxIndex);const g=[];for(;f.length>0;){const S=f.pop();g.push(S);const L=f,x=[];for(let A=0;A<L.length;A++){const O=L[A],C=r[S],$=r[O];x.push(zS(C,$,d))}f=f.filter((A,O)=>x[O]<=h)}return g}const Gi=Ye(Je());function yi(r,l){return Gi.tidy(()=>{const[h,d,f]=l,g=Gi.fill([...r.shape.slice(0,3),1],h,"float32"),S=Gi.fill([...r.shape.slice(0,3),1],d,"float32"),L=Gi.fill([...r.shape.slice(0,3),1],f,"float32"),x=Gi.concat([g,S,L],3);return Gi.sub(r,x)})}const ro=Ye(Je());function HS(r,l=!1){return ro.tidy(()=>{const[h,d]=r.shape.slice(1);if(h===d)return r;const f=Math.abs(h-d),g=Math.round(f*(l?.5:1)),S=h>d?2:1,L=$=>{const z=r.shape.slice();return z[S]=$,ro.fill(z,0,"float32")},x=L(g),A=f-x.shape[S],O=l&&A?L(A):null,C=[O,r,x].filter($=>!!$).map($=>ro.cast($,"float32"));return ro.concat(C,S)})}function FX(r){const l=r.slice();for(let h=l.length-1;h>0;h--){const d=Math.floor(Math.random()*(h+1)),f=l[h];l[h]=l[d],l[d]=f}return l}function Lu(r){return 1/(1+Math.exp(-r))}function _X(r){return Math.log(r/(1-r))}class Su extends Ct{constructor(r,l,h,d,f=!1){super({x:r,y:l,width:h,height:d},f)}}const WX=.5,$X=.43,UX=.45;class qs{constructor(r,l,h=new Ze(0,0)){const{width:d,height:f}=l;this._imgDims=new ms(d,f),this._shift=h,this._positions=r.map(g=>g.mul(new Ze(d,f)).add(h))}get shift(){return new Ze(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 Ze(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 Ze(r,l))}shiftByPoint(r){return this.shiftBy(r.x,r.y)}align(r,l={}){if(r){const f=r instanceof Yt?r.box.floor():new Ct(r);return this.shiftBy(f.x,f.y).align(null,l)}const{useDlibAlignment:h,minBoxPadding:d}=Object.assign({},{useDlibAlignment:!1,minBoxPadding:.2},l);return h?this.alignDlib():this.alignMinBbox(d)}alignDlib(){const r=this.getRefPointsForAlignment(),[l,h,d]=r,f=O=>d.sub(O).magnitude(),g=(f(l)+f(h))/2,S=Math.floor(g/UX),L=ta(r),x=Math.floor(Math.max(0,L.x-WX*S)),A=Math.floor(Math.max(0,L.y-$X*S));return new Su(x,A,Math.min(S,this.imageWidth+x),Math.min(S,this.imageHeight+A))}alignMinBbox(r){const l=GS(this.positions);return l.pad(l.width*r,l.height*r)}getRefPointsForAlignment(){throw new Error("getRefPointsForAlignment not implemented by base class")}}class BX extends qs{getRefPointsForAlignment(){const r=this.positions;return[r[0],r[1],ta([r[3],r[4]])]}}class Iu extends qs{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(ta)}}class km{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?` (${ea(this.distance)})`:""}`}}class Fm extends Ct{static assertIsValidLabeledBox(r,l){if(Ct.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 na{constructor(r,l){if(!(typeof r=="string"))throw new Error("LabeledFaceDescriptors - constructor expected label to be a string");if(!Array.isArray(l)||l.some(h=>!(h 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(h=>new Float32Array(h));return new na(r.label,l)}}class MX extends Fm{static assertIsValidPredictedBox(r,l){if(Fm.assertIsValidLabeledBox(r,l),!Rc(r.score)||!Rc(r.classScore))throw new Error(`${l} - expected properties score (${r.score}) and (${r.classScore}) to be a number between [0, 1]`)}constructor(r,l,h,d){super(r,l);this._score=h,this._classScore=d}get score(){return this._score}get classScore(){return this._classScore}}function Vi(r){return r.detection instanceof Yt}function sa(r,l){const h={detection:l};return Object.assign({},r,h)}function YS(){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 _m(r){let l="";if(!r)try{r=require("fs")}catch(d){l=d.toString()}const h=r?function(d){return new Promise((f,g)=>{r.readFile(d,function(S,L){return S?g(S):f(L)})})}:function(){throw new Error(`readFile - failed to require fs in nodejs environment with error: ${l}`)};return{readFile:h}}function qS(){const r=global.Canvas||global.HTMLCanvasElement,l=global.Image||global.HTMLImageElement,h=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=_m();return{Canvas:r||class{},CanvasRenderingContext2D:global.CanvasRenderingContext2D||class{},Image:l||class{},ImageData:global.ImageData||class{},Video:global.HTMLVideoElement||class{},createCanvasElement:h,createImageElement:d,fetch:f,...g}}function jS(){return typeof window=="object"&&typeof document!="undefined"&&typeof HTMLImageElement!="undefined"&&typeof HTMLCanvasElement!="undefined"&&typeof HTMLVideoElement!="undefined"&&typeof ImageData!="undefined"&&typeof CanvasRenderingContext2D!="undefined"}const KS=Ye(a2());let yn;function PX(){if(!yn)throw new Error("getEnv - environment is not defined, check isNodejs() and isBrowser()");return yn}function XS(r){yn=r}function JS(){if(jS())return XS(YS());if(KS.isNodejs())return XS(qS())}function zX(r){if(yn||JS(),!yn)throw new Error("monkeyPatch - environment is not defined, check isNodejs() and isBrowser()");const{Canvas:l=yn.Canvas,Image:h=yn.Image}=r;yn.Canvas=l,yn.Image=h,yn.createCanvasElement=r.createCanvasElement||(()=>new l),yn.createImageElement=r.createImageElement||(()=>new h),yn.ImageData=r.ImageData||yn.ImageData,yn.Video=r.Video||yn.Video,yn.fetch=r.fetch||yn.fetch,yn.readFile=r.readFile||yn.readFile}const gt={getEnv:PX,setEnv:XS,initialize:JS,createBrowserEnv:YS,createFileSystem:_m,createNodejsEnv:qS,monkeyPatch:zX,isBrowser:jS,isNodejs:KS.isNodejs};JS();function ia(r){return!gt.isNodejs()&&typeof r=="string"?document.getElementById(r):r}function es(r){const{Canvas:l,CanvasRenderingContext2D:h}=gt.getEnv();if(r instanceof h)return r;const d=ia(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 Hi;(function(r){r.TOP_LEFT="TOP_LEFT",r.TOP_RIGHT="TOP_RIGHT",r.BOTTOM_LEFT="BOTTOM_LEFT",r.BOTTOM_RIGHT="BOTTOM_RIGHT"})(Hi||(Hi={}));class Wm{constructor(r={}){const{anchorPosition:l,backgroundColor:h,fontColor:d,fontSize:f,fontStyle:g,padding:S}=r;this.anchorPosition=l||Hi.TOP_LEFT,this.backgroundColor=h||"rgba(0, 0, 0, 0.5)",this.fontColor=d||"rgba(255, 255, 255, 1)",this.fontSize=f||14,this.fontStyle=g||"Georgia",this.padding=S||4}}class Ec{constructor(r,l,h={}){this.text=typeof r=="string"?[r]:r instanceof Ec?r.text:r,this.anchor=l,this.options=new Wm(h)}measureWidth(r){const{padding:l}=this.options;return this.text.map(h=>r.measureText(h).width).reduce((h,d)=>h<d?d:h,0)+2*l}measureHeight(){const{fontSize:r,padding:l}=this.options;return this.text.length*r+2*l}getUpperLeft(r,l){const{anchorPosition:h}=this.options,d=h===Hi.BOTTOM_RIGHT||h===Hi.TOP_RIGHT,f=h===Hi.BOTTOM_LEFT||h===Hi.BOTTOM_RIGHT,g=this.measureWidth(r),S=this.measureHeight(),L=d?this.anchor.x-g:this.anchor.x,x=f?this.anchor.y-S:this.anchor.y;if(l){const{width:A,height:O}=l,C=Math.max(Math.min(L,A-g),0),$=Math.max(Math.min(x,O-S),0);return{x:C,y:$}}return{x:L,y:x}}draw(r){const l=ia(r),h=es(l),{backgroundColor:d,fontColor:f,fontSize:g,fontStyle:S,padding:L}=this.options;h.font=`${g}px ${S}`;const x=this.measureWidth(h),A=this.measureHeight();h.fillStyle=d;const O=this.getUpperLeft(h,l);h.fillRect(O.x,O.y,x,A),h.fillStyle=f,this.text.forEach((C,$)=>{const z=L+O.x,ne=L+O.y+($+1)*g;h.fillText(C,z,ne)})}}class l2{constructor(r={}){const{boxColor:l,lineWidth:h,label:d,drawLabelOptions:f}=r;this.boxColor=l||"rgba(0, 0, 255, 1)",this.lineWidth=h||2,this.label=d;const g={anchorPosition:Hi.BOTTOM_LEFT,backgroundColor:this.boxColor};this.drawLabelOptions=new Wm(Object.assign({},g,f))}}class ZS{constructor(r,l={}){this.box=new Ct(r),this.options=new l2(l)}draw(r){const l=es(r),{boxColor:h,lineWidth:d}=this.options,{x:f,y:g,width:S,height:L}=this.box;l.strokeStyle=h,l.lineWidth=d,l.strokeRect(f,g,S,L);const{label:x}=this.options;x&&new Ec([x],{x:f-d/2,y:g},this.options.drawLabelOptions).draw(r)}}function GX(r,l){const h=Array.isArray(l)?l:[l];h.forEach(d=>{const f=d instanceof Yt?d.score:Vi(d)?d.detection.score:void 0,g=d instanceof Yt?d.box:Vi(d)?d.detection.box:new Ct(d),S=f?`${ea(f)}`:void 0;new ZS(g,{label:S}).draw(r)})}function xu(r){const{Image:l,Video:h}=gt.getEnv();return r instanceof l&&r.complete||r instanceof h&&r.readyState>=3}function QS(r){return new Promise((l,h)=>{if(r instanceof gt.getEnv().Canvas||xu(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),h(g)}r.addEventListener("load",d),r.addEventListener("error",f)})}function eI(r){return new Promise((l,h)=>{if(!(r instanceof Blob))return h("bufferToImage - expected buf to be of type: Blob");const d=new FileReader;d.onload=()=>{if(typeof d.result!="string")return h("bufferToImage - expected reader.result to be a string, in onload");const f=gt.getEnv().createImageElement();f.onload=()=>l(f),f.onerror=h,f.src=d.result},d.onerror=h,d.readAsDataURL(r)})}function ra(r){const{Image:l,Video:h}=gt.getEnv();return r instanceof l?new ms(r.naturalWidth,r.naturalHeight):r instanceof h?new ms(r.videoWidth,r.videoHeight):new ms(r.width,r.height)}function Dc({width:r,height:l}){const{createCanvasElement:h}=gt.getEnv(),d=h();return d.width=r,d.height=l,d}function Tu(r,l){const{ImageData:h}=gt.getEnv();if(!(r instanceof h)&&!xu(r))throw new Error("createCanvasFromMedia - media has not finished loading yet");const{width:d,height:f}=l||ra(r),g=Dc({width:d,height:f});return r instanceof h?es(g).putImageData(r,0,0):es(g).drawImage(r,0,0,d,f),g}const $m=Ye(Je());async function tI(r,l){const h=l||gt.getEnv().createCanvasElement(),[d,f,g]=r.shape.slice(Os(r)?1:0),S=$m.tidy(()=>r.as3D(d,f,g).toInt());return await $m.browser.toPixels(S,h),S.dispose(),h}function Um(r){const{Image:l,Canvas:h,Video:d}=gt.getEnv();return r instanceof l||r instanceof h||r instanceof d}const VX=1e-7,HX=1e-4;class h2{time(r){return ie("time")}read(r){return ie("read")}readSync(r){return ie("readSync")}numDataIds(){return ie("numDataIds")}disposeData(r){return ie("disposeData")}write(r,l,h){return ie("write")}move(r,l,h,d){return ie("move")}memory(){return ie("memory")}floatPrecision(){return ie("floatPrecision")}epsilon(){return this.floatPrecision()===32?VX:HX}batchMatMul(r,l,h,d){return ie("batchMatMul")}fusedBatchMatMul({a:r,b:l,transposeA:h,transposeB:d,bias:f,activation:g,preluActivationWeights:S}){return ie("fusedBatchMatMul")}slice(r,l,h){return ie("slice")}stridedSlice(r,l,h,d){return ie("stridedSlice")}unstack(r,l){return ie("unstack")}reverse(r,l){return ie("reverse")}concat(r,l){return ie("concat")}neg(r){return ie("neg")}add(r,l){return ie("add")}addN(r){return ie("addN")}subtract(r,l){return ie("subtract")}multiply(r,l){return ie("multiply")}realDivide(r,l){return ie("realDivide")}floorDiv(r,l){return ie("floorDiv")}sum(r,l){return ie("sum")}prod(r,l){return ie("prod")}unsortedSegmentSum(r,l,h){return ie("unsortedSegmentSum")}argMin(r,l){return ie("argMin")}argMax(r,l){return ie("argMax")}equal(r,l){return ie("equal")}notEqual(r,l){return ie("notEqual")}less(r,l){return ie("less")}lessEqual(r,l){return ie("lessEqual")}greater(r,l){return ie("greater")}greaterEqual(r,l){return ie("greaterEqual")}logicalNot(r){return ie("logicalNot")}logicalAnd(r,l){return ie("logicalAnd")}logicalOr(r,l){return ie("logicalOr")}where(r){return ie("where")}select(r,l,h){return ie("select")}topk(r,l,h){return ie("topk")}min(r,l){return ie("min")}minimum(r,l){return ie("minimum")}mod(r,l){return ie("mod")}max(r,l){return ie("max")}maximum(r,l){return ie("maximum")}all(r,l){return ie("all")}any(r,l){return ie("any")}squaredDifference(r,l){return ie("squaredDifference")}ceil(r){return ie("ceil")}floor(r){return ie("floor")}round(r){return ie("round")}sign(r){return ie("sign")}isNaN(r){return ie("isNaN")}isInf(r){return ie("isInf")}isFinite(r){return ie("isFinite")}pow(r,l){return ie("pow")}exp(r){return ie("exp")}expm1(r){return ie("expm1")}softmax(r,l){return ie("softmax")}log(r){return ie("log")}log1p(r){return ie("log1p")}sqrt(r){return ie("sqrt")}rsqrt(r){return ie("rsqrt")}square(r){return ie("square")}reciprocal(r){return ie("reciprocal")}relu(r){return ie("relu")}relu6(r){return ie("relu6")}prelu(r,l){return ie("prelu")}elu(r){return ie("elu")}eluDer(r,l){return ie("eluDer")}selu(r){return ie("selu")}int(r){return ie("int")}clip(r,l,h){return ie("clip")}abs(r){return ie("abs")}complexAbs(r){return ie("complexAbs")}sigmoid(r){return ie("sigmoid")}softplus(r){return ie("softplus")}sin(r){return ie("sin")}cos(r){return ie("cos")}tan(r){return ie("tan")}asin(r){return ie("asin")}acos(r){return ie("acos")}atan(r){return ie("atan")}atan2(r,l){return ie("atan2")}sinh(r){return ie("sinh")}cosh(r){return ie("cosh")}tanh(r){return ie("tanh")}asinh(r){return ie("asinh")}acosh(r){return ie("acosh")}atanh(r){return ie("atanh")}erf(r){return ie("erf")}step(r,l){return ie("step")}fusedConv2d({input:r,filter:l,convInfo:h,bias:d,activation:f,preluActivationWeights:g}){return ie("fusedConv2d")}conv2d(r,l,h){return ie("conv2d")}conv2dDerInput(r,l,h){return ie("conv2dDerInput")}conv2dDerFilter(r,l,h){return ie("conv2dDerFilter")}fusedDepthwiseConv2D({input:r,filter:l,convInfo:h,bias:d,activation:f,preluActivationWeights:g}){return ie("fusedDepthwiseConv2D")}depthwiseConv2D(r,l,h){return ie("depthwiseConv2D")}depthwiseConv2DDerInput(r,l,h){return ie("depthwiseConv2DDerInput")}depthwiseConv2DDerFilter(r,l,h){return ie("depthwiseConv2DDerFilter")}conv3d(r,l,h){return ie("conv3d")}conv3dDerInput(r,l,h){return ie("conv3dDerInput")}conv3dDerFilter(r,l,h){return ie("conv3dDerFilter")}maxPool(r,l){return ie("maxPool")}maxPoolBackprop(r,l,h,d){return ie("maxPoolBackprop")}avgPool(r,l){return ie("avgPool")}avgPoolBackprop(r,l,h){return ie("avgPoolBackprop")}avgPool3d(r,l){return ie("avgPool3d")}avgPool3dBackprop(r,l,h){return ie("avgPool3dBackprop")}maxPool3d(r,l){return ie("maxPool3d")}maxPool3dBackprop(r,l,h,d){return ie("maxPool3dBackprop")}reshape(r,l){return ie("reshape")}cast(r,l){return ie("cast")}tile(r,l){return ie("tile")}pad(r,l,h){return ie("pad")}transpose(r,l){return ie("transpose")}gather(r,l,h){return ie("gather")}gatherND(r,l){return ie("gatherND")}scatterND(r,l,h){return ie("scatterND")}batchToSpaceND(r,l,h){return ie("batchToSpaceND")}spaceToBatchND(r,l,h){return ie("spaceToBatchND")}resizeBilinear(r,l,h,d){return ie("resizeBilinear")}resizeBilinearBackprop(r,l,h){return ie("resizeBilinearBackprop")}resizeNearestNeighbor(r,l,h,d){return ie("resizeNearestNeighbor")}resizeNearestNeighborBackprop(r,l,h){return ie("resizeNearestNeighborBackprop")}batchNorm(r,l,h,d,f,g){return ie("batchNorm")}localResponseNormalization4D(r,l,h,d,f){return ie("localResponseNormalization4D")}LRNGrad(r,l,h,d,f,g,S){return ie("LRNGrad")}multinomial(r,l,h,d){return ie("multinomial")}oneHot(r,l,h,d){return ie("oneHot")}cumsum(r,l,h,d){return ie("cumsum")}nonMaxSuppression(r,l,h,d,f){return ie("nonMaxSuppression")}fft(r){return ie("fft")}ifft(r){return ie("ifft")}complex(r,l){return ie("complex")}real(r){return ie("real")}imag(r){return ie("imag")}cropAndResize(r,l,h,d,f,g){return ie("cropAndResize")}depthToSpace(r,l,h){return ie("depthToSpace")}split(r,l,h){return ie("split")}sparseToDense(r,l,h,d){return ie("sparseToDense")}diag(r){return ie("diag")}fill(r,l,h){return ie("fill")}onesLike(r){return ie("onesLike")}zerosLike(r){return ie("zerosLike")}linspace(r,l,h){return ie("linspace")}dispose(){return ie("dispose")}}function ie(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`)}const u2="tfjsflags";class d2{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,h){if(this.flagRegistry[r]={evaluationFn:l,setHook:h},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(l instanceof Promise)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=YX(this.global.location.search);if(u2 in r){const l=r[u2].split(",");l.forEach(h=>{const[d,f]=h.split(":");this.urlFlags[d]=qX(d,f)})}}}function YX(r){const l={};return r.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(h,...d)=>(jX(l,d[0],d[1]),d.join("="))),l}function jX(r,l,h){r[decodeURIComponent(l)]=decodeURIComponent(h||"")}function qX(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 Es(){return p2}let p2=null;function m2(r){p2=r}let nI;function sI(){if(nI==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");nI=r}return nI}function KX(){const r=sI();return r._tfGlobals==null&&(r._tfGlobals=new Map),r._tfGlobals}function iI(r,l){const h=KX();if(h.has(r))return h.get(r);{const d=l();return h.set(r,d),h.get(r)}}const Bm="Abs",f2="Acos",g2="Acosh",kc="Add",y2="AddN",b2="ArgMax",w2="ArgMin",L2="Asin",S2="Asinh",I2="Atan",x2="Atanh",T2="Atan2",A2="AvgPool",v2="AvgPoolBackprop",N2="AvgPool3D",C2="AvgPool3DBackprop",Mm="BatchMatMul",Pm="BatchToSpaceND",zm="BroadcastTo",Fc="Cast",R2="Ceil",O2="ClipByValue",E2="Complex",Gm="Concat",Vm="Conv2D",D2="Conv2DBackpropFilter",Hm="Conv2DBackpropInput",k2="Conv3D",F2="Conv3DBackpropFilterV2",_2="Conv3DBackpropInputV2",Ym="Cos",qm="Cosh",jm="Cumsum",W2="CropAndResize",$2="DepthwiseConv2dNative",U2="DepthwiseConv2dNativeBackpropFilter",B2="DepthwiseConv2dNativeBackpropInput",M2="Dilation2D",P2="Dilation2DBackpropInput",z2="Dilation2DBackpropFilter",Km="Div",G2="Elu",V2="EluGrad",H2="Erf",Y2="Equal",Xm="Exp",q2="Expm1",j2="FFT",K2="Fill",X2="FlipLeftRight",Jm="Floor",Zm="FloorDiv",J2="FusedBatchNorm",Qm="GatherV2",Z2="Greater",ef="GreaterEqual",tf="Identity",Q2="IFFT",eR="Imag",tR="IsFinite",nR="IsInf",sR="IsNan",iR="Less",rR="LessEqual",nf="Log",sf="Log1p",oR="LogicalAnd",aR="LogicalNot",cR="LogSoftmax",lR="LRN",hR="LRNBackprop",rf="Max",of="Maximum",uR="MaxPool",dR="MaxPoolBackprop",pR="MaxPool3D",mR="MaxPool3DBackprop",af="Min",cf="Minimum",fR="Mod",lf="Multiply",hf="Negate",gR="NotEqual",yR="NonMaxSuppressionV3",bR="NonMaxSuppressionV4",wR="NonMaxSuppressionV5",LR="OnesLike",SR="OneHot",uf="PadV2",df="Pow",IR="Prelu",xR="Range",TR="Real",AR="Reciprocal",pf="Relu",mf="Reshape",ff="ResizeNearestNeighbor",vR="ResizeNearestNeighborGrad",gf="ResizeBilinear",NR="ResizeBilinearGrad",CR="Relu6",yf="Reverse",RR="Round",bf="Rsqrt",wf="SelectV2",OR="Selu",Lf="Slice",Sf="Sin",If="Sinh",ER="Sign",xf="Sigmoid",DR="Softplus",Tf="Sqrt",Af="Sum",vf="SpaceToBatchND",Nf="SplitV",kR="Softmax",Cf="SquaredDifference",FR="Square",Rf="Sub",_R="Tan",WR="Tanh",Of="Tile",Ef="Transpose",Df="Unpack",kf="UnsortedSegmentSum",Ff="ZerosLike",_f="Step",rI="FromPixels",$R="RotateWithOffset";const UR=iI("kernelRegistry",()=>new Map),oI=iI("gradRegistry",()=>new Map);function Wf(r,l){const h=XX(r,l);return UR.get(h)}function aI(r){return oI.get(r)}function cI(r){const l=UR.entries(),h=[];for(;;){const{done:d,value:f}=l.next();if(d)break;const[g,S]=f,[L]=g.split("_");L===r&&h.push(S)}return h}function BR(r){const{kernelName:l}=r;oI.has(l)&&(Es().getBool("DEBUG")&&console.warn(`Overriding the gradient for '${l}'`)),oI.set(l,r)}function XX(r,l){return`${l}_${r}`}function Z(r,l){if(!r)throw new Error(typeof l=="string"?l:l())}function Zt(r,l,h=""){Z(oa(r,l),()=>h+` Shapes ${r} and ${l} must match`)}function _c(r){Z(r!=null,()=>"The input to the tensor constructor must be a non-null value.")}function Wc(r,l=[],h=!1){if(l==null&&(l=[]),Array.isArray(r)||Ds(r)&&!h)for(let d=0;d<r.length;++d)Wc(r[d],l,h);else l.push(r);return l}function qt(r){if(r.length===0)return 1;let l=r[0];for(let h=1;h<r.length;h++)l*=r[h];return l}function oa(r,l){if(r===l)return!0;if(r==null||l==null)return!1;if(r.length!==l.length)return!1;for(let h=0;h<r.length;h++)if(r[h]!==l[h])return!1;return!0}function Qt(r){return r%1===0}function $c(r,l){return l<=r.length?r:r+" ".repeat(l-r.length)}function MR(r,l){let h=1,d=-1;for(let g=0;g<r.length;++g)if(r[g]>=0)h*=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!==h)throw Error(`Size(${l}) must match the product of shape ${r}`);return r}if(h===0)throw Error(`Cannot infer the missing size in [${r}] when there are 0 elements`);if(l%h!==0)throw Error(`The implicit shape can't be a fractional number. Got ${l} / ${h}`);const f=r.slice();return f[d]=l/h,f}function ht(r,l){const h=l.length;return r=r==null?l.map((d,f)=>f):[].concat(r),Z(r.every(d=>d>=-h&&d<h),()=>`All values in axis param must be in range [-${h}, ${h}) but got axis ${r}`),Z(r.every(d=>Qt(d)),()=>`All values in axis param must be integers but got axis ${r}`),r.map(d=>d<0?h+d:d)}function PR(r,l){const h=[],d=[],f=l!=null&&Array.isArray(l)&&l.length===0,g=l==null||f?null:ht(l,r).sort();let S=0;for(let L=0;L<r.length;++L){if(g!=null){if(g[S]===L&&r[L]!==1)throw new Error(`Can't squeeze axis ${L} since its dim '${r[L]}' is not 1`);(g[S]==null||g[S]>L)&&r[L]===1&&(h.push(r[L]),d.push(L)),g[S]<=L&&S++}r[L]!==1&&(h.push(r[L]),d.push(L))}return{newShape:h,keptDims:d}}function zR(r,l){let h=null;if(r==null||r==="float32")h=new Float32Array(l);else if(r==="int32")h=new Int32Array(l);else if(r==="bool")h=new Uint8Array(l);else if(r==="string")h=new Array(l);else throw new Error(`Unknown data type ${r}`);return h}function JX(r,l){for(let h=0;h<r.length;h++){const d=r[h];if(isNaN(d)||!isFinite(d))throw Error(`A tensor of type ${l} being uploaded contains ${d}.`)}}function GR(r){return r==="bool"||r==="complex64"||r==="float32"||r==="int32"||r==="string"}function Ds(r){return r instanceof Float32Array||r instanceof Int32Array||r instanceof Uint8Array}function VR(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 HR(r){if(r==null)return 0;let l=0;return r.forEach(h=>l+=h.length),l}function Au(r){return typeof r=="string"||r instanceof String}function ZX(r){return typeof r=="boolean"}function QX(r){return typeof r=="number"}function vu(r){return Array.isArray(r)?vu(r[0]):r instanceof Float32Array?"float32":r instanceof Int32Array||r instanceof Uint8Array?"int32":QX(r)?"float32":Au(r)?"string":ZX(r)?"bool":"float32"}function lI(r){return!!(r&&r.constructor&&r.call&&r.apply)}function Nu(r){const l=r.length;if(l<2)return[];const h=new Array(l-1);h[l-2]=r[l-1];for(let d=l-3;d>=0;--d)h[d]=h[d+1]*r[d+1];return h}function $f(r,l){if(l==="string")throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(r)&&(r=Wc(r)),Es().getBool("DEBUG")&&JX(r,l),eJ(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 h=new Uint8Array(r.length);for(let d=0;d<h.length;++d)Math.round(r[d])!==0&&(h[d]=1);return h}else throw new Error(`Unknown data type ${l}`)}function YR(r,l,h){const d=new Array;if(l.length===1){const f=l[0];for(let g=0;g<f;g++)d[g]=h[r+g]}else{const f=l[0],g=l.slice(1),S=g.reduce((L,x)=>L*x);for(let L=0;L<f;L++)d[L]=YR(r+L*S,g,h)}return d}function hI(r,l){if(r.length===0)return l[0];const h=r.reduce((d,f)=>d*f);if(h===0)return[];if(h!==l.length)throw new Error(`[${r}] does not match the input size ${l.length}.`);return YR(0,r,l)}function eJ(r,l){return r instanceof Float32Array&&l==="float32"||r instanceof Int32Array&&l==="int32"||r instanceof Uint8Array&&l==="bool"}function Uf(r,l){const h=aa(r,l);for(let d=0;d<h.length;d++)h[d]=1;return h}function aa(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 uI(){return Es().platform.now()}function Bf(r){r.forEach(l=>{Z(Number.isInteger(l)&&l>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${r}].`)})}function qR(r,l="utf-8"){return l=l||"utf-8",Es().platform.encode(r,l)}function dI(r,l="utf-8"){return l=l||"utf-8",Es().platform.decode(r,l)}class jR{constructor(r,l){this.backendTimer=r,this.logger=l,l==null&&(this.logger=new nJ)}profileKernel(r,l,h){let d;const f=()=>{d=h()},g=this.backendTimer.time(f);for(let L=0;L<d.length;L++){const x=d[L];x.data().then(A=>{tJ(A,x.dtype,r)})}const S={kernelName:r,outputs:d,inputs:l,timeMs:g.then(L=>L.kernelMs),extraInfo:g.then(L=>L.getExtraProfileInfo!=null?L.getExtraProfileInfo():"")};return S}logKernelProfile(r){const{kernelName:l,outputs:h,timeMs:d,inputs:f,extraInfo:g}=r;h.forEach(S=>{Promise.all([S.data(),d,g]).then(L=>{this.logger.logKernelProfile(l,S,L[0],L[1],f,L[2])})})}}function tJ(r,l,h){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 '${h}'`),!0}return!1}class nJ{logKernelProfile(r,l,h,d,f,g){const S=typeof d=="number"?$c(`${d}ms`,9):d.error,L=$c(r,25),x=l.rank,A=l.size,O=$c(l.shape.toString(),14);let C="";for(const $ in f){const z=f[$];if(z!=null){const ne=z.shape||l.shape,te=ne.length;C+=`${$}: ${te}D ${te>0?ne:""} `}}console.log(`%c${L} %c${S} %c${x}D ${O} %c${A} %c${C} %c${g}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}}function KR(r,l,h){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 A=r[x],O=A.inputs;for(const C in O){const $=O[C];let z=!1;for(let ne=0;ne<l.length;ne++)if(d[$.id]){A.outputs.forEach(te=>d[te.id]=!0),z=!0,f[A.id]=!0;break}if(z)break}}const g={};g[h.id]=!0;const S={};for(let x=r.length-1;x>=0;x--){const A=r[x],O=A.inputs;for(let C=0;C<A.outputs.length;C++)if(g[A.outputs[C].id]){for(const $ in O)g[O[$].id]=!0,S[A.id]=!0;break}}const L=[];for(let x=0;x<r.length;x++){const A=r[x];if(f[A.id]&&S[A.id]){const O={};for(const $ in A.inputs){const z=A.inputs[$];d[z.id]&&(O[$]=z)}const C=Object.assign({},A);C.inputs=O,C.outputs=A.outputs,L.push(C)}}return L}function XR(r,l,h,d){for(let f=l.length-1;f>=0;f--){const g=l[f],S=[];if(g.outputs.forEach(x=>{const A=r[x.id];A!=null?S.push(A):S.push(null)}),g.gradient==null)throw new Error(`Cannot compute gradient: gradient function not found for ${g.kernelName}.`);const L=g.gradient(S);for(const x in g.inputs){if(!(x in L))throw new Error(`Cannot backprop through input ${x}. Available gradients found: ${Object.keys(L)}.`);const A=h(()=>L[x]());if(A.dtype!=="float32")throw new Error(`Error in gradient for op ${g.kernelName}. The gradient of input ${x} must have 'float32' dtype, but has '${A.dtype}'`);const O=g.inputs[x];if(!oa(A.shape,O.shape))throw new Error(`Error in gradient for op ${g.kernelName}. The gradient of input '${x}' has shape '${A.shape}', which does not match the shape of the input '${O.shape}'`);if(r[O.id]==null)r[O.id]=A;else{const C=r[O.id];r[O.id]=d(C,A),C.dispose()}}}}const JR=20,Cu=3,pI=7;function ZR(r,l,h,d){const f=Nu(l),g=sJ(r,l,h,f),S=l.length,L=Mf(r,l,h,f,g),x=["Tensor"];return d&&(x.push(` dtype: ${h}`),x.push(` rank: ${S}`),x.push(` shape: [${l}]`),x.push(" values:")),x.push(L.map(A=>" "+A).join(`
`)),x.join(`
`)}function sJ(r,l,h,d){const f=qt(l),g=d[d.length-1],S=new Array(g).fill(0),L=l.length,x=h==="complex64"?Ou(r):r;if(L>1)for(let A=0;A<f/g;A++){const O=A*g;for(let C=0;C<g;C++)S[C]=Math.max(S[C],Ru(x[O+C],0,h).length)}return S}function Ru(r,l,h){let d;return Array.isArray(r)?d=`${parseFloat(r[0].toFixed(pI))} + ${parseFloat(r[1].toFixed(pI))}j`:Au(r)?d=`'${r}'`:h==="bool"?d=QR(r):d=parseFloat(r.toFixed(pI)).toString(),$c(d,l)}function QR(r){return r===0?"false":"true"}function Mf(r,l,h,d,f,g=!0){const S=h==="complex64"?2:1,L=l[0],x=l.length;if(x===0){if(h==="complex64"){const te=Ou(r);return[Ru(te[0],0,h)]}return h==="bool"?[QR(r[0])]:[r[0].toString()]}if(x===1){if(L>JR){const se=Cu*S;let fe=Array.from(r.slice(0,se)),de=Array.from(r.slice((L-Cu)*S,L*S));return h==="complex64"&&(fe=Ou(fe),de=Ou(de)),["["+fe.map((Ae,xe)=>Ru(Ae,f[xe],h)).join(", ")+", ..., "+de.map((Ae,xe)=>Ru(Ae,f[L-Cu+xe],h)).join(", ")+"]"]}const te=h==="complex64"?Ou(r):Array.from(r);return["["+te.map((se,fe)=>Ru(se,f[fe],h)).join(", ")+"]"]}const A=l.slice(1),O=d.slice(1),C=d[0]*S,$=[];if(L>JR){for(let te=0;te<Cu;te++){const se=te*C,fe=se+C;$.push(...Mf(r.slice(se,fe),A,h,O,f,!1))}$.push("...");for(let te=L-Cu;te<L;te++){const se=te*C,fe=se+C;$.push(...Mf(r.slice(se,fe),A,h,O,f,te===L-1))}}else for(let te=0;te<L;te++){const se=te*C,fe=se+C;$.push(...Mf(r.slice(se,fe),A,h,O,f,te===L-1))}const z=x===2?",":"";$[0]="["+$[0]+z;for(let te=1;te<$.length-1;te++)$[te]=" "+$[te]+z;let ne=`,
`;for(let te=2;te<x;te++)ne+=`
`;return $[$.length-1]=" "+$[$.length-1]+"]"+(g?"":ne),$}function Ou(r){const l=[];for(let h=0;h<r.length;h+=2)l.push([r[h],r[h+1]]);return l}class eO{constructor(r,l,h){if(this.dtype=l,this.shape=r.slice(),this.size=qt(r),h!=null){const d=h.length;Z(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=h||zR(l,this.size),this.strides=Nu(r)}set(r,...l){l.length===0&&(l=[0]),Z(l.length===this.rank,()=>`The number of provided coordinates (${l.length}) must match the rank (${this.rank})`);const h=this.locToIndex(l);this.values[h]=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 h=r[r.length-1];for(let d=0;d<r.length-1;++d)h+=this.strides[d]*r[d];return this.values[h]}locToIndex(r){if(this.rank===0)return 0;if(this.rank===1)return r[0];let l=r[r.length-1];for(let h=0;h<r.length-1;++h)l+=this.strides[h]*r[h];return l}indexToLoc(r){if(this.rank===0)return[];if(this.rank===1)return[r];const l=new Array(this.shape.length);for(let h=0;h<l.length-1;++h)l[h]=Math.floor(r/this.strides[h]),r-=l[h]*this.strides[h];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,Uc=null,iJ=null;function tO(r){Yi=r}function nO(r){Uc=r}function sO(r){iJ=r}class Tn{constructor(r,l,h,d){this.kept=!1,this.isDisposedInternal=!1,this.shape=r.slice(),this.dtype=l||"float32",this.size=qt(r),this.strides=Nu(r),this.dataId=h,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 Uc.buffer(this.shape,this.dtype,r)}bufferSync(){return Uc.buffer(this.shape,this.dtype,this.dataSync())}async array(){const r=await this.data();return hI(this.shape,r)}arraySync(){return hI(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(h=>dI(h))}catch(h){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=>dI(l))}catch(l){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}return r}async bytes(){this.throwIfDisposed();const r=await 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 Uc.print(this,r)}clone(){return this.throwIfDisposed(),Uc.clone(this)}toString(r=!1){const l=this.dataSync();return ZR(l,this.shape,this.dtype,r)}cast(r){return this.throwIfDisposed(),Uc.cast(this,r)}variable(r=!0,l,h){return this.throwIfDisposed(),Yi().makeVariable(this,r,l,h)}}Object.defineProperty(Tn,Symbol.hasInstance,{value:r=>!!r&&r.data!=null&&r.dataSync!=null&&r.throwIfDisposed!=null});class Pf extends Tn{constructor(r,l,h,d){super(r.shape,r.dtype,r.dataId,d);this.trainable=l,this.name=h}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(!oa(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(Pf,Symbol.hasInstance,{value:r=>r instanceof Tn&&r.assign!=null&&r.assign instanceof Function});var iO;(function(r){r.R0="R0",r.R1="R1",r.R2="R2",r.R3="R3",r.R4="R4",r.R5="R5",r.R6="R6"})(iO||(iO={}));var mI;(function(r){r.float32="float32",r.int32="int32",r.bool="int32",r.complex64="complex64"})(mI||(mI={}));var fI;(function(r){r.float32="float32",r.int32="int32",r.bool="bool",r.complex64="complex64"})(fI||(fI={}));var gI;(function(r){r.float32="float32",r.int32="float32",r.bool="float32",r.complex64="complex64"})(gI||(gI={}));var yI;(function(r){r.float32="complex64",r.int32="complex64",r.bool="complex64",r.complex64="complex64"})(yI||(yI={}));const rJ={float32:gI,int32:mI,bool:fI,complex64:yI};function rO(r,l){if(r==="string"||l==="string"){if(r==="string"&&l==="string")return"string";throw new Error(`Can not upcast ${r} with ${l}`)}return rJ[r][l]}function mt(r,l){if(r.dtype===l.dtype)return[r,l];const h=rO(r.dtype,l.dtype);return[r.cast(h),l.cast(h)]}function zf(r){const l=[],h=new Set;return oO(r,l,h),l}function oO(r,l,h){if(r==null)return;if(r instanceof Tn){l.push(r);return}if(!oJ(r))return;const d=r;for(const f in d){const g=d[f];h.has(g)||(h.add(g),oO(g,l,h))}}function oJ(r){return Array.isArray(r)||typeof r=="object"}class aO{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 Eu{constructor(r){this.ENV=r,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new aO}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 h=r[l],d=await this.initializeBackend(h).success;if(d){await this.setBackend(h);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,h=1){return r in this.registryFactory?(console.warn(`${r} backend was already registered. Reusing existing backend factory.`),!1):(this.registryFactory[r]={factory:l,priority:h},!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:h}=this.initializeBackend(r),d=h?await l:l;if(!d)return!1}return this.backendInstance=this.registry[r],this.setupRegisteredKernels(),this.profiler=new jR(this.backendInstance),!0}setupRegisteredKernels(){const r=cI(this.backendName);r.forEach(l=>{l.setupFunc!=null&&l.setupFunc(this.backendInstance)})}disposeRegisteredKernels(r){const l=cI(r);l.forEach(h=>{h.disposeFunc!=null&&h.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 h=l.factory();if(h&&!(h instanceof h2)&&typeof h.then=="function"){const d=++this.pendingBackendInitId,f=h.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]=h,{success:!0,asyncInit:!1}}catch(h){return console.warn(`Initialization of backend ${r} failed`),console.warn(h.stack||h.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 h=r[l],{success:d,asyncInit:f}=this.initializeBackend(h);if(f||d)return{name:h,asyncInit:f}}throw new Error("Could not initialize any backends, all backend initializations failed.")}moveData(r,l){const h=this.state.tensorInfo.get(l),d=h.backend,f=this.readSync(l);d.disposeData(l),h.backend=r,r.move(l,f,h.shape,h.dtype),this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack[this.state.numDataMovesStack.length-1]++}tidy(r,l){let h=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");h=r}let d;return this.scopedRun(()=>this.startScope(h),()=>this.endScope(d),()=>(d=l(),d instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),d))}scopedRun(r,l,h){r();try{const d=h();return l(),d}catch(d){throw l(),d}}nextTensorId(){return Eu.nextTensorId++}nextVariableId(){return Eu.nextVariableId++}clone(r){const l=this.makeTensorFromDataId(r.dataId,r.shape,r.dtype),h={x:r},d=g=>({x:()=>{const S="float32",L={x:g},x={dtype:S};return H.runKernelFunc(A=>A.cast(g,S),L,null,Fc,x)}}),f=[];return this.addTapeNode(this.state.activeScope.name,h,[l],d,f,{}),l}runKernel(r,l,h,d,f){const g=null,S=null;return this.runKernelFunc(g,l,S,r,h,d,f)}shouldCheckForMemLeaks(){return this.ENV.getBool("IS_TEST")}checkKernelForMemLeak(r,l,h){const d=this.backend.numDataIds();let f=0;h.forEach(L=>{f+=L.dtype==="complex64"?3:1});const g=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],S=d-l-f-g;if(S>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${S} data ids) after running '${r}'`)}runKernelFunc(r,l,h,d,f,g,S){let L,x=[];const A=this.isTapeOn();d==null&&(d=this.state.activeScope!=null?this.state.activeScope.name:"");const O=this.state.numBytes,C=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);let $;const z=Wf(d,this.backendName);let ne;if(z!=null)$=()=>{const se=this.backend.numDataIds();ne=z.kernelFunc({inputs:l,attrs:f,backend:this.backend});const fe=Array.isArray(ne)?ne:[ne];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(d,se,fe);const de=fe.map(({dataId:Ae,shape:xe,dtype:Me})=>this.makeTensorFromDataId(Ae,xe,Me));if(A){let Ae=this.getTensorsForGradient(d,l,de);if(Ae==null){S==null&&(S=[]);const xe=de.filter((Me,Ke)=>S[Ke]);Ae=(g||[]).slice().concat(xe)}x=this.saveTensorsForBackwardMode(Ae)}return de};else{const se=fe=>{if(!A)return;x=fe.map(de=>this.keep(this.clone(de)))};$=()=>{const fe=this.backend.numDataIds();ne=this.tidy(()=>r(this.backend,se));const de=Array.isArray(ne)?ne:[ne];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(d,fe,de),de}}let te;return this.scopedRun(()=>this.state.kernelDepth++,()=>this.state.kernelDepth--,()=>{!this.ENV.getBool("DEBUG")&&!this.state.profiling?L=$():(te=this.profiler.profileKernel(d,l,()=>$()),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(te),L=te.outputs)}),A&&this.addTapeNode(d,l,L,h,x,f),this.state.profiling&&this.state.activeProfile.kernels.push({name:d,bytesAdded:this.state.numBytes-O,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-C,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(l).map(se=>l[se]!=null?l[se].shape:null),outputShapes:L.map(se=>se.shape),kernelTimeMs:te.timeMs,extraInfo:te.extraInfo}),Array.isArray(ne)?L:L[0]}saveTensorsForBackwardMode(r){const l=r.map(h=>this.keep(this.clone(h)));return l}getTensorsForGradient(r,l,h){const d=aI(r);if(d!=null){const f=d.inputsToSave||[],g=d.outputsToSave||[];let S;d.saveAllInputs?(Z(Array.isArray(l),()=>"saveAllInputs is true, expected inputs to be an array."),S=Object.keys(l).map(x=>l[x])):S=f.map(x=>l[x]);const L=h.filter((x,A)=>g[A]);return S.concat(L)}return null}makeTensor(r,l,h,d){if(r==null)throw new Error("Values passed to engine.makeTensor() are null");h=h||"float32",d=d||this.backend;let f=r;h==="string"&&Au(r[0])&&(f=r.map(L=>qR(L)));const g=d.write(f,l,h),S=new Tn(l,h,g,this.nextTensorId());if(this.incRef(S,d),h==="string"){const L=this.state.tensorInfo.get(g),x=HR(f);this.state.numBytes+=x-L.bytes,L.bytes=x}return S}makeTensorFromDataId(r,l,h,d){h=h||"float32";const f=new Tn(l,h,r,this.nextTensorId());return this.incRef(f,d),f}makeVariable(r,l=!0,h,d){h=h||this.nextVariableId().toString(),d!=null&&d!==r.dtype&&(r=r.cast(d));const f=new Pf(r,l,h,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 h=this.state.tensorInfo.has(r.dataId)?this.state.tensorInfo.get(r.dataId).refCount:0;if(this.state.numTensors++,r.dtype==="string"&&this.state.numStringTensors++,h===0){this.state.numDataBuffers++;let d=0;r.dtype!=="complex64"&&r.dtype!=="string"&&(d=r.size*VR(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 Pf||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),h=l.refCount;h<=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,h=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-h;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,h,d,f,g){const S={id:this.state.nextTapeNodeId++,kernelName:r,inputs:l,outputs:h,saved:f},L=aI(r);L!=null&&(d=L.gradFunc),d!=null&&(S.gradient=x=>(x=x.map((A,O)=>{if(A==null){const C=h[O],$=aa(C.size,C.dtype);return this.makeTensor($,C.shape,C.dtype)}return A}),d(x.length>1?x:x[0],f,g))),this.state.activeTape.push(S)}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=zf(r),h=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&&!h.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,h,d=!1){if(Z(l.length>0,()=>"gradients() received an empty list of xs."),h!=null&&h.dtype!=="float32")throw new Error(`dy must have 'float32' dtype, but has '${h.dtype}'`);const f=this.scopedRun(()=>this.startTape(),()=>this.endTape(),()=>this.tidy("forward",r));Z(f instanceof Tn,()=>"The result y returned by f() must be a tensor.");const g=KR(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 S={};S[f.id]=h==null?aJ(f.shape):h,XR(S,g,x=>this.tidy(x),cJ);const L=l.map(x=>S[x.id]);return this.state.gradientDepth===0&&(this.state.activeTape.forEach(x=>{for(const A of x.saved)A.dispose()}),this.state.activeTape=null),{value:f,grads:L}})}customGrad(r){return Z(lI(r),()=>"The f passed in customGrad(f) must be a function."),(...l)=>{Z(l.every(f=>f instanceof Tn),()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors");let h;const d={};return l.forEach((f,g)=>{d[g]=f}),this.runKernelFunc((f,g)=>(h=r(...l,g),Z(h.value instanceof Tn,()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),Z(lI(h.gradFunc),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."),h.value),d,(f,g)=>{const S=h.gradFunc(f,g),L=Array.isArray(S)?S:[S];Z(L.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(...)."),Z(L.every(A=>A instanceof Tn),()=>"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 L.forEach((A,O)=>{x[O]=()=>A}),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=uI(),h=await this.backend.time(r);return h.wallMs=uI()-l,h}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 aO;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}}Eu.nextTensorId=0;Eu.nextVariableId=0;function aJ(r){const l=Uf(qt(r),"float32");return H.makeTensor(l,r,"float32")}function bI(){const r=sI();if(r._tfengine==null){const l=new d2(r);r._tfengine=new Eu(l)}return m2(r._tfengine.ENV),tO(()=>r._tfengine),r._tfengine}const H=bI();function cJ(r,l){const h={a:r,b:l};return H.runKernelFunc((d,f)=>{const g=d.add(r,l);return f([r,l]),g},h,null,kc)}function cO(){return typeof window!="undefined"&&window.document!=null||typeof WorkerGlobalScope!="undefined"}const br=Es();br.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.")});br.registerFlag("IS_BROWSER",()=>cO());br.registerFlag("IS_NODE",()=>typeof process!="undefined"&&typeof process.versions!="undefined"&&typeof process.versions.node!="undefined");br.registerFlag("IS_CHROME",()=>typeof navigator!="undefined"&&navigator!=null&&navigator.userAgent!=null&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor));br.registerFlag("PROD",()=>!1);br.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",()=>br.getBool("DEBUG"));br.registerFlag("DEPRECATION_WARNINGS_ENABLED",()=>!0);br.registerFlag("IS_TEST",()=>!1);function wr(r,l){let h=r;if(Ds(r))return l==="string"?[]:[r.length];if(!Array.isArray(r))return[];const d=[];for(;Array.isArray(h)||Ds(h)&&l!=="string";)d.push(h.length),h=h[0];return Array.isArray(r)&&Es().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&lO(r,d,[]),d}function lO(r,l,h){if(h=h||[],!Array.isArray(r)&&!Ds(r)){Z(l.length===0,()=>`Element arr[${h.join("][")}] is a primitive, but should be an array/TypedArray of ${l[0]} elements`);return}Z(l.length>0,()=>`Element arr[${h.join("][")}] should be a primitive, but is an array of ${r.length} elements`),Z(r.length===l[0],()=>`Element arr[${h.join("][")}] should have ${l[0]} elements, but has ${r.length} elements`);const d=l.slice(1);for(let f=0;f<r.length;++f)lO(r[f],d,h.concat(f))}function hO(r,l,h,d){if(r==null)return;if(r!=="numeric"&&r!==l||r==="numeric"&&l==="string")throw new Error(`Argument '${h}' passed to '${d}' must be ${r} tensor, but got ${l} tensor`)}function M(r,l,h,d="numeric"){if(r instanceof Tn)return hO(d,r.dtype,l,h),r;let f=vu(r);if(f!=="string"&&["bool","int32","float32"].indexOf(d)>=0&&(f=d),hO(d,f,l,h),r==null||!Ds(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 '${h}' must be a Tensor or TensorLike, but got '${x}'`)}const g=wr(r,f);!Ds(r)&&!Array.isArray(r)&&(r=[r]);const S=!0,L=f!=="string"?$f(r,f):Wc(r,[],S);return H.makeTensor(L,g,f)}function Gf(r,l,h,d="numeric"){if(!Array.isArray(r))throw new Error(`Argument ${l} passed to ${h} must be a \`Tensor[]\` or \`TensorLike[]\``);const f=r;return f.map((g,S)=>M(g,`${l}[${S}]`,h),d)}const uO="__op";function G(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 h=l[0];const d=r[h];h.endsWith("_")&&(h=h.substring(0,h.length-1)),h=h+uO;const f=(...g)=>{H.startScope(h);try{const S=d(...g);return S instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),H.endScope(S),S}catch(S){throw H.endScope(null),S}};return Object.defineProperty(f,"name",{value:h,configurable:!0}),f}function lJ(r,l){const h=M(r,"real","complex"),d=M(l,"imag","complex");Zt(h.shape,d.shape,`real and imag shapes, ${h.shape} and ${d.shape}, must match in call to tf.complex().`);const f=S=>S.complex(h,d),g={real:h,imag:d};return H.runKernelFunc(f,g,null,E2)}const qi=G({complex_:lJ});function ji(r,l,h,d){if(d==null&&(d=vu(r)),d==="complex64")throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!Ds(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=qt(l),g=qt(h);Z(f===g,()=>`Based on the provided shape, [${l}], the tensor should have ${f} values but has ${g}`);for(let S=0;S<h.length;++S){const L=h[S],x=S===h.length-1?L!==qt(l.slice(S)):!0;Z(h[S]===l[S]||!x,()=>`Error creating a new Tensor. Inferred shape (${h}) does not match the provided shape (${l}). `)}}return!Ds(r)&&!Array.isArray(r)&&(r=[r]),l=l||h,r=d!=="string"?$f(r,d):Wc(r,[],!0),H.makeTensor(r,l,d)}function wI(r,l,h){const d=wr(r,h);return ji(r,l,d,h)}function Du(r,l="float32",h){return l=l||"float32",Bf(r),new eO(r,l,h)}function hJ(r,l){const h=M(r,"x","cast");if(!GR(l))throw new Error(`Failed to cast to unknown dtype ${l}`);if(l==="string"&&h.dtype!=="string"||l!=="string"&&h.dtype==="string")throw new Error("Only strings can be casted to strings");const d={x:h},f={dtype:l};return H.runKernelFunc(g=>g.cast(h,l),d,null,Fc,f)}const Le=G({cast_:hJ});function uJ(r){const l=M(r,"x","clone",null),h=()=>H.makeTensorFromDataId(l.dataId,l.shape,l.dtype),d={x:l};return H.runKernelFunc(h,d,null,tf)}const bi=G({clone_:uJ});function LI(r,l=!1){console.log(r.toString(l))}bI();const dJ={buffer:Du,cast:Le,clone:bi,print:LI};nO(dJ);function pJ(r,l){const h=M(r,"x","reshape",null),d={x:h},f={shape:l},g=(S,L)=>(l=MR(l,h.size),Z(h.size===qt(l),()=>"new shape and old shape must have the same number of elements."),L([h]),S.reshape(h,l));return H.runKernelFunc(g,d,null,mf,f)}const re=G({reshape_:pJ});function mJ(r,l,h=!1,d=!1){let f=M(r,"a","matMul"),g=M(l,"b","matMul");[f,g]=mt(f,g),Z(f.rank>=2&&g.rank>=2&&f.rank===g.rank,()=>`Error in matMul: inputs must have the same rank of at least 2, got ranks ${f.rank} and ${g.rank}.`);const S=h?f.shape[f.rank-2]:f.shape[f.rank-1],L=d?g.shape[g.rank-1]:g.shape[g.rank-2],x=h?f.shape[f.rank-1]:f.shape[f.rank-2],A=d?g.shape[g.rank-2]:g.shape[g.rank-1],O=f.shape.slice(0,-2),C=g.shape.slice(0,-2),$=qt(O),z=qt(C);Z(oa(O,C),()=>`Error in matMul: outer dimensions (${O}) and (${C}) of Tensors with shapes ${f.shape} and ${g.shape} must match.`),Z(S===L,()=>`Error in matMul: inner shapes (${S}) and (${L}) of Tensors with shapes ${f.shape} and ${g.shape} and transposeA=${h} and transposeB=${d} must match.`);const ne=f.shape.slice(0,-2).concat([x,A]),te=h?re(f,[$,S,x]):re(f,[$,x,S]),se=d?re(g,[z,A,L]):re(g,[z,L,A]),fe=(Me,Ke)=>(Ke([te,se]),Me.batchMatMul(te,se,h,d)),de={a:te,b:se},Ae={transposeA:h,transposeB:d},xe=H.runKernelFunc(fe,de,null,Mm,Ae);return re(xe,ne)}const pn=G({matMul_:mJ});function fJ(r,l){const h=M(r,"x","transpose");if(l==null&&(l=h.shape.map((g,S)=>S).reverse()),Z(h.rank===l.length,()=>`Error in transpose: rank of input ${h.rank} must match length of perm ${l}.`),l.forEach(g=>{Z(g>=0&&g<h.rank,()=>`All entries in 'perm' must be between 0 and ${h.rank-1} but got ${l}`)}),h.rank<=1)return h.clone();const d={x:h},f={perm:l};return H.runKernelFunc(g=>g.transpose(h,l),d,null,Ef,f)}const Wt=G({transpose_:fJ});function SI(r,l,h){if(_c(r),l!=null&&l.length!==3)throw new Error("tensor3d() requires shape to have three numbers");const d=wr(r,h);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 ji(r,l,d,h)}const II={};vc(II,{fromPixels:()=>bJ,toPixels:()=>yJ});let Bc;function gJ(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 h=!1,d=!1,f=!1,g=!1,S=!1;if(r.data instanceof Uint8Array)h=!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)S=!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 z=2;if(f&&r.readyState<z)throw new Error("The video element has not loaded data yet. Please wait for `loadeddata` event on the <video> element.")}const L=Wf(rI,H.backendName);if(L!=null){const z={pixels:r},ne={numChannels:l};return H.runKernel(rI,z,ne)}const[x,A]=f?[r.videoWidth,r.videoHeight]:[r.width,r.height];let O;S?O=r.getContext("2d").getImageData(0,0,x,A).data:d||h?O=r.data:(g||f)&&(Bc==null&&(Bc=document.createElement("canvas").getContext("2d")),Bc.canvas.width=x,Bc.canvas.height=A,Bc.drawImage(r,0,0,x,A),O=Bc.getImageData(0,0,x,A).data);let C;if(l===4)C=new Int32Array(O);else{const z=x*A;C=new Int32Array(z*l);for(let ne=0;ne<z;ne++)for(let te=0;te<l;++te)C[ne*l+te]=O[ne*4+te]}const $=[A,x,l];return SI(C,$,"int32")}async function yJ(r,l){let h=M(r,"img","toPixels");if(!(r instanceof Tn)){const A=h;h=Le(A,"int32"),A.dispose()}if(h.rank!==2&&h.rank!==3)throw new Error(`toPixels only supports rank 2 or 3 tensors, got rank ${h.rank}.`);const[d,f]=h.shape.slice(0,2),g=h.rank===2?1:h.shape[2];if(g>4||g===2)throw new Error(`toPixels only supports depth of size 1, 3 or 4 but got ${g}`);if(h.dtype!=="float32"&&h.dtype!=="int32")throw new Error(`Unsupported type for toPixels: ${h.dtype}. Please use float32 or int32 tensors.`);const S=await h.data(),L=h.dtype==="float32"?255:1,x=new Uint8ClampedArray(f*d*4);for(let A=0;A<d*f;++A){const O=[0,0,0,255];for(let $=0;$<g;$++){const z=S[A*g+$];if(h.dtype==="float32"){if(z<0||z>1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${z}.`)}else if(h.dtype==="int32"&&(z<0||z>255))throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${z}.`);g===1?(O[0]=z*L,O[1]=z*L,O[2]=z*L):O[$]=z*L}const C=A*4;x[C+0]=Math.round(O[0]),x[C+1]=Math.round(O[1]),x[C+2]=Math.round(O[2]),x[C+3]=Math.round(O[3])}if(l!=null){l.width=f,l.height=d;const A=l.getContext("2d"),O=new ImageData(x,f,d);A.putImageData(O,0,0)}return h!==r&&h.dispose(),x}const bJ=G({fromPixels_:gJ});function dO(r,l,h){const d=r.shape.length;Z(d===l.length,()=>`Error in slice${d}D: Length of begin ${l} must match the rank of the array (${d}).`),Z(d===h.length,()=>`Error in slice${d}D: Length of size ${h} must match the rank of the array (${d}).`);for(let f=0;f<d;++f)Z(l[f]+h[f]<=r.shape[f],()=>`Error in slice${d}D: begin[${f}] + size[${f}] (${l[f]+h[f]}) would overflow input.shape[${f}] (${r.shape[f]})`)}function Vf(r,l,h){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(S=>{Z(S!==-1,()=>"slice() does not support negative begin indexing.")});let g;return h==null?g=new Array(f).fill(-1):typeof h=="number"?g=[h,...new Array(f-1).fill(-1)]:h.length<f?g=h.concat(new Array(f-h.length).fill(-1)):g=h,g=g.map((S,L)=>S>=0?S:(Z(S===-1,()=>`Negative size values should be exactly -1 but got ${S} for the slice() size at index ${L}.`),r.shape[L]-d[L])),[d,g]}function wJ(r){Es().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(r+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}sO(wJ);function pO(r,l){return H.tidy(r,l)}function mO(r){const l=zf(r);l.forEach(h=>h.dispose())}function LJ(r,l){let h=M(r,"a","add"),d=M(l,"b","add");[h,d]=mt(h,d);const f=(S,L)=>{const x=S.add(h,d);return L([h,d]),x},g={a:h,b:d};return H.runKernelFunc(f,g,null,kc)}const St=G({add_:LJ});function SJ(r,l){let h=M(r,"a","floorDiv"),d=M(l,"b","floorDiv");[h,d]=mt(h,d);const f=(S,L)=>{const x=S.floorDiv(h,d);return L([h,d]),x},g={a:h,b:d};return H.runKernelFunc(f,g,null,Zm)}const xI=G({floorDiv_:SJ});function IJ(r,l){let h=M(r,"a","div"),d=M(l,"b","div");if([h,d]=mt(h,d),h.dtype==="int32"&&d.dtype==="int32")return xI(h,d);const f=(L,x)=>{const A=L.realDivide(h,d);return x([h,d]),A},g={a:h,b:d},S={};return H.runKernelFunc(f,g,null,Km,S)}const ze=G({div_:IJ});function xJ(r,l){let h=M(r,"a","mul"),d=M(l,"b","mul");[h,d]=mt(h,d);const f=(S,L)=>{const x=S.multiply(h,d);return L([h,d]),x},g={a:h,b:d};return H.runKernelFunc(f,g,null,lf)}const ae=G({mul_:xJ});function TJ(r){const l=M(r,"x","abs"),h={x:l};return H.runKernelFunc((d,f)=>(f([l]),l.dtype==="complex64"?d.complexAbs(l):d.abs(l)),h,null,Bm)}const Pn=G({abs_:TJ});function AJ(r,l){for(let h=0;h<r.length;++h)if(r[r.length-h-1]!==l-1-h)return!1;return!0}function vJ(r,l,h){const d=r.length+l.length,f=[];let g=0,S=0;for(let L=0;L<d;L++)h.indexOf(L)===-1?f.push(r[g++]):f.push(l[S++]);return f}function fO(r,l){const h=[],d=r.length;for(let g=0;g<d;g++)l.indexOf(g)===-1&&h.push(r[g]);const f=l.map(g=>r[g]);return[h,f]}function ts(r,l){const h=l.map(d=>1);return vJ(r,h,l)}function fs(r,l){if(AJ(r,l))return null;const h=[];for(let d=0;d<l;++d)r.indexOf(d)===-1&&h.push(d);return r.forEach(d=>h.push(d)),h}function Mc(r){return r.map((l,h)=>[h,l]).sort((l,h)=>l[1]-h[1]).map(l=>l[0])}function oo(r,l){const h=[];for(let d=l-r;d<l;++d)h.push(d);return h}function Yf(r,l,h,d,f,g,S="channelsLast"){const[L,x]=Hf(l);let A;if(S==="channelsLast")A=[L,x,r[3],r[3]];else if(S==="channelsFirst")A=[L,x,r[1],r[1]];else throw new Error(`Unknown dataFormat ${S}`);return Lr(r,A,h,d,f,g,!1,S)}function qf(r,l,h,d,f,g,S="NDHWC"){const[L,x,A]=TI(l);let O,C;if(S==="NDHWC")C="channelsLast",O=[L,x,A,r[4],r[4]];else if(S==="NCDHW")C="channelsFirst",O=[L,x,A,r[1],r[1]];else throw new Error(`Unknown dataFormat ${S}`);return ku(r,O,h,d,f,!1,C,g)}function Lr(r,l,h,d,f,g,S=!1,L="channelsLast"){let[x,A,O,C]=[-1,-1,-1,-1];if(L==="channelsLast")[x,A,O,C]=r;else if(L==="channelsFirst")[x,C,A,O]=r;else throw new Error(`Unknown dataFormat ${L}`);const[$,z,,ne]=l,[te,se]=Hf(h),[fe,de]=Hf(d),Ae=Pc($,fe),xe=Pc(z,de),{padInfo:Me,outHeight:Ke,outWidth:wt}=NJ(f,A,O,te,se,Ae,xe,g,L),$t=S?ne*C:ne;let Kt;return L==="channelsFirst"?Kt=[x,$t,Ke,wt]:L==="channelsLast"&&(Kt=[x,Ke,wt,$t]),{batchSize:x,dataFormat:L,inHeight:A,inWidth:O,inChannels:C,outHeight:Ke,outWidth:wt,outChannels:$t,padInfo:Me,strideHeight:te,strideWidth:se,filterHeight:$,filterWidth:z,effectiveFilterHeight:Ae,effectiveFilterWidth:xe,dilationHeight:fe,dilationWidth:de,inShape:r,outShape:Kt,filterShape:l}}function ku(r,l,h,d,f,g=!1,S="channelsLast",L){let[x,A,O,C,$]=[-1,-1,-1,-1,-1];if(S==="channelsLast")[x,A,O,C,$]=r;else if(S==="channelsFirst")[x,$,A,O,C]=r;else throw new Error(`Unknown dataFormat ${S}`);const[z,ne,te,,se]=l,[fe,de,Ae]=TI(h),[xe,Me,Ke]=TI(d),wt=Pc(z,xe),$t=Pc(ne,Me),Kt=Pc(te,Ke),{padInfo:Fn,outDepth:vn,outHeight:Nn,outWidth:Qs}=CJ(f,A,O,C,fe,de,Ae,wt,$t,Kt,L),Ai=g?se*$:se;let ei;return S==="channelsFirst"?ei=[x,Ai,vn,Nn,Qs]:S==="channelsLast"&&(ei=[x,vn,Nn,Qs,Ai]),{batchSize:x,dataFormat:S,inDepth:A,inHeight:O,inWidth:C,inChannels:$,outDepth:vn,outHeight:Nn,outWidth:Qs,outChannels:Ai,padInfo:Fn,strideDepth:fe,strideHeight:de,strideWidth:Ae,filterDepth:z,filterHeight:ne,filterWidth:te,effectiveFilterDepth:wt,effectiveFilterHeight:$t,effectiveFilterWidth:Kt,dilationDepth:xe,dilationHeight:Me,dilationWidth:Ke,inShape:r,outShape:ei,filterShape:l}}function RJ(r,l,h,d,f){d==null&&(d=gO(r,l,h));const g=r[0],S=r[1],L=ca((g-l+2*d)/h+1,f);Z(Qt(L),()=>`The output # of rows (${L}) must be an integer. Change the stride and/or zero pad parameters`);const x=ca((S-l+2*d)/h+1,f);return Z(Qt(x),()=>`The output # of columns (${x}) must be an integer. Change the stride and/or zero pad parameters`),[L,x]}function OJ(r,l,h,d,f,g){f==null&&(f=gO(r,l,d));const S=r[0],L=r[1],x=r[2],A=ca((S-l+2*f)/d+1,g);Z(Qt(A),()=>`The output # of depths (${A}) must be an integer. Change the stride and/or zero pad parameters`);const O=ca((L-l+2*f)/d+1,g);Z(Qt(O),()=>`The output # of rows (${O}) must be an integer. Change the stride and/or zero pad parameters`);const C=ca((x-l+2*f)/d+1,g);return Z(Qt(C),()=>`The output # of columns (${C}) must be an integer. Change the stride and/or zero pad parameters`),[A,O,C,h]}function gO(r,l,h,d=1){const f=Pc(l,d);return Math.floor((r[0]*(h-1)-h+f)/2)}function Hf(r){return typeof r=="number"?[r,r,r]:r.length===2?[r[0],r[1],1]:r}function TI(r){return typeof r=="number"?[r,r,r]:r}function Pc(r,l){return l<=1?r:r+(r-1)*(l-1)}function NJ(r,l,h,d,f,g,S,L,x){let A,O,C;if(typeof r=="number"){const $=r===0?"VALID":"NUMBER";A={top:r,bottom:r,left:r,right:r,type:$};const z=RJ([l,h],g,d,r,L);O=z[0],C=z[1]}else if(r==="same"){O=Math.ceil(l/d),C=Math.ceil(h/f);const $=Math.max(0,(O-1)*d+g-l),z=Math.max(0,(C-1)*f+S-h),ne=Math.floor($/2),te=$-ne,se=Math.floor(z/2),fe=z-se;A={top:ne,bottom:te,left:se,right:fe,type:"SAME"}}else if(r==="valid")A={top:0,bottom:0,left:0,right:0,type:"VALID"},O=Math.ceil((l-g+1)/d),C=Math.ceil((h-S+1)/f);else if(typeof r=="object"){const $=x==="channelsLast"?r[1][0]:r[2][0],z=x==="channelsLast"?r[1][1]:r[2][1],ne=x==="channelsLast"?r[2][0]:r[3][0],te=x==="channelsLast"?r[2][1]:r[3][1],se=$===0&&z===0&&ne===0&&te===0?"VALID":"EXPLICIT";A={top:$,bottom:z,left:ne,right:te,type:se},O=ca((l-g+$+z)/d+1,L),C=ca((h-S+ne+te)/f+1,L)}else throw Error(`Unknown padding parameter: ${r}`);return{padInfo:A,outHeight:O,outWidth:C}}function CJ(r,l,h,d,f,g,S,L,x,A,O){let C,$,z,ne;if(typeof r=="number"){const te=r===0?"VALID":"NUMBER";C={top:r,bottom:r,left:r,right:r,front:r,back:r,type:te};const se=OJ([l,h,d,1],L,1,f,r,O);$=se[0],z=se[1],ne=se[2]}else if(r==="same"){$=Math.ceil(l/f),z=Math.ceil(h/g),ne=Math.ceil(d/S);const te=($-1)*f+L-l,se=(z-1)*g+x-h,fe=(ne-1)*S+A-d,de=Math.floor(te/2),Ae=te-de,xe=Math.floor(se/2),Me=se-xe,Ke=Math.floor(fe/2),wt=fe-Ke;C={top:xe,bottom:Me,left:Ke,right:wt,front:de,back:Ae,type:"SAME"}}else if(r==="valid")C={top:0,bottom:0,left:0,right:0,front:0,back:0,type:"VALID"},$=Math.ceil((l-L+1)/f),z=Math.ceil((h-x+1)/g),ne=Math.ceil((d-A+1)/S);else throw Error(`Unknown padding parameter: ${r}`);return{padInfo:C,outDepth:$,outHeight:z,outWidth:ne}}function ca(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 ao(r){const[l,h,d]=Hf(r);return l===1&&h===1&&d===1}function co(r,l){return ao(r)||ao(l)}function zc(r){if(r==="NHWC")return"channelsLast";if(r==="NCHW")return"channelsFirst";throw new Error(`Unknown dataFormat ${r}`)}function yO(r,l){const h=r[0].length;r.forEach((f,g)=>{Z(f.length===h,()=>`Error in concat${h}D: rank of tensors[${g}] must be the same as the rank of the rest (${h})`)}),Z(l>=0&&l<h,()=>`Error in concat${h}D: axis must be between 0 and ${h-1}.`);const d=r[0];r.forEach((f,g)=>{for(let S=0;S<h;S++)Z(S===l||f[S]===d[S],()=>`Error in concat${h}D: Shape of tensors[${g}] (${f}) does not match the shape of the rest (${d}) along the non-concatenated axis ${g}.`)})}function bO(r,l){const h=r[0].slice();for(let d=1;d<r.length;d++)h[l]+=r[d][l];return h}function EJ(r,l=0){Z(r.length>=1,()=>"Pass at least one tensor to concat");let h=Gf(r,"tensors","concat");h[0].dtype==="complex64"&&h.forEach(S=>{if(S.dtype!=="complex64")throw new Error(`Cannot concatenate complex64 tensors with a tensor
with dtype ${S.dtype}. `)});const d=(S,L)=>{const x=ht(l,h[0].shape)[0],A=bO(h.map($=>$.shape),x);if(qt(A)===0)return wI([],A);if(h=h.filter($=>$.size>0),h.length===1)return h[0];const O=h.map($=>$.shape);yO(O,x);const C=S.concat(h,x);return L(h),C},f=h,g={axis:l};return H.runKernelFunc(d,f,null,Gm,g)}const bn=G({concat_:EJ});function DJ(r){const l=M(r,"x","sigmoid"),h={x:l};return H.runKernelFunc((d,f)=>{const g=d.sigmoid(l);return f([g]),g},h,null,xf)}const AI=G({sigmoid_:DJ});function kJ(r,l,h){const d=M(r,"x","slice");if(d.rank===0)throw new Error("Slicing scalar is not possible");const f=(L,x)=>{const[A,O]=Vf(d,l,h);return dO(d,A,O),x([d]),L.slice(d,A,O)},g={x:d},S={begin:l,size:h};return H.runKernelFunc(f,g,null,Lf,S)}const At=G({slice_:kJ});function FJ(r,l,h){const d=M(r,"x","batchToSpaceND"),f=l.reduce((x,A)=>x*A);Z(d.rank>=1+l.length,()=>`input rank is ${d.rank} but should be > than blockShape.length ${l.length}`),Z(h.length===l.length,()=>`crops.length is ${h.length} but should be equal to blockShape.length ${l.length}`),Z(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,h),S={x:d},L={blockShape:l,crops:h};return H.runKernelFunc(g,S,null,Pm,L)}const vI=G({batchToSpaceND_:FJ});function _J(r,l){let h=M(r,"broadcastTo","x");const d=h.shape;if(l.some(O=>!(O>0)||O%1!==0))throw new Error(`broadcastTo(): Invalid broadcast shape [${l}].`);if(l.length<h.rank)throw new Error(`broadcastTo(): shape.length=${l.length} < input.rank=${h.rank}.`);if(l.length>h.rank){const O=h.shape.slice();for(;O.length<l.length;)O.unshift(1);h=re(h,O)}const f=h.shape,g=Array.from(l);for(let O=l.length-1;O>=0;O--)if(f[O]===l[O])g[O]=1;else if(h.shape[O]!==1)throw new Error(`broadcastTo(): [${d}] cannot be broadcast to [${l}].`);const S=g.map((O,C)=>O>1?C:-1).filter(O=>O>=0);if(S.length===0)return bi(h);const L=O=>O.tile(h,g),x={x:h},A={shape:l,inputShape:f};return H.runKernelFunc(L,x,null,zm,A)}const jf=G({broadcastTo_:_J});function WJ(r,l,h,d,f="NHWC",g=[1,1],S){const L=M(r,"x","conv2d"),x=M(l,"filter","conv2d");let A=L,O=!1;L.rank===3&&(O=!0,A=re(L,[1,L.shape[0],L.shape[1],L.shape[2]])),Z(A.rank===4,()=>`Error in conv2d: input must be rank 4, but got rank ${A.rank}.`),Z(x.rank===4,()=>`Error in conv2d: filter must be rank 4, but got rank ${x.rank}.`),S!=null&&Z(Qt(d),()=>`Error in conv2d: pad must be an integer when using, dimRoundingMode ${S} but got pad ${d}.`);const C=f==="NHWC"?A.shape[3]:A.shape[1];Z(C===x.shape[2],()=>`Error in conv2d: depth of input (${C}) must match input depth for filter ${x.shape[2]}.`),Z(co(h,g),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${h} and dilations '${g}'`);const $=(se,fe)=>{const de=zc(f),Ae=Lr(A.shape,x.shape,h,g,d,S,!1,de),xe=se.conv2d(A,x,Ae);return fe([A,x]),xe},z={x:A,filter:x},ne={strides:h,pad:d,dataFormat:f,dilations:g,dimRoundingMode:S},te=H.runKernelFunc($,z,null,Vm,ne);return O?re(te,[te.shape[1],te.shape[2],te.shape[3]]):te}const NI=G({conv2d_:WJ});function $J(r,l,h,d,f,g="NHWC",S){Z(r.length===l.rank,()=>`Length of inShape (${r.length}) and rank of dy (${l.rank}) must match`);let L=r,x=l,A=!1;l.rank===3&&(A=!0,x=re(l,[1,l.shape[0],l.shape[1],l.shape[2]]),L=[1,r[0],r[1],r[2]]),Z(L.length===4,()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${L.length}.`),Z(x.rank===4,()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${x.rank}`),Z(h.rank===4,()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${h.rank}`);const O=g==="NHWC"?L[3]:L[1],C=g==="NHWC"?x.shape[3]:x.shape[1];Z(O===h.shape[2],()=>`Error in conv2dDerInput: depth of input (${O}) must match input depth for filter ${h.shape[2]}.`),Z(C===h.shape[3],()=>`Error in conv2dDerInput: depth of output (${C}) must match output depth for filter ${h.shape[3]}.`),S!=null&&Z(Qt(f),()=>`Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode ${S} but got pad ${f}.`);const $=(se,fe)=>{const de=1,Ae=zc(g),xe=Lr(L,h.shape,d,de,f,S,!1,Ae),Me=se.conv2dDerInput(x,h,xe);return fe([x,h]),Me},z={dy:x,filter:h},ne={strides:d,pad:f,dataFormat:g,dimRoundingMode:S,inputShape:L},te=H.runKernelFunc($,z,null,Hm,ne);return A?re(te,[te.shape[1],te.shape[2],te.shape[3]]):te}const wO=G({conv2DBackpropInput_:$J});function UJ(r,l,h,d,f){Z(r.length===l.rank,()=>`Length of inShape (${r.length}) and rank of dy (${l.rank}) must match`);let g=r,S=l,L=!1;l.rank===4&&(L=!0,S=re(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],A=S.shape[4];Z(g.length===5,()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${g.length}.`),Z(S.rank===5,()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${S.rank}`),Z(h.rank===5,()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${h.rank}`),Z(x===h.shape[3],()=>`Error in conv3dDerInput: depth of input (${x}) must match input depth for filter ${h.shape[3]}.`),Z(A===h.shape[4],()=>`Error in conv3dDerInput: depth of output (${A}) must match output depth for filter ${h.shape[4]}.`);const O=ne=>{const te=1,se=ku(g,h.shape,d,te,f);return ne.conv3dDerInput(S,h,se)},C={dy:S},$={pad:f},z=H.runKernelFunc(O,C,null,_2,$);return L?re(z,[z.shape[1],z.shape[2],z.shape[3],z.shape[4]]):z}const LO=G({conv3DBackpropInput_:UJ});function BJ(r){const l=M(r,"x","cos"),h={x:l};return H.runKernelFunc((d,f)=>{const g=d.cos(l);return f([l]),g},h,null,Ym)}const Fu=G({cos_:BJ});function MJ(r){const l=M(r,"x","cosh"),h={x:l};return H.runKernelFunc((d,f)=>{const g=d.cosh(l);return f([l]),g},h,null,qm)}const CI=G({cosh_:MJ});function PJ(r,l=0,h=!1,d=!1){const f=M(r,"x","cumsum"),g=(x,A)=>{const O=fs([l],f.rank);let C=f;O!=null&&(C=Wt(f,O));const $=oo(1,f.rank)[0];let z=x.cumsum(C,$,h,d);if(A([f]),O!=null){const ne=Mc(O);z=Wt(z,ne)}return z},S={x:f},L={axis:l,exclusive:h,reverse:d};return H.runKernelFunc(g,S,null,jm,L)}const RI=G({cumsum_:PJ});function vt(r,l){const h=[];for(let d=0;d<l.length;d++){const f=r[r.length-d-1],g=l.length-d-1,S=l[g];(f==null||f===1&&S>1)&&h.unshift(g)}return h}function rt(r,l){const h=[],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 S=l[l.length-f-1];if(S==null&&(S=1),g===1)h.unshift(S);else if(S===1)h.unshift(g);else if(g!==S){const L=`Operands could not be broadcast together with shapes ${r} and ${l}.`;throw Error(L)}else h.unshift(g)}return h}function zJ(r,l){let h=M(r,"a","equal"),d=M(l,"b","equal");[h,d]=mt(h,d),rt(h.shape,d.shape);const f=S=>S.equal(h,d),g={a:h,b:d};return H.runKernelFunc(f,g,null,Y2)}const OI=G({equal_:zJ});function GJ(r,l,h){const d=M(l,"a","where"),f=M(h,"b","where"),g=M(r,"condition","where","bool"),S=rt(d.shape,f.shape),L=jf(d,S),x=jf(f,S);g.rank===1&&Z(g.shape[0]===d.shape[0],()=>"The first dimension of `a` must match the size of `condition`."),g.rank!==1&&Zt(g.shape,x.shape,"Error in where: ");const A=(C,$)=>{const z=C.select(g,L,x);return $([g]),z},O={condition:g,t:L,e:x};return H.runKernelFunc(A,O,null,wf)}const zn=G({where_:GJ});function VJ(r){const l=M(r,"x","zerosLike"),h={x:l};return H.runKernelFunc(d=>d.zerosLike(l),h,null,Ff)}const je=G({zerosLike_:VJ});function HJ(r){const l=M(r,"x","exp"),h={x:l};return H.runKernelFunc((d,f)=>{const g=d.exp(l);return f([g]),g},h,null,Xm)}const Gn=G({exp_:HJ});function YJ(r,l=0){const h=null,d=M(r,"x","expandDims",h);Z(l<=d.rank,()=>"Axis must be <= rank of the tensor");const f=d.shape.slice();return l<0&&(Z(-(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),re(d,f)}const ks=G({expandDims_:YJ});function qJ(r,l){const h=null,d=M(r,"x","tile",h);Z(d.rank===l.length,()=>`Error in transpose: rank of input ${d.rank} must match length of reps ${l}.`);const f=(x,A)=>{const O=x.tile(d,l);return A([d]),O},g=[d],S={x:d},L={reps:l};return H.runKernelFunc(f,S,null,Of,L,g)}const la=G({tile_:qJ});function jJ(r,l,h,d="float32"){l==null&&(l=r);const f=Du([r,l],d),g=r<=l?r:l;for(let L=0;L<g;++L)f.set(1,L,L);const S=re(f.toTensor(),[r,l]);if(h==null)return S;if(h.length===1)return la(ks(S,0),[h[0],1,1]);if(h.length===2)return la(ks(ks(S,0),0),[h[0],h[1],1,1]);if(h.length===3)return la(ks(ks(ks(S,0),0),0),[h[0],h[1],h[2],1,1]);throw new Error(`eye() currently supports only 1D and 2D batchShapes, but received ${h.length}D.`)}const EI=G({eye_:jJ});function DI(r,l,h){const d={shape:r,value:l,dtype:h};return H.runKernelFunc(f=>f.fill(r,l,h),{},null,K2,d)}function KJ(r){const l=M(r,"x","floor"),h={x:l};return H.runKernelFunc(d=>d.floor(l),h,null,Jm)}const kI=G({floor_:KJ});function SO(r,l,h){const d=r.shape[h],f=[];let g=1,S=1;for(let L=0;L<h;L++)f.push(r.shape[L]),g*=r.shape[L];for(let L=0;L<l.rank;L++)f.push(l.shape[L]);for(let L=h+1;L<r.rank;L++)f.push(r.shape[L]),S*=r.shape[L];return{batchSize:g,sliceSize:S,dimSize:d,outputShape:f}}function XJ(r,l,h=0){const d=M(r,"x","gather"),f=M(l,"indices","gather","int32"),g={x:d,indices:f},S={axis:h},L=(x,A)=>{const O=ht(h,d.shape)[0],C=SO(d,f,O),$=x.gather(d,re(f,[f.size]),O);return A([d,f]),re($,C.outputShape)};return H.runKernelFunc(L,g,null,Qm,S)}const FI=G({gather_:XJ});function JJ(r,l){let h=M(r,"a","greater"),d=M(l,"b","greater");[h,d]=mt(h,d),rt(h.shape,d.shape);const f=S=>S.greater(h,d),g={a:h,b:d};return H.runKernelFunc(f,g,null,Z2)}const wi=G({greater_:JJ});function ZJ(r,l){let h=M(r,"a","greaterEqual"),d=M(l,"b","greaterEqual");[h,d]=mt(h,d),rt(h.shape,d.shape);const f=(S,L)=>{const x=S.greaterEqual(h,d);return L([h,d]),x},g={a:h,b:d};return H.runKernelFunc(f,g,null,ef)}const Sr=G({greaterEqual_:ZJ});function QJ(r){const l=M(r,"input","imag"),h=f=>f.imag(l),d={input:l};return H.runKernelFunc(h,d,null,eR)}const _u=G({imag_:QJ});function e9(r,l){let h=M(r,"a","maximum"),d=M(l,"b","maximum");[h,d]=mt(h,d),h.dtype==="bool"&&(h=Le(h,"int32"),d=Le(d,"int32")),rt(h.shape,d.shape);const f=(S,L)=>{const x=S.maximum(h,d);return L([h,d]),x},g={a:h,b:d};return H.runKernelFunc(f,g,null,of)}const _I=G({maximum_:e9});function ke(r,l){if((Ds(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"&&Ds(r)&&!(r instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");const h=[],d=[];return ji(r,h,d,l)}function t9(r,l){let h=M(r,"a","less"),d=M(l,"b","less");[h,d]=mt(h,d),rt(h.shape,d.shape);const f=S=>S.less(h,d),g={a:h,b:d};return H.runKernelFunc(f,g,null,iR)}const WI=G({less_:t9});function n9(r,l){let h=M(r,"a","lessEqual"),d=M(l,"b","lessEqual");[h,d]=mt(h,d),rt(h.shape,d.shape);const f=(S,L)=>{const x=S.lessEqual(h,d);return L([h,d]),x},g={a:h,b:d};return H.runKernelFunc(f,g,null,rR)}const Ir=G({lessEqual_:n9});function s9(r){const l=M(r,"x","log"),h={x:l};return H.runKernelFunc((d,f)=>{const g=d.log(l);return f([l]),g},h,null,nf)}const lo=G({log_:s9});function i9(r){const l=M(r,"x","log1p"),h={x:l};return H.runKernelFunc((d,f)=>{const g=d.log1p(l);return f([l]),g},h,null,sf)}const $I=G({log1p_:i9});function Kf(r){return H.customGrad(r)}function r9(r){const l=M(r,"x","neg"),h={x:l};return H.runKernelFunc(d=>d.neg(l),h,null,hf)}const yt=G({neg_:r9});function o9(r,l=null,h=!1){const d=M(r,"x","max"),f=(L,x)=>{const A=ht(l,d.shape);let O=A;const C=fs(O,d.rank);let $=d;C!=null&&($=Wt(d,C),O=oo(O.length,$.rank));const z=L.max($,O);C!=null&&$.dispose();let ne=z;if(h){const te=ts(ne.shape,ht(l,d.shape));ne=re(ne,te),z.dispose()}return x([d,ne]),ne},g={x:d},S={reductionIndices:l,keepDims:h};return H.runKernelFunc(f,g,null,rf,S)}const ha=G({max_:o9});function a9(r,l){let h=M(r,"a","sub"),d=M(l,"b","sub");[h,d]=mt(h,d);const f=(S,L)=>{const x=S.subtract(h,d);return L([h,d]),x},g={a:h,b:d};return H.runKernelFunc(f,g,null,Rf)}const Be=G({sub_:a9});function c9(r,l=null,h=!1){let d=M(r,"x","sum");d.dtype==="bool"&&(d=Le(d,"int32"));const f=(L,x)=>{x([d]);const A=ht(l,d.shape),O=fs(A,d.rank);let C=A,$=d;O!=null&&($=Wt(d,O),C=oo(C.length,d.rank));let z=L.sum($,C);if(h){const ne=ts(z.shape,A);z=re(z,ne)}return z},g={x:d},S={axis:l,keepDims:h};return H.runKernelFunc(f,g,null,Af,S)}const Fe=G({sum_:c9});function l9(r,l=null,h=!1){const d=M(r,"x","logSumExp"),f=ht(l,d.shape),g=ha(d,f,!0),S=Be(d,g),L=Gn(S),x=Fe(L,f),A=lo(x),O=St(re(g,A.shape),A);if(h){const C=ts(O.shape,f);return re(O,C)}return O}const UI=G({logSumExp_:l9});function h9(r,l){const h=M(r,"a","logicalAnd","bool"),d=M(l,"b","logicalAnd","bool");rt(h.shape,d.shape);const f={a:h,b:d};return H.runKernelFunc(g=>g.logicalAnd(h,d),f,null,oR)}const ua=G({logicalAnd_:h9});function u9(r){const l=M(r,"x","logicalNot","bool"),h={x:l};return H.runKernelFunc(d=>d.logicalNot(l),h,null,aR)}const BI=G({logicalNot_:u9});function Fs(r,l="float32"){if(l==="complex64"){const d=Fs(r,"float32"),f=Fs(r,"float32");return qi(d,f)}const h=aa(qt(r),l);return H.makeTensor(h,r,l)}function Ki(r,l="float32"){if(l==="complex64"){const d=Ki(r,"float32"),f=Fs(r,"float32");return qi(d,f)}const h=Uf(qt(r),l);return H.makeTensor(h,r,l)}function d9(r,l=null,h=!1){const d=M(r,"x","mean"),f=ht(l,d.shape),g=fO(d.shape,f),S=g[1],L=qt(S),x=Kf(A=>{const O=ke(L),C=O.dtype===A.dtype?A:Le(A,O.dtype),$=ze(C,O),z=Fe($,l,h),ne=te=>{const se=A.shape.slice();f.forEach(Ae=>{se[Ae]=1});const fe=re(te,se),de=ze(ae(fe,Ki(A.shape,"float32")),L);return de};return{value:z,gradFunc:ne}});return x(d)}const MI=G({mean_:d9});function p9(r,l=null,h=!1){const d=M(r,"x","min"),f=(L,x)=>{const A=ht(l,d.shape);let O=A;const C=fs(O,d.rank);let $=d;C!=null&&($=Wt(d,C),O=oo(O.length,d.rank));const z=L.min($,O);C!=null&&$.dispose();let ne=z;if(h){const te=ts(ne.shape,A);ne=re(z,te),z.dispose()}return x([d,ne]),ne},g={x:d},S={axis:l,keepDims:h};return H.runKernelFunc(f,g,null,af,S)}const Xf=G({min_:p9});function m9(r,l){let h=M(r,"a","minimum"),d=M(l,"b","minimum");[h,d]=mt(h,d),h.dtype==="bool"&&(h=Le(h,"int32"),d=Le(d,"int32")),rt(h.shape,d.shape);const f=(S,L)=>{const x=S.minimum(h,d);return L([h,d]),x},g={a:h,b:d};return H.runKernelFunc(f,g,null,cf)}const PI=G({minimum_:m9});function f9(r){const l=M(r,"x","square"),h={},d=[l],f=[];return H.runKernelFunc((g,S)=>(S([l]),g.square(l)),{x:l},null,"Square",h,d,f)}const ut=G({square_:f9});function g9(r,l){let h=M(r,"a","notEqual"),d=M(l,"b","notEqual");[h,d]=mt(h,d),rt(h.shape,d.shape);const f=S=>S.notEqual(h,d),g={a:h,b:d};return H.runKernelFunc(f,g,null,gR)}const zI=G({notEqual_:g9});function y9(r){const l=M(r,"input","real"),h=f=>f.real(l),d={input:l};return H.runKernelFunc(h,d,null,TR)}const Gc=G({real_:y9});function b9(r,l,h=0){const d=M(r,"x","pad");if(d.rank===0)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");const f=(L,x)=>(x([d]),L.pad(d,l,h)),g={paddings:l,constantValue:h},S={x:d};return H.runKernelFunc(f,S,null,uf,g)}const GI=G({pad_:b9});function w9(r,l,h){const d=M(r,"x","spaceToBatchND");Z(d.rank>=1+l.length,()=>`input rank ${d.rank} should be > than [blockShape] ${l.length}`),Z(h.length===l.length,()=>`paddings.shape[0] ${h.length} must be equal to [blockShape] ${l.length}`),Z(d.shape.reduce((L,x,A)=>A>0&&A<=l.length?L&&(x+h[A-1][0]+h[A-1][1])%l[A-1]===0:L,!0),()=>`input spatial dimensions ${d.shape.slice(1)} with paddings ${h.toString()} must be divisible by blockShapes ${l.toString()}`);const f=L=>L.spaceToBatchND(d,l,h),g={x:d},S={blockShape:l,paddings:h};return H.runKernelFunc(f,g,null,vf,S)}const VI=G({spaceToBatchND_:w9});function L9(r,l){let h=M(r,"base","pow"),d=M(l,"exp","pow");[h,d]=mt(h,d);const f={a:h,b:d},g=(S,L)=>{const x=S.pow(h,d);return L([h,d,x]),x};return H.runKernelFunc(g,f,null,df)}const da=G({pow_:L9});function ho(r,l){_c(r);const h=wr(r,l);if(h.length!==1)throw new Error("tensor1d() requires values to be a flat/TypedArray");const d=null;return ji(r,d,h,l)}function Jf(r,l,h=1,d="float32"){if(h===0)throw new Error("Cannot have a step of zero");const f=()=>{const S=r===l,L=r<l&&h<0,x=l<r&&h>1;if(S||L||x)return Fs([0],d);const A=Math.abs(Math.ceil((l-r)/h)),O=aa(A,d);l<r&&h===1&&(h=-1),O[0]=r;for(let C=1;C<O.length;C++)O[C]=O[C-1]+h;return ho(O,d)},g={start:r,stop:l,step:h,dtype:d};return H.runKernelFunc(f,{},null,xR,g)}function S9(r){const l=M(r,"x","relu"),h=(f,g)=>(g([l]),l.dtype==="bool"?Le(l,"int32"):f.relu(l)),d={x:l};return H.runKernelFunc(h,d,null,pf)}const Wu=G({relu_:S9});function I9(r,l){const h=M(r,"x","reverse"),d=S=>{const L=ht(l,h.shape);if(h.rank===0)return bi(h);const x=S.reverse(h,L);return re(x,h.shape)},f={x:h},g={dims:l};return H.runKernelFunc(d,f,null,yf,g)}const Vc=G({reverse_:I9});function x9(r){const l=M(r,"x","rsqrt"),h={x:l};return H.runKernelFunc((d,f)=>{const g=d.rsqrt(l);return f([l]),g},h,null,bf)}const HI=G({rsqrt_:x9});function T9(r){const l=M(r,"x","sin"),h={x:l};return H.runKernelFunc((d,f)=>{const g=d.sin(l);return f([l]),g},h,null,Sf)}const YI=G({sin_:T9});function A9(r){const l=M(r,"x","sinh"),h={x:l};return H.runKernelFunc((d,f)=>{const g=d.sinh(l);return f([l]),g},h,null,If)}const qI=G({sinh_:A9});function v9(r){Z(r.dtype==="complex64",()=>`The dtype for tf.spectral.fft() must be complex64 but got ${r.dtype}.`);const l={input:r};return H.runKernelFunc(h=>{const d=r.shape[r.shape.length-1],f=r.size/d,g=r.as2D(f,d),S=h.fft(g);return S.reshape(r.shape)},l,null,j2)}const $u=G({fft_:v9});function N9(r){Z(r.dtype==="complex64",()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${r.dtype}.`);const l={input:r};return H.runKernelFunc(h=>{const d=r.shape[r.shape.length-1],f=r.size/d,g=re(r,[f,d]),S=h.ifft(g);return re(S,r.shape)},l,null,Q2)}const Hc=G({ifft_:N9});function C9(r){const l=r.shape[r.shape.length-1],h=r.size/l;let d;if(l<=2){const f=re(r,[h,l]);d=Hc(f)}else{const f=[h,2*(l-1)],g=re(Gc(r),[h,l]),S=re(_u(r),[h,l]),L=Vc(At(g,[0,1],[h,l-2]),1),x=ae(Vc(At(S,[0,1],[h,l-2]),1),ke(-1)),A=bn([g,L],1),O=bn([S,x],1),C=re(qi(A,O),[f[0],f[1]]);d=Hc(C)}if(d=Gc(d),r.rank===3&&r.shape[0]!==0){const f=d,g=r.shape[0];d=re(d,[g,d.shape[0]/g,d.shape[1]]),f.dispose()}return d}const jI=G({irfft_:C9});function IO(r,l,h=0){let d=[];if(typeof l=="number")Z(r.shape[h]%l===0,()=>"Number of splits must evenly divide the axis."),d=new Array(l).fill(r.shape[h]/l);else{const f=l.reduce((S,L)=>(L===-1&&(S+=1),S),0);Z(f<=1,()=>"There should be only one negative value in split array.");const g=l.indexOf(-1);if(g!==-1){const S=l.reduce((L,x)=>x>0?L+x:L);l[g]=r.shape[h]-S}Z(r.shape[h]===l.reduce((S,L)=>S+L),()=>"The sum of sizes must match the size of the axis dimension."),d=l}return d}function R9(r,l,h=0){const d=M(r,"x","split"),f=(L,x)=>{const A=ht(h,d.shape)[0],O=IO(d,l,A);return L.split(d,O,A)},g={x:d},S={numOrSizeSplits:l,axis:h};return H.runKernelFunc(f,g,null,Nf,S)}const uo=G({split_:R9});function O9(r,l){Z(r.dtype==="float32",()=>`The dtype for rfft() must be real value but got ${r.dtype}`);let h=r.shape[r.shape.length-1];const d=r.size/h;let f;if(l!=null&&l<h){const ne=r.shape.map(se=>0),te=r.shape.map(se=>se);te[r.shape.length-1]=l,f=At(r,ne,te),h=l}else if(l!=null&&l>h){const ne=r.shape.map(te=>te);ne[r.shape.length-1]=l-h,f=bn([r,Fs(ne)],r.shape.length-1),h=l}else f=r;const g=je(f),S=re(qi(f,g),[d,h]),L=$u(S),x=Math.floor(h/2)+1,A=Gc(L),O=_u(L),C=uo(A,[x,h-x],A.shape.length-1),$=uo(O,[x,h-x],O.shape.length-1),z=f.shape.slice();return z[f.shape.length-1]=x,re(qi(C[0],$[0]),z)}const Uu=G({rfft_:O9});function E9(r){const l=M(r,"x","sqrt"),h={x:l};return H.runKernelFunc((d,f)=>{const g=d.sqrt(l);return f([l]),g},h,null,Tf)}const gs=G({sqrt_:E9});function D9(r,l){let h=M(r,"a","squaredDifference"),d=M(l,"b","squaredDifference");[h,d]=mt(h,d),rt(h.shape,d.shape);const f=(L,x)=>{const A=L.squaredDifference(h,d);return x([h,d]),A},g={a:h,b:d},S={};return H.runKernelFunc(f,g,null,Cf,S)}const KI=G({squaredDifference_:D9});function k9(r,l){const h=M(r,"x","squeeze");return re(h,PR(h.shape,l).newShape)}const XI=G({squeeze_:k9});function F9(r,l=0){const h=Gf(r,"tensors","stack");if(Z(h.length>=1,()=>"Pass at least one tensor to tf.stack"),h.length===1)return ks(h[0],l);const d=h[0].rank,f=h[0].shape,g=h[0].dtype;Z(l<=d,()=>"Axis must be <= rank of the tensor"),h.forEach(L=>{Zt(f,L.shape,"All tensors passed to stack must have matching shapes"),Z(g===L.dtype,()=>"All tensors passed to stack must have matching dtypes")});const S=h.map(L=>ks(L,l));return bn(S,l)}const js=G({stack_:F9});function _9(r,l=0){const h=M(r,"x","step"),d={x:h},f={alpha:l};return H.runKernelFunc(g=>g.step(h,l),d,null,_f,f)}const pa=G({step_:_9});function ma(r,l,h){if(_c(r),l!=null&&l.length!==2)throw new Error("tensor2d() requires shape to have two numbers");const d=wr(r,h);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 ji(r,l,d,h)}function W9(r,l,h){const d=M(r,"x","unsortedSegmentSum"),f=M(l,"segmentIds","unsortedSegmentSum","int32");Z(Qt(h),()=>"numSegments must be of dtype int");const g={x:d,segmentIds:f},S={numSegments:h},L=(x,A)=>{const O=x.unsortedSegmentSum(d,f,h);return A([f]),O};return H.runKernelFunc(L,g,null,kf,S)}const JI=G({unsortedSegmentSum_:W9});function $9(r,l=0){const h=M(r,"x","unstack");Z(l>=-h.shape.length&&l<h.shape.length,()=>`Axis = ${l} is not in [-${h.shape.length}, ${h.shape.length})`),l<0&&(l+=h.shape.length);const d={value:h},f={axis:l},g=S=>S.unstack(h,l);return H.runKernelFunc(g,d,null,Df,f)}const Bu=G({unstack_:$9});function U9(r,l="euclidean",h=null,d=!1){r=M(r,"x","norm");const f=xO(r,l,h);let g=f.shape;if(d){const S=ht(h,r.shape);g=ts(f.shape,S)}return re(f,g)}function xO(r,l,h=null){if(r.rank===0)return Pn(r);if(r.rank!==1&&h===null)return xO(re(r,[-1]),l,h);if(r.rank===1||typeof h=="number"||Array.isArray(h)&&h.length===1){if(l===1)return Fe(Pn(r),h);if(l===Infinity)return ha(Pn(r),h);if(l===-Infinity)return Xf(Pn(r),h);if(l==="euclidean"||l===2)return gs(Fe(da(Pn(r),ke(2,"int32")),h));throw new Error(`Error in norm: invalid ord value: ${l}`)}if(Array.isArray(h)&&h.length===2){if(l===1)return ha(Fe(Pn(r),h[0]),h[1]-1);if(l===Infinity)return ha(Fe(Pn(r),h[1]),h[0]);if(l===-Infinity)return Xf(Fe(Pn(r),h[1]),h[0]);if(l==="fro"||l==="euclidean")return gs(Fe(ut(r),h));throw new Error(`Error in norm: invalid ord value: ${l}`)}throw new Error(`Error in norm: invalid axis: ${h}`)}const Zf=G({norm_:U9});function TO(r){return Math.floor(Math.pow(2,Math.ceil(Math.log(r)/Math.log(2))))}function Qf(r,l,h){const d=1-r%2,f=new Float32Array(r);for(let g=0;g<r;++g){const S=2*Math.PI*g/(r+d-1);f[g]=l-h*Math.cos(S)}return ho(f,"float32")}function B9(r,l,h,d,f,g="NHWC",S){let L=r;r.rank===3&&(L=re(r,[1,r.shape[0],r.shape[1],r.shape[2]]));let x=l;x.rank===3&&(x=re(l,[1,l.shape[0],l.shape[1],l.shape[2]])),Z(L.rank===4,()=>`Error in conv2dDerFilter: input must be rank 4, but got shape ${L.shape}.`),Z(x.rank===4,()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${x.shape}.`),Z(h.length===4,()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${h}.`);const A=g==="NHWC"?L.shape[3]:L.shape[1],O=g==="NHWC"?x.shape[3]:x.shape[1];Z(A===h[2],()=>`Error in conv2dDerFilter: depth of input ${A}) must match input depth in filter (${h[2]}.`),Z(O===h[3],()=>`Error in conv2dDerFilter: depth of dy (${O}) must match output depth for filter (${h[3]}).`),S!=null&&Z(Qt(f),()=>`Error in conv2dDerFilter: pad must be an integer when using, dimRoundingMode ${S} but got pad ${f}.`);const C=ne=>{const te=1,se=zc(g),fe=Lr(L.shape,h,d,te,f,S,!1,se);return ne.conv2dDerFilter(L,x,fe)},$={x:L,dy:x},z={strides:d,pad:f,dataFormat:g,dimRoundingMode:S};return H.runKernelFunc(C,$,null,D2,z)}const eg=G({conv2DBackpropFilter_:B9});function M9(r,l,h,d){let f=r;r.rank===3&&(f=re(r,[1,r.shape[0],r.shape[1],r.shape[2]]));let g=l;g.rank===3&&(g=re(l,[1,l.shape[0],l.shape[1],l.shape[2]]));const S=x=>x.depthwiseConv2DDerFilter(f,g,d),L={x:f,dy:g};return H.runKernelFunc(S,L,null,U2)}const AO=G({depthwiseConv2dNativeBackpropFilter_:M9});function P9(r,l,h,d){let f=l,g=!1;l.rank===3&&(g=!0,f=re(l,[1,l.shape[0],l.shape[1],l.shape[2]]));const S=A=>A.depthwiseConv2DDerInput(f,h,d),L={dy:f},x=H.runKernelFunc(S,L,null,B2);return g?re(x,[x.shape[1],x.shape[2],x.shape[3]]):x}const vO=G({depthwiseConv2dNativeBackpropInput_:P9});function z9(r){return Qf(r,.54,.46)}const NO=G({hammingWindow_:z9});function G9(r){return Qf(r,.5,.5)}const tg=G({hannWindow_:G9});function V9(r,l,h,d=!1,f=0){let g=0;const S=[];for(;g+l<=r.size;)S.push(At(r,g,l)),g+=h;if(d)for(;g<r.size;){const L=g+l-r.size,x=bn([At(r,g,l-L),DI([L],f)]);S.push(x),g+=h}return S.length===0?ma([],[0,l]):re(bn(S),[S.length,l])}const ng=G({frame_:V9});function H9(r,l,h,d,f=tg){d==null&&(d=TO(l));const g=ng(r,l,h),S=ae(g,f(l)),L=[];for(let x=0;x<g.shape[0];x++)L.push(Uu(At(S,[x,0],[1,l]),d));return bn(L)}const CO=G({stft_:H9});function Y9(r,l,h,d,f,g){const S=M(r,"image","cropAndResize"),L=M(l,"boxes","cropAndResize","float32"),x=M(h,"boxInd","cropAndResize","int32");f=f||"bilinear",g=g||0;const A=L.shape[0];Z(S.rank===4,()=>`Error in cropAndResize: image must be rank 4,but got rank ${S.rank}.`),Z(L.rank===2&&L.shape[1]===4,()=>`Error in cropAndResize: boxes must be have size [${A},4] but had shape ${L.shape}.`),Z(x.rank===1&&x.shape[0]===A,()=>`Error in cropAndResize: boxInd must be have size [${A}] but had shape ${L.shape}.`),Z(d.length===2,()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${d.length}.`),Z(d[0]>=1&&d[1]>=1,()=>`cropSize must be atleast [1,1], but was ${d}`),Z(f==="bilinear"||f==="nearest",()=>`method must be bilinear or nearest, but was ${f}`);const O=ne=>ne.cropAndResize(S,L,x,d,f,g),C={image:S,boxes:L,boxInd:x},$={method:f,extrapolationValue:g,cropSize:d},z=H.runKernelFunc(O,C,null,W2,$);return z}const RO=G({cropAndResize_:Y9});function q9(r){const l=M(r,"image","flipLeftRight","float32");Z(l.rank===4,()=>`Error in flipLeftRight: image must be rank 4,but got rank ${l.rank}.`);const h={image:l},d=H.runKernel(X2,h,{});return d}const OO=G({flipLeftRight_:q9});function j9(r,l,h=0,d=.5){const f=M(r,"image","rotateWithOffset","float32");Z(f.rank===4,()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${f.rank}.`);const g={image:f},S={radians:l,fillValue:h,center:d},L=H.runKernel($R,g,S);return L}const EO=G({rotateWithOffset_:j9});function Ks(r,l,h,d,f,g){d==null&&(d=.5),f==null&&(f=Number.NEGATIVE_INFINITY),g==null&&(g=0);const S=r.shape[0];return h=Math.min(h,S),Z(0<=d&&d<=1,()=>`iouThreshold must be in [0, 1], but was '${d}'`),Z(r.rank===2,()=>`boxes must be a 2D tensor, but was of rank '${r.rank}'`),Z(r.shape[1]===4,()=>`boxes must have 4 columns, but 2nd dimension was ${r.shape[1]}`),Z(l.rank===1,()=>"scores must be a 1D tensor"),Z(l.shape[0]===S,()=>`scores has incompatible shape with boxes. Expected ${S}, but was ${l.shape[0]}`),Z(0<=g&&g<=1,()=>`softNmsSigma must be in [0, 1], but was '${g}'`),{maxOutputSize:h,iouThreshold:d,scoreThreshold:f,softNmsSigma:g}}function K9(r,l,h,d=.5,f=Number.NEGATIVE_INFINITY){const g=M(r,"boxes","nonMaxSuppression"),S=M(l,"scores","nonMaxSuppression"),L=Ks(g,S,h,d,f);h=L.maxOutputSize,d=L.iouThreshold,f=L.scoreThreshold;const x={maxOutputSize:h,iouThreshold:d,scoreThreshold:f};return H.runKernelFunc(A=>A.nonMaxSuppression(g,S,h,d,f),{boxes:g,scores:S},null,yR,x)}const DO=G({nonMaxSuppression_:K9});function kO(r,l,h){const d=X9(r,l,h),f=d<0?-(d+1):d;r.splice(f,0,l)}function X9(r,l,h){return Z9(r,l,h||J9)}function J9(r,l){return r>l?1:r<l?-1:0}function Z9(r,l,h){let d=0,f=r.length,g=0,S=!1;for(;d<f;){g=d+(f-d>>>1);const L=h(l,r[g]);L>0?d=g+1:(f=g,S=!L)}return S?d:-d-1}function FO(r,l,h,d,f){return ZI(r,l,h,d,f,0).selectedIndices}function _O(r,l,h,d,f,g){return ZI(r,l,h,d,f,0,!1,g,!0)}function WO(r,l,h,d,f,g){return ZI(r,l,h,d,f,g,!0)}function ZI(r,l,h,d,f,g,S=!1,L=!1,x=!1){const A=[];for(let se=0;se<l.length;se++)l[se]>f&&A.push({score:l[se],boxIndex:se,suppressBeginIndex:0});A.sort($O);const O=g>0?-.5/g:0,C=[],$=[];for(;C.length<h&&A.length>0;){const se=A.pop(),{score:fe,boxIndex:de,suppressBeginIndex:Ae}=se;if(fe<f)break;let xe=!1;for(let Me=C.length-1;Me>=Ae;--Me){const Ke=Q9(r,de,C[Me]);if(Ke>=d){xe=!0;break}if(se.score=se.score*eZ(d,O,Ke),se.score<=f)break}se.suppressBeginIndex=C.length,xe||(se.score===fe?(C.push(de),$.push(se.score)):se.score>f&&kO(A,se,$O))}const z=C.length,ne=h-z;L&&ne>0&&(C.push(...new Array(ne).fill(0)),$.push(...new Array(ne).fill(0)));const te={selectedIndices:ho(C,"int32")};return S&&(te.selectedScores=ho($,"float32")),x&&(te.validOutputs=ke(z,"int32")),te}function Q9(r,l,h){const d=r.subarray(l*4,l*4+4),f=r.subarray(h*4,h*4+4),g=Math.min(d[0],d[2]),S=Math.min(d[1],d[3]),L=Math.max(d[0],d[2]),x=Math.max(d[1],d[3]),A=Math.min(f[0],f[2]),O=Math.min(f[1],f[3]),C=Math.max(f[0],f[2]),$=Math.max(f[1],f[3]),z=(L-g)*(x-S),ne=(C-A)*($-O);if(z<=0||ne<=0)return 0;const te=Math.max(g,A),se=Math.max(S,O),fe=Math.min(L,C),de=Math.min(x,$),Ae=Math.max(fe-te,0)*Math.max(de-se,0);return Ae/(z+ne-Ae)}function eZ(r,l,h){const d=Math.exp(l*h*h);return h<=r?d:0}function $O(r,l){return r.score-l.score||r.score===l.score&&l.boxIndex-r.boxIndex}async function tZ(r,l,h,d=.5,f=Number.NEGATIVE_INFINITY){const g=M(r,"boxes","nonMaxSuppressionAsync"),S=M(l,"scores","nonMaxSuppressionAsync"),L=Ks(g,S,h,d,f);h=L.maxOutputSize,d=L.iouThreshold,f=L.scoreThreshold;const x=await Promise.all([g.data(),S.data()]),A=x[0],O=x[1],C=FO(A,O,h,d,f);return g!==r&&g.dispose(),S!==l&&S.dispose(),C}const UO=tZ;function nZ(r,l,h,d=.5,f=Number.NEGATIVE_INFINITY,g=0){const S=M(r,"boxes","nonMaxSuppression"),L=M(l,"scores","nonMaxSuppression"),x=Ks(S,L,h,d,f,g);h=x.maxOutputSize,d=x.iouThreshold,f=x.scoreThreshold,g=x.softNmsSigma;const A={boxes:S,scores:L},O={maxOutputSize:h,iouThreshold:d,scoreThreshold:f,softNmsSigma:g},C=H.runKernel(wR,A,O);return{selectedIndices:C[0],selectedScores:C[1]}}const BO=G({nonMaxSuppressionWithScore_:nZ});async function sZ(r,l,h,d=.5,f=Number.NEGATIVE_INFINITY,g=0){const S=M(r,"boxes","nonMaxSuppressionAsync"),L=M(l,"scores","nonMaxSuppressionAsync"),x=Ks(S,L,h,d,f,g);h=x.maxOutputSize,d=x.iouThreshold,f=x.scoreThreshold,g=x.softNmsSigma;const A=await Promise.all([S.data(),L.data()]),O=A[0],C=A[1],$=WO(O,C,h,d,f,g);return S!==r&&S.dispose(),L!==l&&L.dispose(),$}const MO=sZ;function iZ(r,l,h,d=.5,f=Number.NEGATIVE_INFINITY,g=!1){const S=M(r,"boxes","nonMaxSuppression"),L=M(l,"scores","nonMaxSuppression"),x=Ks(S,L,h,d,f,null),A=x.maxOutputSize,O=x.iouThreshold,C=x.scoreThreshold,$={boxes:S,scores:L},z={maxOutputSize:A,iouThreshold:O,scoreThreshold:C,padToMaxOutputSize:g},ne=H.runKernel(bR,$,z);return{selectedIndices:ne[0],validOutputs:ne[1]}}const PO=G({nonMaxSuppressionPadded_:iZ});async function rZ(r,l,h,d=.5,f=Number.NEGATIVE_INFINITY,g=!1){const S=M(r,"boxes","nonMaxSuppressionAsync"),L=M(l,"scores","nonMaxSuppressionAsync"),x=Ks(S,L,h,d,f,null),A=x.maxOutputSize,O=x.iouThreshold,C=x.scoreThreshold,[$,z]=await Promise.all([S.data(),L.data()]),ne=_O($,z,A,O,C,g);return S!==r&&S.dispose(),L!==l&&L.dispose(),ne}const zO=rZ;function oZ(r,l,h=!1){const d=M(r,"images","resizeBilinear");Z(d.rank===3||d.rank===4,()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${d.rank}.`),Z(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=re(d,[1,d.shape[0],d.shape[1],d.shape[2]]));const[S,L]=l,x=($,z)=>(z([f]),$.resizeBilinear(f,S,L,h)),A={images:f},O={alignCorners:h,size:l},C=H.runKernelFunc(x,A,null,gf,O);return g?re(C,[C.shape[1],C.shape[2],C.shape[3]]):C}const GO=G({resizeBilinear_:oZ});function aZ(r,l,h=!1){const d=M(r,"images","resizeNearestNeighbor");Z(d.rank===3||d.rank===4,()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${d.rank}.`),Z(l.length===2,()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${l}.`),Z(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=re(d,[1,d.shape[0],d.shape[1],d.shape[2]]));const[S,L]=l,x={images:f},A={alignCorners:h,size:l},O=($,z)=>(z([f]),$.resizeNearestNeighbor(f,S,L,h)),C=H.runKernelFunc(O,x,null,ff,A);return g?re(C,[C.shape[1],C.shape[2],C.shape[3]]):C}const VO=G({resizeNearestNeighbor_:aZ});function cZ(r,l,h){Z(l%1===0,()=>`bandPart(): numLower must be an integer, got ${l}.`),Z(h%1===0,()=>`bandPart(): numUpper must be an integer, got ${h}.`);const d=M(r,"a","bandPart");Z(d.rank>=2,()=>`bandPart(): Rank must be at least 2, got ${d.rank}.`);const f=d.shape,[g,S]=d.shape.slice(-2);if(!(l<=g))throw new Error(`bandPart(): numLower (${l}) must not be greater than the number of rows (${g}).`);if(!(h<=S))throw new Error(`bandPart(): numUpper (${h}) must not be greater than the number of columns (${S}).`);l<0&&(l=g),h<0&&(h=S);const L=re(Jf(0,g,1,"int32"),[-1,1]),x=Jf(0,S,1,"int32"),A=Be(L,x),O=ua(Ir(A,ke(+l,"int32")),Sr(A,ke(-h,"int32"))),C=Fs([g,S],d.dtype);return re(js(Bu(re(d,[-1,g,S])).map($=>zn(O,$,C))),f)}const HO=G({bandPart_:cZ});function lZ(r){let l;if(Array.isArray(r)){l=!1,Z(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)Z(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=uo(r,r.shape[0],0).map(f=>XI(f,[0]));Z(r.length<=r[0].shape[0],()=>`Gram-Schmidt: Number of vectors (${r.length}) exceeds number of dimensions (${r[0].shape[0]}).`);const h=[],d=r;for(let f=0;f<r.length;++f)h.push(H.tidy(()=>{let g=d[f];if(f>0)for(let S=0;S<f;++S){const L=ae(Fe(ae(h[S],g)),h[S]);g=Be(g,L)}return ze(g,Zf(g,"euclidean"))}));return l?js(h,0):h}const YO=G({gramSchmidt_:lZ});function hZ(r,l=!1){if(Z(r.rank>=2,()=>`qr() requires input tensor to have a rank >= 2, but got rank ${r.rank}`),r.rank===2)return qO(r,l);{const h=r.shape.slice(0,r.shape.length-2).reduce((x,A)=>x*A),d=Bu(re(r,[h,r.shape[r.shape.length-2],r.shape[r.shape.length-1]]),0),f=[],g=[];d.forEach(x=>{const[A,O]=qO(x,l);f.push(A),g.push(O)});const S=re(js(f,0),r.shape),L=re(js(g,0),r.shape);return[S,L]}}function qO(r,l=!1){return H.tidy(()=>{Z(r.shape.length===2,()=>`qr2d() requires a 2D Tensor, but got a ${r.shape.length}D Tensor.`);const h=r.shape[0],d=r.shape[1];let f=EI(h),g=bi(r);const S=ma([[1]],[1,1]);let L=bi(S);const x=h>=d?d:h;for(let A=0;A<x;++A){const O=g,C=L,$=f;[L,g,f]=H.tidy(()=>{const z=At(g,[A,A],[h-A,1]),ne=Zf(z),te=At(g,[A,A],[1,1]),se=zn(wi(te,0),ma([[-1]]),ma([[1]])),fe=Be(te,ae(se,ne)),de=ze(z,fe);de.shape[0]===1?L=bi(S):L=bn([S,At(de,[1,0],[de.shape[0]-1,de.shape[1]])],0);const Ae=yt(ze(pn(se,fe),ne)),xe=At(g,[A,0],[h-A,d]),Me=ae(Ae,L),Ke=Wt(L);if(A===0)g=Be(xe,pn(Me,pn(Ke,xe)));else{const Kt=Be(xe,pn(Me,pn(Ke,xe)));g=bn([At(g,[0,0],[A,d]),Kt],0)}const wt=Wt(Me),$t=At(f,[0,A],[h,f.shape[1]-A]);if(A===0)f=Be($t,pn(pn($t,L),wt));else{const Kt=Be($t,pn(pn($t,L),wt));f=bn([At(f,[0,0],[h,A]),Kt],1)}return[L,g,f]}),mO([O,C,$])}return!l&&h>d&&(f=At(f,[0,0],[h,d]),g=At(g,[0,0],[d,d])),[f,g]})}const jO=G({qr_:hZ});var jt;(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"})(jt||(jt={}));function uZ(r,l,h=jt.SUM_BY_NONZERO_WEIGHTS){const d=M(r,"losses","computeWeightedLoss");let f=null;l!=null&&(f=M(l,"weights","computeWeightedLoss"));const g=f==null?d:ae(d,f);if(h===jt.NONE)return g;if(h===jt.SUM)return Fe(g);if(h===jt.MEAN){if(f==null)return MI(g);{const S=d.size/f.size,L=ze(Fe(g),Fe(f));return S>1?ze(L,ke(S)):L}}if(h===jt.SUM_BY_NONZERO_WEIGHTS){if(f==null)return ze(Fe(g),ke(d.size));{const S=ae(f,Ki(d.shape)),L=Le(Fe(zI(S,ke(0))),"float32");return ze(Fe(g),L)}}throw Error(`Unknown reduction: ${h}`)}const An=G({computeWeightedLoss_:uZ});function dZ(r,l,h,d=jt.SUM_BY_NONZERO_WEIGHTS){const f=M(r,"labels","absoluteDifference"),g=M(l,"predictions","absoluteDifference");let S=null;h!=null&&(S=M(h,"weights","absoluteDifference")),Zt(f.shape,g.shape,"Error in absoluteDifference: ");const L=Pn(Be(f,g));return An(L,S,d)}const KO=G({absoluteDifference_:dZ});function pZ(r,l,h,d,f=jt.SUM_BY_NONZERO_WEIGHTS){const g=M(r,"labels","cosineDistance"),S=M(l,"predictions","cosineDistance");let L=null;d!=null&&(L=M(d,"weights","cosineDistance")),Zt(g.shape,S.shape,"Error in cosineDistance: ");const x=ke(1),A=Be(x,Fe(ae(g,S),h,!0));return An(A,L,f)}const XO=G({cosineDistance_:pZ});function mZ(r,l,h,d=jt.SUM_BY_NONZERO_WEIGHTS){let f=M(r,"labels","hingeLoss");const g=M(l,"predictions","hingeLoss");let S=null;h!=null&&(S=M(h,"weights","hingeLoss")),Zt(f.shape,g.shape,"Error in hingeLoss: ");const L=ke(1);f=Be(ae(ke(2),f),L);const x=Wu(Be(L,ae(f,g)));return An(x,S,d)}const JO=G({hingeLoss_:mZ});function fZ(r,l,h,d=1,f=jt.SUM_BY_NONZERO_WEIGHTS){const g=M(r,"labels","huberLoss"),S=M(l,"predictions","huberLoss");let L=null;h!=null&&(L=M(h,"weights","huberLoss")),Zt(g.shape,S.shape,"Error in huberLoss: ");const x=ke(d),A=Pn(Be(S,g)),O=PI(A,x),C=Be(A,O),$=St(ae(ke(.5),ut(O)),ae(x,C));return An($,L,f)}const ZO=G({huberLoss_:fZ});function gZ(r,l,h,d=1e-7,f=jt.SUM_BY_NONZERO_WEIGHTS){const g=M(r,"labels","logLoss"),S=M(l,"predictions","logLoss");let L=null;h!=null&&(L=M(h,"weights","logLoss")),Zt(g.shape,S.shape,"Error in logLoss: ");const x=ke(1),A=ke(d),O=yt(ae(g,lo(St(S,A)))),C=ae(Be(x,g),lo(St(Be(x,S),A))),$=Be(O,C);return An($,L,f)}const QO=G({logLoss_:gZ});function yZ(r,l,h,d=jt.SUM_BY_NONZERO_WEIGHTS){const f=M(r,"labels","meanSquaredError"),g=M(l,"predictions","meanSquaredError");let S=null;h!=null&&(S=M(h,"weights","meanSquaredError")),Zt(f.shape,g.shape,"Error in meanSquaredError: ");const L=KI(f,g);return An(L,S,d)}const e1=G({meanSquaredError_:yZ});function bZ(r,l){const h=M(r,"labels","sigmoidCrossEntropyWithLogits"),d=M(l,"logits","sigmoidCrossEntropyWithLogits");Zt(h.shape,d.shape,"Error in sigmoidCrossEntropyWithLogits: ");const f=Wu(d),g=ae(d,h),S=$I(Gn(yt(Pn(d))));return St(Be(f,g),S)}function wZ(r,l,h,d=0,f=jt.SUM_BY_NONZERO_WEIGHTS){let g=M(r,"multiClassLabels","sigmoidCrossEntropy");const S=M(l,"logits","sigmoidCrossEntropy");let L=null;if(h!=null&&(L=M(h,"weights","sigmoidCrossEntropy")),Zt(g.shape,S.shape,"Error in sigmoidCrossEntropy: "),d>0){const A=ke(d),O=ke(1),C=ke(.5);g=St(ae(g,Be(O,A)),ae(C,A))}const x=bZ(g,S);return An(x,L,f)}const t1=G({sigmoidCrossEntropy_:wZ});function LZ(r,l,h=-1){if(h===-1&&(h=l.rank-1),h!==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 ${h}`);const d=Kf((f,g,S)=>{const L=!0,x=UI(g,[h],L),A=Be(Le(g,"float32"),x);S([f,A]);const O=yt(ae(A,f)),C=Fe(O,[h]),$=(z,ne)=>{const[te,se]=ne,fe=ts(z.shape,[h]);return[ae(re(z,fe),Be(Le(te,"float32"),Gn(se))),ae(re(z,fe),Be(Gn(se),Le(te,"float32")))]};return{value:C,gradFunc:$}});return d(r,l)}function SZ(r,l,h,d=0,f=jt.SUM_BY_NONZERO_WEIGHTS){let g=M(r,"onehotLabels","softmaxCrossEntropy");const S=M(l,"logits","softmaxCrossEntropy");let L=null;if(h!=null&&(L=M(h,"weights","softmaxCrossEntropy")),Zt(g.shape,S.shape,"Error in softmaxCrossEntropy: "),d>0){const A=ke(d),O=ke(1),C=ke(g.shape[1]);g=St(ae(g,Be(O,A)),ze(A,C))}const x=LZ(g,S);return An(x,L,f)}const n1=G({softmaxCrossEntropy_:SZ});const yAe={fft:$u,ifft:Hc,rfft:Uu,irfft:jI},IAe={hammingWindow:NO,hannWindow:tg,frame:ng,stft:CO},s1={flipLeftRight:OO,resizeNearestNeighbor:VO,resizeBilinear:GO,rotateWithOffset:EO,cropAndResize:RO,nonMaxSuppression:DO,nonMaxSuppressionAsync:UO,nonMaxSuppressionWithScore:BO,nonMaxSuppressionWithScoreAsync:MO,nonMaxSuppressionPadded:PO,nonMaxSuppressionPaddedAsync:zO},$Ae={bandPart:HO,gramSchmidt:YO,qr:jO},qAe={absoluteDifference:KO,computeWeightedLoss:An,cosineDistance:XO,hingeLoss:JO,huberLoss:ZO,logLoss:QO,meanSquaredError:e1,sigmoidCrossEntropy:t1,softmaxCrossEntropy:n1};const i1=1.7580993408473768,r1=1.0507009873554805;const o1={kernelName:Bm,inputsToSave:["x"],gradFunc:(r,l)=>{const[h]=l;return{x:()=>ae(r,pa(Le(h,"float32"),-1))}}};const a1={kernelName:f2,inputsToSave:["x"],gradFunc:(r,l)=>{const[h]=l;return{x:()=>{const d=ut(Le(h,"float32")),f=gs(Be(ke(1),d));return yt(ze(r,f))}}}};const c1={kernelName:g2,inputsToSave:["x"],gradFunc:(r,l)=>{const[h]=l;return{x:()=>{const d=gs(Be(ut(Le(h,"float32")),1));return ze(r,d)}}}};const l1={kernelName:kc,inputsToSave:["a","b"],gradFunc:(r,l)=>{const[h,d]=l,f=rt(h.shape,d.shape),g=()=>{let L=r;const x=vt(h.shape,f);return x.length>0&&(L=Fe(L,x)),re(L,h.shape)},S=()=>{let L=r;const x=vt(d.shape,f);return x.length>0&&(L=Fe(L,x)),re(L,d.shape)};return{a:g,b:S}}};const h1={kernelName:y2,saveAllInputs:!0,gradFunc:(r,l)=>{const h={};return l.forEach((d,f)=>{h[f]=()=>r.clone()}),h}};const u1={kernelName:b2,inputsToSave:["x"],gradFunc:(r,l)=>{const[h]=l;return{x:()=>je(h)}}};const d1={kernelName:w2,inputsToSave:["x"],gradFunc:(r,l)=>{const[h]=l;return{x:()=>je(h)}}};const p1={kernelName:L2,inputsToSave:["x"],gradFunc:(r,l)=>{const[h]=l;return{x:()=>ze(r,gs(Be(ke(1),ut(Le(h,"float32")))))}}};const m1={kernelName:S2,inputsToSave:["x"],gradFunc:(r,l)=>{const[h]=l;return{x:()=>{const d=gs(St(ke(1),ut(Le(h,"float32"))));return ze(r,d)}}}};const f1={kernelName:T2,inputsToSave:["a","b"],gradFunc:(r,l)=>{const[h,d]=l,f=rt(h.shape,d.shape),g=()=>{const L=St(ut(h),ut(d));let x=ae(r,ze(d,L));const A=vt(h.shape,f);return A.length>0&&(x=Fe(x,A)),re(x,h.shape)},S=()=>{const L=St(ut(h),ut(d));let x=yt(ae(r,ze(h,L)));const A=vt(d.shape,f);return A.length>0&&(x=Fe(x,A)),re(x,d.shape)};return{a:g,b:S}}};const g1={kernelName:I2,inputsToSave:["x"],gradFunc:(r,l)=>{const[h]=l;return{x:()=>ze(r,St(ut(Le(h,"float32")),1))}}};const y1={kernelName:x2,inputsToSave:["x"],gradFunc:(r,l)=>{const[h]=l;return{x:()=>ze(r,Be(ke(1),ut(Le(h,"float32"))))}}};function IZ(r,l,h,d,f=[1,1,1],g,S){const L=M(r,"dy","avgPool3dBackprop"),x=M(l,"input","avgPool3dBackprop");let A=L,O=x,C=!1;x.rank===4&&(C=!0,A=re(L,[1,L.shape[0],L.shape[1],L.shape[2],L.shape[3]]),O=re(x,[1,x.shape[0],x.shape[1],x.shape[2],x.shape[3]])),Z(A.rank===5,()=>`Error in avgPool3dBackprop: dy must be rank 5 but got rank ${A.rank}.`),Z(O.rank===5,()=>`Error in avgPool3dBackprop: input must be rank 5 but got rank ${O.rank}.`),Z(co(d,f),()=>`Error in avgPool3dBackprop: Either strides or dilations must be 1. Got strides ${d} and dilations '${f}'`),S!=null&&Z(Qt(g),()=>`Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode ${S} but got pad ${g}.`);const $=se=>{const fe=qf(O.shape,h,d,f,g,S);return se.avgPool3dBackprop(A,O,fe)},z={dy:A,input:O},ne={filterSize:h,strides:d,dilations:f,pad:g,dimRoundingMode:S},te=H.runKernelFunc($,z,null,C2,ne);return C?re(te,[te.shape[1],te.shape[2],te.shape[3],te.shape[4]]):te}const b1=G({avgPool3dBackprop_:IZ});const w1={kernelName:N2,inputsToSave:["x"],gradFunc:(r,l,h)=>{const[d]=l,{filterSize:f,strides:g,dilations:S,pad:L,dimRoundingMode:x}=h,A=S==null?[1,1,1]:S;return{x:()=>b1(r,d,f,g,A,L,x)}}};function xZ(r,l,h,d,f){const g=M(r,"dy","avgPoolBackprop"),S=M(l,"input","avgPoolBackprop");Z(S.rank===g.rank,()=>`Rank of input (${S.rank}) does not match rank of dy (${g.rank})`);let L=S,x=g,A=!1;S.rank===3&&(A=!0,L=re(S,[1,S.shape[0],S.shape[1],S.shape[2]]),x=re(g,[1,g.shape[0],g.shape[1],g.shape[2]])),Z(x.rank===4,()=>`Error in avgPoolBackprop: dy must be rank 4 but got rank ${x.rank}.`),Z(L.rank===4,()=>`Error in avgPoolBackprop: input must be rank 4 but got rank ${L.rank}.`);const O=ne=>{const te=Yf(L.shape,h,d,1,f);return ne.avgPoolBackprop(x,L,te)},C={dy:x,input:L},$={filterSize:h,strides:d,pad:f},z=H.runKernelFunc(O,C,null,v2,$);return A?re(z,[z.shape[1],z.shape[2],z.shape[3]]):z}const L1=G({avgPoolBackprop_:xZ});const S1={kernelName:A2,inputsToSave:["x"],gradFunc:(r,l,h)=>{const[d]=l,{filterSize:f,strides:g,pad:S}=h;return{x:()=>L1(r,d,f,g,S)}}};const I1={kernelName:Mm,inputsToSave:["a","b"],gradFunc:(r,l,h)=>{const[d,f]=l,{transposeA:g,transposeB:S}=h;return!g&&!S?{a:()=>pn(r,f,!1,!0),b:()=>pn(d,r,!0,!1)}:!g&&S?{a:()=>pn(r,f,!1,!1),b:()=>pn(r,d,!0,!1)}:g&&!S?{a:()=>pn(f,r,!1,!0),b:()=>pn(d,r,!1,!1)}:{a:()=>pn(f,r,!0,!0),b:()=>pn(r,d,!0,!0)}}};const x1={kernelName:Pm,gradFunc:(r,l,h)=>{const{blockShape:d,crops:f}=h;return{x:()=>VI(r,d,f)}}};const T1={kernelName:zm,gradFunc:(r,l,h)=>{const d=h,f=d.inputShape,g=d.shape,S=Array.from(g);for(let x=f.length-1;x>=0;x--)if(f[x]===g[x])S[x]=1;else if(f[x]!==1)throw new Error(`broadcastTo(): [${f}] cannot be broadcast to [${g}].`);const L=[];for(let x=0;x<S.length;x++)S[x]>1&&L.push(x);return{x:()=>Fe(r,L,!0)}}};const A1={kernelName:Fc,gradFunc:r=>({x:()=>r.clone()})};const v1={kernelName:R2,gradFunc:r=>({x:()=>je(r)})};const N1={kernelName:O2,inputsToSave:["x"],gradFunc:(r,l,h)=>{const[d]=l,{clipValueMin:f,clipValueMax:g}=h;return{x:()=>zn(ua(Sr(d,f),Ir(d,g)),r,je(r))}}};const C1={kernelName:Gm,saveAllInputs:!0,gradFunc:(r,l,h)=>{const d=l.map(x=>x.shape),{axis:f}=h,g=ht(f,l[0].shape)[0],S=d.map(x=>x[g]),L=uo(r,S,g);return L.map(x=>()=>x)}};const R1={kernelName:Vm,inputsToSave:["x","filter"],gradFunc:(r,l,h)=>{const[d,f]=l,{dilations:g,strides:S,pad:L,dataFormat:x}=h;return Z(ao(g),()=>`Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${g}'`),{x:()=>wO(d.shape,r,f,S,L,x),filter:()=>eg(d,r,f.shape,S,L,x)}}};const O1={kernelName:Hm,inputsToSave:["dy","filter"],gradFunc:(r,l,h)=>{const[d,f]=l,{strides:g,pad:S,dataFormat:L,dimRoundingMode:x}=h;return{dy:()=>NI(r,f,g,S,L,1,x),filter:()=>eg(r,d,f.shape,g,S,L,x)}}};function TZ(r,l,h,d,f){let g=r;r.rank===4&&(g=re(r,[1,r.shape[0],r.shape[1],r.shape[2],r.shape[3]]));let S=l;S.rank===4&&(S=re(l,[1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]])),Z(g.rank===5,()=>`Error in conv3dDerFilter: input must be rank 5, but got shape ${g.shape}.`),Z(S.rank===5,()=>`Error in conv3dDerFilter: dy must be rank 5, but got shape ${S.shape}.`),Z(h.length===5,()=>`Error in conv3dDerFilter: filterShape must be length 5, but got ${h}.`),Z(g.shape[4]===h[3],()=>`Error in conv3dDerFilter: depth of input ${g.shape[4]}) must match input depth in filter (${h[3]}.`),Z(S.shape[4]===h[4],()=>`Error in conv3dDerFilter: depth of dy (${S.shape[4]}) must match output depth for filter (${h[4]}).`);const L=O=>{const C=1,$=ku(g.shape,h,d,C,f);return O.conv3dDerFilter(g,S,$)},x={x:g,y:S},A={strides:d,pad:f};return H.runKernelFunc(L,x,null,F2,A)}const E1=G({conv3DBackpropFilter_:TZ});const D1={kernelName:k2,inputsToSave:["x","filter"],gradFunc:(r,l,h)=>{const{dilations:d,strides:f,pad:g}=h;Z(ao(d),()=>`Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${d}'`);const[S,L]=l;return{x:()=>LO(S.shape,r,L,f,g),filter:()=>E1(S,r,L.shape,f,g)}}};const k1={kernelName:Ym,inputsToSave:["x"],gradFunc:(r,l)=>{const[h]=l;return{x:()=>ae(yt(YI(Le(h,"float32"))),r)}}};const F1={kernelName:qm,inputsToSave:["x"],gradFunc:(r,l)=>{const[h]=l;return{x:()=>ae(qI(Le(h,"float32")),r)}}};const _1={kernelName:jm,inputsToSave:["x"],gradFunc:(r,l,h)=>{const[d]=l,{axis:f,exclusive:g,reverse:S}=h;return{x:()=>{const L=fs([f],d.rank);let x=RI(r,f,g,!S);return L!=null&&(x=Wt(x,L)),x}}}};const W1={kernelName:$2,inputsToSave:["x","filter"],gradFunc:(r,l,h)=>{const{dilations:d,strides:f,pad:g,dimRoundingMode:S}=h,L=d==null?[1,1]:d;Z(ao(L),()=>`Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations '${L}'`);const[x,A]=l;Z(x.rank===4,()=>`Error in gradient of depthwiseConv2dNative: input must be rank 4, but got rank ${x.rank}.`),Z(A.rank===4,()=>`Error in gradient of depthwiseConv2dNative: filter must be rank 4, but got rank ${A.rank}.`),Z(x.shape[3]===A.shape[2],()=>`Error in gradient of depthwiseConv2d: number of input channels (${x.shape[3]}) must match the inChannels dimension in filter ${A.shape[2]}.`),Z(co(f,L),()=>`Error in gradient of depthwiseConv2d: Either strides or dilations must be 1. Got strides ${f} and dilations '${L}'.`),S!=null&&Z(Qt(g),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${S} but got pad ${g}.`);const O=Lr(x.shape,A.shape,f,L,g,S,!0);return{x:()=>vO(x.shape,r,A,O),filter:()=>AO(x,r,A.shape,O)}}};const $1={kernelName:M2,inputsToSave:["x","filter"],gradFunc:(r,l,h)=>{const[d,f]=l,g={x:d,filter:f,dy:r},S={x:d,filter:f,dy:r};return{x:()=>H.runKernel(P2,g,h),filter:()=>H.runKernel(z2,S,h)}}};const U1={kernelName:Km,inputsToSave:["a","b"],gradFunc:(r,l)=>{const[h,d]=l,f=rt(h.shape,d.shape),g=()=>{const L=ze(r,Le(d,"float32")),x=vt(h.shape,f);return x.length>0?re(Fe(L,x),h.shape):L},S=()=>{let L=ae(r,Le(h,"float32"));const x=vt(d.shape,f);x.length>0&&(L=re(Fe(L,x),d.shape));const A=ut(d);return yt(ze(L,Le(A,"float32")))};return{a:g,b:S}}};const B1={kernelName:G2,outputsToSave:[!0],gradFunc:(r,l)=>{const[h]=l,d=g=>g.eluDer(r,h),f={dy:r,y:h};return{x:()=>H.runKernelFunc(d,f,null,V2)}}};const M1={kernelName:H2,inputsToSave:["x"],gradFunc:(r,l)=>{const[h]=l,d=ae(Gn(yt(ut(h))),2/Math.sqrt(Math.PI));return{x:()=>ae(r,d)}}};const P1={kernelName:Xm,outputsToSave:[!0],gradFunc:(r,l)=>{const[h]=l;return{x:()=>ae(r,h)}}};const z1={kernelName:q2,inputsToSave:["x"],gradFunc:(r,l)=>{const[h]=l;return{x:()=>ae(r,Gn(h))}}};const G1={kernelName:Jm,gradFunc:r=>({x:()=>je(r)})};const V1={kernelName:Zm,inputsToSave:["a","b"],gradFunc:(r,l)=>{const[h,d]=l,f=rt(h.shape,d.shape),g=()=>{const L=ze(r,Le(d,"float32")),x=vt(h.shape,f);return x.length>0?re(Fe(L,x),h.shape):L},S=()=>{let L=ae(r,Le(h,"float32"));const x=vt(d.shape,f);x.length>0&&(L=re(Fe(L,x),d.shape));const A=ut(d);return yt(ze(L,Le(A,"float32")))};return{a:g,b:S}}};const H1={kernelName:J2,inputsToSave:["x","mean","variance","scale"],gradFunc:(r,l,h)=>{const{varianceEpsilon:d}=h,[f,g,S,L]=l,x=L==null?ke(1):L,A=vt(g.shape,f.shape),O=[];if(g.rank===1){for(let xe=0;xe<f.shape.length-1;++xe)O.push(f.shape[xe]);O.push(1)}const C=Be(f,g),$=ae(r,x),z=HI(St(S,ke(d))),ne=ae(ae(ae(z,z),z),ke(-.5)),te=()=>g.rank===1?re(ae(ae(r,la(re(z,[1,1,1,g.shape[0]]),O)),x),f.shape):re(ae(ae(r,z),x),f.shape),se=()=>{let xe=ae(ae(z,ke(-1)),$);return g.rank===1&&(xe=Fe(xe,A)),re(xe,g.shape)},fe=()=>{let xe=ae(ae(ne,C),$);return g.rank===1&&(xe=Fe(xe,A)),re(xe,g.shape)},de=()=>{const xe=ae(C,z);let Me=ae(r,xe);return g.rank===1&&(Me=Fe(Me,A)),re(Me,g.shape)},Ae=()=>{let xe=r;return g.rank===1&&(xe=Fe(xe,A)),re(xe,g.shape)};return{x:te,mean:se,variance:fe,scale:de,offset:Ae}}};const j1={kernelName:Qm,inputsToSave:["x","indices"],gradFunc:(r,l,h)=>{const[d,f]=l,{axis:g}=h,S=ht(g,d.shape)[0],L=()=>{const x=d.shape,A=f.size,O=x.slice(0,S),C=O.length,$=x.slice(g,x.length).slice(1),z=$.length,ne=Y1(0,C),te=Y1(C+1,C+1+z),se=q1([O,[A],$]),fe=re(r,se),de=re(f,[A]),Ae=q1([[C],ne,te]),xe=Wt(fe,Ae);let Me=JI(xe,de,d.shape[S]);const Ke=Mc(Ae);return Me=Wt(Me,Ke),Me};return{x:L,indices:()=>f}}};function Y1(r,l){const h=[];for(let d=r;d<l;++d)h.push(d);return h}function q1(r){const l=[];for(let h=0;h<r.length;++h)for(let d=0;d<r[h].length;++d)l.push(r[h][d]);return l}const K1={kernelName:ef,inputsToSave:["a","b"],gradFunc:(r,l)=>{const[h,d]=l;return{a:()=>je(h),b:()=>je(d)}}};const X1={kernelName:tf,gradFunc:r=>({x:()=>Le(r,"float32")})};const J1={kernelName:tR,gradFunc:r=>({x:()=>je(r)})};const Z1={kernelName:nR,gradFunc:r=>({x:()=>je(r)})};const Q1={kernelName:sR,gradFunc:r=>({x:()=>je(r)})};const eE={kernelName:sf,inputsToSave:["x"],gradFunc:(r,l)=>{const[h]=l;return{x:()=>ze(r,St(h,1))}}};const tE={kernelName:nf,inputsToSave:["x"],gradFunc:(r,l)=>{const[h]=l;return{x:()=>ze(r,Le(h,"float32"))}}};const nE={kernelName:cR,inputsToSave:[],outputsToSave:[!0],gradFunc:(r,l,h)=>{const[d]=l,{axis:f}=h;return{logits:()=>{const g=!0,S=Gn(d);return Be(r,ae(Fe(r,f,g),S))}}}};function AZ(r,l,h,d=5,f=1,g=1,S=.5){const L=O=>O.LRNGrad(h,r,l,d,f,g,S),x={x:r,y:l,dy:h},A={depthRadius:d,bias:f,alpha:g,beta:S};return H.runKernelFunc(L,x,null,hR,A)}const sE=G({localResponseNormalizationBackprop_:AZ});const iE={kernelName:lR,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(r,l,h)=>{const[d,f]=l,{depthRadius:g,bias:S,alpha:L,beta:x}=h;return{x:()=>sE(d,f,r,g,S,L,x)}}};function sg(r,l,h,d,f){return l.rank<h.rank&&(l=re(l,ts(l.shape,d))),r.rank<h.rank&&(r=re(r,ts(r.shape,d))),{x:()=>{const g=ae(r,Le(OI(h,l),r.dtype));return f==null?g:Wt(g,f)}}}const QI={kernelName:rf,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(r,l,h)=>{const d=h,{reductionIndices:f}=d,[g,S]=l,L=ht(f,g.shape),x=fs(L,g.rank),A=sg(r,S,g,L,x);return{x:()=>{let O=A.x();return x!=null&&(O=Wt(O)),O}}}};const rE={kernelName:of,inputsToSave:["a","b"],gradFunc:(r,l)=>{const[h,d]=l,f=()=>ae(r,Le(Sr(h,d),"float32")),g=()=>ae(r,Le(WI(h,d),"float32"));return{a:f,b:g}}};function vZ(r,l,h,d,f,g=[1,1,1],S,L){const x=M(r,"dy","maxPool3dBackprop"),A=M(l,"input","maxPool3dBackprop"),O=M(h,"output","maxPool3dBackprop");let C=x,$=A,z=O,ne=!1;A.rank===4&&(ne=!0,C=re(x,[1,x.shape[0],x.shape[1],x.shape[2],x.shape[3]]),$=re(A,[1,A.shape[0],A.shape[1],A.shape[2],A.shape[3]]),z=re(O,[1,O.shape[0],O.shape[1],O.shape[2],O.shape[3]])),Z(C.rank===5,()=>`Error in maxPool3dBackprop: dy must be rank 5 but got rank ${C.rank}.`),Z($.rank===5,()=>`Error in maxPool3dBackprop: input must be rank 5 but got rank ${$.rank}.`),Z(z.rank===5,()=>`Error in maxPool3dBackprop: output must be rank 5 but got rank ${z.rank}.`),Z(co(f,g),()=>`Error in maxPool3dBackprop: Either strides or dilations must be 1. Got strides ${f} and dilations '${g}'`),L!=null&&Z(Qt(S),()=>`Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode ${L} but got pad ${S}.`);const te=Ae=>{const xe=qf($.shape,d,f,g,S,L);return Ae.maxPool3dBackprop(C,$,z,xe)},se={dy:C,input:$,output:z},fe={filterSize:d,strides:f,dilations:g,pad:S,dimRoundingMode:L},de=H.runKernelFunc(te,se,null,mR,fe);return ne?re(de,[de.shape[1],de.shape[2],de.shape[3],de.shape[4]]):de}const oE=G({maxPool3dBackprop_:vZ});const aE={kernelName:pR,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(r,l,h)=>{const[d,f]=l,{filterSize:g,strides:S,dilations:L,pad:x,dimRoundingMode:A}=h,O=L==null?[1,1,1]:L;return{x:()=>oE(r,d,f,g,S,O,x,A)}}};function NZ(r,l,h,d,f,g,S){const L=M(r,"dy","maxPoolBackprop"),x=M(l,"input","maxPoolBackprop"),A=M(h,"output","maxPoolBackprop");Z(x.rank===L.rank,()=>`Rank of input (${x.rank}) does not match rank of dy (${L.rank})`),Z(L.rank===4,()=>`Error in maxPoolBackprop: dy must be rank 4 but got rank ${L.rank}.`),Z(x.rank===4,()=>`Error in maxPoolBackprop: input must be rank 4 but got rank ${x.rank}.`),S!=null&&Z(Qt(g),()=>`Error in maxPoolBackprop: pad must be an integer when using, dimRoundingMode ${S} but got pad ${g}.`);const O=z=>{const ne=Yf(x.shape,d,f,1,g,S);return z.maxPoolBackprop(L,x,A,ne)},C={dy:L,input:x,output:A},$={filterSize:d,strides:f,pad:g,dimRoundingMode:S};return H.runKernelFunc(O,C,null,dR,$)}const cE=G({maxPoolBackprop_:NZ});const lE={kernelName:uR,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(r,l,h)=>{const[d,f]=l,{filterSize:g,strides:S,pad:L}=h;return{x:()=>cE(r,d,f,g,S,L)}}};const hE={kernelName:af,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(r,l,h)=>{const d=h,{axis:f}=d,[g,S]=l,L=ht(f,g.shape),x=fs(L,g.rank),A=sg(r,S,g,L,x);return{x:()=>{let O=A.x();return x!=null&&(O=Wt(O)),O}}}};const uE={kernelName:cf,inputsToSave:["a","b"],gradFunc:(r,l)=>{const[h,d]=l,f=()=>ae(r,Le(Ir(h,d),"float32")),g=()=>ae(r,Le(wi(h,d),"float32"));return{a:f,b:g}}};const dE={kernelName:fR,inputsToSave:["a","b"],gradFunc:(r,l)=>{const[h,d]=l,f=rt(h.shape,d.shape),g=()=>{const L=vt(h.shape,f);return L.length>0?re(Fe(r,L),h.shape):r},S=()=>{const L=ae(r,yt(kI(ze(h,d)))),x=vt(d.shape,f);return x.length>0?re(Fe(L,x),d.shape):L};return{a:g,b:S}}};const pE={kernelName:lf,inputsToSave:["a","b"],gradFunc:(r,l)=>{const[h,d]=l,f=rt(h.shape,d.shape),g=()=>{const L=ae(r,Le(d,"float32")),x=vt(h.shape,f);return x.length>0?re(Fe(L,x),h.shape):L},S=()=>{const L=ae(r,Le(h,"float32")),x=vt(d.shape,f);return x.length>0?re(Fe(L,x),d.shape):L};return{a:g,b:S}}};const mE={kernelName:hf,gradFunc:r=>({x:()=>yt(r)})};const fE={kernelName:SR,inputsToSave:["indices"],gradFunc:(r,l)=>{const h=l[0];return{indices:()=>Fs(h.shape,"float32")}}};const gE={kernelName:LR,gradFunc:r=>({x:()=>je(r)})};const ex={kernelName:uf,inputsToSave:["x"],gradFunc:(r,l,h)=>{const d=l[0],{paddings:f}=h,g=f.map(S=>S[0]);return{x:()=>At(r,g,d.shape)}}};const yE={kernelName:df,inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:(r,l)=>{const[h,d,f]=l,g=h,S=d,L=rt(g.shape,S.shape),x=()=>{const O=Le(S,"float32");let C=ae(r,ae(O,da(g,Be(O,ke(1)))));const $=vt(g.shape,L);return $.length>0&&(C=Fe(C,$)),re(C,g.shape)},A=()=>{const O=wi(g,0),C=zn(O,lo(g),je(g));let $=ae(r,ae(f,C));const z=vt(S.shape,L);return z.length>0&&($=Fe($,z)),re($,S.shape)};return{a:x,b:A}}};const bE={kernelName:IR,inputsToSave:["x","alpha"],gradFunc:(r,l)=>{const[h,d]=l,f=wi(h,0);return{x:()=>zn(f,r,ae(r,d)),alpha:()=>{let g=zn(f,je(r),ae(r,h));const S=vt(d.shape,r.shape);return S.length>0&&(g=Fe(g,S)),re(g,d.shape)}}}};const wE={kernelName:AR,inputsToSave:["x"],gradFunc:(r,l)=>{const[h]=l;return{x:()=>ze(r,yt(ut(h)))}}};const LE={kernelName:CR,inputsToSave:["x"],gradFunc:(r,l)=>{const[h]=l,d=ae(Ir(h,6),pa(h));return{x:()=>ae(r,Le(d,"float32"))}}};const SE={kernelName:pf,inputsToSave:["x"],gradFunc:(r,l)=>{const[h]=l;return{x:()=>ae(r,Le(pa(h),"float32"))}}};const IE={kernelName:mf,inputsToSave:["x"],gradFunc:(r,l)=>{const[h]=l;return{x:()=>re(r,h.shape)}}};const xE={kernelName:gf,inputsToSave:["images"],gradFunc:(r,l,h)=>{const[d]=l,f=L=>{const{alignCorners:x}=h;return L.resizeBilinearBackprop(r,d,x)},g={images:d},S=()=>H.runKernelFunc(f,g,null,NR,h);return{images:S}}};const TE={kernelName:ff,inputsToSave:["images"],gradFunc:(r,l,h)=>{const[d]=l,f=L=>{const{alignCorners:x}=h;return L.resizeNearestNeighborBackprop(r,d,x)},g={images:d},S=()=>H.runKernelFunc(f,g,null,vR,h);return{images:S}}};const AE={kernelName:yf,gradFunc:(r,l,h)=>{const{dims:d}=h,f=ht(d,r.shape);return{x:()=>Vc(r,f)}}};const vE={kernelName:RR,gradFunc:r=>({x:()=>je(r)})};const NE={kernelName:bf,inputsToSave:["x"],gradFunc:(r,l)=>{const[h]=l;return{x:()=>yt(ze(r,ae(da(h,1.5),2)))}}};const CE={kernelName:wf,inputsToSave:["condition"],gradFunc:(r,l)=>{const[h]=l;return{condition:()=>Le(je(h),"float32"),t:()=>ae(r,Le(h,r.dtype)),e:()=>ae(r,Le(BI(h),r.dtype))}}};const RE={kernelName:OR,inputsToSave:["x"],gradFunc:(r,l)=>{const[h]=l;return{x:()=>{const d=wi(h,ke(0)),f=ke(i1),g=ke(r1),S=ae(r,g),L=ae(ae(r,f),Gn(Le(h,"float32")));return zn(d,S,L)}}}};const OE={kernelName:xf,outputsToSave:[!0],gradFunc:(r,l)=>{const[h]=l;return{x:()=>ae(r,ae(h,Be(ke(1),h)))}}};const EE={kernelName:ER,gradFunc:r=>({x:()=>je(r)})};const DE={kernelName:Sf,inputsToSave:["x"],gradFunc:(r,l)=>{const[h]=l;return{x:()=>ae(Fu(Le(h,"float32")),r)}}};const kE={kernelName:If,inputsToSave:["x"],gradFunc:(r,l)=>{const[h]=l;return{x:()=>ae(CI(Le(h,"float32")),r)}}};const FE={kernelName:Lf,inputsToSave:["x"],gradFunc:(r,l,h)=>{const[d]=l,{begin:f,size:g}=h,S=d.shape,[L,x]=Vf(d,f,g),A=[];for(let O=0;O<r.rank;O++)A.push([L[O],S[O]-L[O]-x[O]]);return{x:()=>GI(r,A)}}};const _E={kernelName:kR,outputsToSave:[!0],gradFunc:(r,l,h)=>{const[d]=l,{dim:f}=h,g=!0,S=ae(r,d);return{logits:()=>Be(S,ae(Fe(S,[f],g),d))}}};const WE={kernelName:DR,inputsToSave:["x"],gradFunc:(r,l)=>{const[h]=l;return{x:()=>ae(r,AI(h))}}};const tx={kernelName:vf,gradFunc:(r,l,h)=>{const{blockShape:d,paddings:f}=h;return{x:()=>vI(r,d,f)}}};const nx={kernelName:Nf,gradFunc:(r,l,h)=>{const{axis:d}=h;return{x:()=>bn(r,d)}}};const $E={kernelName:Tf,inputsToSave:["x"],gradFunc:(r,l)=>{const[h]=l;return{x:()=>ze(r,ae(gs(Le(h,"float32")),2))}}};const UE={kernelName:FR,inputsToSave:["x"],gradFunc:(r,l)=>{const[h]=l;return{x:()=>ae(r,ae(Le(h,"float32"),2))}}};const BE={kernelName:Cf,inputsToSave:["a","b"],gradFunc:(r,l)=>{const[h,d]=l,f=ke(2),g=()=>ae(r,ae(f,Be(h,d))),S=()=>ae(r,ae(f,Be(d,h)));return{a:g,b:S}}};const ME={kernelName:_f,gradFunc:r=>({x:()=>je(r)})};const PE={kernelName:Rf,inputsToSave:["a","b"],gradFunc:(r,l)=>{const[h,d]=l,f=rt(h.shape,d.shape),g=()=>{let L=r;const x=vt(h.shape,f);return x.length>0&&(L=Fe(L,x)),re(L,h.shape)},S=()=>{let L=r;const x=vt(d.shape,f);return x.length>0&&(L=Fe(L,x)),re(yt(L),d.shape)};return{a:g,b:S}}};const zE={kernelName:Af,inputsToSave:["x"],gradFunc:(r,l,h)=>{const[d]=l,f=d.shape.slice(),{axis:g}=h,S=ht(g,d.shape);S.forEach(A=>{f[A]=1});const L=re(r,f),x=ae(L,Ki(d.shape,"float32"));return{x:()=>x}}};const GE={kernelName:_R,inputsToSave:["x"],gradFunc:(r,l)=>{const[h]=l;return{x:()=>ze(r,ut(Fu(h)))}}};const VE={kernelName:WR,outputsToSave:[!0],gradFunc:(r,l)=>{const[h]=l;return{x:()=>ae(Be(ke(1),ut(h)),r)}}};const HE={kernelName:Of,inputsToSave:["x"],gradFunc:(r,l,h)=>{const[d]=l,{reps:f}=h,g=()=>{let S=je(d);if(d.rank===1)for(let L=0;L<f[0];++L)S=St(S,At(r,[L*d.shape[0]],[d.shape[0]]));else if(d.rank===2)for(let L=0;L<f[0];++L)for(let x=0;x<f[1];++x)S=St(S,At(r,[L*d.shape[0],x*d.shape[1]],[d.shape[0],d.shape[1]]));else if(d.rank===3)for(let L=0;L<f[0];++L)for(let x=0;x<f[1];++x)for(let A=0;A<f[2];++A)S=St(S,At(r,[L*d.shape[0],x*d.shape[1],A*d.shape[2]],[d.shape[0],d.shape[1],d.shape[2]]));else if(d.rank===4)for(let L=0;L<f[0];++L)for(let x=0;x<f[1];++x)for(let A=0;A<f[2];++A)for(let O=0;O<f[3];++O)S=St(S,At(r,[L*d.shape[0],x*d.shape[1],A*d.shape[2],O*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 S};return{x:g}}};const YE={kernelName:Ef,gradFunc:(r,l,h)=>{const d=h,{perm:f}=d,g=Mc(f);return{x:()=>Wt(r,g)}}};const qE={kernelName:Df,gradFunc:(r,l,h)=>{const d=h,{axis:f}=d;return{value:()=>js(r,f)}}};const jE={kernelName:kf,inputsToSave:["segmentIds"],gradFunc:(r,l)=>{const[h]=l,d=()=>CZ(r,h);return{x:d}}};function CZ(r,l){const h=_I(l,je(l)),d=FI(r,h);let f=Sr(l,ke(0,"int32"));const g=d.rank-f.rank;for(let L=0;L<g;++L)f=ks(f,L+1);f=ua(f,Ki(d.shape,"bool"));const S=je(d);return zn(f,d,S)}const KE={kernelName:Ff,gradFunc:r=>({x:()=>je(r)})};const RZ=[o1,a1,c1,l1,h1,u1,d1,p1,m1,f1,g1,y1,w1,S1,I1,x1,T1,A1,v1,N1,C1,O1,R1,D1,k1,F1,_1,W1,$1,U1,B1,M1,P1,z1,V1,G1,H1,j1,K1,X1,J1,Z1,Q1,eE,tE,nE,iE,QI,QI,rE,aE,lE,hE,uE,dE,pE,mE,fE,gE,ex,ex,yE,bE,wE,LE,SE,IE,xE,TE,AE,vE,NE,CE,RE,OE,EE,DE,kE,FE,_E,WE,tx,tx,nx,nx,$E,BE,UE,ME,PE,zE,GE,VE,HE,YE,qE,jE,KE];for(const r of RZ)BR(r);function sx(r,l,h=!1){const{Image:d,Canvas:f}=gt.getEnv();if(!(r instanceof d||r instanceof f))throw new Error("imageToSquare - expected arg0 to be HTMLImageElement | HTMLCanvasElement");const g=ra(r),S=l/Math.max(g.height,g.width),L=S*g.width,x=S*g.height,A=Dc({width:l,height:l}),O=r instanceof f?r:Tu(r),C=Math.abs(L-x)/2,$=h&&L<x?C:0,z=h&&x<L?C:0;return es(A).drawImage(O,$,z,L,x),A}class po{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((h,d)=>{if(yr(h)){this._imageTensors[d]=h,this._inputDimensions[d]=h.shape;return}if(Os(h)){const g=h.shape[0];if(g!==1)throw new Error(`NetInput - tf.Tensor4D with batchSize ${g} passed, but not supported in input array`);this._imageTensors[d]=h,this._inputDimensions[d]=h.shape.slice(1);return}const f=h instanceof gt.getEnv().Canvas?h:Tu(h);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 zi(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),h=this.getInputHeight(r);return PS({width:l,height:h},this.inputSize)}toBatchTensor(r,l=!0){return this._inputSize=r,pO(()=>{const h=zi(this.batchSize,0,1).map(f=>{const g=this.getInput(f);if(g instanceof Tn){let S=Os(g)?g:g.expandDims();return S=HS(S,l),(S.shape[1]!==r||S.shape[2]!==r)&&(S=s1.resizeBilinear(S,[r,r])),S.as3D(r,r,3)}if(g instanceof gt.getEnv().Canvas)return II.fromPixels(sx(g,r,l));throw new Error(`toBatchTensor - at batchIdx ${f}, expected input to be instanceof tf.Tensor or instanceof HTMLCanvasElement, instead have ${g}`)}),d=js(h.map(f=>Le(f,"float32"))).as4D(this.batchSize,r,r,3);return d})}}async function Rt(r){if(r instanceof po)return r;let l=Array.isArray(r)?r:[r];if(!l.length)throw new Error("toNetInput - empty array passed as input");const h=f=>Array.isArray(r)?` at input index ${f}:`:"",d=l.map(ia);return d.forEach((f,g)=>{if(!Um(f)&&!yr(f)&&!Os(f))throw typeof l[g]=="string"?new Error(`toNetInput -${h(g)} string passed, but could not resolve HTMLElement for element id ${l[g]}`):new Error(`toNetInput -${h(g)} expected media to be of type HTMLImageElement | HTMLVideoElement | HTMLCanvasElement | tf.Tensor3D, or to be an element id`);if(Os(f)){const S=f.shape[0];if(S!==1)throw new Error(`toNetInput -${h(g)} tf.Tensor4D with batchSize ${S} passed, but not supported in input array`)}}),await Promise.all(d.map(f=>Um(f)&&QS(f))),new po(d,Array.isArray(r))}async function Yc(r,l){const{Canvas:h}=gt.getEnv();let d=r;if(!(r instanceof h)){const S=await Rt(r);if(S.batchSize>1)throw new Error("extractFaces - batchSize > 1 not supported");const L=S.getInput(0);d=L instanceof h?L:await tI(L)}const f=es(d),g=l.map(S=>S instanceof Yt?S.forSize(d.width,d.height).box.floor():S).map(S=>S.clipAtImageBorders(d.width,d.height));return g.map(({x:S,y:L,width:x,height:A})=>{const O=Dc({width:x,height:A});return es(O).putImageData(f.getImageData(S,L,x,A),0,0),O})}const ig=Ye(Je());async function qc(r,l){if(!yr(r)&&!Os(r))throw new Error("extractFaceTensors - expected image tensor to be 3D or 4D");if(Os(r)&&r.shape[0]>1)throw new Error("extractFaceTensors - batchSize > 1 not supported");return ig.tidy(()=>{const[h,d,f]=r.shape.slice(Os(r)?1:0),g=l.map(L=>L instanceof Yt?L.forSize(d,h).box:L).map(L=>L.clipAtImageBorders(d,h)),S=g.map(({x:L,y:x,width:A,height:O})=>ig.slice3d(r.as3D(h,d,f),[x,L,0],[O,A,f]));return S})}async function fa(r,l){const h=gt.getEnv().fetch,d=await h(r,l);if(!(d.status<400))throw new Error(`failed to fetch: (${d.status}) ${d.statusText}, from url: ${d.url}`);return d}async function OZ(r){const l=await fa(r),h=await l.blob();if(!h.type.startsWith("image/"))throw new Error(`fetchImage - expected blob type to be of type image/*, instead have: ${h.type}, for url: ${l.url}`);return eI(h)}async function ix(r){return(await fa(r)).json()}async function EZ(r){return new Float32Array(await(await fa(r)).arrayBuffer())}function rg(r,l){const h=`${l}-weights_manifest.json`;if(!r)return{modelBaseUri:"",manifestUri:h};if(r==="/")return{modelBaseUri:"/",manifestUri:`/${h}`};const d=r.startsWith("http://")?"http://":r.startsWith("https://")?"https://":"";r=r.replace(d,"");const f=r.split("/").filter(L=>L),g=r.endsWith(".json")?f[f.length-1]:h;let S=d+(r.endsWith(".json")?f.slice(0,f.length-1):f).join("/");return S=r.startsWith("/")?`/${S}`:S,{modelBaseUri:S,manifestUri:S==="/"?`/${g}`:`${S}/${g}`}}const XE=Ye(Je());async function rx(r,l){const{manifestUri:h,modelBaseUri:d}=rg(r,l);let f=await ix(h);return XE.io.loadWeights(f,d)}function DZ(r,l,h=!1){const{width:d,height:f}=h?ra(l):l;return r.width=d,r.height=f,{width:d,height:f}}const xr=Ye(Je());class kn{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:h}=this.traversePropertyPath(r);return l[h]}reassignParamFromPath(r,l){const{obj:h,objProp:d}=this.traversePropertyPath(r);h[d].dispose(),h[d]=l}getParamList(){return this._paramMappings.map(({paramPath:r})=>({path:r,tensor:this.getParamFromPath(r)}))}getTrainableParams(){return this.getParamList().filter(r=>r.tensor instanceof xr.Variable)}getFrozenParams(){return this.getParamList().filter(r=>!(r.tensor instanceof xr.Variable))}variable(){this.getFrozenParams().forEach(({path:r,tensor:l})=>{this.reassignParamFromPath(r,l.variable())})}freeze(){this.getTrainableParams().forEach(({path:r,tensor:l})=>{const h=xr.tensor(l.dataSync());l.dispose(),this.reassignParamFromPath(r,h)})}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 rx(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}=gt.getEnv(),{manifestUri:h,modelBaseUri:d}=rg(r,this.getDefaultModelName()),f=x=>Promise.all(x.map(A=>l(A).then(O=>O.buffer))),g=xr.io.weightsLoaderFactory(f),S=JSON.parse((await l(h)).toString()),L=await g(S,d);this.loadFromWeightMap(L)}loadFromWeightMap(r){const{paramMappings:l,params:h}=this.extractParamsFromWeigthMap(r);this._paramMappings=l,this._params=h}extractWeights(r){const{paramMappings:l,params:h}=this.extractParams(r);this._paramMappings=l,this._params=h}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:h,objProp:d}=l;if(!h||!d||!(h[d]instanceof xr.Tensor))throw new Error(`traversePropertyPath - parameter is not a tensor, for path ${r}`);return{obj:h,objProp:d}}}const jc=Ye(Je());function ns(r,l,h){return jc.tidy(()=>{let d=jc.separableConv2d(r,l.depthwise_filter,l.pointwise_filter,h,"same");return d=jc.add(d,l.bias),d})}const Dt=Ye(Je());function og(r,l,h=!1){return Dt.tidy(()=>{const d=Dt.relu(h?Dt.add(Dt.conv2d(r,l.conv0.filters,[2,2],"same"),l.conv0.bias):ns(r,l.conv0,[2,2])),f=ns(d,l.conv1,[1,1]),g=Dt.relu(Dt.add(d,f)),S=ns(g,l.conv2,[1,1]);return Dt.relu(Dt.add(d,Dt.add(f,S)))})}function Mu(r,l,h=!1,d=!0){return Dt.tidy(()=>{const f=Dt.relu(h?Dt.add(Dt.conv2d(r,l.conv0.filters,d?[2,2]:[1,1],"same"),l.conv0.bias):ns(r,l.conv0,d?[2,2]:[1,1])),g=ns(f,l.conv1,[1,1]),S=Dt.relu(Dt.add(f,g)),L=ns(S,l.conv2,[1,1]),x=Dt.relu(Dt.add(f,Dt.add(g,L))),A=ns(x,l.conv3,[1,1]);return Dt.relu(Dt.add(f,Dt.add(g,Dt.add(L,A))))})}const mo=Ye(Je());function ga(r,l,h="same",d=!1){return mo.tidy(()=>{const f=mo.add(mo.conv2d(r,l.filters,[1,1],h),l.bias);return d?mo.relu(f):f})}function Vn(r,l){Object.keys(r).forEach(h=>{l.some(d=>d.originalPath===h)||r[h].dispose()})}const ag=Ye(Je());function Kc(r,l){return function(h,d,f,g){const S=ag.tensor4d(r(h*d*f*f),[f,f,h,d]),L=ag.tensor1d(r(d));return l.push({paramPath:`${g}/filters`},{paramPath:`${g}/bias`}),{filters:S,bias:L}}}const cg=Ye(Je());function lg(r,l){return function(h,d,f){const g=cg.tensor2d(r(h*d),[h,d]),S=cg.tensor1d(r(d));return l.push({paramPath:`${f}/weights`},{paramPath:`${f}/bias`}),{weights:g,bias:S}}}class ox{constructor(r,l,h){this.depthwise_filter=r;this.pointwise_filter=l;this.bias=h}}const Pu=Ye(Je());function Xc(r,l){return function(h,d,f){const g=Pu.tensor4d(r(3*3*h),[3,3,h,1]),S=Pu.tensor4d(r(h*d),[1,1,h,d]),L=Pu.tensor1d(r(d));return l.push({paramPath:`${f}/depthwise_filter`},{paramPath:`${f}/pointwise_filter`},{paramPath:`${f}/bias`}),new ox(g,S,L)}}function Jc(r){return function(l){const h=r(`${l}/depthwise_filter`,4),d=r(`${l}/pointwise_filter`,4),f=r(`${l}/bias`,1);return new ox(h,d,f)}}function ys(r,l){return function(h,d,f){const g=r[h];if(!Qo(g,d))throw new Error(`expected weightMap[${h}] to be a Tensor${d}D, instead have ${g}`);return l.push({originalPath:h,paramPath:f||h}),g}}function Hn(r){let l=r;function h(f){const g=l.slice(0,f);return l=l.slice(f),g}function d(){return l}return{extractWeights:h,getRemainingWeights:d}}function hg(r,l){const h=Kc(r,l),d=Xc(r,l);function f(S,L,x,A=!1){const O=A?h(S,L,3,`${x}/conv0`):d(S,L,`${x}/conv0`),C=d(L,L,`${x}/conv1`),$=d(L,L,`${x}/conv2`);return{conv0:O,conv1:C,conv2:$}}function g(S,L,x,A=!1){const{conv0:O,conv1:C,conv2:$}=f(S,L,x,A),z=d(L,L,`${x}/conv3`);return{conv0:O,conv1:C,conv2:$,conv3:z}}return{extractDenseBlock3Params:f,extractDenseBlock4Params:g}}function JE(r){const l=[],{extractWeights:h,getRemainingWeights:d}=Hn(r),{extractDenseBlock4Params:f}=hg(h,l),g=f(3,32,"dense0",!0),S=f(32,64,"dense1"),L=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:S,dense2:L,dense3:x}}}function ug(r){return function(l){const h=r(`${l}/filters`,4),d=r(`${l}/bias`,1);return{filters:h,bias:d}}}function dg(r,l){const h=ys(r,l),d=ug(h),f=Jc(h);function g(L,x=!1){const A=x?d(`${L}/conv0`):f(`${L}/conv0`),O=f(`${L}/conv1`),C=f(`${L}/conv2`);return{conv0:A,conv1:O,conv2:C}}function S(L,x=!1){const A=x?d(`${L}/conv0`):f(`${L}/conv0`),O=f(`${L}/conv1`),C=f(`${L}/conv2`),$=f(`${L}/conv3`);return{conv0:A,conv1:O,conv2:C,conv3:$}}return{extractDenseBlock3Params:g,extractDenseBlock4Params:S}}function ZE(r){const l=[],{extractDenseBlock4Params:h}=dg(r,l),d={dense0:h("dense0",!0),dense1:h("dense1"),dense2:h("dense2"),dense3:h("dense3")};return Vn(r,l),{params:d,paramMappings:l}}const fo=Ye(Je());class pg extends kn{constructor(){super("FaceFeatureExtractor")}forwardInput(r){const{params:l}=this;if(!l)throw new Error("FaceFeatureExtractor - load model before inference");return fo.tidy(()=>{const h=fo.cast(r.toBatchTensor(112,!0),"float32"),d=[122.782,117.001,104.298],f=yi(h,d).div(fo.scalar(255));let g=Mu(f,l.dense0,!0);return g=Mu(g,l.dense1),g=Mu(g,l.dense2),g=Mu(g,l.dense3),g=fo.avgPool(g,[7,7],[2,2],"valid"),g})}async forward(r){return this.forwardInput(await Rt(r))}getDefaultModelName(){return"face_feature_extractor_model"}extractParamsFromWeigthMap(r){return ZE(r)}extractParams(r){return JE(r)}}const Zc=Ye(Je());function zu(r,l){return Zc.tidy(()=>Zc.add(Zc.matMul(r,l.weights),l.bias))}function QE(r,l,h){const d=[],{extractWeights:f,getRemainingWeights:g}=Hn(r),S=lg(f,d),L=S(l,h,"fc");if(g().length!==0)throw new Error(`weights remaing after extract: ${g().length}`);return{paramMappings:d,params:{fc:L}}}function eD(r){const l=[],h=ys(r,l);function d(g){const S=h(`${g}/weights`,2),L=h(`${g}/bias`,1);return{weights:S,bias:L}}const f={fc:d("fc")};return Vn(r,l),{params:f,paramMappings:l}}function mg(r){const l={},h={};return Object.keys(r).forEach(d=>{const f=d.startsWith("fc")?h:l;f[d]=r[d]}),{featureExtractorMap:l,classifierMap:h}}const tD=Ye(Je());class fg extends kn{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 tD.tidy(()=>{const h=r instanceof po?this.faceFeatureExtractor.forwardInput(r):r;return zu(h.as2D(h.shape[0],-1),l.fc)})}dispose(r=!0){this.faceFeatureExtractor.dispose(r),super.dispose(r)}loadClassifierParams(r){const{params:l,paramMappings:h}=this.extractClassifierParams(r);this._params=l,this._paramMappings=h}extractClassifierParams(r){return QE(r,this.getClassifierChannelsIn(),this.getClassifierChannelsOut())}extractParamsFromWeigthMap(r){const{featureExtractorMap:l,classifierMap:h}=mg(r);return this.faceFeatureExtractor.loadFromWeightMap(l),eD(h)}extractParams(r){const l=this.getClassifierChannelsIn(),h=this.getClassifierChannelsOut(),d=h*l+h,f=r.slice(0,r.length-d),g=r.slice(r.length-d);return this.faceFeatureExtractor.extractWeights(f),this.extractClassifierParams(g)}}const ax=["neutral","happy","sad","angry","fearful","disgusted","surprised"];class ya{constructor(r){if(r.length!==7)throw new Error(`FaceExpressions.constructor - expected probabilities.length to be 7, have: ${r.length}`);ax.forEach((l,h)=>{this[l]=r[h]})}asSortedArray(){return ax.map(r=>({expression:r,probability:this[r]})).sort((r,l)=>l.probability-r.probability)}}const Qc=Ye(Je());class cx extends fg{constructor(r=new pg){super("FaceExpressionNet",r)}forwardInput(r){return Qc.tidy(()=>Qc.softmax(this.runNet(r)))}async forward(r){return this.forwardInput(await Rt(r))}async predictExpressions(r){const l=await Rt(r),h=await this.forwardInput(l),d=await Promise.all(Qc.unstack(h).map(async g=>{const S=await g.data();return g.dispose(),S}));h.dispose();const f=d.map(g=>new ya(g));return l.isBatchInput?f:f[0]}getDefaultModelName(){return"face_expression_model"}getClassifierChannelsIn(){return 256}getClassifierChannelsOut(){return 7}}function lx(r){return r.expressions instanceof ya}function gg(r,l){const h={expressions:l};return Object.assign({},r,h)}function kZ(r,l,h=.1,d){const f=Array.isArray(l)?l:[l];f.forEach(g=>{const S=g instanceof ya?g:lx(g)?g.expressions:void 0;if(!S)throw new Error("drawFaceExpressions - expected faceExpressions to be FaceExpressions | WithFaceExpressions<{}> or array thereof");const L=S.asSortedArray(),x=L.filter(C=>C.probability>h),A=Vi(g)?g.detection.box.bottomLeft:d||new Ze(0,0),O=new Ec(x.map(C=>`${C.expression} (${ea(C.probability)})`),A);O.draw(r)})}function ba(r){return Vi(r)&&r.landmarks instanceof qs&&r.unshiftedLandmarks instanceof qs&&r.alignedRect instanceof Yt}function el(r,l){const{box:h}=r.detection,d=l.shiftBy(h.x,h.y),f=d.align(),{imageDims:g}=r.detection,S=new Yt(r.detection.score,f.rescale(g.reverse()),g),L={landmarks:d,unshiftedLandmarks:l,alignedRect:S};return Object.assign({},r,L)}class nD{constructor(r={}){const{drawLines:l=!0,drawPoints:h=!0,lineWidth:d,lineColor:f,pointSize:g,pointColor:S}=r;this.drawLines=l,this.drawPoints=h,this.lineWidth=d||1,this.pointSize=g||2,this.lineColor=f||"rgba(0, 255, 255, 1)",this.pointColor=S||"rgba(255, 0, 255, 1)"}}class sD{constructor(r,l={}){this.faceLandmarks=r,this.options=new nD(l)}draw(r){const l=es(r),{drawLines:h,drawPoints:d,lineWidth:f,lineColor:g,pointSize:S,pointColor:L}=this.options;if(h&&this.faceLandmarks instanceof Iu&&(l.strokeStyle=g,l.lineWidth=f,gr(l,this.faceLandmarks.getJawOutline()),gr(l,this.faceLandmarks.getLeftEyeBrow()),gr(l,this.faceLandmarks.getRightEyeBrow()),gr(l,this.faceLandmarks.getNose()),gr(l,this.faceLandmarks.getLeftEye(),!0),gr(l,this.faceLandmarks.getRightEye(),!0),gr(l,this.faceLandmarks.getMouth(),!0)),d){l.strokeStyle=L,l.fillStyle=L;const x=A=>{l.beginPath(),l.arc(A.x,A.y,S,0,2*Math.PI),l.fill()};this.faceLandmarks.positions.forEach(x)}}}function FZ(r,l){const h=Array.isArray(l)?l:[l];h.forEach(d=>{const f=d instanceof qs?d:ba(d)?d.landmarks:void 0;if(!f)throw new Error("drawFaceLandmarks - expected faceExpressions to be FaceLandmarks | WithFaceLandmarks<WithFaceDetection<{}>> or array thereof");new sD(f).draw(r)})}const hx={};vc(hx,{AnchorPosition:()=>Hi,DrawBox:()=>ZS,DrawBoxOptions:()=>l2,DrawFaceLandmarks:()=>sD,DrawFaceLandmarksOptions:()=>nD,DrawTextField:()=>Ec,DrawTextFieldOptions:()=>Wm,drawContour:()=>gr,drawDetections:()=>GX,drawFaceExpressions:()=>kZ,drawFaceLandmarks:()=>FZ});function _Z(r,l){const h=Kc(r,l),d=Xc(r,l);function f(S,L,x){const A=d(S,L,`${x}/separable_conv0`),O=d(L,L,`${x}/separable_conv1`),C=h(S,L,1,`${x}/expansion_conv`);return{separable_conv0:A,separable_conv1:O,expansion_conv:C}}function g(S,L){const x=d(S,S,`${L}/separable_conv0`),A=d(S,S,`${L}/separable_conv1`),O=d(S,S,`${L}/separable_conv2`);return{separable_conv0:x,separable_conv1:A,separable_conv2:O}}return{extractConvParams:h,extractSeparableConvParams:d,extractReductionBlockParams:f,extractMainBlockParams:g}}function iD(r,l){const h=[],{extractWeights:d,getRemainingWeights:f}=Hn(r),{extractConvParams:g,extractSeparableConvParams:S,extractReductionBlockParams:L,extractMainBlockParams:x}=_Z(d,h),A=g(3,32,3,"entry_flow/conv_in"),O=L(32,64,"entry_flow/reduction_block_0"),C=L(64,128,"entry_flow/reduction_block_1"),$={conv_in:A,reduction_block_0:O,reduction_block_1:C},z={};zi(l,0,1).forEach(fe=>{z[`main_block_${fe}`]=x(128,`middle_flow/main_block_${fe}`)});const ne=L(128,256,"exit_flow/reduction_block"),te=S(256,512,"exit_flow/separable_conv"),se={reduction_block:ne,separable_conv:te};if(f().length!==0)throw new Error(`weights remaing after extract: ${f().length}`);return{paramMappings:h,params:{entry_flow:$,middle_flow:z,exit_flow:se}}}function WZ(r,l){const h=ys(r,l),d=ug(h),f=Jc(h);function g(L){const x=f(`${L}/separable_conv0`),A=f(`${L}/separable_conv1`),O=d(`${L}/expansion_conv`);return{separable_conv0:x,separable_conv1:A,expansion_conv:O}}function S(L){const x=f(`${L}/separable_conv0`),A=f(`${L}/separable_conv1`),O=f(`${L}/separable_conv2`);return{separable_conv0:x,separable_conv1:A,separable_conv2:O}}return{extractConvParams:d,extractSeparableConvParams:f,extractReductionBlockParams:g,extractMainBlockParams:S}}function rD(r,l){const h=[],{extractConvParams:d,extractSeparableConvParams:f,extractReductionBlockParams:g,extractMainBlockParams:S}=WZ(r,h),L=d("entry_flow/conv_in"),x=g("entry_flow/reduction_block_0"),A=g("entry_flow/reduction_block_1"),O={conv_in:L,reduction_block_0:x,reduction_block_1:A},C={};zi(l,0,1).forEach(te=>{C[`main_block_${te}`]=S(`middle_flow/main_block_${te}`)});const $=g("exit_flow/reduction_block"),z=f("exit_flow/separable_conv"),ne={reduction_block:$,separable_conv:z};return Vn(r,h),{params:{entry_flow:O,middle_flow:C,exit_flow:ne},paramMappings:h}}const tn=Ye(Je());function oD(r,l,h){return tn.add(tn.conv2d(r,l.filters,h,"same"),l.bias)}function ux(r,l,h=!0){let d=h?tn.relu(r):r;return d=ns(d,l.separable_conv0,[1,1]),d=ns(tn.relu(d),l.separable_conv1,[1,1]),d=tn.maxPool(d,[3,3],[2,2],"same"),d=tn.add(d,oD(r,l.expansion_conv,[2,2])),d}function $Z(r,l){let h=ns(tn.relu(r),l.separable_conv0,[1,1]);return h=ns(tn.relu(h),l.separable_conv1,[1,1]),h=ns(tn.relu(h),l.separable_conv2,[1,1]),h=tn.add(h,r),h}class aD extends kn{constructor(r){super("TinyXception");this._numMainBlocks=r}forwardInput(r){const{params:l}=this;if(!l)throw new Error("TinyXception - load model before inference");return tn.tidy(()=>{const h=tn.cast(r.toBatchTensor(112,!0),"float32"),d=[122.782,117.001,104.298],f=yi(h,d).div(tn.scalar(256));let g=tn.relu(oD(f,l.entry_flow.conv_in,[2,2]));return g=ux(g,l.entry_flow.reduction_block_0,!1),g=ux(g,l.entry_flow.reduction_block_1),zi(this._numMainBlocks,0,1).forEach(S=>{g=$Z(g,l.middle_flow[`main_block_${S}`])}),g=ux(g,l.exit_flow.reduction_block),g=tn.relu(ns(g,l.exit_flow.separable_conv,[1,1])),g})}async forward(r){return this.forwardInput(await Rt(r))}getDefaultModelName(){return"tiny_xception_model"}extractParamsFromWeigthMap(r){return rD(r,this._numMainBlocks)}extractParams(r){return iD(r,this._numMainBlocks)}}function cD(r){const l=[],{extractWeights:h,getRemainingWeights:d}=Hn(r),f=lg(h,l),g=f(512,1,"fc/age"),S=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:S}}}}function lD(r){const l=[],h=ys(r,l);function d(g){const S=h(`${g}/weights`,2),L=h(`${g}/bias`,1);return{weights:S,bias:L}}const f={fc:{age:d("fc/age"),gender:d("fc/gender")}};return Vn(r,l),{params:f,paramMappings:l}}var Tr;(function(r){r.FEMALE="female",r.MALE="male"})(Tr||(Tr={}));const Xi=Ye(Je());class dx extends kn{constructor(r=new aD(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 h=r instanceof po?this.faceFeatureExtractor.forwardInput(r):r,d=Xi.avgPool(h,[7,7],[2,2],"valid").as2D(h.shape[0],-1),f=zu(d,l.fc.age).as1D(),g=zu(d,l.fc.gender);return{age:f,gender:g}})}forwardInput(r){return Xi.tidy(()=>{const{age:l,gender:h}=this.runNet(r);return{age:l,gender:Xi.softmax(h)}})}async forward(r){return this.forwardInput(await Rt(r))}async predictAgeAndGender(r){const l=await Rt(r),h=await this.forwardInput(l),d=Xi.unstack(h.age),f=Xi.unstack(h.gender),g=d.map((L,x)=>({ageTensor:L,genderTensor:f[x]})),S=await Promise.all(g.map(async({ageTensor:L,genderTensor:x})=>{const A=(await L.data())[0],O=(await x.data())[0],C=O>.5,$=C?Tr.MALE:Tr.FEMALE,z=C?O:1-O;return L.dispose(),x.dispose(),{age:A,gender:$,genderProbability:z}}));return h.age.dispose(),h.gender.dispose(),l.isBatchInput?S:S[0]}getDefaultModelName(){return"age_gender_model"}dispose(r=!0){this.faceFeatureExtractor.dispose(r),super.dispose(r)}loadClassifierParams(r){const{params:l,paramMappings:h}=this.extractClassifierParams(r);this._params=l,this._paramMappings=h}extractClassifierParams(r){return cD(r)}extractParamsFromWeigthMap(r){const{featureExtractorMap:l,classifierMap:h}=mg(r);return this.faceFeatureExtractor.loadFromWeightMap(l),lD(h)}extractParams(r){const l=512*1+1+(512*2+2),h=r.slice(0,r.length-l),d=r.slice(r.length-l);return this.faceFeatureExtractor.extractWeights(h),this.extractClassifierParams(d)}}const bs=Ye(Je());class yg extends fg{postProcess(r,l,h){const d=h.map(({width:g,height:S})=>{const L=l/Math.max(S,g);return{width:g*L,height:S*L}}),f=d.length;return bs.tidy(()=>{const g=(O,C)=>bs.stack([bs.fill([68],O,"float32"),bs.fill([68],C,"float32")],1).as2D(1,136).as1D(),S=(O,C)=>{const{width:$,height:z}=d[O];return C($,z)?Math.abs($-z)/2:0},L=O=>S(O,(C,$)=>C<$),x=O=>S(O,(C,$)=>$<C),A=r.mul(bs.fill([f,136],l,"float32")).sub(bs.stack(Array.from(Array(f),(O,C)=>g(L(C),x(C))))).div(bs.stack(Array.from(Array(f),(O,C)=>g(d[C].width,d[C].height))));return A})}forwardInput(r){return bs.tidy(()=>{const l=this.runNet(r);return this.postProcess(l,r.inputSize,r.inputDimensions.map(([h,d])=>({height:h,width:d})))})}async forward(r){return this.forwardInput(await Rt(r))}async detectLandmarks(r){const l=await Rt(r),h=bs.tidy(()=>bs.unstack(this.forwardInput(l))),d=await Promise.all(h.map(async(f,g)=>{const S=Array.from(await f.data()),L=S.filter((A,O)=>Em(O)),x=S.filter((A,O)=>!Em(O));return new Iu(Array(68).fill(0).map((A,O)=>new Ze(L[O],x[O])),{height:l.getInputHeight(g),width:l.getInputWidth(g)})}));return h.forEach(f=>f.dispose()),l.isBatchInput?d:d[0]}getClassifierChannelsOut(){return 136}}class Gu extends yg{constructor(r=new pg){super("FaceLandmark68Net",r)}getDefaultModelName(){return"face_landmark_68_model"}getClassifierChannelsIn(){return 256}}function hD(r){const l=[],{extractDenseBlock3Params:h}=dg(r,l),d={dense0:h("dense0",!0),dense1:h("dense1"),dense2:h("dense2")};return Vn(r,l),{params:d,paramMappings:l}}function uD(r){const l=[],{extractWeights:h,getRemainingWeights:d}=Hn(r),{extractDenseBlock3Params:f}=hg(h,l),g=f(3,32,"dense0",!0),S=f(32,64,"dense1"),L=f(64,128,"dense2");if(d().length!==0)throw new Error(`weights remaing after extract: ${d().length}`);return{paramMappings:l,params:{dense0:g,dense1:S,dense2:L}}}const go=Ye(Je());class dD extends kn{constructor(){super("TinyFaceFeatureExtractor")}forwardInput(r){const{params:l}=this;if(!l)throw new Error("TinyFaceFeatureExtractor - load model before inference");return go.tidy(()=>{const h=go.cast(r.toBatchTensor(112,!0),"float32"),d=[122.782,117.001,104.298],f=yi(h,d).div(go.scalar(255));let g=og(f,l.dense0,!0);return g=og(g,l.dense1),g=og(g,l.dense2),g=go.avgPool(g,[14,14],[2,2],"valid"),g})}async forward(r){return this.forwardInput(await Rt(r))}getDefaultModelName(){return"face_feature_extractor_tiny_model"}extractParamsFromWeigthMap(r){return hD(r)}extractParams(r){return uD(r)}}class px extends yg{constructor(r=new dD){super("FaceLandmark68TinyNet",r)}getDefaultModelName(){return"face_landmark_68_tiny_model"}getClassifierChannelsIn(){return 128}}class UZ extends Gu{}const bg=Ye(Je());function pD(r,l){return bg.add(bg.mul(r,l.weights),l.biases)}const tl=Ye(Je());function mx(r,l,h,d,f="same"){const{filters:g,bias:S}=l.conv;let L=tl.conv2d(r,g,h,f);return L=tl.add(L,S),L=pD(L,l.scale),d?tl.relu(L):L}function mD(r,l){return mx(r,l,[1,1],!0)}function fx(r,l){return mx(r,l,[1,1],!1)}function wg(r,l){return mx(r,l,[2,2],!0,"valid")}const ws=Ye(Je());function BZ(r,l){function h(L,x,A){const O=r(L),C=O.length/(x*A*A);if(MS(C))throw new Error(`depth has to be an integer: ${C}, weights.length: ${O.length}, numFilters: ${x}, filterSize: ${A}`);return ws.tidy(()=>ws.transpose(ws.tensor4d(O,[x,C,A,A]),[2,3,1,0]))}function d(L,x,A,O){const C=h(L,x,A),$=ws.tensor1d(r(x));return l.push({paramPath:`${O}/filters`},{paramPath:`${O}/bias`}),{filters:C,bias:$}}function f(L,x){const A=ws.tensor1d(r(L)),O=ws.tensor1d(r(L));return l.push({paramPath:`${x}/weights`},{paramPath:`${x}/biases`}),{weights:A,biases:O}}function g(L,x,A,O){const C=d(L,x,A,`${O}/conv`),$=f(x,`${O}/scale`);return{conv:C,scale:$}}function S(L,x,A,O,C=!1){const $=g((C?.5:1)*L,x,A,`${O}/conv1`),z=g(L,x,A,`${O}/conv2`);return{conv1:$,conv2:z}}return{extractConvLayerParams:g,extractResidualLayerParams:S}}function fD(r){const{extractWeights:l,getRemainingWeights:h}=Hn(r),d=[],{extractConvLayerParams:f,extractResidualLayerParams:g}=BZ(l,d),S=f(4704,32,7,"conv32_down"),L=g(9216,32,3,"conv32_1"),x=g(9216,32,3,"conv32_2"),A=g(9216,32,3,"conv32_3"),O=g(36864,64,3,"conv64_down",!0),C=g(36864,64,3,"conv64_1"),$=g(36864,64,3,"conv64_2"),z=g(36864,64,3,"conv64_3"),ne=g(147456,128,3,"conv128_down",!0),te=g(147456,128,3,"conv128_1"),se=g(147456,128,3,"conv128_2"),fe=g(589824,256,3,"conv256_down",!0),de=g(589824,256,3,"conv256_1"),Ae=g(589824,256,3,"conv256_2"),xe=g(589824,256,3,"conv256_down_out"),Me=ws.tidy(()=>ws.transpose(ws.tensor2d(l(256*128),[128,256]),[1,0]));if(d.push({paramPath:"fc"}),h().length!==0)throw new Error(`weights remaing after extract: ${h().length}`);const Ke={conv32_down:S,conv32_1:L,conv32_2:x,conv32_3:A,conv64_down:O,conv64_1:C,conv64_2:$,conv64_3:z,conv128_down:ne,conv128_1:te,conv128_2:se,conv256_down:fe,conv256_1:de,conv256_2:Ae,conv256_down_out:xe,fc:Me};return{params:Ke,paramMappings:d}}function MZ(r,l){const h=ys(r,l);function d(S){const L=h(`${S}/scale/weights`,1),x=h(`${S}/scale/biases`,1);return{weights:L,biases:x}}function f(S){const L=h(`${S}/conv/filters`,4),x=h(`${S}/conv/bias`,1),A=d(S);return{conv:{filters:L,bias:x},scale:A}}function g(S){return{conv1:f(`${S}/conv1`),conv2:f(`${S}/conv2`)}}return{extractConvLayerParams:f,extractResidualLayerParams:g}}function gD(r){const l=[],{extractConvLayerParams:h,extractResidualLayerParams:d}=MZ(r,l),f=h("conv32_down"),g=d("conv32_1"),S=d("conv32_2"),L=d("conv32_3"),x=d("conv64_down"),A=d("conv64_1"),O=d("conv64_2"),C=d("conv64_3"),$=d("conv128_down"),z=d("conv128_1"),ne=d("conv128_2"),te=d("conv256_down"),se=d("conv256_1"),fe=d("conv256_2"),de=d("conv256_down_out"),Ae=r.fc;if(l.push({originalPath:"fc",paramPath:"fc"}),!BS(Ae))throw new Error(`expected weightMap[fc] to be a Tensor2D, instead have ${Ae}`);const xe={conv32_down:f,conv32_1:g,conv32_2:S,conv32_3:L,conv64_down:x,conv64_1:A,conv64_2:O,conv64_3:C,conv128_down:$,conv128_1:z,conv128_2:ne,conv256_down:te,conv256_1:se,conv256_2:fe,conv256_down_out:de,fc:Ae};return Vn(r,l),{params:xe,paramMappings:l}}const Yn=Ye(Je());function Li(r,l){let h=mD(r,l.conv1);return h=fx(h,l.conv2),h=Yn.add(h,r),h=Yn.relu(h),h}function Vu(r,l){let h=wg(r,l.conv1);h=fx(h,l.conv2);let d=Yn.avgPool(r,2,2,"valid");const f=Yn.zeros(d.shape),g=d.shape[3]!==h.shape[3],S=d.shape[1]!==h.shape[1]||d.shape[2]!==h.shape[2];if(S){const L=[...h.shape];L[1]=1;const x=Yn.zeros(L);h=Yn.concat([h,x],1);const A=[...h.shape];A[2]=1;const O=Yn.zeros(A);h=Yn.concat([h,O],2)}return d=g?Yn.concat([d,f],3):d,h=Yn.add(d,h),h=Yn.relu(h),h}const _s=Ye(Je());class Hu extends kn{constructor(){super("FaceRecognitionNet")}forwardInput(r){const{params:l}=this;if(!l)throw new Error("FaceRecognitionNet - load model before inference");return _s.tidy(()=>{const h=_s.cast(r.toBatchTensor(150,!0),"float32"),d=[122.782,117.001,104.298],f=yi(h,d).div(_s.scalar(256));let g=wg(f,l.conv32_down);g=_s.maxPool(g,3,2,"valid"),g=Li(g,l.conv32_1),g=Li(g,l.conv32_2),g=Li(g,l.conv32_3),g=Vu(g,l.conv64_down),g=Li(g,l.conv64_1),g=Li(g,l.conv64_2),g=Li(g,l.conv64_3),g=Vu(g,l.conv128_down),g=Li(g,l.conv128_1),g=Li(g,l.conv128_2),g=Vu(g,l.conv256_down),g=Li(g,l.conv256_1),g=Li(g,l.conv256_2),g=Vu(g,l.conv256_down_out);const S=g.mean([1,2]),L=_s.matMul(S,l.fc);return L})}async forward(r){return this.forwardInput(await Rt(r))}async computeFaceDescriptor(r){const l=await Rt(r),h=_s.tidy(()=>_s.unstack(this.forwardInput(l))),d=await Promise.all(h.map(f=>f.data()));return h.forEach(f=>f.dispose()),l.isBatchInput?d:d[0]}getDefaultModelName(){return"face_recognition_model"}extractParamsFromWeigthMap(r){return gD(r)}extractParams(r){return fD(r)}}function PZ(r){const l=new Hu;return l.extractWeights(r),l}function Lg(r,l){const h={descriptor:l};return Object.assign({},r,h)}function zZ(r){return typeof r.age=="number"}function Sg(r,l){const h={age:l};return Object.assign({},r,h)}function GZ(r){return(r.gender===Tr.MALE||r.gender===Tr.FEMALE)&&Rc(r.genderProbability)}function Ig(r,l,h){const d={gender:l,genderProbability:h};return Object.assign({},r,d)}const Si=Ye(Je());function VZ(r,l){function h(x,A){const O=Si.tensor4d(r(3*3*x),[3,3,x,1]),C=Si.tensor1d(r(x)),$=Si.tensor1d(r(x)),z=Si.tensor1d(r(x)),ne=Si.tensor1d(r(x));return l.push({paramPath:`${A}/filters`},{paramPath:`${A}/batch_norm_scale`},{paramPath:`${A}/batch_norm_offset`},{paramPath:`${A}/batch_norm_mean`},{paramPath:`${A}/batch_norm_variance`}),{filters:O,batch_norm_scale:C,batch_norm_offset:$,batch_norm_mean:z,batch_norm_variance:ne}}function d(x,A,O,C,$){const z=Si.tensor4d(r(x*A*O*O),[O,O,x,A]),ne=Si.tensor1d(r(A));return l.push({paramPath:`${C}/filters`},{paramPath:`${C}/${$?"batch_norm_offset":"bias"}`}),{filters:z,bias:ne}}function f(x,A,O,C){const{filters:$,bias:z}=d(x,A,O,C,!0);return{filters:$,batch_norm_offset:z}}function g(x,A,O){const C=h(x,`${O}/depthwise_conv`),$=f(x,A,1,`${O}/pointwise_conv`);return{depthwise_conv:C,pointwise_conv:$}}function S(){const x=f(3,32,3,"mobilenetv1/conv_0"),A=g(32,64,"mobilenetv1/conv_1"),O=g(64,128,"mobilenetv1/conv_2"),C=g(128,128,"mobilenetv1/conv_3"),$=g(128,256,"mobilenetv1/conv_4"),z=g(256,256,"mobilenetv1/conv_5"),ne=g(256,512,"mobilenetv1/conv_6"),te=g(512,512,"mobilenetv1/conv_7"),se=g(512,512,"mobilenetv1/conv_8"),fe=g(512,512,"mobilenetv1/conv_9"),de=g(512,512,"mobilenetv1/conv_10"),Ae=g(512,512,"mobilenetv1/conv_11"),xe=g(512,1024,"mobilenetv1/conv_12"),Me=g(1024,1024,"mobilenetv1/conv_13");return{conv_0:x,conv_1:A,conv_2:O,conv_3:C,conv_4:$,conv_5:z,conv_6:ne,conv_7:te,conv_8:se,conv_9:fe,conv_10:de,conv_11:Ae,conv_12:xe,conv_13:Me}}function L(){const x=f(1024,256,1,"prediction_layer/conv_0"),A=f(256,512,3,"prediction_layer/conv_1"),O=f(512,128,1,"prediction_layer/conv_2"),C=f(128,256,3,"prediction_layer/conv_3"),$=f(256,128,1,"prediction_layer/conv_4"),z=f(128,256,3,"prediction_layer/conv_5"),ne=f(256,64,1,"prediction_layer/conv_6"),te=f(64,128,3,"prediction_layer/conv_7"),se=d(512,12,1,"prediction_layer/box_predictor_0/box_encoding_predictor"),fe=d(512,9,1,"prediction_layer/box_predictor_0/class_predictor"),de=d(1024,24,1,"prediction_layer/box_predictor_1/box_encoding_predictor"),Ae=d(1024,18,1,"prediction_layer/box_predictor_1/class_predictor"),xe=d(512,24,1,"prediction_layer/box_predictor_2/box_encoding_predictor"),Me=d(512,18,1,"prediction_layer/box_predictor_2/class_predictor"),Ke=d(256,24,1,"prediction_layer/box_predictor_3/box_encoding_predictor"),wt=d(256,18,1,"prediction_layer/box_predictor_3/class_predictor"),$t=d(256,24,1,"prediction_layer/box_predictor_4/box_encoding_predictor"),Kt=d(256,18,1,"prediction_layer/box_predictor_4/class_predictor"),Fn=d(128,24,1,"prediction_layer/box_predictor_5/box_encoding_predictor"),vn=d(128,18,1,"prediction_layer/box_predictor_5/class_predictor"),Nn={box_encoding_predictor:se,class_predictor:fe},Qs={box_encoding_predictor:de,class_predictor:Ae},Ai={box_encoding_predictor:xe,class_predictor:Me},ei={box_encoding_predictor:Ke,class_predictor:wt},xa={box_encoding_predictor:$t,class_predictor:Kt},hl={box_encoding_predictor:Fn,class_predictor:vn};return{conv_0:x,conv_1:A,conv_2:O,conv_3:C,conv_4:$,conv_5:z,conv_6:ne,conv_7:te,box_predictor_0:Nn,box_predictor_1:Qs,box_predictor_2:Ai,box_predictor_3:ei,box_predictor_4:xa,box_predictor_5:hl}}return{extractMobilenetV1Params:S,extractPredictionLayerParams:L}}function yD(r){const l=[],{extractWeights:h,getRemainingWeights:d}=Hn(r),{extractMobilenetV1Params:f,extractPredictionLayerParams:g}=VZ(h,l),S=f(),L=g(),x=Si.tensor3d(h(5118*4),[1,5118,4]),A={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:S,prediction_layer:L,output_layer:A},paramMappings:l}}function HZ(r,l){const h=ys(r,l);function d(A,O,C){const $=h(`${A}/Conv2d_${O}_pointwise/weights`,4,`${C}/filters`),z=h(`${A}/Conv2d_${O}_pointwise/convolution_bn_offset`,1,`${C}/batch_norm_offset`);return{filters:$,batch_norm_offset:z}}function f(A){const O=`mobilenetv1/conv_${A}`,C=`MobilenetV1/Conv2d_${A}_depthwise`,$=`${O}/depthwise_conv`,z=`${O}/pointwise_conv`,ne=h(`${C}/depthwise_weights`,4,`${$}/filters`),te=h(`${C}/BatchNorm/gamma`,1,`${$}/batch_norm_scale`),se=h(`${C}/BatchNorm/beta`,1,`${$}/batch_norm_offset`),fe=h(`${C}/BatchNorm/moving_mean`,1,`${$}/batch_norm_mean`),de=h(`${C}/BatchNorm/moving_variance`,1,`${$}/batch_norm_variance`);return{depthwise_conv:{filters:ne,batch_norm_scale:te,batch_norm_offset:se,batch_norm_mean:fe,batch_norm_variance:de},pointwise_conv:d("MobilenetV1",A,z)}}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 S(A,O){const C=h(`${A}/weights`,4,`${O}/filters`),$=h(`${A}/biases`,1,`${O}/bias`);return{filters:C,bias:$}}function L(A){const O=S(`Prediction/BoxPredictor_${A}/BoxEncodingPredictor`,`prediction_layer/box_predictor_${A}/box_encoding_predictor`),C=S(`Prediction/BoxPredictor_${A}/ClassPredictor`,`prediction_layer/box_predictor_${A}/class_predictor`);return{box_encoding_predictor:O,class_predictor:C}}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:L(0),box_predictor_1:L(1),box_predictor_2:L(2),box_predictor_3:L(3),box_predictor_4:L(4),box_predictor_5:L(5)}}return{extractMobilenetV1Params:g,extractPredictionLayerParams:x}}function bD(r){const l=[],{extractMobilenetV1Params:h,extractPredictionLayerParams:d}=HZ(r,l),f=r["Output/extra_dim"];if(l.push({originalPath:"Output/extra_dim",paramPath:"output_layer/extra_dim"}),!yr(f))throw new Error(`expected weightMap['Output/extra_dim'] to be a Tensor3D, instead have ${f}`);const g={mobilenetv1:h(),prediction_layer:d(),output_layer:{extra_dim:f}};return Vn(r,l),{params:g,paramMappings:l}}const yo=Ye(Je());function Xs(r,l,h){return yo.tidy(()=>{let d=yo.conv2d(r,l.filters,h,"same");return d=yo.add(d,l.batch_norm_offset),yo.clipByValue(d,0,6)})}const Ar=Ye(Je()),YZ=.0010000000474974513;function qZ(r,l,h){return Ar.tidy(()=>{let d=Ar.depthwiseConv2d(r,l.filters,h,"same");return d=Ar.batchNorm(d,l.batch_norm_mean,l.batch_norm_variance,l.batch_norm_offset,l.batch_norm_scale,YZ),Ar.clipByValue(d,0,6)})}function jZ(r){return[2,4,6,12].some(l=>l===r)?[2,2]:[1,1]}function wD(r,l){return Ar.tidy(()=>{let h,d=Xs(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,S)=>{const L=S+1,x=jZ(L);d=qZ(d,g.depthwise_conv,x),d=Xs(d,g.pointwise_conv,[1,1]),L===11&&(h=d)}),h===null)throw new Error("mobileNetV1 - output of conv layer 11 is null");return{out:d,conv11:h}})}function LD(r,l,h,d,f){const g=r.shape[0],S=Math.min(h,g),L=l.map((O,C)=>({score:O,boxIndex:C})).filter(O=>O.score>f).sort((O,C)=>C.score-O.score),x=O=>O<=d?1:0,A=[];return L.forEach(O=>{if(A.length>=S)return;const C=O.score;for(let $=A.length-1;$>=0;--$){const z=KZ(r,O.boxIndex,A[$]);if(z===0)continue;if(O.score*=x(z),O.score<=f)break}C===O.score&&A.push(O.boxIndex)}),A}function KZ(r,l,h){const d=r.arraySync(),f=Math.min(d[l][0],d[l][2]),g=Math.min(d[l][1],d[l][3]),S=Math.max(d[l][0],d[l][2]),L=Math.max(d[l][1],d[l][3]),x=Math.min(d[h][0],d[h][2]),A=Math.min(d[h][1],d[h][3]),O=Math.max(d[h][0],d[h][2]),C=Math.max(d[h][1],d[h][3]),$=(S-f)*(L-g),z=(O-x)*(C-A);if($<=0||z<=0)return 0;const ne=Math.max(f,x),te=Math.max(g,A),se=Math.min(S,O),fe=Math.min(L,C),de=Math.max(se-ne,0)*Math.max(fe-te,0);return de/($+z-de)}const De=Ye(Je());function XZ(r){const l=De.unstack(De.transpose(r,[1,0])),h=[De.sub(l[2],l[0]),De.sub(l[3],l[1])],d=[De.add(l[0],De.div(h[0],De.scalar(2))),De.add(l[1],De.div(h[1],De.scalar(2)))];return{sizes:h,centers:d}}function JZ(r,l){const{sizes:h,centers:d}=XZ(r),f=De.unstack(De.transpose(l,[1,0])),g=De.div(De.mul(De.exp(De.div(f[2],De.scalar(5))),h[0]),De.scalar(2)),S=De.add(De.mul(De.div(f[0],De.scalar(10)),h[0]),d[0]),L=De.div(De.mul(De.exp(De.div(f[3],De.scalar(5))),h[1]),De.scalar(2)),x=De.add(De.mul(De.div(f[1],De.scalar(10)),h[1]),d[1]);return De.transpose(De.stack([De.sub(S,g),De.sub(x,L),De.add(S,g),De.add(x,L)]),[1,0])}function SD(r,l,h){return De.tidy(()=>{const d=r.shape[0];let f=JZ(De.reshape(De.tile(h.extra_dim,[d,1,1]),[-1,4]),De.reshape(r,[-1,4]));f=De.reshape(f,[d,f.shape[0]/d,4]);const g=De.sigmoid(De.slice(l,[0,0,1],[-1,-1,-1]));let S=De.slice(g,[0,0,0],[-1,-1,1]);S=De.reshape(S,[d,S.shape[1]]);const L=De.unstack(f),x=De.unstack(S);return{boxes:L,scores:x}})}const Yu=Ye(Je());function wa(r,l){return Yu.tidy(()=>{const h=r.shape[0],d=Yu.reshape(ga(r,l.box_encoding_predictor),[h,-1,1,4]),f=Yu.reshape(ga(r,l.class_predictor),[h,-1,3]);return{boxPredictionEncoding:d,classPrediction:f}})}const qu=Ye(Je());function ID(r,l,h){return qu.tidy(()=>{const d=Xs(r,h.conv_0,[1,1]),f=Xs(d,h.conv_1,[2,2]),g=Xs(f,h.conv_2,[1,1]),S=Xs(g,h.conv_3,[2,2]),L=Xs(S,h.conv_4,[1,1]),x=Xs(L,h.conv_5,[2,2]),A=Xs(x,h.conv_6,[1,1]),O=Xs(A,h.conv_7,[2,2]),C=wa(l,h.box_predictor_0),$=wa(r,h.box_predictor_1),z=wa(f,h.box_predictor_2),ne=wa(S,h.box_predictor_3),te=wa(x,h.box_predictor_4),se=wa(O,h.box_predictor_5),fe=qu.concat([C.boxPredictionEncoding,$.boxPredictionEncoding,z.boxPredictionEncoding,ne.boxPredictionEncoding,te.boxPredictionEncoding,se.boxPredictionEncoding],1),de=qu.concat([C.classPrediction,$.classPrediction,z.classPrediction,ne.classPrediction,te.classPrediction,se.classPrediction],1);return{boxPredictions:fe,classPredictions:de}})}class Ii{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 xi=Ye(Je());class nl extends kn{constructor(){super("SsdMobilenetv1")}forwardInput(r){const{params:l}=this;if(!l)throw new Error("SsdMobilenetv1 - load model before inference");return xi.tidy(()=>{const h=xi.cast(r.toBatchTensor(512,!1),"float32"),d=xi.sub(xi.mul(h,xi.scalar(.007843137718737125)),xi.scalar(1)),f=wD(d,l.mobilenetv1),{boxPredictions:g,classPredictions:S}=ID(f.out,f.conv11,l.prediction_layer);return SD(g,S,l.output_layer)})}async forward(r){return this.forwardInput(await Rt(r))}async locateFaces(r,l={}){const{maxResults:h,minConfidence:d}=new Ii(l),f=await Rt(r),{boxes:g,scores:S}=this.forwardInput(f),L=g[0],x=S[0];for(let de=1;de<g.length;de++)g[de].dispose(),S[de].dispose();const A=Array.from(await x.data()),O=.5,C=LD(L,A,h,O,d),$=f.getReshapedInputDimensions(0),z=f.inputSize,ne=z/$.width,te=z/$.height,se=L.arraySync(),fe=C.map(de=>{const[Ae,xe]=[Math.max(0,se[de][0]),Math.min(1,se[de][2])].map(wt=>wt*te),[Me,Ke]=[Math.max(0,se[de][1]),Math.min(1,se[de][3])].map(wt=>wt*ne);return new Yt(A[de],new Su(Me,Ae,Ke-Me,xe-Ae),{height:f.getInputHeight(0),width:f.getInputWidth(0)})});return L.dispose(),x.dispose(),fe}getDefaultModelName(){return"ssd_mobilenetv1_model"}extractParamsFromWeigthMap(r){return bD(r)}extractParams(r){return yD(r)}}function xD(r){const l=new nl;return l.extractWeights(r),l}function ZZ(r){return xD(r)}class QZ extends nl{}const TD=.4,AD=[new Ze(.738768,.874946),new Ze(2.42204,2.65704),new Ze(4.30971,7.04493),new Ze(10.246,4.59428),new Ze(12.6868,11.8741)],vD=[new Ze(1.603231,2.094468),new Ze(6.041143,7.080126),new Ze(2.882459,3.518061),new Ze(4.266906,5.178857),new Ze(9.041765,10.66308)],ND=[117.001,114.697,97.404],CD="tiny_yolov2_model",RD="tiny_yolov2_separable_conv_model";const xg=r=>typeof r=="number";function gx(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(!xg(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=>xg(l.x)&&xg(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(xg)))throw new Error(`config.meanRgb has to be an array of shape [number, number, number], have: ${JSON.stringify(r.meanRgb)}`)}const Js=Ye(Je());function sl(r){return Js.tidy(()=>{const l=Js.mul(r,Js.scalar(.10000000149011612));return Js.add(Js.relu(Js.sub(r,l)),l)})}const Zs=Ye(Je());function vr(r,l){return Zs.tidy(()=>{let h=Zs.pad(r,[[0,0],[1,1],[1,1],[0,0]]);return h=Zs.conv2d(h,l.conv.filters,[1,1],"valid"),h=Zs.sub(h,l.bn.sub),h=Zs.mul(h,l.bn.truediv),h=Zs.add(h,l.conv.bias),sl(h)})}const bo=Ye(Je());function Nr(r,l){return bo.tidy(()=>{let h=bo.pad(r,[[0,0],[1,1],[1,1],[0,0]]);return h=bo.separableConv2d(h,l.depthwise_filter,l.pointwise_filter,[1,1],"valid"),h=bo.add(h,l.bias),sl(h)})}const yx=Ye(Je());function eQ(r,l){const h=Kc(r,l);function d(S,L){const x=yx.tensor1d(r(S)),A=yx.tensor1d(r(S));return l.push({paramPath:`${L}/sub`},{paramPath:`${L}/truediv`}),{sub:x,truediv:A}}function f(S,L,x){const A=h(S,L,3,`${x}/conv`),O=d(L,`${x}/bn`);return{conv:A,bn:O}}const g=Xc(r,l);return{extractConvParams:h,extractConvWithBatchNormParams:f,extractSeparableConvParams:g}}function OD(r,l,h,d){const{extractWeights:f,getRemainingWeights:g}=Hn(r),S=[],{extractConvParams:L,extractConvWithBatchNormParams:x,extractSeparableConvParams:A}=eQ(f,S);let O;if(l.withSeparableConvs){const[C,$,z,ne,te,se,fe,de,Ae]=d,xe=l.isFirstLayerConv2d?L(C,$,3,"conv0"):A(C,$,"conv0"),Me=A($,z,"conv1"),Ke=A(z,ne,"conv2"),wt=A(ne,te,"conv3"),$t=A(te,se,"conv4"),Kt=A(se,fe,"conv5"),Fn=de?A(fe,de,"conv6"):void 0,vn=Ae?A(de,Ae,"conv7"):void 0,Nn=L(Ae||de||fe,5*h,1,"conv8");O={conv0:xe,conv1:Me,conv2:Ke,conv3:wt,conv4:$t,conv5:Kt,conv6:Fn,conv7:vn,conv8:Nn}}else{const[C,$,z,ne,te,se,fe,de,Ae]=d,xe=x(C,$,"conv0"),Me=x($,z,"conv1"),Ke=x(z,ne,"conv2"),wt=x(ne,te,"conv3"),$t=x(te,se,"conv4"),Kt=x(se,fe,"conv5"),Fn=x(fe,de,"conv6"),vn=x(de,Ae,"conv7"),Nn=L(Ae,5*h,1,"conv8");O={conv0:xe,conv1:Me,conv2:Ke,conv3:wt,conv4:$t,conv5:Kt,conv6:Fn,conv7:vn,conv8:Nn}}if(g().length!==0)throw new Error(`weights remaing after extract: ${g().length}`);return{params:O,paramMappings:S}}function tQ(r,l){const h=ys(r,l);function d(L){const x=h(`${L}/sub`,1),A=h(`${L}/truediv`,1);return{sub:x,truediv:A}}function f(L){const x=h(`${L}/filters`,4),A=h(`${L}/bias`,1);return{filters:x,bias:A}}function g(L){const x=f(`${L}/conv`),A=d(`${L}/bn`);return{conv:x,bn:A}}const S=Jc(h);return{extractConvParams:f,extractConvWithBatchNormParams:g,extractSeparableConvParams:S}}function ED(r,l){const h=[],{extractConvParams:d,extractConvWithBatchNormParams:f,extractSeparableConvParams:g}=tQ(r,h);let S;if(l.withSeparableConvs){const L=l.filterSizes&&l.filterSizes.length||9;S={conv0:l.isFirstLayerConv2d?d("conv0"):g("conv0"),conv1:g("conv1"),conv2:g("conv2"),conv3:g("conv3"),conv4:g("conv4"),conv5:g("conv5"),conv6:L>7?g("conv6"):void 0,conv7:L>8?g("conv7"):void 0,conv8:d("conv8")}}else S={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 Vn(r,h),{params:S,paramMappings:h}}var bx;(function(r){r[r.XS=224]="XS",r[r.SM=320]="SM",r[r.MD=416]="MD",r[r.LG=608]="LG"})(bx||(bx={}));class Cr{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 kt=Ye(Je());class il extends kn{constructor(r){super("TinyYolov2");gx(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 h=vr(r,l.conv0);return h=kt.maxPool(h,[2,2],[2,2],"same"),h=vr(h,l.conv1),h=kt.maxPool(h,[2,2],[2,2],"same"),h=vr(h,l.conv2),h=kt.maxPool(h,[2,2],[2,2],"same"),h=vr(h,l.conv3),h=kt.maxPool(h,[2,2],[2,2],"same"),h=vr(h,l.conv4),h=kt.maxPool(h,[2,2],[2,2],"same"),h=vr(h,l.conv5),h=kt.maxPool(h,[2,2],[1,1],"same"),h=vr(h,l.conv6),h=vr(h,l.conv7),ga(h,l.conv8,"valid",!1)}runMobilenet(r,l){let h=this.config.isFirstLayerConv2d?sl(ga(r,l.conv0,"valid",!1)):Nr(r,l.conv0);return h=kt.maxPool(h,[2,2],[2,2],"same"),h=Nr(h,l.conv1),h=kt.maxPool(h,[2,2],[2,2],"same"),h=Nr(h,l.conv2),h=kt.maxPool(h,[2,2],[2,2],"same"),h=Nr(h,l.conv3),h=kt.maxPool(h,[2,2],[2,2],"same"),h=Nr(h,l.conv4),h=kt.maxPool(h,[2,2],[2,2],"same"),h=Nr(h,l.conv5),h=kt.maxPool(h,[2,2],[1,1],"same"),h=l.conv6?Nr(h,l.conv6):h,h=l.conv7?Nr(h,l.conv7):h,ga(h,l.conv8,"valid",!1)}forwardInput(r,l){const{params:h}=this;if(!h)throw new Error("TinyYolov2 - load model before inference");return kt.tidy(()=>{let d=kt.cast(r.toBatchTensor(l,!1),"float32");return d=this.config.meanRgb?yi(d,this.config.meanRgb):d,d=d.div(kt.scalar(256)),this.config.withSeparableConvs?this.runMobilenet(d,h):this.runTinyYolov2(d,h)})}async forward(r,l){return await this.forwardInput(await Rt(r),l)}async detect(r,l={}){const{inputSize:h,scoreThreshold:d}=new Cr(l),f=await Rt(r),g=await this.forwardInput(f,h),S=kt.tidy(()=>kt.unstack(g)[0].expandDims()),L={width:f.getInputWidth(0),height:f.getInputHeight(0)},x=await this.extractBoxes(S,f.getReshapedInputDimensions(0),d);g.dispose(),S.dispose();const A=x.map(te=>te.box),O=x.map(te=>te.score),C=x.map(te=>te.classScore),$=x.map(te=>this.config.classes[te.label]),z=VS(A.map(te=>te.rescale(h)),O,this.config.iouThreshold,!0),ne=z.map(te=>new Oc(O[te],C[te],$[te],A[te],L));return ne}getDefaultModelName(){return""}extractParamsFromWeigthMap(r){return ED(r,this.config)}extractParams(r){const l=this.config.filterSizes||il.DEFAULT_FILTER_SIZES,h=l?l.length:void 0;if(h!==7&&h!==8&&h!==9)throw new Error(`TinyYolov2 - expected 7 | 8 | 9 convolutional filters, but found ${h} filterSizes in config`);return OD(r,this.config,this.boxEncodingSize,l)}async extractBoxes(r,l,h){const{width:d,height:f}=l,g=Math.max(d,f),S=g/d,L=g/f,x=r.shape[1],A=this.config.anchors.length,[O,C,$]=kt.tidy(()=>{const se=r.reshape([x,x,A,this.boxEncodingSize]),fe=se.slice([0,0,0,0],[x,x,A,4]),de=se.slice([0,0,0,4],[x,x,A,1]),Ae=this.withClassScores?kt.softmax(se.slice([0,0,0,5],[x,x,A,this.config.classes.length]),3):kt.scalar(0);return[fe,de,Ae]}),z=[],ne=await C.array(),te=await O.array();for(let se=0;se<x;se++)for(let fe=0;fe<x;fe++)for(let de=0;de<A;de++){const Ae=Lu(ne[se][fe][de][0]);if(!h||Ae>h){const xe=(fe+Lu(te[se][fe][de][0]))/x*S,Me=(se+Lu(te[se][fe][de][1]))/x*L,Ke=Math.exp(te[se][fe][de][2])*this.config.anchors[de].x/x*S,wt=Math.exp(te[se][fe][de][3])*this.config.anchors[de].y/x*L,$t=xe-Ke/2,Kt=Me-wt/2,Fn={row:se,col:fe,anchor:de},{classScore:vn,label:Nn}=this.withClassScores?await this.extractPredictedClass($,Fn):{classScore:1,label:0};z.push({box:new wu($t,Kt,$t+Ke,Kt+wt),score:Ae,classScore:Ae*vn,label:Nn,...Fn})}}return O.dispose(),C.dispose(),$.dispose(),z}async extractPredictedClass(r,l){const{row:h,col:d,anchor:f}=l,g=await r.array();return Array(this.config.classes.length).fill(0).map((S,L)=>g[h][d][f][L]).map((S,L)=>({classScore:S,label:L})).reduce((S,L)=>S.classScore>L.classScore?S:L)}}il.DEFAULT_FILTER_SIZES=[3,16,32,64,128,256,512,1024,1024];class ju extends il{constructor(r=!0){const l=Object.assign({},{withSeparableConvs:r,iouThreshold:TD,classes:["face"]},r?{anchors:vD,meanRgb:ND}:{anchors:AD,withClassScores:!0});super(l)}get withSeparableConvs(){return this.config.withSeparableConvs}get anchors(){return this.config.anchors}async locateFaces(r,l){const h=await this.detect(r,l);return h.map(d=>new Yt(d.score,d.relativeBox,{width:d.imageWidth,height:d.imageHeight}))}getDefaultModelName(){return this.withSeparableConvs?RD:CD}extractParamsFromWeigthMap(r){return super.extractParamsFromWeigthMap(r)}}function nQ(r,l=!0){const h=new ju(l);return h.extractWeights(r),h}class wx extends Cr{constructor(){super(...arguments);this._name="TinyFaceDetectorOptions"}}class Ti{async then(r){return r(await this.run())}async run(){throw new Error("ComposableTask - run is not implemented")}}const Lx=Ye(Je());async function La(r,l,h,d,f=({alignedRect:g})=>g){const g=r.map(x=>ba(x)?f(x):x.detection),S=d||(l instanceof Lx.Tensor?await qc(l,g):await Yc(l,g)),L=await h(S);return S.forEach(x=>x instanceof Lx.Tensor&&x.dispose()),L}async function rl(r,l,h,d,f){return La([r],l,async g=>h(g[0]),d,f)}const DD=.4,kD=[new Ze(1.603231,2.094468),new Ze(6.041143,7.080126),new Ze(2.882459,3.518061),new Ze(4.266906,5.178857),new Ze(9.041765,10.66308)],FD=[117.001,114.697,97.404];class Ku extends il{constructor(){const r={withSeparableConvs:!0,iouThreshold:DD,classes:["face"],anchors:kD,meanRgb:FD,isFirstLayerConv2d:!0,filterSizes:[3,16,32,64,128,256,512]};super(r)}get anchors(){return this.config.anchors}async locateFaces(r,l){const h=await this.detect(r,l);return h.map(d=>new Yt(d.score,d.relativeBox,{width:d.imageWidth,height:d.imageHeight}))}getDefaultModelName(){return"tiny_face_detector_model"}extractParamsFromWeigthMap(r){return super.extractParamsFromWeigthMap(r)}}const pt={ssdMobilenetv1:new nl,tinyFaceDetector:new Ku,tinyYolov2:new ju,faceLandmark68Net:new Gu,faceLandmark68TinyNet:new px,faceRecognitionNet:new Hu,faceExpressionNet:new cx,ageGenderNet:new dx},_D=(r,l)=>pt.ssdMobilenetv1.locateFaces(r,l),sQ=(r,l)=>pt.tinyFaceDetector.locateFaces(r,l),iQ=(r,l)=>pt.tinyYolov2.locateFaces(r,l),WD=r=>pt.faceLandmark68Net.detectLandmarks(r),rQ=r=>pt.faceLandmark68TinyNet.detectLandmarks(r),oQ=r=>pt.faceRecognitionNet.computeFaceDescriptor(r),aQ=r=>pt.faceExpressionNet.predictExpressions(r),cQ=r=>pt.ageGenderNet.predictAgeAndGender(r),$D=r=>pt.ssdMobilenetv1.load(r),lQ=r=>pt.tinyFaceDetector.load(r),hQ=r=>pt.tinyYolov2.load(r),uQ=r=>pt.faceLandmark68Net.load(r),dQ=r=>pt.faceLandmark68TinyNet.load(r),pQ=r=>pt.faceRecognitionNet.load(r),mQ=r=>pt.faceExpressionNet.load(r),fQ=r=>pt.ageGenderNet.load(r),gQ=$D,yQ=_D,bQ=WD;class UD extends Ti{constructor(r,l,h){super();this.parentTask=r;this.input=l;this.extractedFaces=h}}class Zu extends UD{async run(){const r=await this.parentTask,l=await La(r,this.input,async h=>await Promise.all(h.map(d=>pt.faceExpressionNet.predictExpressions(d))),this.extractedFaces);return r.map((h,d)=>gg(h,l[d]))}withAgeAndGender(){return new Xu(this,this.input)}}class Qu extends UD{async run(){const r=await this.parentTask;if(!r)return;const l=await rl(r,this.input,h=>pt.faceExpressionNet.predictExpressions(h),this.extractedFaces);return gg(r,l)}withAgeAndGender(){return new Ju(this,this.input)}}class cl extends Zu{withAgeAndGender(){return new ol(this,this.input)}withFaceDescriptors(){return new Sa(this,this.input)}}class ll extends Qu{withAgeAndGender(){return new al(this,this.input)}withFaceDescriptor(){return new Ia(this,this.input)}}class BD extends Ti{constructor(r,l,h){super();this.parentTask=r;this.input=l;this.extractedFaces=h}}class Xu extends BD{async run(){const r=await this.parentTask,l=await La(r,this.input,async h=>await Promise.all(h.map(d=>pt.ageGenderNet.predictAgeAndGender(d))),this.extractedFaces);return r.map((h,d)=>{const{age:f,gender:g,genderProbability:S}=l[d];return Sg(Ig(h,g,S),f)})}withFaceExpressions(){return new Zu(this,this.input)}}class Ju extends BD{async run(){const r=await this.parentTask;if(!r)return;const{age:l,gender:h,genderProbability:d}=await rl(r,this.input,f=>pt.ageGenderNet.predictAgeAndGender(f),this.extractedFaces);return Sg(Ig(r,h,d),l)}withFaceExpressions(){return new Qu(this,this.input)}}class ol extends Xu{withFaceExpressions(){return new cl(this,this.input)}withFaceDescriptors(){return new Sa(this,this.input)}}class al extends Ju{withFaceExpressions(){return new ll(this,this.input)}withFaceDescriptor(){return new Ia(this,this.input)}}class Sx extends Ti{constructor(r,l){super();this.parentTask=r;this.input=l}}class Sa extends Sx{async run(){const r=await this.parentTask,l=await La(r,this.input,h=>Promise.all(h.map(d=>pt.faceRecognitionNet.computeFaceDescriptor(d))),null,h=>h.landmarks.align(null,{useDlibAlignment:!0}));return l.map((h,d)=>Lg(r[d],h))}withFaceExpressions(){return new cl(this,this.input)}withAgeAndGender(){return new ol(this,this.input)}}class Ia extends Sx{async run(){const r=await this.parentTask;if(!r)return;const l=await rl(r,this.input,h=>pt.faceRecognitionNet.computeFaceDescriptor(h),null,h=>h.landmarks.align(null,{useDlibAlignment:!0}));return Lg(r,l)}withFaceExpressions(){return new ll(this,this.input)}withAgeAndGender(){return new al(this,this.input)}}const ed=Ye(Je());class Ix extends Ti{constructor(r,l,h){super();this.parentTask=r;this.input=l;this.useTinyLandmarkNet=h}get landmarkNet(){return this.useTinyLandmarkNet?pt.faceLandmark68TinyNet:pt.faceLandmark68Net}}class xx extends Ix{async run(){const r=await this.parentTask,l=r.map(f=>f.detection),h=this.input instanceof ed.Tensor?await qc(this.input,l):await Yc(this.input,l),d=await Promise.all(h.map(f=>this.landmarkNet.detectLandmarks(f)));return h.forEach(f=>f instanceof ed.Tensor&&f.dispose()),r.map((f,g)=>el(f,d[g]))}withFaceExpressions(){return new cl(this,this.input)}withAgeAndGender(){return new ol(this,this.input)}withFaceDescriptors(){return new Sa(this,this.input)}}class Tx extends Ix{async run(){const r=await this.parentTask;if(!r)return;const{detection:l}=r,h=this.input instanceof ed.Tensor?await qc(this.input,[l]):await Yc(this.input,[l]),d=await this.landmarkNet.detectLandmarks(h[0]);return h.forEach(f=>f instanceof ed.Tensor&&f.dispose()),el(r,d)}withFaceExpressions(){return new ll(this,this.input)}withAgeAndGender(){return new al(this,this.input)}withFaceDescriptor(){return new Ia(this,this.input)}}class Ax extends Ti{constructor(r,l=new Ii){super();this.input=r;this.options=l}}class Tg extends Ax{async run(){const{input:r,options:l}=this,h=l instanceof wx?d=>pt.tinyFaceDetector.locateFaces(d,l):l instanceof Ii?d=>pt.ssdMobilenetv1.locateFaces(d,l):l instanceof Cr?d=>pt.tinyYolov2.locateFaces(d,l):null;if(!h)throw new Error("detectFaces - expected options to be instance of TinyFaceDetectorOptions | SsdMobilenetv1Options | MtcnnOptions | TinyYolov2Options");return h(r)}runAndExtendWithFaceDetections(){return new Promise(async r=>{const l=await this.run();return r(l.map(h=>sa({},h)))})}withFaceLandmarks(r=!1){return new xx(this.runAndExtendWithFaceDetections(),this.input,r)}withFaceExpressions(){return new Zu(this.runAndExtendWithFaceDetections(),this.input)}withAgeAndGender(){return new Xu(this.runAndExtendWithFaceDetections(),this.input)}}class vx extends Ax{async run(){const r=await new Tg(this.input,this.options);let l=r[0];return r.forEach(h=>{h.score>l.score&&(l=h)}),l}runAndExtendWithFaceDetection(){return new Promise(async r=>{const l=await this.run();return r(l?sa({},l):void 0)})}withFaceLandmarks(r=!1){return new Tx(this.runAndExtendWithFaceDetection(),this.input,r)}withFaceExpressions(){return new Qu(this.runAndExtendWithFaceDetection(),this.input)}withAgeAndGender(){return new Ju(this.runAndExtendWithFaceDetection(),this.input)}}function wQ(r,l=new Ii){return new vx(r,l)}function Ag(r,l=new Ii){return new Tg(r,l)}async function MD(r,l){return console.warn("allFacesSsdMobilenetv1 is deprecated and will be removed soon, use the high level api instead"),await Ag(r,new Ii(l?{minConfidence:l}:{})).withFaceLandmarks().withFaceDescriptors()}async function LQ(r,l={}){return console.warn("allFacesTinyYolov2 is deprecated and will be removed soon, use the high level api instead"),await Ag(r,new Cr(l)).withFaceLandmarks().withFaceDescriptors()}const SQ=MD;function Nx(r,l){if(r.length!==l.length)throw new Error("euclideanDistance: arr1.length !== arr2.length");const h=Array.from(r),d=Array.from(l);return Math.sqrt(h.map((f,g)=>f-d[g]).reduce((f,g)=>f+Math.pow(g,2),0))}class PD{constructor(r,l=.6){this._distanceThreshold=l;const h=Array.isArray(r)?r:[r];if(!h.length)throw new Error("FaceRecognizer.constructor - expected atleast one input");let d=1;const f=()=>`person ${d++}`;this._labeledDescriptors=h.map(g=>{if(g instanceof na)return g;if(g instanceof Float32Array)return new na(f(),[g]);if(g.descriptor&&g.descriptor instanceof Float32Array)return new na(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(h=>Nx(h,r)).reduce((h,d)=>h+d,0)/(l.length||1)}matchDescriptor(r){return this.labeledDescriptors.map(({descriptors:l,label:h})=>new km(h,this.computeMeanDistance(r,l))).reduce((l,h)=>l.distance<h.distance?l:h)}findBestMatch(r){const l=this.matchDescriptor(r);return l.distance<this.distanceThreshold?l:new km("unknown",l.distance)}toJSON(){return{distanceThreshold:this.distanceThreshold,labeledDescriptors:this.labeledDescriptors.map(r=>r.toJSON())}}static fromJSON(r){const l=r.labeledDescriptors.map(h=>na.fromJSON(h));return new PD(l,r.distanceThreshold)}}function IQ(r){const l=new Ku;return l.extractWeights(r),l}function zD(r,l){const{width:h,height:d}=new ms(l.width,l.height);if(h<=0||d<=0)throw new Error(`resizeResults - invalid dimensions: ${JSON.stringify({width:h,height:d})}`);if(Array.isArray(r))return r.map(f=>zD(f,{width:h,height:d}));if(ba(r)){const f=r.detection.forSize(h,d),g=r.unshiftedLandmarks.forSize(f.box.width,f.box.height);return el(sa(r,f),g)}return Vi(r)?sa(r,r.detection.forSize(h,d)):r instanceof qs||r instanceof Yt?r.forSize(h,d):r}var GD="0.8.3";vc(exports,{AgeGenderNet:()=>dx,BoundingBox:()=>wu,Box:()=>Ct,ComposableTask:()=>Ti,ComputeAllFaceDescriptorsTask:()=>Sa,ComputeFaceDescriptorsTaskBase:()=>Sx,ComputeSingleFaceDescriptorTask:()=>Ia,DetectAllFaceLandmarksTask:()=>xx,DetectAllFacesTask:()=>Tg,DetectFaceLandmarksTaskBase:()=>Ix,DetectFacesTaskBase:()=>Ax,DetectSingleFaceLandmarksTask:()=>Tx,DetectSingleFaceTask:()=>vx,Dimensions:()=>ms,FACE_EXPRESSION_LABELS:()=>ax,FaceDetection:()=>Yt,FaceDetectionNet:()=>QZ,FaceExpressionNet:()=>cx,FaceExpressions:()=>ya,FaceLandmark68Net:()=>Gu,FaceLandmark68TinyNet:()=>px,FaceLandmarkNet:()=>UZ,FaceLandmarks:()=>qs,FaceLandmarks5:()=>BX,FaceLandmarks68:()=>Iu,FaceMatch:()=>km,FaceMatcher:()=>PD,FaceRecognitionNet:()=>Hu,Gender:()=>Tr,LabeledBox:()=>Fm,LabeledFaceDescriptors:()=>na,NetInput:()=>po,NeuralNetwork:()=>kn,ObjectDetection:()=>Oc,Point:()=>Ze,PredictedBox:()=>MX,Rect:()=>Su,SsdMobilenetv1:()=>nl,SsdMobilenetv1Options:()=>Ii,TinyFaceDetector:()=>Ku,TinyFaceDetectorOptions:()=>wx,TinyYolov2:()=>ju,TinyYolov2Options:()=>Cr,TinyYolov2SizeType:()=>bx,allFaces:()=>SQ,allFacesSsdMobilenetv1:()=>MD,allFacesTinyYolov2:()=>LQ,awaitMediaLoaded:()=>QS,bufferToImage:()=>eI,computeFaceDescriptor:()=>oQ,createCanvas:()=>Dc,createCanvasFromMedia:()=>Tu,createFaceDetectionNet:()=>ZZ,createFaceRecognitionNet:()=>PZ,createSsdMobilenetv1:()=>xD,createTinyFaceDetector:()=>IQ,createTinyYolov2:()=>nQ,detectAllFaces:()=>Ag,detectFaceLandmarks:()=>WD,detectFaceLandmarksTiny:()=>rQ,detectLandmarks:()=>bQ,detectSingleFace:()=>wQ,draw:()=>hx,env:()=>gt,euclideanDistance:()=>Nx,extendWithAge:()=>Sg,extendWithFaceDescriptor:()=>Lg,extendWithFaceDetection:()=>sa,extendWithFaceExpressions:()=>gg,extendWithFaceLandmarks:()=>el,extendWithGender:()=>Ig,extractFaceTensors:()=>qc,extractFaces:()=>Yc,fetchImage:()=>OZ,fetchJson:()=>ix,fetchNetWeights:()=>EZ,fetchOrThrow:()=>fa,getContext2dOrThrow:()=>es,getMediaDimensions:()=>ra,imageTensorToCanvas:()=>tI,imageToSquare:()=>sx,inverseSigmoid:()=>_X,iou:()=>zS,isMediaElement:()=>Um,isMediaLoaded:()=>xu,isWithAge:()=>zZ,isWithFaceDetection:()=>Vi,isWithFaceExpressions:()=>lx,isWithFaceLandmarks:()=>ba,isWithGender:()=>GZ,loadAgeGenderModel:()=>fQ,loadFaceDetectionModel:()=>gQ,loadFaceExpressionModel:()=>mQ,loadFaceLandmarkModel:()=>uQ,loadFaceLandmarkTinyModel:()=>dQ,loadFaceRecognitionModel:()=>pQ,loadSsdMobilenetv1Model:()=>$D,loadTinyFaceDetectorModel:()=>lQ,loadTinyYolov2Model:()=>hQ,loadWeightMap:()=>rx,locateFaces:()=>yQ,matchDimensions:()=>DZ,minBbox:()=>GS,nets:()=>pt,nonMaxSuppression:()=>VS,normalize:()=>yi,padToSquare:()=>HS,predictAgeAndGender:()=>cQ,recognizeFaceExpressions:()=>aQ,resizeResults:()=>zD,resolveInput:()=>ia,shuffleArray:()=>FX,sigmoid:()=>Lu,ssdMobilenetv1:()=>_D,tf:()=>xQ,tinyFaceDetector:()=>sQ,tinyYolov2:()=>iQ,toNetInput:()=>Rt,utils:()=>US,validateConfig:()=>gx,version:()=>vQ});const xQ=Ye(Je()),TQ=typeof process!="undefined",AQ=typeof navigator!="undefined"&&typeof navigator.userAgent!="undefined",vQ={faceapi:GD,node:TQ,browser:AQ};
/**
* @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