>>15,m^=m<<4,m^=m>>>13,g>=0&&(y=y+1640531527|0,h=b[g&127]^=m+y,f=h==0?f+1:0);for(f>=128&&(b[(c&&c.length||0)&127]=-1),f=127,g=4*128;g>0;--g)m=b[f+34&127],h=b[f=f+1&127],m^=m<<13,h^=h<<17,m^=m>>>15,h^=h>>>12,b[f]=m^h;d.w=y,d.X=b,d.i=f}p(u,l)}function i(l,u){return u.i=l.i,u.w=l.w,u.X=l.X.slice(),u}function o(l,u){l==null&&(l=+new Date);var p=new s(l),d=u&&u.state,c=function(){return(p.next()>>>0)/4294967296};return c.double=function(){do var h=p.next()>>>11,m=(p.next()>>>0)/4294967296,f=(h+m)/(1<<21);while(f===0);return f},c.int32=p.next,c.quick=c,d&&(d.X&&i(d,p),c.state=function(){return i(p,{})}),c}a&&a.exports?a.exports=o:r&&r.amd?r(function(){return o}):this.xor4096=o})(e,typeof t=="object"&&t,typeof define=="function"&&define)}),bF=Bt((e,t)=>{(function(n,a,r){function s(l){var u=this,p="";u.next=function(){var c=u.b,h=u.c,m=u.d,f=u.a;return c=c<<25^c>>>7^h,h=h-m|0,m=m<<24^m>>>8^f,f=f-c|0,u.b=c=c<<20^c>>>12^h,u.c=h=h-m|0,u.d=m<<16^h>>>16^f,u.a=f-c|0},u.a=0,u.b=0,u.c=-1640531527,u.d=1367130551,l===Math.floor(l)?(u.a=l/4294967296|0,u.b=l|0):p+=l;for(var d=0;d>>0)/4294967296};return c.double=function(){do var h=p.next()>>>11,m=(p.next()>>>0)/4294967296,f=(h+m)/(1<<21);while(f===0);return f},c.int32=p.next,c.quick=c,d&&(typeof d=="object"&&i(d,p),c.state=function(){return i(p,{})}),c}a&&a.exports?a.exports=o:r&&r.amd?r(function(){return o}):this.tychei=o})(e,typeof t=="object"&&t,typeof define=="function"&&define)}),xF=Bt(()=>{}),vF=Bt((e,t)=>{(function(n,a,r){var s=256,i=6,o=52,l="random",u=r.pow(s,i),p=r.pow(2,o),d=p*2,c=s-1,h;function m(I,T,C){var E=[];T=T==!0?{entropy:!0}:T||{};var A=b(y(T.entropy?[I,w(a)]:I==null?x():I,3),E),R=new f(E),F=function(){for(var S=R.g(i),M=u,B=0;S=d;)S/=2,M/=2,B>>>=1;return(S+B)/M};return F.int32=function(){return R.g(4)|0},F.quick=function(){return R.g(4)/4294967296},F.double=F,b(w(R.S),a),(T.pass||C||function(S,M,B,U){return U&&(U.S&&g(U,R),S.state=function(){return g(R,{})}),B?(r[l]=S,M):S})(F,A,"global"in T?T.global:this==r,T.state)}function f(I){var T,C=I.length,E=this,A=0,R=E.i=E.j=0,F=E.S=[];for(C||(I=[C++]);A{var n=hF(),a=mF(),r=fF(),s=gF(),i=yF(),o=bF(),l=vF();l.alea=n,l.xor128=a,l.xorwow=r,l.xorshift7=s,l.xor4096=i,l.tychei=o,t.exports=l}),wI=Bt(()=>{}),xx=Bt(()=>{}),dh=Bt(()=>{}),wF=Bt(()=>{}),kF=Bt(()=>{}),IF=Bt(()=>{}),SF=Bt((e,t)=>{var n=(()=>{var a=typeof document!="undefined"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename!="undefined"&&(a=a||__filename),function(r){r=r||{};function s(){return ue.buffer!=ze&&it(ue.buffer),dt}function i(){return ue.buffer!=ze&&it(ue.buffer),Hn}function o(){return ue.buffer!=ze&&it(ue.buffer),Mt}function l(){return ue.buffer!=ze&&it(ue.buffer),sn}function u(){return ue.buffer!=ze&&it(ue.buffer),Fn}function p(){return ue.buffer!=ze&&it(ue.buffer),ia}function d(){return ue.buffer!=ze&&it(ue.buffer),Dn}var c=typeof r!="undefined"?r:{},h,m;c.ready=new Promise(function(D,j){h=D,m=j});var f;typeof process!="undefined"&&process.listeners&&(f={uncaughtException:process.listeners("uncaughtException"),unhandledRejection:process.listeners("unhandledRejection")});var g=Object.assign({},c),y=[],b="./this.program",x=(D,j)=>{throw j},w=typeof window=="object",I=typeof importScripts=="function",T=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",C=c.ENVIRONMENT_IS_PTHREAD||!1,E="";function A(D){return c.locateFile?c.locateFile(D,E):E+D}var R,F,S,M;function B(D){D instanceof Rs||Q("exiting due to exception: "+D)}if(T){I?E=dh().dirname(E)+"/":E=__dirname+"/";var U,G;typeof vI=="function"&&(U=xx(),G=dh()),R=(j,re)=>(j=G.normalize(j),U.readFileSync(j,re?void 0:"utf8")),S=j=>{var re=R(j,!0);return re.buffer||(re=new Uint8Array(re)),re},F=(j,re,ce)=>{j=G.normalize(j),U.readFile(j,function(ke,je){ke?ce(ke):re(je.buffer)})},process.argv.length>1&&(b=process.argv[1].replace(/\\/g,"/")),y=process.argv.slice(2),process.on("uncaughtException",function(j){if(!(j instanceof Rs))throw j}),process.on("unhandledRejection",function(j){throw j}),x=(j,re)=>{if(wa())throw process.exitCode=j,re;B(re),process.exit(j)},c.inspect=function(){return"[Emscripten Module object]"};let D;try{D=wF()}catch(j){throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'),j}global.Worker=D.Worker}else(w||I)&&(I?E=self.location.href:typeof document!="undefined"&&document.currentScript&&(E=document.currentScript.src),typeof a!="undefined"&&a&&(E=a),E.indexOf("blob:")!==0?E=E.substr(0,E.replace(/[?#].*/,"").lastIndexOf("/")+1):E="",T||(R=D=>{var j=new XMLHttpRequest;return j.open("GET",D,!1),j.send(null),j.responseText},I&&(S=D=>{var j=new XMLHttpRequest;return j.open("GET",D,!1),j.responseType="arraybuffer",j.send(null),new Uint8Array(j.response)}),F=(D,j,re)=>{var ce=new XMLHttpRequest;ce.open("GET",D,!0),ce.responseType="arraybuffer",ce.onload=()=>{if(ce.status==200||ce.status==0&&ce.response){j(ce.response);return}re()},ce.onerror=re,ce.send(null)}),M=D=>document.title=D);T&&typeof performance=="undefined"&&(global.performance=kF().performance);var q=console.log.bind(console),K=console.warn.bind(console);T&&(q=D=>U.writeSync(1,D+`
-`),K=D=>U.writeSync(2,D+`
-`));var Z=c.print||q,Q=c.printErr||K;Object.assign(c,g),g=null,c.arguments&&(y=c.arguments),c.thisProgram&&(b=c.thisProgram),c.quit&&(x=c.quit);var ee=4,ae=Atomics.load,te=Atomics.store,le=Atomics.compareExchange,ie;c.wasmBinary&&(ie=c.wasmBinary);var ye=c.noExitRuntime||!0;typeof WebAssembly!="object"&&Lo("no native wasm support detected");var ue,xe,Ie=!1,Se;function Le(D,j){D||Lo(j)}var Ve=typeof TextDecoder!="undefined"?new TextDecoder("utf8"):void 0;function nt(D,j,re){for(var ce=j+re,ke=j;D[ke]&&!(ke>=ce);)++ke;if(ke-j>16&&D.buffer&&Ve)return Ve.decode(D.buffer instanceof SharedArrayBuffer?D.slice(j,ke):D.subarray(j,ke));for(var je="";j>10,56320|la&1023)}}return je}function st(D,j){return D?nt(i(),D,j):""}function Je(D,j,re,ce){if(!(ce>0))return 0;for(var ke=re,je=re+ce-1,Ce=0;Ce=55296&&De<=57343){var Ot=D.charCodeAt(++Ce);De=65536+((De&1023)<<10)|Ot&1023}if(De<=127){if(re>=je)break;j[re++]=De}else if(De<=2047){if(re+1>=je)break;j[re++]=192|De>>6,j[re++]=128|De&63}else if(De<=65535){if(re+2>=je)break;j[re++]=224|De>>12,j[re++]=128|De>>6&63,j[re++]=128|De&63}else{if(re+3>=je)break;j[re++]=240|De>>18,j[re++]=128|De>>12&63,j[re++]=128|De>>6&63,j[re++]=128|De&63}}return j[re]=0,re-ke}function at(D,j,re){return Je(D,i(),j,re)}var ze,dt,Hn,Mt,sa,sn,Fn,ia,Dn;C&&(ze=c.buffer);function it(D){ze=D,c.HEAP8=dt=new Int8Array(D),c.HEAP16=Mt=new Int16Array(D),c.HEAP32=sn=new Int32Array(D),c.HEAPU8=Hn=new Uint8Array(D),c.HEAPU16=sa=new Uint16Array(D),c.HEAPU32=Fn=new Uint32Array(D),c.HEAPF32=ia=new Float32Array(D),c.HEAPF64=Dn=new Float64Array(D)}var Rn=c.INITIAL_MEMORY||16777216;if(C)ue=c.wasmMemory,ze=c.buffer;else if(c.wasmMemory)ue=c.wasmMemory;else if(ue=new WebAssembly.Memory({initial:Rn/65536,maximum:32768,shared:!0}),!(ue.buffer instanceof SharedArrayBuffer))throw Q("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),T&&console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"),Error("bad memory");ue&&(ze=ue.buffer),Rn=ze.byteLength,it(ze);var jn,gr=[],Mo=[],Ja=[],mp=!1;function wa(){return ye}function Po(){if(c.preRun)for(typeof c.preRun=="function"&&(c.preRun=[c.preRun]);c.preRun.length;)bg(c.preRun.shift());bp(gr)}function Xt(){mp=!0,!C&&bp(Mo)}function bd(){if(!C){if(c.postRun)for(typeof c.postRun=="function"&&(c.postRun=[c.postRun]);c.postRun.length;)I1(c.postRun.shift());bp(Ja)}}function bg(D){gr.unshift(D)}function xg(D){Mo.unshift(D)}function I1(D){Ja.unshift(D)}var Br=0,Oo=null,yr=null;function S1(D){Br++,c.monitorRunDependencies&&c.monitorRunDependencies(Br)}function T1(D){if(Br--,c.monitorRunDependencies&&c.monitorRunDependencies(Br),Br==0&&(Oo!==null&&(clearInterval(Oo),Oo=null),yr)){var j=yr;yr=null,j()}}function Lo(D){C?postMessage({cmd:"onAbort",arg:D}):c.onAbort&&c.onAbort(D),D="Aborted("+D+")",Q(D),Ie=!0,Se=1,D+=". Build with -sASSERTIONS for more info.";var j=new WebAssembly.RuntimeError(D);throw m(j),j}var vg="data:application/octet-stream;base64,";function xd(D){return D.startsWith(vg)}function fp(D){return D.startsWith("file://")}var yn;yn="tfjs-backend-wasm-threaded-simd.wasm",xd(yn)||(yn=A(yn));function vd(D){try{if(D==yn&&ie)return new Uint8Array(ie);if(S)return S(D);throw"both async and sync fetching of the wasm failed"}catch(j){Lo(j)}}function wg(){if(!ie&&(w||I)){if(typeof fetch=="function"&&!fp(yn))return fetch(yn,{credentials:"same-origin"}).then(function(D){if(!D.ok)throw"failed to load wasm binary file at '"+yn+"'";return D.arrayBuffer()}).catch(function(){return vd(yn)});if(F)return new Promise(function(D,j){F(yn,function(re){D(new Uint8Array(re))},j)})}return Promise.resolve().then(function(){return vd(yn)})}function kg(){var D={env:Fd,wasi_snapshot_preview1:Fd};function j(Ce,De){var Ot=Ce.exports;if(c.asm=Ot,Fg(c.asm._emscripten_tls_init),jn=c.asm.__indirect_function_table,xg(c.asm.__wasm_call_ctors),xe=De,!C){var la=$e.unusedWorkers.length;$e.unusedWorkers.forEach(function(xr){$e.loadWasmModuleToWorker(xr,function(){--la||T1("wasm-instantiate")})})}}C||S1("wasm-instantiate");function re(Ce){j(Ce.instance,Ce.module)}function ce(Ce){return wg().then(function(De){return WebAssembly.instantiate(De,D)}).then(function(De){return De}).then(Ce,function(De){Q("failed to asynchronously prepare wasm: "+De),Lo(De)})}function ke(){return!ie&&typeof WebAssembly.instantiateStreaming=="function"&&!xd(yn)&&!fp(yn)&&!T&&typeof fetch=="function"?fetch(yn,{credentials:"same-origin"}).then(function(Ce){var De=WebAssembly.instantiateStreaming(Ce,D);return De.then(re,function(Ot){return Q("wasm streaming compile failed: "+Ot),Q("falling back to ArrayBuffer instantiation"),ce(re)})}):ce(re)}if(c.instantiateWasm)try{var je=c.instantiateWasm(D,j);return je}catch(Ce){Q("Module.instantiateWasm callback failed with error: "+Ce),m(Ce)}return ke().catch(m),{}}var Ig,N1,Sg={};function Rs(D){this.name="ExitStatus",this.message="Program terminated with exit("+D+")",this.status=D}function Tg(D){var j=$e.pthreads[D];delete $e.pthreads[D],j.terminate(),eb(D),$e.runningWorkers.splice($e.runningWorkers.indexOf(j),1),j.pthread_ptr=0}function Ng(D){var j=$e.pthreads[D];j.postMessage({cmd:"cancel"})}function gp(D){var j=$e.pthreads[D];Le(j),$e.returnWorkerToPool(j)}function wd(D){var j=$e.getNewWorker();if(!j)return 6;$e.runningWorkers.push(j),$e.pthreads[D.pthread_ptr]=j,j.pthread_ptr=D.pthread_ptr;var re={cmd:"run",start_routine:D.startRoutine,arg:D.arg,pthread_ptr:D.pthread_ptr};return j.runPthread=()=>{re.time=performance.now(),j.postMessage(re,D.transferList)},j.loaded&&(j.runPthread(),delete j.runPthread),0}var kd={varargs:void 0,get:function(){kd.varargs+=4;var D=l()[kd.varargs-4>>2];return D},getStr:function(D){var j=st(D);return j}};function yp(D){if(C)return Vr(1,1,D);Se=D,wa()||($e.terminateAllThreads(),c.onExit&&c.onExit(D),Ie=!0),x(D,new Rs(D))}function C1(D,j){if(Se=D,!j&&C)throw Sd(D),"unwind";yp(D)}var Id=C1;function Cg(D){if(D instanceof Rs||D=="unwind")return Se;x(1,D)}var $e={unusedWorkers:[],runningWorkers:[],tlsInitFunctions:[],pthreads:{},init:function(){C?$e.initWorker():$e.initMainThread()},initMainThread:function(){for(var D=8;D--;)$e.allocateUnusedWorker()},initWorker:function(){ye=!1},setExitStatus:function(D){Se=D},terminateAllThreads:function(){for(var D of Object.values($e.pthreads))$e.returnWorkerToPool(D);for(var D of $e.unusedWorkers)D.terminate();$e.unusedWorkers=[]},returnWorkerToPool:function(D){var j=D.pthread_ptr;delete $e.pthreads[j],$e.unusedWorkers.push(D),$e.runningWorkers.splice($e.runningWorkers.indexOf(D),1),D.pthread_ptr=0,eb(j)},receiveObjectTransfer:function(D){},threadInitTLS:function(){$e.tlsInitFunctions.forEach(D=>D())},loadWasmModuleToWorker:function(D,j){D.onmessage=re=>{var ce=re.data,ke=ce.cmd;if(D.pthread_ptr&&($e.currentProxiedOperationCallerThread=D.pthread_ptr),ce.targetThread&&ce.targetThread!=Ld()){var je=$e.pthreads[ce.targetThread];je?je.postMessage(ce,ce.transferList):Q('Internal error! Worker sent a message "'+ke+'" to target pthread '+ce.targetThread+", but that thread no longer exists!"),$e.currentProxiedOperationCallerThread=void 0;return}ke==="processProxyingQueue"?xp(ce.queue):ke==="spawnThread"?wd(ce):ke==="cleanupThread"?gp(ce.thread):ke==="killThread"?Tg(ce.thread):ke==="cancelThread"?Ng(ce.thread):ke==="loaded"?(D.loaded=!0,j&&j(D),D.runPthread&&(D.runPthread(),delete D.runPthread)):ke==="print"?Z("Thread "+ce.threadId+": "+ce.text):ke==="printErr"?Q("Thread "+ce.threadId+": "+ce.text):ke==="alert"?alert("Thread "+ce.threadId+": "+ce.text):ce.target==="setimmediate"?D.postMessage(ce):ke==="onAbort"?c.onAbort&&c.onAbort(ce.arg):ke&&Q("worker sent an unknown command "+ke),$e.currentProxiedOperationCallerThread=void 0},D.onerror=re=>{var ce="worker sent an error!";throw Q(ce+" "+re.filename+":"+re.lineno+": "+re.message),re},T&&(D.on("message",function(re){D.onmessage({data:re})}),D.on("error",function(re){D.onerror(re)}),D.on("detachedExit",function(){})),D.postMessage({cmd:"load",urlOrBlob:c.mainScriptUrlOrBlob||a,wasmMemory:ue,wasmModule:xe})},allocateUnusedWorker:function(){var D=A("tfjs-backend-wasm-threaded-simd.worker.js");$e.unusedWorkers.push(new Worker(D))},getNewWorker:function(){return $e.unusedWorkers.length==0&&($e.allocateUnusedWorker(),$e.loadWasmModuleToWorker($e.unusedWorkers[0])),$e.unusedWorkers.pop()}};c.PThread=$e;function bp(D){for(;D.length>0;)D.shift()(c)}function _g(D){var j=tb(),re=D();return zd(j),re}function _1(D){return D}function E1(D){var j=/\b_Z[\w\d_]+/g;return D.replace(j,function(re){var ce=re;return re===ce?re:ce+" ["+re+"]"})}function Eg(){var D=Ld(),j=l()[D+44>>2],re=l()[D+48>>2],ce=j-re;P1(j,ce),zd(j)}c.establishStackSpace=Eg;function Sd(D){if(C)return Vr(2,0,D);try{Id(D)}catch(j){Cg(j)}}var zo=[];function Ag(D){var j=zo[D];return j||(D>=zo.length&&(zo.length=D+1),zo[D]=j=jn.get(D)),j}function $g(D,j){var re=Ag(D)(j);wa()?$e.setExitStatus(re):M1(re)}c.invokeEntryPoint=$g;function A1(){var D=new Error;if(!D.stack){try{throw new Error}catch(j){D=j}if(!D.stack)return"(no stack trace available)"}return D.stack.toString()}function Fg(D){$e.tlsInitFunctions.push(D)}function Dg(D,j){s().set(D,j)}function Rg(D){F1(D,!I,1,!w),$e.threadInitTLS()}function Mg(D){C?postMessage({cmd:"cleanupThread",thread:D}):gp(D)}function Td(D,j,re,ce){return C?Vr(3,1,D,j,re,ce):Nd(D,j,re,ce)}function Nd(D,j,re,ce){if(typeof SharedArrayBuffer=="undefined")return Q("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var ke=[],je=0;if(C&&(ke.length===0||je))return Td(D,j,re,ce);if(je)return je;var Ce={startRoutine:re,pthread_ptr:D,arg:ce,transferList:ke};return C?(Ce.cmd="spawnThread",postMessage(Ce,ke),0):wd(Ce)}function Pg(){return 2097152}var Og=!0;function Lg(){return Og}function xp(D){Atomics.store(l(),D>>2,1),Ld()&&R1(D),Atomics.compareExchange(l(),D>>2,1,0)}c.executeNotifiedProxyingQueue=xp;function zg(D,j,re,ce){if(D==j)setTimeout(()=>xp(ce));else if(C)postMessage({targetThread:D,cmd:"processProxyingQueue",queue:ce});else{var ke=$e.pthreads[D];if(!ke)return;ke.postMessage({cmd:"processProxyingQueue",queue:ce})}return 1}function Wg(D,j,re){return-1}function Bg(){Lo("")}function Ms(D){Ms.shown||(Ms.shown={}),Ms.shown[D]||(Ms.shown[D]=1,T&&(D="warning: "+D),Q(D))}function Vg(){T||I||Ms("Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread")}function Ug(){return Date.now()}function Cd(){return 2147483648}function Gg(){return Cd()}var Wo;T?Wo=()=>{var D=process.hrtime();return D[0]*1e3+D[1]/1e6}:C?Wo=()=>performance.now()-c.__performance_now_clock_drift:Wo=()=>performance.now();function Hg(D,j,re){i().copyWithin(D,j,j+re)}function jg(){return T?IF().cpus().length:navigator.hardwareConcurrency}function Vr(D,j){var re=arguments.length-2,ce=arguments;return _g(()=>{for(var ke=re,je=Wd(ke*8),Ce=je>>3,De=0;De>3,ke=0;ke>>16),it(ue.buffer),1}catch(j){}}function Xg(D){var j=i().length;if(D=D>>>0,D<=j)return!1;var re=Cd();if(D>re)return!1;let ce=(Ot,la)=>Ot+(la-Ot%la)%la;for(var ke=1;ke<=4;ke*=2){var je=j*(1+.2/ke);je=Math.min(je,D+100663296);var Ce=Math.min(re,ce(Math.max(D,je),65536)),De=Kg(Ce);if(De)return!0}return!1}function Yg(){throw"unwind"}function _d(D){return C?Vr(4,1,D):52}function Ed(D,j,re,ce,ke){return C?Vr(5,1,D,j,re,ce,ke):70}var Zg=[null,[],[]];function Jg(D,j){var re=Zg[D];j===0||j===10?((D===1?Z:Q)(nt(re,0)),re.length=0):re.push(j)}function Ad(D,j,re,ce){if(C)return Vr(6,1,D,j,re,ce);for(var ke=0,je=0;je>2],De=u()[j+4>>2];j+=8;for(var Ot=0;Ot>2]=ke,0}function $d(D){var j=c["_"+D];return j}function Qg(D,j,re,ce,ke){var je={string:ua=>{var Go=0;if(ua!=null&&ua!==0){var z1=(ua.length<<2)+1;Go=Wd(z1),at(ua,Go,z1)}return Go},array:ua=>{var Go=Wd(ua.length);return Dg(ua,Go),Go}};function Ce(ua){return j==="string"?st(ua):j==="boolean"?Boolean(ua):ua}var De=$d(D),Ot=[],la=0;if(ce)for(var xr=0;xrCe==="number"||Ce==="boolean"),je=j!=="string";return je&&ke&&!ce?$d(D):function(){return Qg(D,j,re,arguments,ce)}}$e.init();var ty=[null,yp,Sd,Td,_d,Ed,Ad],Fd={__emscripten_init_main_thread_js:Rg,__emscripten_thread_cleanup:Mg,__pthread_create_js:Nd,_emscripten_default_pthread_stack_size:Pg,_emscripten_get_now_is_monotonic:Lg,_emscripten_notify_task_queue:zg,_emscripten_set_offscreencanvas_size:Wg,abort:Bg,emscripten_check_blocking_allowed:Vg,emscripten_date_now:Ug,emscripten_get_heap_max:Gg,emscripten_get_now:Wo,emscripten_memcpy_big:Hg,emscripten_num_logical_cores:jg,emscripten_receive_on_main_thread_js:qg,emscripten_resize_heap:Xg,emscripten_unwind_to_js_event_loop:Yg,exit:Id,fd_close:_d,fd_seek:Ed,fd_write:Ad,memory:ue||c.wasmMemory},$1=kg(),ny=c.___wasm_call_ctors=function(){return(ny=c.___wasm_call_ctors=c.asm.__wasm_call_ctors).apply(null,arguments)},ay=c._init=function(){return(ay=c._init=c.asm.init).apply(null,arguments)},ry=c._init_with_threads_count=function(){return(ry=c._init_with_threads_count=c.asm.init_with_threads_count).apply(null,arguments)},sy=c._get_threads_count=function(){return(sy=c._get_threads_count=c.asm.get_threads_count).apply(null,arguments)},iy=c._register_tensor=function(){return(iy=c._register_tensor=c.asm.register_tensor).apply(null,arguments)},oy=c._dispose_data=function(){return(oy=c._dispose_data=c.asm.dispose_data).apply(null,arguments)},ly=c._dispose=function(){return(ly=c._dispose=c.asm.dispose).apply(null,arguments)},uy=c._Abs=function(){return(uy=c._Abs=c.asm.Abs).apply(null,arguments)},py=c._Add=function(){return(py=c._Add=c.asm.Add).apply(null,arguments)},cy=c._AddN=function(){return(cy=c._AddN=c.asm.AddN).apply(null,arguments)},dy=c._All=function(){return(dy=c._All=c.asm.All).apply(null,arguments)},hy=c._Any=function(){return(hy=c._Any=c.asm.Any).apply(null,arguments)},my=c._ArgMax=function(){return(my=c._ArgMax=c.asm.ArgMax).apply(null,arguments)},fy=c._AvgPool=function(){return(fy=c._AvgPool=c.asm.AvgPool).apply(null,arguments)},gy=c._BatchMatMul=function(){return(gy=c._BatchMatMul=c.asm.BatchMatMul).apply(null,arguments)},yy=c._Ceil=function(){return(yy=c._Ceil=c.asm.Ceil).apply(null,arguments)},by=c._ClipByValue=function(){return(by=c._ClipByValue=c.asm.ClipByValue).apply(null,arguments)},xy=c._Conv2D=function(){return(xy=c._Conv2D=c.asm.Conv2D).apply(null,arguments)},vy=c._Conv2DBackpropInput=function(){return(vy=c._Conv2DBackpropInput=c.asm.Conv2DBackpropInput).apply(null,arguments)},wy=c._Cos=function(){return(wy=c._Cos=c.asm.Cos).apply(null,arguments)},ky=c._Cosh=function(){return(ky=c._Cosh=c.asm.Cosh).apply(null,arguments)},Iy=c._CropAndResize=function(){return(Iy=c._CropAndResize=c.asm.CropAndResize).apply(null,arguments)},Sy=c._Cumprod=function(){return(Sy=c._Cumprod=c.asm.Cumprod).apply(null,arguments)},Ty=c._Cumsum=function(){return(Ty=c._Cumsum=c.asm.Cumsum).apply(null,arguments)},Ny=c._DepthToSpace=function(){return(Ny=c._DepthToSpace=c.asm.DepthToSpace).apply(null,arguments)},Cy=c._DepthwiseConv2dNative=function(){return(Cy=c._DepthwiseConv2dNative=c.asm.DepthwiseConv2dNative).apply(null,arguments)},_y=c._Elu=function(){return(_y=c._Elu=c.asm.Elu).apply(null,arguments)},Ey=c._Equal=function(){return(Ey=c._Equal=c.asm.Equal).apply(null,arguments)},Ay=c._Exp=function(){return(Ay=c._Exp=c.asm.Exp).apply(null,arguments)},$y=c._FlipLeftRight=function(){return($y=c._FlipLeftRight=c.asm.FlipLeftRight).apply(null,arguments)},Fy=c._Floor=function(){return(Fy=c._Floor=c.asm.Floor).apply(null,arguments)},Dy=c._FloorDiv=function(){return(Dy=c._FloorDiv=c.asm.FloorDiv).apply(null,arguments)},Ry=c._FusedBatchNorm=function(){return(Ry=c._FusedBatchNorm=c.asm.FusedBatchNorm).apply(null,arguments)},My=c._FusedConv2D=function(){return(My=c._FusedConv2D=c.asm.FusedConv2D).apply(null,arguments)},Py=c._FusedDepthwiseConv2D=function(){return(Py=c._FusedDepthwiseConv2D=c.asm.FusedDepthwiseConv2D).apply(null,arguments)},Oy=c._Gather=function(){return(Oy=c._Gather=c.asm.Gather).apply(null,arguments)},Ly=c._GatherNd=function(){return(Ly=c._GatherNd=c.asm.GatherNd).apply(null,arguments)},zy=c._Greater=function(){return(zy=c._Greater=c.asm.Greater).apply(null,arguments)},Wy=c._GreaterEqual=function(){return(Wy=c._GreaterEqual=c.asm.GreaterEqual).apply(null,arguments)},By=c._LeakyRelu=function(){return(By=c._LeakyRelu=c.asm.LeakyRelu).apply(null,arguments)},Vy=c._Less=function(){return(Vy=c._Less=c.asm.Less).apply(null,arguments)},Uy=c._LessEqual=function(){return(Uy=c._LessEqual=c.asm.LessEqual).apply(null,arguments)},Gy=c._Log=function(){return(Gy=c._Log=c.asm.Log).apply(null,arguments)},Hy=c._LogicalAnd=function(){return(Hy=c._LogicalAnd=c.asm.LogicalAnd).apply(null,arguments)},jy=c._LogicalNot=function(){return(jy=c._LogicalNot=c.asm.LogicalNot).apply(null,arguments)},qy=c._LogicalOr=function(){return(qy=c._LogicalOr=c.asm.LogicalOr).apply(null,arguments)},Ky=c._LogicalXor=function(){return(Ky=c._LogicalXor=c.asm.LogicalXor).apply(null,arguments)},Xy=c._Max=function(){return(Xy=c._Max=c.asm.Max).apply(null,arguments)},Dd=c._MaxPool=function(){return(Dd=c._MaxPool=c.asm.MaxPool).apply(null,arguments)},Rd=c._Maximum=function(){return(Rd=c._Maximum=c.asm.Maximum).apply(null,arguments)},wp=c._Mean=function(){return(wp=c._Mean=c.asm.Mean).apply(null,arguments)},Yy=c._Min=function(){return(Yy=c._Min=c.asm.Min).apply(null,arguments)},Zy=c._Minimum=function(){return(Zy=c._Minimum=c.asm.Minimum).apply(null,arguments)},Bo=c._MirrorPad=function(){return(Bo=c._MirrorPad=c.asm.MirrorPad).apply(null,arguments)},Md=c._Multiply=function(){return(Md=c._Multiply=c.asm.Multiply).apply(null,arguments)},Vo=c._Neg=function(){return(Vo=c._Neg=c.asm.Neg).apply(null,arguments)},Uo=c._NonMaxSuppressionV3=function(){return(Uo=c._NonMaxSuppressionV3=c.asm.NonMaxSuppressionV3).apply(null,arguments)},Jy=c._NonMaxSuppressionV4=function(){return(Jy=c._NonMaxSuppressionV4=c.asm.NonMaxSuppressionV4).apply(null,arguments)},X=c._NonMaxSuppressionV5=function(){return(X=c._NonMaxSuppressionV5=c.asm.NonMaxSuppressionV5).apply(null,arguments)},se=c._NotEqual=function(){return(se=c._NotEqual=c.asm.NotEqual).apply(null,arguments)},we=c._OneHot=function(){return(we=c._OneHot=c.asm.OneHot).apply(null,arguments)},He=c._PadV2=function(){return(He=c._PadV2=c.asm.PadV2).apply(null,arguments)},wt=c._Pow=function(){return(wt=c._Pow=c.asm.Pow).apply(null,arguments)},kt=c._Prelu=function(){return(kt=c._Prelu=c.asm.Prelu).apply(null,arguments)},Ue=c._Prod=function(){return(Ue=c._Prod=c.asm.Prod).apply(null,arguments)},We=c._RealDiv=function(){return(We=c._RealDiv=c.asm.RealDiv).apply(null,arguments)},Pt=c._Relu=function(){return(Pt=c._Relu=c.asm.Relu).apply(null,arguments)},oa=c._Relu6=function(){return(oa=c._Relu6=c.asm.Relu6).apply(null,arguments)},br=c._ResizeBilinear=function(){return(br=c._ResizeBilinear=c.asm.ResizeBilinear).apply(null,arguments)},Pd=c._ResizeNearestNeighbor=function(){return(Pd=c._ResizeNearestNeighbor=c.asm.ResizeNearestNeighbor).apply(null,arguments)},kp=c._Reverse=function(){return(kp=c._Reverse=c.asm.Reverse).apply(null,arguments)},Qy=c._RotateWithOffset=function(){return(Qy=c._RotateWithOffset=c.asm.RotateWithOffset).apply(null,arguments)},Mn=c._Round=function(){return(Mn=c._Round=c.asm.Round).apply(null,arguments)},Ur=c._Rsqrt=function(){return(Ur=c._Rsqrt=c.asm.Rsqrt).apply(null,arguments)},Od=c._ScatterNd=function(){return(Od=c._ScatterNd=c.asm.ScatterNd).apply(null,arguments)},S$=c._SelectV2=function(){return(S$=c._SelectV2=c.asm.SelectV2).apply(null,arguments)},T$=c._Sigmoid=function(){return(T$=c._Sigmoid=c.asm.Sigmoid).apply(null,arguments)},N$=c._Sin=function(){return(N$=c._Sin=c.asm.Sin).apply(null,arguments)},C$=c._Softmax=function(){return(C$=c._Softmax=c.asm.Softmax).apply(null,arguments)},_$=c._SparseFillEmptyRows=function(){return(_$=c._SparseFillEmptyRows=c.asm.SparseFillEmptyRows).apply(null,arguments)},E$=c._SparseReshape=function(){return(E$=c._SparseReshape=c.asm.SparseReshape).apply(null,arguments)},A$=c._SparseSegmentReduction=function(){return(A$=c._SparseSegmentReduction=c.asm.SparseSegmentReduction).apply(null,arguments)},$$=c._Sqrt=function(){return($$=c._Sqrt=c.asm.Sqrt).apply(null,arguments)},F$=c._Square=function(){return(F$=c._Square=c.asm.Square).apply(null,arguments)},D$=c._SquaredDifference=function(){return(D$=c._SquaredDifference=c.asm.SquaredDifference).apply(null,arguments)},R$=c._Step=function(){return(R$=c._Step=c.asm.Step).apply(null,arguments)},M$=c._StridedSlice=function(){return(M$=c._StridedSlice=c.asm.StridedSlice).apply(null,arguments)},P$=c._Sub=function(){return(P$=c._Sub=c.asm.Sub).apply(null,arguments)},O$=c._Sum=function(){return(O$=c._Sum=c.asm.Sum).apply(null,arguments)},L$=c._Tan=function(){return(L$=c._Tan=c.asm.Tan).apply(null,arguments)},z$=c._Tanh=function(){return(z$=c._Tanh=c.asm.Tanh).apply(null,arguments)},W$=c._Tile=function(){return(W$=c._Tile=c.asm.Tile).apply(null,arguments)},B$=c._TopK=function(){return(B$=c._TopK=c.asm.TopK).apply(null,arguments)},V$=c._Transform=function(){return(V$=c._Transform=c.asm.Transform).apply(null,arguments)},U$=c._Transpose=function(){return(U$=c._Transpose=c.asm.Transpose).apply(null,arguments)},G$=c.__FusedMatMul=function(){return(G$=c.__FusedMatMul=c.asm._FusedMatMul).apply(null,arguments)},H$=c._malloc=function(){return(H$=c._malloc=c.asm.malloc).apply(null,arguments)},j$=c._free=function(){return(j$=c._free=c.asm.free).apply(null,arguments)},q$=c.__emscripten_tls_init=function(){return(q$=c.__emscripten_tls_init=c.asm._emscripten_tls_init).apply(null,arguments)},Ld=c._pthread_self=function(){return(Ld=c._pthread_self=c.asm.pthread_self).apply(null,arguments)},K$=c.___errno_location=function(){return(K$=c.___errno_location=c.asm.__errno_location).apply(null,arguments)},F1=c.__emscripten_thread_init=function(){return(F1=c.__emscripten_thread_init=c.asm._emscripten_thread_init).apply(null,arguments)},X$=c.__emscripten_thread_crashed=function(){return(X$=c.__emscripten_thread_crashed=c.asm._emscripten_thread_crashed).apply(null,arguments)},Y$=c._emscripten_main_thread_process_queued_calls=function(){return(Y$=c._emscripten_main_thread_process_queued_calls=c.asm.emscripten_main_thread_process_queued_calls).apply(null,arguments)},Z$=c._emscripten_main_browser_thread_id=function(){return(Z$=c._emscripten_main_browser_thread_id=c.asm.emscripten_main_browser_thread_id).apply(null,arguments)},D1=c._emscripten_run_in_main_runtime_thread_js=function(){return(D1=c._emscripten_run_in_main_runtime_thread_js=c.asm.emscripten_run_in_main_runtime_thread_js).apply(null,arguments)},J$=c._emscripten_dispatch_to_thread_=function(){return(J$=c._emscripten_dispatch_to_thread_=c.asm.emscripten_dispatch_to_thread_).apply(null,arguments)},R1=c.__emscripten_proxy_execute_task_queue=function(){return(R1=c.__emscripten_proxy_execute_task_queue=c.asm._emscripten_proxy_execute_task_queue).apply(null,arguments)},eb=c.__emscripten_thread_free_data=function(){return(eb=c.__emscripten_thread_free_data=c.asm._emscripten_thread_free_data).apply(null,arguments)},M1=c.__emscripten_thread_exit=function(){return(M1=c.__emscripten_thread_exit=c.asm._emscripten_thread_exit).apply(null,arguments)},P1=c._emscripten_stack_set_limits=function(){return(P1=c._emscripten_stack_set_limits=c.asm.emscripten_stack_set_limits).apply(null,arguments)},tb=c.stackSave=function(){return(tb=c.stackSave=c.asm.stackSave).apply(null,arguments)},zd=c.stackRestore=function(){return(zd=c.stackRestore=c.asm.stackRestore).apply(null,arguments)},Wd=c.stackAlloc=function(){return(Wd=c.stackAlloc=c.asm.stackAlloc).apply(null,arguments)},Q$=c.dynCall_iijjiiii=function(){return(Q$=c.dynCall_iijjiiii=c.asm.dynCall_iijjiiii).apply(null,arguments)},eF=c.dynCall_jiji=function(){return(eF=c.dynCall_jiji=c.asm.dynCall_jiji).apply(null,arguments)};c.keepRuntimeAlive=wa,c.wasmMemory=ue,c.cwrap=ey,c.ExitStatus=Rs,c.PThread=$e;var Bd;yr=function D(){Bd||O1(),Bd||(yr=D)};function O1(D){if(D=D||y,Br>0)return;if(C){h(c),Xt(),postMessage({cmd:"loaded"});return}if(Po(),Br>0)return;function j(){Bd||(Bd=!0,c.calledRun=!0,!Ie&&(Xt(),h(c),c.onRuntimeInitialized&&c.onRuntimeInitialized(),bd()))}c.setStatus?(c.setStatus("Running..."),setTimeout(function(){setTimeout(function(){c.setStatus("")},1),j()},1)):j()}if(c.preInit)for(typeof c.preInit=="function"&&(c.preInit=[c.preInit]);c.preInit.length>0;)c.preInit.pop()();O1();var Vd;f&&(Vd={uncaughtException:process.listeners("uncaughtException").filter(function(D){return!f.uncaughtException.indexOf(D)>-1}),unhandledRejection:process.listeners("unhandledRejection").filter(function(D){return!f.unhandledRejection.indexOf(D)>-1})});var Ud;if(typeof WasmBackendModule!="undefined")Ud=WasmBackendModule;else if(typeof r!="undefined")Ud=r;else throw new Error("Could not find wasm module in post.js");if(Vd){var tF=Ud._dispose;Ud._dispose=function(){tF(),Vd.uncaughtException.forEach(function(D){process.removeListener("uncaughtException",D)}),Vd.unhandledRejection.forEach(function(D){process.removeListener("unhandledRejection",D)})}}return r.ready}})();typeof e=="object"&&typeof t=="object"?t.exports=n:typeof define=="function"&&define.amd?define([],function(){return n}):typeof e=="object"&&(e.WasmBackendModuleThreadedSimd=n)}),TF=Bt((e,t)=>{t.exports.wasmWorkerContents=`"use strict";var Module={};var ENVIRONMENT_IS_NODE=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string";if(ENVIRONMENT_IS_NODE){var nodeWorkerThreads=require("worker_threads");var parentPort=nodeWorkerThreads.parentPort;parentPort.on("message",data=>onmessage({data:data}));var fs=require("fs");Object.assign(global,{self:global,require:require,Module:Module,location:{href:__filename},Worker:nodeWorkerThreads.Worker,importScripts:function(f){(0,eval)(fs.readFileSync(f,"utf8"))},postMessage:function(msg){parentPort.postMessage(msg)},performance:global.performance||{now:function(){return Date.now()}}})}var initializedJS=false;var pendingNotifiedProxyingQueues=[];function threadPrintErr(){var text=Array.prototype.slice.call(arguments).join(" ");if(ENVIRONMENT_IS_NODE){fs.writeSync(2,text+"
-");return}console.error(text)}function threadAlert(){var text=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:text,threadId:Module["_pthread_self"]()})}var err=threadPrintErr;self.alert=threadAlert;Module["instantiateWasm"]=(info,receiveInstance)=>{var instance=new WebAssembly.Instance(Module["wasmModule"],info);receiveInstance(instance);Module["wasmModule"]=null;return instance.exports};self.onunhandledrejection=e=>{throw e.reason??e};self.onmessage=e=>{try{if(e.data.cmd==="load"){Module["wasmModule"]=e.data.wasmModule;Module["wasmMemory"]=e.data.wasmMemory;Module["buffer"]=Module["wasmMemory"].buffer;Module["ENVIRONMENT_IS_PTHREAD"]=true;if(typeof e.data.urlOrBlob=="string"){importScripts(e.data.urlOrBlob)}else{var objectUrl=URL.createObjectURL(e.data.urlOrBlob);importScripts(objectUrl);URL.revokeObjectURL(objectUrl)}WasmBackendModuleThreadedSimd(Module).then(function(instance){Module=instance})}else if(e.data.cmd==="run"){Module["__performance_now_clock_drift"]=performance.now()-e.data.time;Module["__emscripten_thread_init"](e.data.pthread_ptr,0,0,1);Module["establishStackSpace"]();Module["PThread"].receiveObjectTransfer(e.data);Module["PThread"].threadInitTLS();if(!initializedJS){pendingNotifiedProxyingQueues.forEach(queue=>{Module["executeNotifiedProxyingQueue"](queue)});pendingNotifiedProxyingQueues=[];initializedJS=true}try{Module["invokeEntryPoint"](e.data.start_routine,e.data.arg)}catch(ex){if(ex!="unwind"){if(ex instanceof Module["ExitStatus"]){if(Module["keepRuntimeAlive"]()){}else{Module["__emscripten_thread_exit"](ex.status)}}else{throw ex}}}}else if(e.data.cmd==="cancel"){if(Module["_pthread_self"]()){Module["__emscripten_thread_exit"](-1)}}else if(e.data.target==="setimmediate"){}else if(e.data.cmd==="processProxyingQueue"){if(initializedJS){Module["executeNotifiedProxyingQueue"](e.data.queue)}else{pendingNotifiedProxyingQueues.push(e.data.queue)}}else if(e.data.cmd){err("worker.js received unknown command "+e.data.cmd);err(e.data)}}catch(ex){if(Module["__emscripten_thread_crashed"]){Module["__emscripten_thread_crashed"]()}throw ex}};`}),NF=Bt((e,t)=>{var n=(()=>{var a=typeof document!="undefined"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename!="undefined"&&(a=a||__filename),function(r){r=r||{};var s=typeof r!="undefined"?r:{},i,o;s.ready=new Promise(function(X,se){i=X,o=se});var l;typeof process!="undefined"&&process.listeners&&(l={uncaughtException:process.listeners("uncaughtException"),unhandledRejection:process.listeners("unhandledRejection")});var u=Object.assign({},s),p=[],d="./this.program",c=(X,se)=>{throw se},h=typeof window=="object",m=typeof importScripts=="function",f=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",g="";function y(X){return s.locateFile?s.locateFile(X,g):g+X}var b,x,w,I;function T(X){X instanceof Oo||R("exiting due to exception: "+X)}if(f){m?g=dh().dirname(g)+"/":g=__dirname+"/";var C,E;typeof vI=="function"&&(C=xx(),E=dh()),b=(X,se)=>(X=E.normalize(X),C.readFileSync(X,se?void 0:"utf8")),w=X=>{var se=b(X,!0);return se.buffer||(se=new Uint8Array(se)),se},x=(X,se,we)=>{X=E.normalize(X),C.readFile(X,function(He,wt){He?we(He):se(wt.buffer)})},process.argv.length>1&&(d=process.argv[1].replace(/\\/g,"/")),p=process.argv.slice(2),process.on("uncaughtException",function(X){if(!(X instanceof Oo))throw X}),process.on("unhandledRejection",function(X){throw X}),c=(X,se)=>{if(Hn())throw process.exitCode=X,se;T(se),process.exit(X)},s.inspect=function(){return"[Emscripten Module object]"}}else(h||m)&&(m?g=self.location.href:typeof document!="undefined"&&document.currentScript&&(g=document.currentScript.src),a&&(g=a),g.indexOf("blob:")!==0?g=g.substr(0,g.replace(/[?#].*/,"").lastIndexOf("/")+1):g="",b=X=>{var se=new XMLHttpRequest;return se.open("GET",X,!1),se.send(null),se.responseText},m&&(w=X=>{var se=new XMLHttpRequest;return se.open("GET",X,!1),se.responseType="arraybuffer",se.send(null),new Uint8Array(se.response)}),x=(X,se,we)=>{var He=new XMLHttpRequest;He.open("GET",X,!0),He.responseType="arraybuffer",He.onload=()=>{if(He.status==200||He.status==0&&He.response){se(He.response);return}we()},He.onerror=we,He.send(null)},I=X=>document.title=X);var A=s.print||console.log.bind(console),R=s.printErr||console.warn.bind(console);Object.assign(s,u),u=null,s.arguments&&(p=s.arguments),s.thisProgram&&(d=s.thisProgram),s.quit&&(c=s.quit);var F=4,S;s.wasmBinary&&(S=s.wasmBinary);var M=s.noExitRuntime||!0;typeof WebAssembly!="object"&&Ja("no native wasm support detected");var B,U=!1,G;function q(X,se){X||Ja(se)}var K=typeof TextDecoder!="undefined"?new TextDecoder("utf8"):void 0;function Z(X,se,we){for(var He=se+we,wt=se;X[wt]&&!(wt>=He);)++wt;if(wt-se>16&&X.buffer&&K)return K.decode(X.subarray(se,wt));for(var kt="";se>10,56320|oa&1023)}}return kt}function Q(X,se){return X?Z(ie,X,se):""}function ee(X,se,we,He){if(!(He>0))return 0;for(var wt=we,kt=we+He-1,Ue=0;Ue=55296&&We<=57343){var Pt=X.charCodeAt(++Ue);We=65536+((We&1023)<<10)|Pt&1023}if(We<=127){if(we>=kt)break;se[we++]=We}else if(We<=2047){if(we+1>=kt)break;se[we++]=192|We>>6,se[we++]=128|We&63}else if(We<=65535){if(we+2>=kt)break;se[we++]=224|We>>12,se[we++]=128|We>>6&63,se[we++]=128|We&63}else{if(we+3>=kt)break;se[we++]=240|We>>18,se[we++]=128|We>>12&63,se[we++]=128|We>>6&63,se[we++]=128|We&63}}return se[we]=0,we-wt}function ae(X,se,we){return ee(X,ie,se,we)}var te,le,ie,ye,ue,xe,Ie,Se,Le;function Ve(X){te=X,s.HEAP8=le=new Int8Array(X),s.HEAP16=ye=new Int16Array(X),s.HEAP32=xe=new Int32Array(X),s.HEAPU8=ie=new Uint8Array(X),s.HEAPU16=ue=new Uint16Array(X),s.HEAPU32=Ie=new Uint32Array(X),s.HEAPF32=Se=new Float32Array(X),s.HEAPF64=Le=new Float64Array(X)}var nt=s.INITIAL_MEMORY||16777216,st,Je=[],at=[],ze=[],dt=!1;function Hn(){return M}function Mt(){if(s.preRun)for(typeof s.preRun=="function"&&(s.preRun=[s.preRun]);s.preRun.length;)Fn(s.preRun.shift());yr(Je)}function sa(){dt=!0,yr(at)}function sn(){if(s.postRun)for(typeof s.postRun=="function"&&(s.postRun=[s.postRun]);s.postRun.length;)Dn(s.postRun.shift());yr(ze)}function Fn(X){Je.unshift(X)}function ia(X){at.unshift(X)}function Dn(X){ze.unshift(X)}var it=0,Rn=null,jn=null;function gr(X){it++,s.monitorRunDependencies&&s.monitorRunDependencies(it)}function Mo(X){if(it--,s.monitorRunDependencies&&s.monitorRunDependencies(it),it==0&&(Rn!==null&&(clearInterval(Rn),Rn=null),jn)){var se=jn;jn=null,se()}}function Ja(X){s.onAbort&&s.onAbort(X),X="Aborted("+X+")",R(X),U=!0,G=1,X+=". Build with -sASSERTIONS for more info.";var se=new WebAssembly.RuntimeError(X);throw o(se),se}var mp="data:application/octet-stream;base64,";function wa(X){return X.startsWith(mp)}function Po(X){return X.startsWith("file://")}var Xt;Xt="tfjs-backend-wasm.wasm",wa(Xt)||(Xt=y(Xt));function bd(X){try{if(X==Xt&&S)return new Uint8Array(S);if(w)return w(X);throw"both async and sync fetching of the wasm failed"}catch(se){Ja(se)}}function bg(){if(!S&&(h||m)){if(typeof fetch=="function"&&!Po(Xt))return fetch(Xt,{credentials:"same-origin"}).then(function(X){if(!X.ok)throw"failed to load wasm binary file at '"+Xt+"'";return X.arrayBuffer()}).catch(function(){return bd(Xt)});if(x)return new Promise(function(X,se){x(Xt,function(we){X(new Uint8Array(we))},se)})}return Promise.resolve().then(function(){return bd(Xt)})}function xg(){var X={env:yp,wasi_snapshot_preview1:yp};function se(Ue,We){var Pt=Ue.exports;s.asm=Pt,B=s.asm.memory,Ve(B.buffer),st=s.asm.__indirect_function_table,ia(s.asm.__wasm_call_ctors),Mo("wasm-instantiate")}gr("wasm-instantiate");function we(Ue){se(Ue.instance)}function He(Ue){return bg().then(function(We){return WebAssembly.instantiate(We,X)}).then(function(We){return We}).then(Ue,function(We){R("failed to asynchronously prepare wasm: "+We),Ja(We)})}function wt(){return!S&&typeof WebAssembly.instantiateStreaming=="function"&&!wa(Xt)&&!Po(Xt)&&!f&&typeof fetch=="function"?fetch(Xt,{credentials:"same-origin"}).then(function(Ue){var We=WebAssembly.instantiateStreaming(Ue,X);return We.then(we,function(Pt){return R("wasm streaming compile failed: "+Pt),R("falling back to ArrayBuffer instantiation"),He(we)})}):He(we)}if(s.instantiateWasm)try{var kt=s.instantiateWasm(X,se);return kt}catch(Ue){R("Module.instantiateWasm callback failed with error: "+Ue),o(Ue)}return wt().catch(o),{}}var I1,Br;function Oo(X){this.name="ExitStatus",this.message="Program terminated with exit("+X+")",this.status=X}function yr(X){for(;X.length>0;)X.shift()(s)}function S1(X){return X}function T1(X){var se=/\b_Z[\w\d_]+/g;return X.replace(se,function(we){var He=we;return we===He?we:He+" ["+we+"]"})}function Lo(){var X=new Error;if(!X.stack){try{throw new Error}catch(se){X=se}if(!X.stack)return"(no stack trace available)"}return X.stack.toString()}function vg(X,se){le.set(X,se)}function xd(){Ja("")}function fp(){return 2147483648}function yn(){return fp()}function vd(X,se,we){ie.copyWithin(X,se,se+we)}function wg(X){try{return B.grow(X-te.byteLength+65535>>>16),Ve(B.buffer),1}catch(se){}}function kg(X){var se=ie.length;X=X>>>0;var we=fp();if(X>we)return!1;let He=(Pt,oa)=>Pt+(oa-Pt%oa)%oa;for(var wt=1;wt<=4;wt*=2){var kt=se*(1+.2/wt);kt=Math.min(kt,X+100663296);var Ue=Math.min(we,He(Math.max(X,kt),65536)),We=wg(Ue);if(We)return!0}return!1}var Ig={varargs:void 0,get:function(){Ig.varargs+=4;var X=xe[Ig.varargs-4>>2];return X},getStr:function(X){var se=Q(X);return se}};function N1(X){return 52}function Sg(X,se,we,He,wt){return 70}var Rs=[null,[],[]];function Tg(X,se){var we=Rs[X];se===0||se===10?((X===1?A:R)(Z(we,0)),we.length=0):we.push(se)}function Ng(X,se,we,He){for(var wt=0,kt=0;kt>2],We=Ie[se+4>>2];se+=8;for(var Pt=0;Pt>2]=wt,0}function gp(X){var se=s["_"+X];return se}function wd(X,se,we,He,wt){var kt={string:Mn=>{var Ur=0;if(Mn!=null&&Mn!==0){var Od=(Mn.length<<2)+1;Ur=wp(Od),ae(Mn,Ur,Od)}return Ur},array:Mn=>{var Ur=wp(Mn.length);return vg(Mn,Ur),Ur}};function Ue(Mn){return se==="string"?Q(Mn):se==="boolean"?Boolean(Mn):Mn}var We=gp(X),Pt=[],oa=0;if(He)for(var br=0;brUe==="number"||Ue==="boolean"),kt=se!=="string";return kt&&wt&&!He?gp(X):function(){return wd(X,se,we,arguments,He)}}var yp={abort:xd,emscripten_get_heap_max:yn,emscripten_memcpy_big:vd,emscripten_resize_heap:kg,fd_close:N1,fd_seek:Sg,fd_write:Ng},C1=xg(),Id=s.___wasm_call_ctors=function(){return(Id=s.___wasm_call_ctors=s.asm.__wasm_call_ctors).apply(null,arguments)},Cg=s._init=function(){return(Cg=s._init=s.asm.init).apply(null,arguments)},$e=s._init_with_threads_count=function(){return($e=s._init_with_threads_count=s.asm.init_with_threads_count).apply(null,arguments)},bp=s._get_threads_count=function(){return(bp=s._get_threads_count=s.asm.get_threads_count).apply(null,arguments)},_g=s._register_tensor=function(){return(_g=s._register_tensor=s.asm.register_tensor).apply(null,arguments)},_1=s._dispose_data=function(){return(_1=s._dispose_data=s.asm.dispose_data).apply(null,arguments)},E1=s._dispose=function(){return(E1=s._dispose=s.asm.dispose).apply(null,arguments)},Eg=s._Abs=function(){return(Eg=s._Abs=s.asm.Abs).apply(null,arguments)},Sd=s._Add=function(){return(Sd=s._Add=s.asm.Add).apply(null,arguments)},zo=s._AddN=function(){return(zo=s._AddN=s.asm.AddN).apply(null,arguments)},Ag=s._All=function(){return(Ag=s._All=s.asm.All).apply(null,arguments)},$g=s._Any=function(){return($g=s._Any=s.asm.Any).apply(null,arguments)},A1=s._ArgMax=function(){return(A1=s._ArgMax=s.asm.ArgMax).apply(null,arguments)},Fg=s._AvgPool=function(){return(Fg=s._AvgPool=s.asm.AvgPool).apply(null,arguments)},Dg=s._BatchMatMul=function(){return(Dg=s._BatchMatMul=s.asm.BatchMatMul).apply(null,arguments)},Rg=s._Ceil=function(){return(Rg=s._Ceil=s.asm.Ceil).apply(null,arguments)},Mg=s._ClipByValue=function(){return(Mg=s._ClipByValue=s.asm.ClipByValue).apply(null,arguments)},Td=s._Conv2D=function(){return(Td=s._Conv2D=s.asm.Conv2D).apply(null,arguments)},Nd=s._Conv2DBackpropInput=function(){return(Nd=s._Conv2DBackpropInput=s.asm.Conv2DBackpropInput).apply(null,arguments)},Pg=s._Cos=function(){return(Pg=s._Cos=s.asm.Cos).apply(null,arguments)},Og=s._Cosh=function(){return(Og=s._Cosh=s.asm.Cosh).apply(null,arguments)},Lg=s._CropAndResize=function(){return(Lg=s._CropAndResize=s.asm.CropAndResize).apply(null,arguments)},xp=s._Cumprod=function(){return(xp=s._Cumprod=s.asm.Cumprod).apply(null,arguments)},zg=s._Cumsum=function(){return(zg=s._Cumsum=s.asm.Cumsum).apply(null,arguments)},Wg=s._DepthToSpace=function(){return(Wg=s._DepthToSpace=s.asm.DepthToSpace).apply(null,arguments)},Bg=s._DepthwiseConv2dNative=function(){return(Bg=s._DepthwiseConv2dNative=s.asm.DepthwiseConv2dNative).apply(null,arguments)},Ms=s._Elu=function(){return(Ms=s._Elu=s.asm.Elu).apply(null,arguments)},Vg=s._Equal=function(){return(Vg=s._Equal=s.asm.Equal).apply(null,arguments)},Ug=s._Exp=function(){return(Ug=s._Exp=s.asm.Exp).apply(null,arguments)},Cd=s._FlipLeftRight=function(){return(Cd=s._FlipLeftRight=s.asm.FlipLeftRight).apply(null,arguments)},Gg=s._Floor=function(){return(Gg=s._Floor=s.asm.Floor).apply(null,arguments)},Wo=s._FloorDiv=function(){return(Wo=s._FloorDiv=s.asm.FloorDiv).apply(null,arguments)},Hg=s._FusedBatchNorm=function(){return(Hg=s._FusedBatchNorm=s.asm.FusedBatchNorm).apply(null,arguments)},jg=s._FusedConv2D=function(){return(jg=s._FusedConv2D=s.asm.FusedConv2D).apply(null,arguments)},Vr=s._FusedDepthwiseConv2D=function(){return(Vr=s._FusedDepthwiseConv2D=s.asm.FusedDepthwiseConv2D).apply(null,arguments)},vp=s._Gather=function(){return(vp=s._Gather=s.asm.Gather).apply(null,arguments)},qg=s._GatherNd=function(){return(qg=s._GatherNd=s.asm.GatherNd).apply(null,arguments)},Kg=s._Greater=function(){return(Kg=s._Greater=s.asm.Greater).apply(null,arguments)},Xg=s._GreaterEqual=function(){return(Xg=s._GreaterEqual=s.asm.GreaterEqual).apply(null,arguments)},Yg=s._LeakyRelu=function(){return(Yg=s._LeakyRelu=s.asm.LeakyRelu).apply(null,arguments)},_d=s._Less=function(){return(_d=s._Less=s.asm.Less).apply(null,arguments)},Ed=s._LessEqual=function(){return(Ed=s._LessEqual=s.asm.LessEqual).apply(null,arguments)},Zg=s._Log=function(){return(Zg=s._Log=s.asm.Log).apply(null,arguments)},Jg=s._LogicalAnd=function(){return(Jg=s._LogicalAnd=s.asm.LogicalAnd).apply(null,arguments)},Ad=s._LogicalNot=function(){return(Ad=s._LogicalNot=s.asm.LogicalNot).apply(null,arguments)},$d=s._LogicalOr=function(){return($d=s._LogicalOr=s.asm.LogicalOr).apply(null,arguments)},Qg=s._LogicalXor=function(){return(Qg=s._LogicalXor=s.asm.LogicalXor).apply(null,arguments)},ey=s._Max=function(){return(ey=s._Max=s.asm.Max).apply(null,arguments)},ty=s._MaxPool=function(){return(ty=s._MaxPool=s.asm.MaxPool).apply(null,arguments)},Fd=s._Maximum=function(){return(Fd=s._Maximum=s.asm.Maximum).apply(null,arguments)},$1=s._Mean=function(){return($1=s._Mean=s.asm.Mean).apply(null,arguments)},ny=s._Min=function(){return(ny=s._Min=s.asm.Min).apply(null,arguments)},ay=s._Minimum=function(){return(ay=s._Minimum=s.asm.Minimum).apply(null,arguments)},ry=s._MirrorPad=function(){return(ry=s._MirrorPad=s.asm.MirrorPad).apply(null,arguments)},sy=s._Multiply=function(){return(sy=s._Multiply=s.asm.Multiply).apply(null,arguments)},iy=s._Neg=function(){return(iy=s._Neg=s.asm.Neg).apply(null,arguments)},oy=s._NonMaxSuppressionV3=function(){return(oy=s._NonMaxSuppressionV3=s.asm.NonMaxSuppressionV3).apply(null,arguments)},ly=s._NonMaxSuppressionV4=function(){return(ly=s._NonMaxSuppressionV4=s.asm.NonMaxSuppressionV4).apply(null,arguments)},uy=s._NonMaxSuppressionV5=function(){return(uy=s._NonMaxSuppressionV5=s.asm.NonMaxSuppressionV5).apply(null,arguments)},py=s._NotEqual=function(){return(py=s._NotEqual=s.asm.NotEqual).apply(null,arguments)},cy=s._OneHot=function(){return(cy=s._OneHot=s.asm.OneHot).apply(null,arguments)},dy=s._PadV2=function(){return(dy=s._PadV2=s.asm.PadV2).apply(null,arguments)},hy=s._Pow=function(){return(hy=s._Pow=s.asm.Pow).apply(null,arguments)},my=s._Prelu=function(){return(my=s._Prelu=s.asm.Prelu).apply(null,arguments)},fy=s._Prod=function(){return(fy=s._Prod=s.asm.Prod).apply(null,arguments)},gy=s._RealDiv=function(){return(gy=s._RealDiv=s.asm.RealDiv).apply(null,arguments)},yy=s._Relu=function(){return(yy=s._Relu=s.asm.Relu).apply(null,arguments)},by=s._Relu6=function(){return(by=s._Relu6=s.asm.Relu6).apply(null,arguments)},xy=s._ResizeBilinear=function(){return(xy=s._ResizeBilinear=s.asm.ResizeBilinear).apply(null,arguments)},vy=s._ResizeNearestNeighbor=function(){return(vy=s._ResizeNearestNeighbor=s.asm.ResizeNearestNeighbor).apply(null,arguments)},wy=s._Reverse=function(){return(wy=s._Reverse=s.asm.Reverse).apply(null,arguments)},ky=s._RotateWithOffset=function(){return(ky=s._RotateWithOffset=s.asm.RotateWithOffset).apply(null,arguments)},Iy=s._Round=function(){return(Iy=s._Round=s.asm.Round).apply(null,arguments)},Sy=s._Rsqrt=function(){return(Sy=s._Rsqrt=s.asm.Rsqrt).apply(null,arguments)},Ty=s._ScatterNd=function(){return(Ty=s._ScatterNd=s.asm.ScatterNd).apply(null,arguments)},Ny=s._SelectV2=function(){return(Ny=s._SelectV2=s.asm.SelectV2).apply(null,arguments)},Cy=s._Sigmoid=function(){return(Cy=s._Sigmoid=s.asm.Sigmoid).apply(null,arguments)},_y=s._Sin=function(){return(_y=s._Sin=s.asm.Sin).apply(null,arguments)},Ey=s._Softmax=function(){return(Ey=s._Softmax=s.asm.Softmax).apply(null,arguments)},Ay=s._SparseFillEmptyRows=function(){return(Ay=s._SparseFillEmptyRows=s.asm.SparseFillEmptyRows).apply(null,arguments)},$y=s._SparseReshape=function(){return($y=s._SparseReshape=s.asm.SparseReshape).apply(null,arguments)},Fy=s._SparseSegmentReduction=function(){return(Fy=s._SparseSegmentReduction=s.asm.SparseSegmentReduction).apply(null,arguments)},Dy=s._Sqrt=function(){return(Dy=s._Sqrt=s.asm.Sqrt).apply(null,arguments)},Ry=s._Square=function(){return(Ry=s._Square=s.asm.Square).apply(null,arguments)},My=s._SquaredDifference=function(){return(My=s._SquaredDifference=s.asm.SquaredDifference).apply(null,arguments)},Py=s._Step=function(){return(Py=s._Step=s.asm.Step).apply(null,arguments)},Oy=s._StridedSlice=function(){return(Oy=s._StridedSlice=s.asm.StridedSlice).apply(null,arguments)},Ly=s._Sub=function(){return(Ly=s._Sub=s.asm.Sub).apply(null,arguments)},zy=s._Sum=function(){return(zy=s._Sum=s.asm.Sum).apply(null,arguments)},Wy=s._Tan=function(){return(Wy=s._Tan=s.asm.Tan).apply(null,arguments)},By=s._Tanh=function(){return(By=s._Tanh=s.asm.Tanh).apply(null,arguments)},Vy=s._Tile=function(){return(Vy=s._Tile=s.asm.Tile).apply(null,arguments)},Uy=s._TopK=function(){return(Uy=s._TopK=s.asm.TopK).apply(null,arguments)},Gy=s._Transform=function(){return(Gy=s._Transform=s.asm.Transform).apply(null,arguments)},Hy=s._Transpose=function(){return(Hy=s._Transpose=s.asm.Transpose).apply(null,arguments)},jy=s.__FusedMatMul=function(){return(jy=s.__FusedMatMul=s.asm._FusedMatMul).apply(null,arguments)},qy=s._malloc=function(){return(qy=s._malloc=s.asm.malloc).apply(null,arguments)},Ky=s._free=function(){return(Ky=s._free=s.asm.free).apply(null,arguments)},Xy=s.___errno_location=function(){return(Xy=s.___errno_location=s.asm.__errno_location).apply(null,arguments)},Dd=s.stackSave=function(){return(Dd=s.stackSave=s.asm.stackSave).apply(null,arguments)},Rd=s.stackRestore=function(){return(Rd=s.stackRestore=s.asm.stackRestore).apply(null,arguments)},wp=s.stackAlloc=function(){return(wp=s.stackAlloc=s.asm.stackAlloc).apply(null,arguments)},Yy=s.dynCall_iijjiiii=function(){return(Yy=s.dynCall_iijjiiii=s.asm.dynCall_iijjiiii).apply(null,arguments)},Zy=s.dynCall_jiji=function(){return(Zy=s.dynCall_jiji=s.asm.dynCall_jiji).apply(null,arguments)};s.cwrap=kd;var Bo;jn=function X(){Bo||Md(),Bo||(jn=X)};function Md(X){if(X=X||p,it>0||(Mt(),it>0))return;function se(){Bo||(Bo=!0,s.calledRun=!0,!U&&(sa(),i(s),s.onRuntimeInitialized&&s.onRuntimeInitialized(),sn()))}s.setStatus?(s.setStatus("Running..."),setTimeout(function(){setTimeout(function(){s.setStatus("")},1),se()},1)):se()}if(s.preInit)for(typeof s.preInit=="function"&&(s.preInit=[s.preInit]);s.preInit.length>0;)s.preInit.pop()();Md();var Vo;l&&(Vo={uncaughtException:process.listeners("uncaughtException").filter(function(X){return!l.uncaughtException.indexOf(X)>-1}),unhandledRejection:process.listeners("unhandledRejection").filter(function(X){return!l.unhandledRejection.indexOf(X)>-1})});var Uo;if(typeof r!="undefined")Uo=r;else if(typeof WasmBackendModuleThreadedSimd!="undefined")Uo=WasmBackendModuleThreadedSimd;else throw new Error("Could not find wasm module in post.js");if(Vo){var Jy=Uo._dispose;Uo._dispose=function(){Jy(),Vo.uncaughtException.forEach(function(X){process.removeListener("uncaughtException",X)}),Vo.unhandledRejection.forEach(function(X){process.removeListener("unhandledRejection",X)})}}return r.ready}})();typeof e=="object"&&typeof t=="object"?t.exports=n:typeof define=="function"&&define.amd?define([],function(){return n}):typeof e=="object"&&(e.WasmBackendModule=n)}),jh=class{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}},rc=class{refCount(e){return qn("refCount")}incRef(e){return qn("incRef")}timerAvailable(){return!0}time(e){return qn("time")}read(e){return qn("read")}readSync(e){return qn("readSync")}readToGPU(e,t){return qn("readToGPU")}numDataIds(){return qn("numDataIds")}disposeData(e,t){return qn("disposeData")}write(e,t,n){return qn("write")}move(e,t,n,a,r){return qn("move")}createTensorFromTexture(e,t,n){return qn("createTensorFromTexture")}memory(){return qn("memory")}floatPrecision(){return qn("floatPrecision")}epsilon(){return this.floatPrecision()===32?1e-7:1e-4}dispose(){return qn("dispose")}};function qn(e){throw new Error(`'${e}' not yet implemented or not found in the registry. This kernel may not be supported by the tfjs backend you have chosen`)}function kI(e){let t=e.length,n=0;for(;t>0;)n=Math.random()*t|0,t--,hh(e,t,n)}function CF(e,t){if(e.length!==t.length)throw new Error(`Array sizes must match to be shuffled together First array length was ${e.length}Second array length was ${t.length}`);let n=e.length,a=0;for(;n>0;)a=Math.random()*n|0,n--,hh(e,n,a),hh(t,n,a)}function Vp(e,t,n){return Math.max(e,Math.min(t,n))}function _F(e){return e%2===0?e:e+1}function hh(e,t,n){let a=e[t];e[t]=e[n],e[n]=a}function EF(e){let t=0;for(let n=0;nn+` Shapes ${e} and ${t} must match`)}function hi(e){$(e!=null,()=>"The input to the tensor constructor must be a non-null value.")}function Zs(e,t=[],n=!1){if(t==null&&(t=[]),Array.isArray(e)||hn(e)&&!n)for(let a=0;a0,n,a){return new Promise((r,s)=>{let i=0,o=()=>{if(e()){r();return}i++;let l=t(i);if(n!=null&&i>=n){s();return}a!=null?a(o,l):setTimeout(o,l)};o()})}function OF(e,t){let n=1,a=-1;for(let s=0;s=0)n*=e[s];else if(e[s]===-1){if(a!==-1)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${a} and dim ${s}`);a=s}else if(e[s]<0)throw Error(`Shapes can not be < 0. Found ${e[s]} at dim ${s}`);if(a===-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}`);let r=e.slice();return r[a]=t/n,r}function Aa(e,t){let n=t.length;return e=e==null?t.map((a,r)=>r):[].concat(e),$(e.every(a=>a>=-n&&a`All values in axis param must be in range [-${n}, ${n}) but got axis ${e}`),$(e.every(a=>tl(a)),()=>`All values in axis param must be integers but got axis ${e}`),e.map(a=>a<0?n+a:a)}function II(e,t){let n=[],a=[],r=t!=null&&Array.isArray(t)&&t.length===0,s=t==null||r?null:Aa(t,e).sort(),i=0;for(let o=0;oo)&&e[o]===1&&(n.push(e[o]),a.push(o)),s[i]<=o&&i++}e[o]!==1&&(n.push(e[o]),a.push(o))}return{newShape:n,keptDims:a}}function SI(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 TI(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 NI(e,t){for(let n=0;nt+=n.length),t}function Kr(e){return typeof e=="string"||e instanceof String}function EI(e){return typeof e=="boolean"}function AI(e){return typeof e=="number"}function qh(e){return Array.isArray(e)?qh(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray?"int32":AI(e)?"float32":Kr(e)?"string":EI(e)?"bool":"float32"}function es(e){return!!(e&&e.constructor&&e.call&&e.apply)}function mh(e,t){for(let n=t;n=0;--a)n[a]=n[a+1]*e[a+1];return n}function $I(e,t,n,a=!1){let r=new Array;if(t.length===1){let s=t[0]*(a?2:1);for(let i=0;il*u)*(a?2:1);for(let l=0;lr*s)*(n?2:1);if(a===0)return[];if(a!==t.length)throw new Error(`[${e}] does not match the input size ${t.length}${n?" for a complex tensor":""}.`);return $I(0,e,t,n)}function vx(e,t){let n=Kh(e,t);for(let a=0;aa*r,1);if(t==null||t==="float32")return Zo(e,new Float32Array(n));if(t==="int32")return Zo(e,new Int32Array(n));if(t==="bool")return Zo(e,new Uint8Array(n));throw new Error(`Unknown data type ${t}`)}function wx(e){e.forEach(t=>{$(Number.isInteger(t)&&t>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`)})}function WF(e,t,n){if(t===0)return 0;if(t===1)return e[0];let a=e[e.length-1];for(let r=0;r{let[n,a]=t.split(":");this.urlFlags[n]=GF(n,a)})}};function VF(e){let t={};return e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(n,...a)=>(UF(t,a[0],a[1]),a.join("="))),t}function UF(e,t,n){e[decodeURIComponent(t)]=decodeURIComponent(n||"")}function GF(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 H(){return Ix}var Ix=null;function HF(e){Ix=e}var rb;function DI(){if(rb==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");rb=e}return rb}function jF(){let e=DI();return e._tfGlobals==null&&(e._tfGlobals=new Map),e._tfGlobals}function Sx(e,t){let n=jF();if(n.has(e))return n.get(e);{let a=t();return n.set(e,a),n.get(e)}}var wl="Abs",kl="Acos",Il="Acosh",cs="Add",mi="AddN",Sl="All",Tl="Any",fi="ArgMax",sc="ArgMin",Nl="Asin",Cl="Asinh",_l="Atan",El="Atanh",Al="Atan2",gi="AvgPool",Xh="AvgPoolGrad",ic="AvgPool3D",Yh="AvgPool3DGrad",yi="BatchMatMul",$l="BatchToSpaceND",Zh="Bincount",RI="BroadcastTo",Jh="BroadcastArgs",bi="Cast",xi="Ceil",ds="ClipByValue",Qh="Complex",oc="ComplexAbs",Fl="Concat",vi="Conv2D",em="Conv2DBackpropFilter",wi="Conv2DBackpropInput",lc="Conv3D",tm="Conv3DBackpropFilterV2",nm="Conv3DBackpropInputV2",ki="Cos",Ii="Cosh",Dl="Cumprod",Si="Cumsum",Rl="CropAndResize",am="DenseBincount",Ml="DepthToSpace",Ti="DepthwiseConv2dNative",rm="DepthwiseConv2dNativeBackpropFilter",sm="DepthwiseConv2dNativeBackpropInput",im="Diag",uc="Dilation2D",fh="Dilation2DBackpropInput",gh="Dilation2DBackpropFilter",Ni="RealDiv",om="Einsum",Ci="Elu",lm="EluGrad",Pl="Erf",Ol="Equal",_i="Exp",Ll="ExpandDims",zl="Expm1",um="FFT",pc="Fill",Wl="FlipLeftRight",Ei="Floor",Ai="FloorDiv",$i="FusedBatchNorm",Bl="GatherV2",Vl="GatherNd",Ul="Greater",Fi="GreaterEqual",Di="Identity",pm="IFFT",cm="Imag",Gl="IsFinite",Hl="IsInf",jl="IsNan",Ri="LeakyRelu",ql="Less",Kl="LessEqual",dm="LinSpace",Mi="Log",Xl="Log1p",Yl="LogicalAnd",Zl="LogicalNot",Jl="LogicalOr",MI="LogicalXor",PI="LogSoftmax",qF="LowerBound",cc="LRN",hm="LRNGrad",Pi="Max",Oi="Maximum",Li="MaxPool",mm="MaxPoolGrad",dc="MaxPool3D",fm="MaxPool3DGrad",gm="MaxPoolWithArgmax",zi="Mean",Wi="Min",Bi="Minimum",Vi="MirrorPad",Ql="Mod",ym="Multinomial",Ui="Multiply",eu="Neg",tu="NotEqual",nu="NonMaxSuppressionV3",au="NonMaxSuppressionV4",ru="NonMaxSuppressionV5",su="OnesLike",Gi="OneHot",iu="Pack",Hi="PadV2",KF="Pool",ji="Pow",qi="Prelu",Ki="Prod",bm="RaggedGather",xm="RaggedRange",vm="RaggedTensorToTensor",hc="Range",wm="Real",ou="Reciprocal",Xi="Relu",lu="Reshape",Yi="ResizeNearestNeighbor",km="ResizeNearestNeighborGrad",Zi="ResizeBilinear",Im="ResizeBilinearGrad",Ji="Relu6",Qi="Reverse",eo="Round",to="Rsqrt",uu="ScatterNd",Sm="SearchSorted",pu="Select",cu="Selu",du="Slice",no="Sin",hu="Sinh",mu="Sign",ao="Sigmoid",fu="Softplus",ro="Sqrt",so="Sum",gu="SpaceToBatchND",yu="SplitV",io="Softmax",mc="SparseFillEmptyRows",bu="SparseReshape",fc="SparseSegmentMean",gc="SparseSegmentSum",Tm="SparseToDense",oo="SquaredDifference",yc="Square",xu="StridedSlice",bc="StringNGrams",xc="StringSplit",vc="StringToHashBucketFast",lo="Sub",uo="Tan",po="Tanh",hs="Tile",vu="TopK",wu="Transform",Tr="Transpose",Nm="Unique",ku="Unpack",wc="UnsortedSegmentSum",XF="UpperBound",Iu="ZerosLike",ms="Step",yh="FromPixels",Su="RotateWithOffset",Js="_FusedMatMul",Qs="FusedConv2D",ei="FusedDepthwiseConv2D";function qr(...e){H().getBool("IS_TEST")||H().getBool("PROD")||console.warn(...e)}function YF(...e){H().getBool("IS_TEST")||H().getBool("PROD")||console.log(...e)}var nl=Sx("kernelRegistry",()=>new Map),Up=Sx("gradRegistry",()=>new Map);function bh(e,t){let n=Tx(e,t);return nl.get(n)}function xb(e){return Up.get(e)}function xh(e){let t=nl.entries(),n=[];for(;;){let{done:a,value:r}=t.next();if(a)break;let[s,i]=r,[o]=s.split("_");o===e&&n.push(i)}return n}function kc(e){let{kernelName:t,backendName:n}=e,a=Tx(t,n);nl.has(a)&&qr(`The kernel '${t}' for backend '${n}' is already registered`),nl.set(a,e)}function OI(e){let{kernelName:t}=e;Up.has(t)&&H().getBool("DEBUG")&&qr(`Overriding the gradient for '${t}'`),Up.set(t,e)}function ZF(e,t){let n=Tx(e,t);if(!nl.has(n))throw new Error(`The kernel '${e}' for backend '${t}' is not registered`);nl.delete(n)}function JF(e){if(!Up.has(e))throw new Error(`The gradient '${e}' for backend is not registered`);Up.delete(e)}function QF(e,t){xh(e).forEach(n=>{let a=Object.assign({},n,{backendName:t});kc(a)})}function Tx(e,t){return`${t}_${e}`}var v={};Ae(v,{arraysEqual:()=>ps,assert:()=>$,assertNonNegativeIntegerDimensions:()=>wx,assertNonNull:()=>hi,assertShapesMatch:()=>Sn,bytesFromStringArray:()=>_I,bytesPerElement:()=>bb,checkConversionForErrors:()=>NI,clamp:()=>Vp,computeStrides:()=>vl,createScalarValue:()=>sD,createShuffledIndices:()=>MF,decodeString:()=>vh,distSquared:()=>$F,encodeString:()=>Sc,fetch:()=>oD,fingerPrint64:()=>rD,flatten:()=>Zs,getArrayFromDType:()=>TI,getTypedArrayFromDType:()=>SI,hasEncodingLoss:()=>LF,hexToLong:()=>Ic,indexToLoc:()=>BF,inferDtype:()=>qh,inferFromImplicitShape:()=>OF,isBoolean:()=>EI,isFunction:()=>es,isInt:()=>tl,isNumber:()=>AI,isPromise:()=>kx,isScalarShape:()=>FF,isString:()=>Kr,isTypedArray:()=>hn,isValidDtype:()=>CI,locToIndex:()=>WF,makeOnesTypedArray:()=>vx,makeZerosNestedTypedArray:()=>zF,makeZerosTypedArray:()=>Kh,nearestDivisor:()=>mh,nearestLargerEven:()=>_F,now:()=>Gp,parseAxisParam:()=>Aa,randUniform:()=>AF,repeatedTry:()=>PF,rightPad:()=>Lp,shuffle:()=>kI,shuffleCombo:()=>CF,sizeFromShape:()=>mt,sizeToSquarishShape:()=>RF,squeezeShape:()=>II,sum:()=>EF,swap:()=>hh,tanh:()=>DF,toNestedArray:()=>Zo,toTypedArray:()=>Cm});var B1=us(pF()),Ws=B1.default||B1;function Ic(e){return Ws.fromString(e,!0,16)}var LI=Ic("c3a5c85c97cb3127"),Ls=Ic("b492b66fbe98f273"),bn=Ic("9ae16a3b2f90404f");function vb(e){return e.xor(e.shru(47))}function zI(e,t,n){let a=e.slice(t,t+n);return Ws.fromBytes(Array.from(a),!0,!0)}function ht(e,t){return zI(e,t,8)}function V1(e,t){return zI(e,t,4)}function Yt(e,t){return t===0?e:e.shru(t).or(e.shl(64-t))}function Zr(e,t,n=Ic("9ddfea08eb382d69")){let a=e.xor(t).mul(n);a=a.xor(a.shru(47));let r=t.xor(a).mul(n);return r=r.xor(r.shru(47)),r=r.mul(n),r}function eD(e,t,n,a,r,s){r=r.add(e),s=Yt(s.add(r).add(a),21);let i=r;return r=r.add(t),r=r.add(n),s=s.add(Yt(r,44)),[r.add(a),s.add(i)]}function Gd(e,t,n,a){return eD(ht(e,t),ht(e,t+8),ht(e,t+16),ht(e,t+24),n,a)}function tD(e,t=e.length){if(t>=8){let n=bn.add(t*2),a=ht(e,0).add(bn),r=ht(e,t-8),s=Yt(r,37).mul(n).add(a),i=Yt(a,25).add(r).mul(n);return Zr(s,i,n)}if(t>=4){let n=bn.add(t*2),a=V1(e,0);return Zr(a.shl(3).add(t),V1(e,t-4),n)}if(t>0){let n=e[0],a=e[t>>1],r=e[t-1],s=n+(a<<8),i=t+(r<<2);return vb(bn.mul(s).xor(LI.mul(i))).mul(bn)}return bn}function nD(e,t=e.length){let n=bn.add(t*2),a=ht(e,0).mul(Ls),r=ht(e,8),s=ht(e,t-8).mul(n),i=ht(e,t-16).mul(bn);return Zr(Yt(a.add(r),43).add(Yt(s,30)).add(i),a.add(Yt(r.add(bn),18)).add(s),n)}function aD(e,t=e.length){let n=bn.add(t*2),a=ht(e,0).mul(bn),r=ht(e,8),s=ht(e,t-8).mul(n),i=ht(e,t-16).mul(bn),o=Yt(a.add(r),43).add(Yt(s,30)).add(i),l=Zr(o,a.add(Yt(r.add(bn),18)).add(s),n),u=ht(e,16).mul(n),p=ht(e,24),d=o.add(ht(e,t-32)).mul(n),c=l.add(ht(e,t-24)).mul(n);return Zr(Yt(u.add(p),43).add(Yt(d,30)).add(c),u.add(Yt(p.add(a),18)).add(d),n)}function rD(e,t=e.length){let n=Ws.fromNumber(81,!0);if(t<=32)return t<=16?tD(e,t):nD(e,t);if(t<=64)return aD(e,t);let a=n,r=n.mul(Ls).add(113),s=vb(r.mul(bn).add(113)).mul(bn),i=[Ws.UZERO,Ws.UZERO],o=[Ws.UZERO,Ws.UZERO];a=a.mul(bn).add(ht(e,0));let l=0,u=(t-1>>6)*64,p=u+(t-1&63)-63;do a=Yt(a.add(r).add(i[0]).add(ht(e,l+8)),37).mul(Ls),r=Yt(r.add(i[1]).add(ht(e,l+48)),42).mul(Ls),a=a.xor(o[1]),r=r.add(i[0]).add(ht(e,l+40)),s=Yt(s.add(o[0]),33).mul(Ls),i=Gd(e,l,i[1].mul(Ls),a.add(o[0])),o=Gd(e,l+32,s.add(o[1]),r.add(ht(e,l+16))),[s,a]=[a,s],l+=64;while(l!==u);let d=Ls.add(s.and(255).shl(1));return l=p,o[0]=o[0].add(t-1&63),i[0]=i[0].add(o[0]),o[0]=o[0].add(i[0]),a=Yt(a.add(r).add(i[0]).add(ht(e,l+8)),37).mul(d),r=Yt(r.add(i[1]).add(ht(e,l+48)),42).mul(d),a=a.xor(o[1].mul(9)),r=r.add(i[0].mul(9).add(ht(e,l+40))),s=Yt(s.add(o[0]),33).mul(d),i=Gd(e,l,i[1].mul(d),a.add(o[0])),o=Gd(e,l+32,s.add(o[1]),r.add(ht(e,l+16))),[s,a]=[a,s],Zr(Zr(i[0],o[0],d).add(vb(r).mul(LI)).add(s),Zr(i[1],o[1],d).add(a),d)}function sD(e,t){return t==="string"?Sc(e):Cm([e],t)}function iD(e,t){return e instanceof Float32Array&&t==="float32"||e instanceof Int32Array&&t==="int32"||e instanceof Uint8Array&&t==="bool"}function Cm(e,t){if(t==="string")throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=Zs(e)),H().getBool("DEBUG")&&NI(e,t),iD(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"){let n=new Uint8Array(e.length);for(let a=0;a{a=n()},s,i=Gp();if(this.backendTimer.timerAvailable())s=this.backendTimer.time(r);else{r();for(let o of a)o.dataSync();s=Promise.resolve({kernelMs:Gp()-i})}if(H().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let o=0;o{uD(u,l.dtype,e)})}return{kernelName:e,outputs:a,inputs:t,timeMs:s.then(o=>o.kernelMs),extraInfo:s.then(o=>o.getExtraProfileInfo!=null?o.getExtraProfileInfo():"")}}logKernelProfile(e){let{kernelName:t,outputs:n,timeMs:a,inputs:r,extraInfo:s}=e;n.forEach(i=>{Promise.all([i.data(),a,s]).then(o=>{this.logger.logKernelProfile(t,i,o[0],o[1],r,o[2])})})}};function uD(e,t,n){if(t!=="float32")return!1;for(let a=0;a0?m:""} `}}console.log(`%c${o} %c${i} %c${l}D ${p} %c${u} %c${d} %c${s}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}};function cD(e,t,n){let a={},r={};for(let l=0;la[f.id]=!0),h=!0,r[u.id]=!0;break}if(h)break}}let s={};s[n.id]=!0;let i={};for(let l=e.length-1;l>=0;l--){let u=e[l],p=u.inputs;for(let d=0;d=0;r--){let s=t[r],i=[];if(s.outputs.forEach(l=>{let u=e[l.id];u!=null?i.push(u):i.push(null)}),s.gradient==null)throw new Error(`Cannot compute gradient: gradient function not found for ${s.kernelName}.`);let o=s.gradient(i);for(let l in s.inputs){if(!(l in o))throw new Error(`Cannot backprop through input ${l}. Available gradients found: ${Object.keys(o)}.`);let u=n(()=>o[l]());if(u.dtype!=="float32")throw new Error(`Error in gradient for op ${s.kernelName}. The gradient of input ${l} must have 'float32' dtype, but has '${u.dtype}'`);let p=s.inputs[l];if(!ps(u.shape,p.shape))throw new Error(`Error in gradient for op ${s.kernelName}. The gradient of input '${l}' has shape '${u.shape}', which does not match the shape of the input '${p.shape}'`);if(e[p.id]==null)e[p.id]=u;else{let d=e[p.id];e[p.id]=a(d,u),d.dispose()}}}}var U1=20,Ip=3,sb=7;function hD(e,t,n,a){let r=vl(t),s=mD(e,t,n,r),i=t.length,o=ah(e,t,n,r,s),l=["Tensor"];return a&&(l.push(` dtype: ${n}`),l.push(` rank: ${i}`),l.push(` shape: [${t}]`),l.push(" values:")),l.push(o.map(u=>" "+u).join(`
-`)),l.join(`
-`)}function mD(e,t,n,a){let r=mt(t),s=a[a.length-1],i=new Array(s).fill(0),o=t.length,l=n==="complex64"?_p(e):e;if(o>1)for(let u=0;uU1){let g=Ip*i,y=Array.from(e.slice(0,g)),b=Array.from(e.slice((o-Ip)*i,o*i));return n==="complex64"&&(y=_p(y),b=_p(b)),["["+y.map((x,w)=>Cp(x,r[w],n)).join(", ")+", ..., "+b.map((x,w)=>Cp(x,r[o-Ip+w],n)).join(", ")+"]"]}let f=n==="complex64"?_p(e):Array.from(e);return["["+f.map((g,y)=>Cp(g,r[y],n)).join(", ")+"]"]}let u=t.slice(1),p=a.slice(1),d=a[0]*i,c=[];if(o>U1){for(let f=0;f`Length of values '${a}' 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||TI(t,this.size),this.strides=vl(e)}set(e,...t){t.length===0&&(t=[0]),$(t.length===this.rank,()=>`The number of provided coordinates (${t.length}) must match the rank (${this.rank})`);let n=this.locToIndex(t);this.values[n]=e}get(...e){e.length===0&&(e=[0]);let t=0;for(let a of e){if(a<0||a>=this.shape[t]){let r=`Requested out of range element at ${e}. Buffer shape=${this.shape}`;throw new Error(r)}t++}let n=e[e.length-1];for(let a=0;avh(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}dataToGPU(e){return this.throwIfDisposed(),Oa().readToGPU(this.dataId,e)}dataSync(){this.throwIfDisposed();let e=Oa().readSync(this.dataId);if(this.dtype==="string")try{return e.map(t=>vh(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();let e=await Oa().read(this.dataId);return this.dtype==="string"?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(Oa().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return Ko.print(this,e)}clone(){return this.throwIfDisposed(),Ko.clone(this)}toString(e=!1){let t=this.dataSync();return hD(t,this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),Ko.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),Oa().makeVariable(this,e,t,n)}};Object.defineProperty(Te,Symbol.hasInstance,{value:e=>!!e&&e.data!=null&&e.dataSync!=null&&e.throwIfDisposed!=null});function J(){return Sx("Tensor",()=>Te)}J();var ts=class extends Te{constructor(e,t,n,a){super(e.shape,e.dtype,e.dataId,a),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(!ps(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);Oa().disposeTensor(this),this.dataId=e.dataId,Oa().incRef(this,null)}dispose(){Oa().disposeVariable(this),this.isDisposedInternal=!0}};Object.defineProperty(ts,Symbol.hasInstance,{value:e=>e instanceof Te&&e.assign!=null&&e.assign instanceof Function});var Va={};Ae(Va,{assertTypesMatch:()=>BI,getTensorsInContainer:()=>Nx,isTensorInList:()=>vD,makeTypesMatch:()=>_t});var wb;(function(e){e.R0="R0",e.R1="R1",e.R2="R2",e.R3="R3",e.R4="R4",e.R5="R5",e.R6="R6"})(wb||(wb={}));var kb;(function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"})(kb||(kb={}));var Ib;(function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"})(Ib||(Ib={}));var Sb;(function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"})(Sb||(Sb={}));var Tb;(function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"})(Tb||(Tb={}));var xD={float32:Sb,int32:kb,bool:Ib,complex64:Tb};function ma(e,t){if(e==="string"||t==="string"){if(e==="string"&&t==="string")return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return xD[e][t]}function _m(e){return ma(e,"int32")}function _t(e,t){if(e.dtype===t.dtype)return[e,t];let n=ma(e.dtype,t.dtype);return[e.cast(n),t.cast(n)]}function BI(e,t){$(e.dtype===t.dtype,()=>`The dtypes of the first(${e.dtype}) and second(${t.dtype}) input must match`)}function vD(e,t){return t.some(n=>n.id===e.id)}function Nx(e){let t=[];return VI(e,t,new Set),t}function VI(e,t,n){if(e==null)return;if(e instanceof Te){t.push(e);return}if(!wD(e))return;let a=e;for(let r in a){let s=a[r];n.has(s)||(n.add(s),VI(s,t,n))}}function wD(e){return Array.isArray(e)||typeof e=="object"}function ib(e){return e.kernelName!=null}var G1=class{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,get kernelNames(){return Array.from(new Set(this.kernels.map(e=>e.name)))}}}dispose(){for(let e in this.registeredVariables)this.registeredVariables[e].dispose()}},Hp=class{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new G1}async ready(){if(this.pendingBackendInit!=null)return this.pendingBackendInit.then(()=>{});if(this.backendInstance!=null)return;let e=this.getSortedBackends();for(let t=0;t{e.setupFunc!=null&&e.setupFunc(this.backendInstance)})}disposeRegisteredKernels(e){xh(e).forEach(t=>{t.disposeFunc!=null&&t.disposeFunc(this.registry[e])})}initializeBackend(e){let t=this.registryFactory[e];if(t==null)throw new Error(`Cannot initialize backend ${e}, no registration found.`);try{let n=t.factory();if(n&&!(n instanceof rc)&&typeof n.then=="function"){let a=++this.pendingBackendInitId,r=n.then(s=>a(athis.registryFactory[t].priority-this.registryFactory[e].priority)}initializeBackendsAndReturnBest(){let e=this.getSortedBackends();for(let t=0;tthis.startScope(n),()=>this.endScope(a),()=>(a=t(),a instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),a))}scopedRun(e,t,n){e();try{let a=n();return t(),a}catch(a){throw t(),a}}nextTensorId(){return Hp.nextTensorId++}nextVariableId(){return Hp.nextVariableId++}clone(e){let t=O.runKernel(Di,{x:e}),n={x:e},a=s=>({x:()=>{let i="float32",o={x:s},l={dtype:i};return O.runKernel(bi,o,l)}}),r=[];return this.addTapeNode(this.state.activeScope.name,n,[t],a,r,{}),t}runKernel(e,t,n){if(this.backendName==null&&this.backend,bh(e,this.backendName)==null)throw new Error(`Kernel '${e}' not registered for backend '${this.backendName}'`);return this.runKernelFunc({kernelName:e,inputs:t,attrs:n})}shouldCheckForMemLeaks(){return this.ENV.getBool("IS_TEST")}checkKernelForMemLeak(e,t,n){let a=this.backend.numDataIds(),r=0;n.forEach(o=>{r+=o.dtype==="complex64"?3:1});let s=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],i=a-t-r-s;if(i>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${i} data ids) after running '${e}'`)}runKernelFunc(e){let t,n=[],a=this.isTapeOn(),r=this.state.numBytes,s=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);let i;this.backendName==null&&this.backend;let o,l=ib(e)?e.kernelName:this.state.activeScope!=null?this.state.activeScope.name:"";if(ib(e)){let{kernelName:h,inputs:m,attrs:f}=e;this.backendName==null&&this.backend;let g=bh(h,this.backendName);$(g!=null,()=>`Cannot find registered kernel '${h}' for backend '${this.backendName}'`),i=()=>{let y=this.backend.numDataIds();o=g.kernelFunc({inputs:m,attrs:f,backend:this.backend});let b=Array.isArray(o)?o:[o];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(h,y,b);let x=b.map(w=>w.rank!=null?w:this.makeTensorFromTensorInfo(w));if(a){let w=this.getTensorsForGradient(h,m,x);n=this.saveTensorsForBackwardMode(w)}return x}}else{let{forwardFunc:h}=e,m=f=>{!a||(n=f.map(g=>this.keep(this.clone(g))))};i=()=>{let f=this.backend.numDataIds();o=this.tidy(()=>h(this.backend,m));let g=Array.isArray(o)?o:[o];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(l,f,g),g}}let{inputs:u,attrs:p}=e,d=ib(e)?null:e.backwardsFunc,c;return this.scopedRun(()=>this.state.kernelDepth++,()=>this.state.kernelDepth--,()=>{!this.ENV.getBool("DEBUG")&&!this.state.profiling?t=i():(c=this.profiler.profileKernel(l,u,()=>i()),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(c),t=c.outputs)}),a&&this.addTapeNode(l,u,t,d,n,p),this.state.profiling&&this.state.activeProfile.kernels.push({name:l,bytesAdded:this.state.numBytes-r,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-s,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(u).map(h=>u[h]!=null?u[h].shape:null),outputShapes:t.map(h=>h.shape),kernelTimeMs:c.timeMs,extraInfo:c.extraInfo}),Array.isArray(o)?t:t[0]}saveTensorsForBackwardMode(e){return e.map(t=>this.keep(this.clone(t)))}getTensorsForGradient(e,t,n){let a=xb(e);if(a!=null){let r=a.inputsToSave||[],s=a.outputsToSave||[],i;a.saveAllInputs?($(Array.isArray(t),()=>"saveAllInputs is true, expected inputs to be an array."),i=Object.keys(t).map(l=>t[l])):i=r.map(l=>t[l]);let o=n.filter((l,u)=>s[u]);return i.concat(o)}return[]}makeTensor(e,t,n,a){if(e==null)throw new Error("Values passed to engine.makeTensor() are null");n=n||"float32",a=a||this.backend;let r=e;n==="string"&&Kr(e[0])&&(r=e.map(o=>Sc(o)));let s=a.write(r,t,n),i=new Te(t,n,s,this.nextTensorId());if(this.trackTensor(i,a),n==="string"){let o=this.state.tensorInfo.get(s),l=_I(r);this.state.numBytes+=l-o.bytes,o.bytes=l}return i}makeTensorFromDataId(e,t,n,a){n=n||"float32";let r={dataId:e,shape:t,dtype:n};return this.makeTensorFromTensorInfo(r,a)}makeTensorFromTensorInfo(e,t){let{dataId:n,shape:a,dtype:r}=e,s=new Te(a,r,n,this.nextTensorId());return this.trackTensor(s,t),s}makeVariable(e,t=!0,n,a){n=n||this.nextVariableId().toString(),a!=null&&a!==e.dtype&&(e=e.cast(a));let r=new ts(e,t,n,this.nextTensorId());if(this.state.registeredVariables[r.name]!=null)throw new Error(`Variable with name ${r.name} was already registered`);return this.state.registeredVariables[r.name]=r,this.incRef(r,this.backend),r}trackTensor(e,t){this.state.numTensors++,e.dtype==="string"&&this.state.numStringTensors++;let n=0;e.dtype!=="complex64"&&e.dtype!=="string"&&(n=e.size*bb(e.dtype)),this.state.numBytes+=n,this.state.tensorInfo.has(e.dataId)||(this.state.numDataBuffers++,this.state.tensorInfo.set(e.dataId,{backend:t||this.backend,dtype:e.dtype,shape:e.shape,bytes:n})),e instanceof ts||this.track(e)}incRef(e,t){this.trackTensor(e,t),this.backend.incRef(e.dataId)}removeDataId(e,t){this.state.tensorInfo.has(e)&&this.state.tensorInfo.get(e).backend===t&&(this.state.tensorInfo.delete(e),this.state.numDataBuffers--)}disposeTensor(e){if(!this.state.tensorInfo.has(e.dataId))return;let t=this.state.tensorInfo.get(e.dataId);if(this.state.numTensors--,e.dtype==="string"&&(this.state.numStringTensors--,this.state.numBytes-=t.bytes),e.dtype!=="complex64"&&e.dtype!=="string"){let n=e.size*bb(e.dtype);this.state.numBytes-=n}t.backend.disposeData(e.dataId)&&this.removeDataId(e.dataId,t.backend)}disposeVariables(){for(let e in this.state.registeredVariables){let 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(){let 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;let 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(a=>a.totalBytesSnapshot)),this.state.activeProfile.newBytes=this.state.numBytes-t,this.state.activeProfile.newTensors=this.state.numTensors-n;for(let a of this.state.activeProfile.kernels)a.kernelTimeMs=await a.kernelTimeMs,a.extraInfo=await a.extraInfo;return this.state.activeProfile}isTapeOn(){return this.state.gradientDepth>0&&this.state.kernelDepth===0}addTapeNode(e,t,n,a,r,s){let i={id:this.state.nextTapeNodeId++,kernelName:e,inputs:t,outputs:n,saved:r},o=xb(e);o!=null&&(a=o.gradFunc),a!=null&&(i.gradient=l=>(l=l.map((u,p)=>{if(u==null){let d=n[p],c=Kh(d.size,d.dtype);return this.makeTensor(c,d.shape,d.dtype)}return u}),a(l.length>1?l:l[0],r,s))),this.state.activeTape.push(i)}keep(e){return e.kept=!0,e}startTape(){this.state.gradientDepth===0&&(this.state.activeTape=[]),this.state.gradientDepth++}endTape(){this.state.gradientDepth--}startScope(e){let t={track:[],name:"unnamed scope",id:this.state.nextScopeId++};e&&(t.name=e),this.state.scopeStack.push(t),this.state.activeScope=t}endScope(e){let t=Nx(e),n=new Set(t.map(r=>r.id));for(let r=0;r{!r.kept&&r.scopeId===a.id&&this.track(r)})}gradients(e,t,n,a=!1){if($(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}'`);let r=this.scopedRun(()=>this.startTape(),()=>this.endTape(),()=>this.tidy("forward",e));$(r instanceof Te,()=>"The result y returned by f() must be a tensor.");let s=cD(this.state.activeTape,t,r);if(!a&&s.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",()=>{let i={};i[r.id]=n==null?kD(r.shape):n,dD(i,s,l=>this.tidy(l),ID);let o=t.map(l=>i[l.id]);return this.state.gradientDepth===0&&(this.state.activeTape.forEach(l=>{for(let u of l.saved)u.dispose()}),this.state.activeTape=null),{value:r,grads:o}})}customGrad(e){return $(es(e),()=>"The f passed in customGrad(f) must be a function."),(...t)=>{$(t.every(i=>i instanceof Te),()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors");let n,a={};t.forEach((i,o)=>{a[o]=i});let r=(i,o)=>(n=e(...t,o),$(n.value instanceof Te,()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),$(es(n.gradFunc),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."),n.value),s=(i,o)=>{let l=n.gradFunc(i,o),u=Array.isArray(l)?l:[l];$(u.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(...)."),$(u.every(d=>d instanceof Te),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors.");let p={};return u.forEach((d,c)=>{p[c]=()=>d}),p};return this.runKernelFunc({forwardFunc:r,backwardsFunc:s,inputs:a})}}readSync(e){return this.state.tensorInfo.get(e).backend.readSync(e)}read(e){return this.state.tensorInfo.get(e).backend.read(e)}readToGPU(e,t){return this.state.tensorInfo.get(e).backend.readToGPU(e,t)}async time(e){let t=Gp(),n=await this.backend.time(e);return n.wallMs=Gp()-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 G1;for(let e in this.registry)this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e];this.backendName=null,this.backendInstance=null,this.pendingBackendInit=null}};Hp.nextTensorId=0;Hp.nextVariableId=0;function kD(e){let t=vx(mt(e),"float32");return O.makeTensor(t,e,"float32")}function UI(){let e=DI();if(e._tfengine==null){let t=new FI(e);e._tfengine=new Hp(t)}return HF(e._tfengine.ENV),gD(()=>e._tfengine),e._tfengine}var O=UI();function ID(e,t){let n={a:e,b:t};return O.runKernel(cs,n)}var Tc={};Ae(Tc,{isBrowser:()=>GI,isMobile:()=>ND,mockIsMobile:()=>TD});function SD(){return typeof navigator!="undefined"&&navigator!=null}var Nb;function TD(e){Nb=e}function ND(e){if(Nb!==void 0)return Nb;if(e||SD()){if(e||(e=navigator),e.product==="ReactNative")return!0;let t=e.userAgent||e.vendor||(typeof window!="undefined"?window.opera:"");if(!t){let n=e;return n.userAgentData&&n.userAgentData.mobile}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(t)||/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(t.substr(0,4))}return!1}function GI(){return typeof window!="undefined"&&window.document!=null||typeof WorkerGlobalScope!="undefined"}var Jn=H();Jn.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.")});Jn.registerFlag("IS_BROWSER",()=>GI());Jn.registerFlag("IS_NODE",()=>typeof process!="undefined"&&typeof process.versions!="undefined"&&typeof process.versions.node!="undefined");Jn.registerFlag("IS_CHROME",()=>typeof navigator!="undefined"&&navigator!=null&&navigator.userAgent!=null&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor));Jn.registerFlag("PROD",()=>!1);Jn.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",()=>Jn.getBool("DEBUG"));Jn.registerFlag("DEPRECATION_WARNINGS_ENABLED",()=>!0);Jn.registerFlag("IS_TEST",()=>!1);Jn.registerFlag("CHECK_COMPUTATION_FOR_ERRORS",()=>!0);Jn.registerFlag("WRAP_TO_IMAGEBITMAP",()=>!1);Jn.registerFlag("ENGINE_COMPILE_ONLY",()=>!1);Jn.registerFlag("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU",()=>!1);Jn.registerFlag("USE_SETTIMEOUTCUSTOM",()=>!1);function ir(e,t){let n=e;if(hn(e))return t==="string"?[]:[e.length];if(typeof e=="object"&&"texture"in e){let r=e.channels||"RGBA";return[e.height,e.width*r.length]}if(!Array.isArray(e))return[];let a=[];for(;Array.isArray(n)||hn(n)&&t!=="string";)a.push(n.length),n=n[0];return Array.isArray(e)&&H().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&HI(e,a,[]),a}function HI(e,t,n){if(n=n||[],!Array.isArray(e)&&!hn(e)){$(t.length===0,()=>`Element arr[${n.join("][")}] is a primitive, but should be an array/TypedArray of ${t[0]} elements`);return}$(t.length>0,()=>`Element arr[${n.join("][")}] should be a primitive, but is an array of ${e.length} elements`),$(e.length===t[0],()=>`Element arr[${n.join("][")}] should have ${t[0]} elements, but has ${e.length} elements`);let a=t.slice(1);for(let r=0;r=0&&(r=a),H1(a,r,t,n),e==null||!hn(e)&&!Array.isArray(e)&&typeof e!="number"&&typeof e!="boolean"&&typeof e!="string"){let o=e==null?"null":e.constructor.name;throw new Error(`Argument '${t}' passed to '${n}' must be a Tensor or TensorLike, but got '${o}'`)}let s=ir(e,r);!hn(e)&&!Array.isArray(e)&&(e=[e]);let i=r!=="string"?Cm(e,r):Zs(e,[],!0);return O.makeTensor(i,s,r)}function jp(e,t,n,a="numeric"){if(!Array.isArray(e))throw new Error(`Argument ${t} passed to ${n} must be a \`Tensor[]\` or \`TensorLike[]\``);return e.map((r,s)=>_(r,`${t}[${s}]`,n,a))}var Cx="__op";function L(e){let 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],a=e[n];n.endsWith("_")&&(n=n.substring(0,n.length-1)),n=n+Cx;let r=(...s)=>{O.startScope(n);try{let i=a(...s);return kx(i)&&console.error("Cannot return a Promise inside of tidy."),O.endScope(i),i}catch(i){throw O.endScope(null),i}};return Object.defineProperty(r,"name",{value:n,configurable:!0}),r}function CD(e,t){let n=_(e,"real","complex"),a=_(t,"imag","complex");Sn(n.shape,a.shape,`real and imag shapes, ${n.shape} and ${a.shape}, must match in call to tf.complex().`);let r={real:n,imag:a};return O.runKernel(Qh,r)}var Cr=L({complex_:CD});function fs(e,t,n,a){if(a==null&&(a=qh(e)),a==="complex64")throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(typeof e=="object"&&"texture"in e){if(a!=="float32"&&a!=="int32")throw new Error(`Creating tensor from texture only supports 'float32'|'int32' dtype, while the dtype is ${a}.`);return e.channels=e.channels||"RGBA",O.backend.createTensorFromTexture(e,t||n,a)}if(!hn(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){wx(t);let r=mt(t),s=mt(n);$(r===s,()=>`Based on the provided shape, [${t}], the tensor should have ${r} values but has ${s}`);for(let i=0;i`Error creating a new Tensor. Inferred shape (${n}) does not match the provided shape (${t}). `)}}return!hn(e)&&!Array.isArray(e)&&(e=[e]),t=t||n,e=a!=="string"?Cm(e,a):Zs(e,[],!0),O.makeTensor(e,t,a)}function kn(e,t,n){let a=ir(e,n);return fs(e,t,a,n)}var Cb={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8},wh=4;async function _D(e,t){let n=[],a=[],r=Array.isArray(e)?e.map(i=>i.name):Object.keys(e);for(let i=0;i{let c=await l.bytes(),h=c.reduce((g,y)=>g+y.length,0)+wh*c.length,m=new Uint8Array(h),f=0;for(let g=0;g{if(t+=s.byteLength,n.push(s.byteLength===s.buffer.byteLength?s:new s.constructor(s)),!(s instanceof Float32Array||s instanceof Int32Array||s instanceof Uint8Array))throw new Error(`Unsupported TypedArray subtype: ${s.constructor.name}`)});let a=new Uint8Array(t),r=0;return n.forEach(s=>{a.set(new Uint8Array(s.buffer),r),r+=s.byteLength}),a.buffer}var _x=typeof Buffer!="undefined"&&(typeof Blob=="undefined"||typeof atob=="undefined"||typeof btoa=="undefined");function j1(e){return _x?Buffer.byteLength(e):new Blob([e]).size}function AD(e){if(_x)return Buffer.from(e).toString("base64");let t=new Uint8Array(e),n="";for(let a=0,r=t.length;a{t+=r.byteLength});let n=new Uint8Array(t),a=0;return e.forEach(r=>{n.set(new Uint8Array(r),a),a+=r.byteLength}),n.buffer}function q1(e){let t="/";for(e=e.trim();e.endsWith(t);)e=e.slice(0,e.length-1);let n=e.split(t);return n[n.length-1]}function qI(e,t){let n={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,weightsManifest:t};return e.signature!=null&&(n.signature=e.signature),e.userDefinedMetadata!=null&&(n.userDefinedMetadata=e.userDefinedMetadata),e.modelInitializer!=null&&(n.modelInitializer=e.modelInitializer),e.initializerSignature!=null&&(n.initializerSignature=e.initializerSignature),e.trainingConfig!=null&&(n.trainingConfig=e.trainingConfig),n}function KI(e,t,n){let a={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy};if(e.trainingConfig!=null&&(a.trainingConfig=e.trainingConfig),e.weightsManifest!=null){if(!t)throw new Error("modelJSON has weightsManifest but weightSpecs is null");if(!n)throw new Error("modelJSON has weightsManifest but weightData is null");a.weightSpecs=t,a.weightData=n}return e.signature!=null&&(a.signature=e.signature),e.userDefinedMetadata!=null&&(a.userDefinedMetadata=e.userDefinedMetadata),e.modelInitializer!=null&&(a.modelInitializer=e.modelInitializer),e.initializerSignature!=null&&(a.initializerSignature=e.initializerSignature),a}async function Ax(e,t){let n,a;return e.weightsManifest!=null&&([n,a]=await t(e.weightsManifest)),KI(e,n,a)}function Nc(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:j1(JSON.stringify(e.modelTopology)),weightSpecsBytes:e.weightSpecs==null?0:j1(JSON.stringify(e.weightSpecs)),weightDataBytes:e.weightData==null?0:e.weightData.byteLength}}function XI(e){let t=[];for(let n of e)t.push(...n.weights);return t}function FD(){let e=n=>{let a=n<<13,r=0;for(;(a&8388608)===0;)r-=8388608,a<<=1;return a&=-8388609,r+=947912704,a|r},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 DD(){let 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 RD(){let e=new Uint32Array(64);for(let t=0;t<64;t++)e[t]=1024;return e[0]=e[32]=0,e}function MD(){let e=FD(),t=DD(),n=RD();return a=>{let r=new ArrayBuffer(4*a.length),s=new Uint32Array(r);for(let i=0;i>10]+(o&1023)]+t[o>>10];s[i]=l}return new Float32Array(r)}}var At=class{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return At.instance==null&&(At.instance=new At),At.instance}static registerSaveRouter(e){At.getInstance().saveRouters.push(e)}static registerLoadRouter(e){At.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return At.getHandlers(e,"save")}static getLoadHandlers(e,t){return At.getHandlers(e,"load",t)}static getHandlers(e,t,n){let a=[];return(t==="load"?At.getInstance().loadRouters:At.getInstance().saveRouters).forEach(r=>{let s=r(e,n);s!==null&&a.push(s)}),a}},PD=e=>At.registerSaveRouter(e),OD=e=>At.registerLoadRouter(e),LD=e=>At.getSaveHandlers(e),zD=(e,t)=>At.getLoadHandlers(e,t),_b="tensorflowjs",Eb=1,Gs="models_store",Xr="model_info_store";function YI(){if(!H().getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");let 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 Ab(e){let t=e.result;t.createObjectStore(Gs,{keyPath:"modelPath"}),t.createObjectStore(Xr,{keyPath:"modelPath"})}var ti=class{constructor(e){if(this.indexedDB=YI(),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,a)=>{let r=this.indexedDB.open(_b,Eb);r.onupgradeneeded=()=>Ab(r),r.onsuccess=()=>{let s=r.result;if(t==null){let i=s.transaction(Gs,"readonly"),o=i.objectStore(Gs).get(this.modelPath);o.onsuccess=()=>{if(o.result==null)return s.close(),a(new Error(`Cannot find model with path '${this.modelPath}' in IndexedDB.`));n(o.result.modelArtifacts)},o.onerror=l=>(s.close(),a(o.error)),i.oncomplete=()=>s.close()}else{let i=Nc(t),o=s.transaction(Xr,"readwrite"),l=o.objectStore(Xr),u=l.put({modelPath:this.modelPath,modelArtifactsInfo:i}),p;u.onsuccess=()=>{p=s.transaction(Gs,"readwrite");let d=p.objectStore(Gs).put({modelPath:this.modelPath,modelArtifacts:t,modelArtifactsInfo:i});d.onsuccess=()=>n({modelArtifactsInfo:i}),d.onerror=c=>{l=o.objectStore(Xr);let h=l.delete(this.modelPath);h.onsuccess=()=>(s.close(),a(d.error)),h.onerror=m=>(s.close(),a(d.error))}},u.onerror=d=>(s.close(),a(u.error)),o.oncomplete=()=>{p==null?s.close():p.oncomplete=()=>s.close()}}},r.onerror=s=>a(r.error)})}};ti.URL_SCHEME="indexeddb://";var ZI=e=>H().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(ti.URL_SCHEME)?WD(e.slice(ti.URL_SCHEME.length)):null;At.registerSaveRouter(ZI);At.registerLoadRouter(ZI);function WD(e){return new ti(e)}function BD(e){return e.startsWith(ti.URL_SCHEME)?e.slice(ti.URL_SCHEME.length):e}var VD=class{constructor(){this.indexedDB=YI()}async listModels(){return new Promise((e,t)=>{let n=this.indexedDB.open(_b,Eb);n.onupgradeneeded=()=>Ab(n),n.onsuccess=()=>{let a=n.result,r=a.transaction(Xr,"readonly"),s=r.objectStore(Xr).getAll();s.onsuccess=()=>{let i={};for(let o of s.result)i[o.modelPath]=o.modelArtifactsInfo;e(i)},s.onerror=i=>(a.close(),t(s.error)),r.oncomplete=()=>a.close()},n.onerror=a=>t(n.error)})}async removeModel(e){return e=BD(e),new Promise((t,n)=>{let a=this.indexedDB.open(_b,Eb);a.onupgradeneeded=()=>Ab(a),a.onsuccess=()=>{let r=a.result,s=r.transaction(Xr,"readwrite"),i=s.objectStore(Xr),o=i.get(e),l;o.onsuccess=()=>{if(o.result==null)return r.close(),n(new Error(`Cannot find model with path '${e}' in IndexedDB.`));{let u=i.delete(e),p=()=>{l=r.transaction(Gs,"readwrite");let d=l.objectStore(Gs).delete(e);d.onsuccess=()=>t(o.result.modelArtifactsInfo),d.onerror=c=>n(o.error)};u.onsuccess=p,u.onerror=d=>(p(),r.close(),n(o.error))}},o.onerror=u=>(r.close(),n(o.error)),s.oncomplete=()=>{l==null?r.close():l.oncomplete=()=>r.close()}},a.onerror=r=>n(a.error)})}},Ir="/",Xo="tensorflowjs_models",JI="info",UD="model_topology",GD="weight_specs",HD="weight_data",jD="model_metadata";function QI(e){return{info:[Xo,e,JI].join(Ir),topology:[Xo,e,UD].join(Ir),weightSpecs:[Xo,e,GD].join(Ir),weightData:[Xo,e,HD].join(Ir),modelMetadata:[Xo,e,jD].join(Ir)}}function eS(e){for(let t of Object.values(e))window.localStorage.removeItem(t)}function qD(e){let t=e.split(Ir);if(t.length<3)throw new Error(`Invalid key format: ${e}`);return t.slice(1,t.length-1).join(Ir)}function KD(e){return e.startsWith(ni.URL_SCHEME)?e.slice(ni.URL_SCHEME.length):e}var ni=class{constructor(e){if(!H().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=QI(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.");{let t=JSON.stringify(e.modelTopology),n=JSON.stringify(e.weightSpecs),a=Nc(e);try{this.LS.setItem(this.keys.info,JSON.stringify(a)),this.LS.setItem(this.keys.topology,t),this.LS.setItem(this.keys.weightSpecs,n),this.LS.setItem(this.keys.weightData,AD(e.weightData));let r={format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,signature:e.signature!=null?e.signature:void 0,userDefinedMetadata:e.userDefinedMetadata!=null?e.userDefinedMetadata:void 0,modelInitializer:e.modelInitializer!=null?e.modelInitializer:void 0,initializerSignature:e.initializerSignature!=null?e.initializerSignature:void 0,trainingConfig:e.trainingConfig!=null?e.trainingConfig:void 0};return this.LS.setItem(this.keys.modelMetadata,JSON.stringify(r)),{modelArtifactsInfo:a}}catch(r){throw eS(this.keys),new Error(`Failed to save model '${this.modelPath}' to local storage: size quota being exceeded is a possible cause of this failure: modelTopologyBytes=${a.modelTopologyBytes}, weightSpecsBytes=${a.weightSpecsBytes}, weightDataBytes=${a.weightDataBytes}.`)}}}async load(){let 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.");let 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;let a=JSON.parse(this.LS.getItem(this.keys.weightSpecs));if(a==null)throw new Error(`In local storage, the weight specs of model '${this.modelPath}' are missing.`);t.weightSpecs=a;let r=this.LS.getItem(this.keys.modelMetadata);if(r!=null){let i=JSON.parse(r);t.format=i.format,t.generatedBy=i.generatedBy,t.convertedBy=i.convertedBy,i.signature!=null&&(t.signature=i.signature),i.userDefinedMetadata!=null&&(t.userDefinedMetadata=i.userDefinedMetadata),i.modelInitializer!=null&&(t.modelInitializer=i.modelInitializer),i.initializerSignature!=null&&(t.initializerSignature=i.initializerSignature),i.trainingConfig!=null&&(t.trainingConfig=i.trainingConfig)}let s=this.LS.getItem(this.keys.weightData);if(s==null)throw new Error(`In local storage, the binary weight values of model '${this.modelPath}' are missing.`);return t.weightData=$D(s),t}};ni.URL_SCHEME="localstorage://";var tS=e=>H().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(ni.URL_SCHEME)?XD(e.slice(ni.URL_SCHEME.length)):null;At.registerSaveRouter(tS);At.registerLoadRouter(tS);function XD(e){return new ni(e)}var YD=class{constructor(){$(H().getBool("IS_BROWSER"),()=>"Current environment is not a web browser"),$(typeof window=="undefined"||typeof window.localStorage!="undefined",()=>"Current browser does not appear to support localStorage"),this.LS=window.localStorage}async listModels(){let e={},t=Xo+Ir,n=Ir+JI;for(let a=0;a"scheme must not be undefined or null."),e.endsWith(Jo)&&(e=e.slice(0,e.indexOf(Jo))),$(e.length>0,()=>"scheme must not be an empty string.");let n=Pn.getInstance();$(n.managers[e]==null,()=>`A model store manager is already registered for scheme '${e}'.`),n.managers[e]=t}static getManager(e){let t=Pn.getInstance().managers[e];if(t==null)throw new Error(`Cannot find model manager for scheme '${e}'`);return t}static getSchemes(){return Object.keys(Pn.getInstance().managers)}};function rh(e){if(e.indexOf(Jo)===-1)throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${Pn.getSchemes().join(",")}`);return{scheme:e.split(Jo)[0],path:e.split(Jo)[1]}}async function nS(e,t,n=!1){$(e!==t,()=>`Old path and new path are the same: '${e}'`);let a=At.getLoadHandlers(e);$(a.length>0,()=>`Copying failed because no load handler is found for source URL ${e}.`),$(a.length<2,()=>`Copying failed because more than one (${a.length}) load handlers for source URL ${e}.`);let r=a[0],s=At.getSaveHandlers(t);$(s.length>0,()=>`Copying failed because no save handler is found for destination URL ${t}.`),$(s.length<2,()=>`Copying failed because more than one (${a.length}) save handlers for destination URL ${t}.`);let i=s[0],o=rh(e).scheme,l=rh(e).path,u=o===rh(e).scheme,p=await r.load();n&&u&&await Pn.getManager(o).removeModel(l);let d=await i.save(p);return n&&!u&&await Pn.getManager(o).removeModel(l),d.modelArtifactsInfo}async function ZD(){let e=Pn.getSchemes(),t={};for(let n of e){let a=await Pn.getManager(n).listModels();for(let r in a){let s=n+Jo+r;t[s]=a[r]}}return t}async function JD(e){let t=rh(e);return Pn.getManager(t.scheme).removeModel(t.path)}async function QD(e,t){return nS(e,t,!1)}async function eR(e,t){return nS(e,t,!0)}var tR=class{constructor(){this.messageName="setTimeoutCustom",this.functionRefs=[],this.handledMessageCount=0,this.hasEventListener=!1}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)}setTimeoutCustom(e,t){if(typeof window=="undefined"||!H().getBool("USE_SETTIMEOUTCUSTOM")){setTimeout(e,t);return}this.functionRefs.push(e),setTimeout(()=>{window.postMessage({name:this.messageName,index:this.functionRefs.length-1},"*")},t),this.hasEventListener||(this.hasEventListener=!0,window.addEventListener("message",n=>{if(n.source===window&&n.data.name===this.messageName){n.stopPropagation();let a=this.functionRefs[n.data.index];a(),this.handledMessageCount++,this.handledMessageCount===this.functionRefs.length&&(this.functionRefs=[],this.handledMessageCount=0)}},!0))}};if(H().get("IS_BROWSER")){H().setPlatform("browser",new tR);try{Pn.registerManager(ni.URL_SCHEME,new YD)}catch(e){}try{Pn.registerManager(ti.URL_SCHEME,new VD)}catch(e){}}var nR={importFetch:()=>cF()},ob,aR=class{constructor(){this.util=dF(),this.textEncoder=new this.util.TextEncoder}fetch(e,t){return H().global.fetch!=null?H().global.fetch(e,t):(ob==null&&(ob=nR.importFetch()),ob(e,t))}now(){let 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)}};H().get("IS_NODE")&&!H().get("IS_BROWSER")&&H().setPlatform("node",new aR);function Pe(e,t="float32",n){return t=t||"float32",wx(e),new Ht(e,t,n)}function rR(e,t){let n=_(e,"x","cast");if(!CI(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");let a={x:n},r={dtype:t};return O.runKernel(bi,a,r)}var oe=L({cast_:rR});function sR(e){let t={x:_(e,"x","clone","string_or_numeric")};return O.runKernel(Di,t)}var rr=L({clone_:sR});function $x(e,t=!1){console.log(e.toString(t))}UI();var iR={buffer:Pe,cast:oe,clone:rr,print:$x};yD(iR);var Ut={};Ae(Ut,{browserFiles:()=>hR,browserHTTPRequest:()=>bR,concatenateArrayBuffers:()=>Ex,copyModel:()=>QD,decodeWeights:()=>jI,encodeWeights:()=>_D,fromMemory:()=>vR,fromMemorySync:()=>oS,getLoadHandlers:()=>zD,getModelArtifactsForJSON:()=>Ax,getModelArtifactsForJSONSync:()=>KI,getModelArtifactsInfoForJSON:()=>Nc,getSaveHandlers:()=>LD,getWeightSpecs:()=>XI,http:()=>Dx,isHTTPScheme:()=>$b,listModels:()=>ZD,loadWeights:()=>mR,moveModel:()=>eR,registerLoadRouter:()=>OD,registerSaveRouter:()=>PD,removeModel:()=>JD,weightsLoaderFactory:()=>rS,withSaveHandler:()=>wR,withSaveHandlerSync:()=>kR});var oR="model",lR=".json",uR=".weights.bin";function K1(e){return new Promise(t=>setTimeout(t)).then(e)}var al=class{constructor(e){if(!H().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(al.URL_SCHEME)&&(e=e.slice(al.URL_SCHEME.length)),(e==null||e.length===0)&&(e=oR),this.modelJsonFileName=e+lR,this.weightDataFileName=e+uR}async save(e){if(typeof document=="undefined")throw new Error("Browser downloads are not supported in this environment since `document` is not present");let 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.");{let n=[{paths:["./"+this.weightDataFileName],weights:e.weightSpecs}],a=qI(e,n),r=window.URL.createObjectURL(new Blob([JSON.stringify(a)],{type:"application/json"})),s=this.modelJsonAnchor==null?document.createElement("a"):this.modelJsonAnchor;if(s.download=this.modelJsonFileName,s.href=r,await K1(()=>s.dispatchEvent(new MouseEvent("click"))),e.weightData!=null){let i=this.weightDataAnchor==null?document.createElement("a"):this.weightDataAnchor;i.download=this.weightDataFileName,i.href=t,await K1(()=>i.dispatchEvent(new MouseEvent("click")))}return{modelArtifactsInfo:Nc(e)}}}};al.URL_SCHEME="downloads://";var pR=class{constructor(e){if(e==null||e.length<1)throw new Error(`When calling browserFiles, at least 1 file is required, but received ${e}`);this.jsonFile=e[0],this.weightsFiles=e.slice(1)}async load(){return new Promise((e,t)=>{let n=new FileReader;n.onload=a=>{let r=JSON.parse(a.target.result),s=r.modelTopology;if(s==null){t(new Error(`modelTopology field is missing from file ${this.jsonFile.name}`));return}if(r.weightsManifest==null){t(new Error(`weightManifest field is missing from file ${this.jsonFile.name}`));return}if(this.weightsFiles.length===0){e({modelTopology:s});return}let i=Ax(r,o=>this.loadWeights(o));e(i)},n.onerror=a=>t(`Failed to read model topology and weights manifest JSON from file '${this.jsonFile.name}'. BrowserFiles supports loading Keras-style tf.Model artifacts only.`),n.readAsText(this.jsonFile)})}loadWeights(e){let t=[],n=[];for(let s of e)t.push(...s.weights),n.push(...s.paths);let a=this.checkManifestAndWeightFiles(e),r=n.map(s=>this.loadWeightsFile(s,a[s]));return Promise.all(r).then(s=>[t,Ex(s)])}loadWeightsFile(e,t){return new Promise((n,a)=>{let r=new FileReader;r.onload=s=>{let i=s.target.result;n(i)},r.onerror=s=>a(`Failed to weights data from file of path '${e}'.`),r.readAsArrayBuffer(t)})}checkManifestAndWeightFiles(e){let t=[],n=this.weightsFiles.map(r=>q1(r.name)),a={};for(let r of e)r.paths.forEach(s=>{let i=q1(s);if(t.indexOf(i)!==-1)throw new Error(`Duplicate file basename found in weights manifest: '${i}'`);if(t.push(i),n.indexOf(i)===-1)throw new Error(`Weight file with basename '${i}' is not provided.`);a[s]=this.weightsFiles[n.indexOf(i)]});if(t.length!==this.weightsFiles.length)throw new Error(`Mismatch in the number of files in weights manifest (${t.length}) and the number of weight files provided (${this.weightsFiles.length}).`);return a}},cR=e=>H().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(al.URL_SCHEME)?dR(e.slice(al.URL_SCHEME.length)):null;At.registerSaveRouter(cR);function dR(e="model"){return new al(e)}function hR(e){return new pR(e)}function X1(e,t,n,a){i(e),n=n==null?0:n,a=a==null?1:a,o(n,a);let r=0,s=l=>(l.then(u=>{let p=n+ ++r/e.length*(a-n);return t(p),u}),l);function i(l){$(l!=null&&Array.isArray(l)&&l.length>0,()=>"promises must be a none empty array")}function o(l,u){$(l>=0&&l<=1,()=>`Progress fraction must be in range [0, 1], but got startFraction ${l}`),$(u>=0&&u<=1,()=>`Progress fraction must be in range [0, 1], but got endFraction ${u}`),$(u>=l,()=>`startFraction must be no more than endFraction, but got startFraction ${l} and endFraction ${u}`)}return Promise.all(e.map(s))}async function aS(e,t){t==null&&(t={});let n=t.fetchFunc==null?H().platform.fetch:t.fetchFunc,a=e.map(u=>n(u,t.requestInit,{isBinary:!0})),r=0,s=.5,i=(t.onProgress==null?await Promise.all(a):await X1(a,t.onProgress,r,s)).map(u=>u.arrayBuffer()),o=.5,l=1;return t.onProgress==null?await Promise.all(i):await X1(i,t.onProgress,o,l)}async function mR(e,t="",n,a){return rS(r=>aS(r,{requestInit:a}))(e,t,n)}function rS(e){return async(t,n="",a)=>{let r=t.map(()=>!1),s={},i=a!=null?a.map(()=>!1):[],o=[];if(t.forEach((h,m)=>{let f=0;h.weights.forEach(g=>{let y="quantization"in g?g.quantization.dtype:g.dtype,b=Cb[y]*mt(g.shape),x=()=>{r[m]=!0,s[m]==null&&(s[m]=[]),s[m].push({manifestEntry:g,groupOffset:f,sizeBytes:b})};a!=null?a.forEach((w,I)=>{w===g.name&&(x(),i[I]=!0)}):x(),o.push(g.name),f+=b})}),!i.every(h=>h)){let h=a.filter((m,f)=>!i[f]);throw new Error(`Could not find weights in manifest with names: ${h.join(", ")}.
-Manifest JSON has weights with names: ${o.join(", ")}.`)}let l=r.reduce((h,m,f)=>(m&&h.push(f),h),[]),u=[];l.forEach(h=>{t[h].paths.forEach(m=>{let f=n+(n.endsWith("/")?"":"/")+m;u.push(f)})});let p=await e(u),d={},c=0;return l.forEach(h=>{let m=t[h].paths.length,f=0;for(let x=0;x{let w=g.slice(x.groupOffset,x.groupOffset+x.sizeBytes),I=jI(w,[x.manifestEntry]);for(let T in I)d[T]=I[T]}),c+=m}),d}}var fR="application/octet-stream",gR="application/json",Fx=class{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?($(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=H().platform.fetch,$(e!=null&&e.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(e)&&$(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.");let t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit);t.body=new FormData;let n=[{paths:["./model.weights.bin"],weights:e.weightSpecs}],a=qI(e,n);t.body.append("model.json",new Blob([JSON.stringify(a)],{type:gR}),"model.json"),e.weightData!=null&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:fR}),"model.weights.bin");let r=await this.fetch(this.path,t);if(r.ok)return{modelArtifactsInfo:Nc(e),responses:[r]};throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${r.status}.`)}async load(){let 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(r){let s=`Failed to parse model JSON of response from ${this.path}.`;throw this.path.endsWith(".pb")?s+=" 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.":s+=" Please make sure the server is serving valid JSON for this request.",new Error(s)}let n=t.modelTopology,a=t.weightsManifest;if(n==null&&a==null)throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`);return Ax(t,r=>this.loadWeights(r))}async loadWeights(e){let t=Array.isArray(this.path)?this.path[1]:this.path,[n,a]=yR(t),r=this.weightPathPrefix||n,s=XI(e),i=[],o=[];for(let u of e)for(let p of u.paths)this.weightUrlConverter!=null?o.push(this.weightUrlConverter(p)):i.push(r+p+a);this.weightUrlConverter&&i.push(...await Promise.all(o));let l=await aS(i,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress});return[s,Ex(l)]}};Fx.URL_SCHEME_REGEX=/^https?:\/\//;function yR(e){let t=e.lastIndexOf("/"),n=e.lastIndexOf("?"),a=e.substring(0,t),r=n>t?e.substring(n):"";return[a+"/",r]}function $b(e){return e.match(Fx.URL_SCHEME_REGEX)!=null}var sS=(e,t)=>{if(typeof fetch=="undefined"&&(t==null||t.fetchFunc==null))return null;{let n=!0;if(Array.isArray(e)?n=e.every(a=>$b(a)):n=$b(e),n)return Dx(e,t)}return null};At.registerSaveRouter(sS);At.registerLoadRouter(sS);function Dx(e,t){return new Fx(e,t)}function bR(e,t){return Dx(e,t)}var lb=class{constructor(e){this.modelArtifacts=e}load(){return this.modelArtifacts}},iS=class{constructor(e){this.saveHandler=e}save(e){return this.saveHandler(e)}},xR=class{constructor(e){e.load&&(this.load=()=>Promise.resolve(e.load())),e.save&&(this.save=t=>Promise.resolve(e.save(t)))}};function vR(e,t,n,a){let r=arguments;return new xR(oS(...r))}function oS(e,t,n,a){return arguments.length===1?e.modelTopology!=null||e.weightSpecs!=null?new lb(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 lb({modelTopology: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 lb({modelTopology:e,weightSpecs:t,weightData:n,trainingConfig:a}))}function wR(e){return new iS(e)}function kR(e){return new iS(e)}var lS={};Ae(lS,{confusionMatrix:()=>UR});function IR(e,t,n=!1,a=!1){let r=_(e,"a","matMul"),s=_(t,"b","matMul");[r,s]=_t(r,s);let i={a:r,b:s},o={transposeA:n,transposeB:a};return O.runKernel(yi,i,o)}var Fe=L({matMul_:IR});function SR(e,t,n=1,a=0,r="int32"){if(t<2)throw new Error(`Error in oneHot: depth must be >=2, but it is ${t}`);let s={indices:_(e,"indices","oneHot","int32")},i={dtype:r,depth:t,onValue:n,offValue:a};return O.runKernel(Gi,s,i)}var rl=L({oneHot_:SR});function TR(){H().set("PROD",!0)}function NR(){H().set("DEBUG",!0)}function CR(){H().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function Rx(e){H().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(e+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}bD(Rx);function _R(){O.disposeVariables()}function Na(){return O}function kh(){return O.memory()}function ER(e){return O.profile(e)}function P(e,t){return O.tidy(e,t)}function _e(e){Nx(e).forEach(t=>t.dispose())}function Jt(e){return O.keep(e)}function AR(e){return O.time(e)}function $R(e){return O.setBackend(e)}function FR(){return O.ready()}function DR(){return O.backendName}function RR(e){O.removeBackend(e)}function MR(e){return O.findBackend(e)}function PR(e){return O.findBackendFactory(e)}function Em(e,t,n=1){return O.registerBackend(e,t,n)}function uS(){return O.backend}function OR(e,t){H().setPlatform(e,t)}function LR(e){let t={input:_(e,"input","imag")};return O.runKernel(cm,t)}var Cc=L({imag_:LR});function zR(e){let t={x:_(e,"x","neg")};return O.runKernel(eu,t)}var bt=L({neg_:zR});function WR(e){let t={input:_(e,"input","real")};return O.runKernel(wm,t)}var sl=L({real_:WR});function BR(e,t,n){let a=_(e,"x","transpose");if(t==null&&(t=a.shape.map((i,o)=>o).reverse()),$(a.rank===t.length,()=>`Error in transpose: rank of input ${a.rank} must match length of perm ${t}.`),t.forEach(i=>{$(i>=0&&i`All entries in 'perm' must be between 0 and ${a.rank-1} but got ${t}`)}),a.rank<=1)return a.clone();let r={x:a},s={perm:t};return a.dtype==="complex64"?P(()=>{let i=sl(a),o=Cc(a);return i=O.runKernel(Tr,{x:i},s),o=O.runKernel(Tr,{x:o},s),n&&(o=bt(o)),Cr(i,o)}):O.runKernel(Tr,r,s)}var Ee=L({transpose_:BR});function VR(e,t,n){let a=_(e,"labels","confusionMatrix"),r=_(t,"predictions","confusionMatrix");$(n==null||n>0&&Number.isInteger(n),()=>`If provided, numClasses must be a positive integer, but got ${n}`),$(a.rank===1,()=>`Expected the rank of labels to be 1, but got ${a.rank}`),$(r.rank===1,()=>`Expected the rank of predictions to be 1, but got ${r.rank}`),$(a.shape[0]===r.shape[0],()=>`Mismatch in the number of examples: ${a.shape[0]} vs. ${r.shape[0]}. Labels and predictions should have the same number of elements.`),$(n>0&&Number.isInteger(n),()=>`numClasses is required to be a positive integer, but got ${n}`);let s=rl(oe(a,"int32"),n),i=rl(oe(r,"int32"),n),o=Ee(s),l=Fe(o,i);return oe(l,"int32")}var UR=L({confusionMatrix_:VR}),Tu={};Ae(Tu,{assertAndGetBroadcastShape:()=>lt,getBroadcastDims:()=>pS,getReductionAxes:()=>Wt});function pS(e,t){let n=e.length,a=[];for(let r=0;r1&&i===1&&a.unshift(s)}return a}function Wt(e,t){let n=[];for(let a=0;a1)&&n.unshift(s)}return n}function lt(e,t){let n=[],a=Math.max(e.length,t.length);for(let r=0;rYR,fromPixelsAsync:()=>KR,toPixels:()=>XR});function _c(e,t,n){if(hi(e),t!=null&&t.length!==3)throw new Error("tensor3d() requires shape to have three numbers");let a=ir(e,n);if(a.length!==3&&a.length!==1)throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");if(a.length===1&&t==null)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return fs(e,t,a,n)}var Ps;function cS(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,a=!1,r=!1,s=!1,i=!1,o=!1;if(e.data instanceof Uint8Array)n=!0;else if(typeof ImageData!="undefined"&&e instanceof ImageData)a=!0;else if(typeof HTMLVideoElement!="undefined"&&e instanceof HTMLVideoElement)r=!0;else if(typeof HTMLImageElement!="undefined"&&e instanceof HTMLImageElement)s=!0;else if(e.getContext!=null)i=!0;else if(typeof ImageBitmap!="undefined"&&e instanceof ImageBitmap)o=!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(bh(yh,O.backendName)!=null){let c={pixels:e},h={numChannels:t};return O.runKernel(yh,c,h)}let[l,u]=r?[e.videoWidth,e.videoHeight]:[e.width,e.height],p;if(i)p=e.getContext("2d").getImageData(0,0,l,u).data;else if(a||n)p=e.data;else if(s||r||o){if(Ps==null)if(typeof document=="undefined")if(typeof OffscreenCanvas!="undefined"&&typeof OffscreenCanvasRenderingContext2D!="undefined")Ps=new OffscreenCanvas(1,1).getContext("2d");else throw new Error("Cannot parse input in current context. Reason: OffscreenCanvas Context2D rendering is not supported.");else Ps=document.createElement("canvas").getContext("2d",{willReadFrequently:!0});Ps.canvas.width=l,Ps.canvas.height=u,Ps.drawImage(e,0,0,l,u),p=Ps.getImageData(0,0,l,u).data}let d;if(t===4)d=new Int32Array(p);else{let c=l*u;d=new Int32Array(c*t);for(let h=0;h4||s===2)throw new Error(`toPixels only supports depth of size 1, 3 or 4 but got ${s}`);if(n.dtype!=="float32"&&n.dtype!=="int32")throw new Error(`Unsupported type for toPixels: ${n.dtype}. Please use float32 or int32 tensors.`);let i=await n.data(),o=n.dtype==="float32"?255:1,l=new Uint8ClampedArray(r*a*4);for(let u=0;u1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${h}.`)}else if(n.dtype==="int32"&&(h<0||h>255))throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${h}.`);s===1?(p[0]=h*o,p[1]=h*o,p[2]=h*o):p[c]=h*o}let d=u*4;l[d+0]=Math.round(p[0]),l[d+1]=Math.round(p[1]),l[d+2]=Math.round(p[2]),l[d+3]=Math.round(p[3])}if(t!=null){t.width=r,t.height=a;let u=t.getContext("2d"),p=new ImageData(l,r,a);u.putImageData(p,0,0)}return n!==e&&n.dispose(),l}var YR=L({fromPixels_:cS}),Mx={};Ae(Mx,{prepareAndValidate:()=>dS});function dS(e,t){let n=e.shape.length,a=t.shape.length;if(n<1)throw new Error(`tf.gatherND() expects the input to be rank 1 or higher, but the rank was ${n}.`);if(a<1)throw new Error(`tf.gatherND() expects the indices to be rank 1 or higher, but the rank was ${a}.`);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[a-1]>n)throw new Error(`index innermost dimension length must be <= tensor rank; saw: ${t.shape[a-1]} vs. ${n}`);if(mt(e.shape)===0)throw new Error(`Requested more than 0 entries, but input is empty. Input shape: ${e.shape}.`);let r=t.shape,s=r[r.length-1],i=1;for(let d=0;dd/u),1].slice(0,s);return[l,i,u,p]}var Px={};Ae(Px,{calculateShapes:()=>hS,validateInput:()=>Lx,validateUpdateShape:()=>Ox});function Ox(e,t,n){let a=t.rank>1?t.shape[t.rank-1]:1,r=t.rank>1?t.rank-1:1,s=`Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: ${n.shape}, indices.shape: ${t.shape}, shape: ${e}, sliceDim: ${a}, and batchDim: ${r}.`;if(n.rank1?t.shape[a-1]:1,s=n.length,i=1;for(let d=r;dJR,computeFlatOffset:()=>aM,computeOutShape:()=>eM,getNormalizedAxes:()=>tM,isSliceContinous:()=>nM,maskToAxes:()=>QR,parseSliceParams:()=>kS,sliceInfo:()=>rM,startForAxis:()=>vS,startIndicesWithElidedDims:()=>yS,stopForAxis:()=>wS,stopIndicesWithElidedDims:()=>bS,stridesForAxis:()=>xS,stridesWithElidedDims:()=>mS});var Fb=-2,ZR=-1;function JR(e,t,n){let a=e.shape.length;$(a===t.length,()=>`Error in slice${a}D: Length of begin ${t} must match the rank of the array (${a}).`),$(a===n.length,()=>`Error in slice${a}D: Length of size ${n} must match the rank of the array (${a}).`);for(let r=0;r`Error in slice${a}D: begin[${r}] + size[${r}] (${t[r]+n[r]}) would overflow input.shape[${r}] (${e.shape[r]})`)}function QR(e){let t=[],n=0;for(;e>0;)e&1&&t.push(n),e/=2,n++;return t}function eM(e,t,n){let a=[];for(let r=0;r0){let h=t[0],m=n+1;p=yS(i,h,m,a,e),d=bS(o,h,m,r,e),c=mS(s,h,m,e)}else for(let h=0;h-1)s[o]=0;else{let l=fS(t,n,o),u=a[l];e&1<-1)s[o]=Number.MAX_SAFE_INTEGER;else{let l=fS(t,n,o),u=a[l];e&1<0?i=Number.MIN_SAFE_INTEGER:i=Number.MAX_SAFE_INTEGER);let l=a[r];return i<0&&(i+=l),i=Vp(0,i,l-1),i}function wS(e,t,n,a,r,s){let i=t[r],o=n[r]||1;(e&1<0?i=Number.MAX_SAFE_INTEGER:i=Number.MIN_SAFE_INTEGER);let l=a[r];return i<0&&(i+=l),o>0?i=Vp(0,i,l):i=Vp(-1,i,l-1),i}function nM(e,t,n){let a=n.length;for(let r=0;r1){a=r;break}for(let r=a+1;r0||n[r]!==e[r])return!1;return!0}function aM(e,t){let n=e.length>0?e[e.length-1]:1;for(let a=0;a{$(i!==-1,()=>"slice() does not support negative begin indexing.")});let s;return n==null?s=new Array(r).fill(-1):typeof n=="number"?s=[n,...new Array(r-1).fill(-1)]:n.lengthi>=0?i:($(i===-1,()=>`Negative size values should be exactly -1 but got ${i} for the slice() size at index ${o}.`),e.shape[o]-a[o])),[a,s]}function rM(e,t,n,a,r,s,i,o,l){let u;if(a==null?(u=new Array(t.length),u.fill(1)):u=a,i!=null&&(i&i-1)!==0)throw new Error("Multiple ellipses in slice is not allowed.");let p=!1,d={dims:u.length,numAddAxisAfterEllipsis:0,begin:t.slice(),end:n.slice(),strides:u.slice(),beginMask:r,endMask:s,ellipsisMask:i,newAxisMask:o,shrinkAxisMask:l};for(let b=0;b0?0:-1,c.strides[b]>0?w:w-1];if(x&&c.strides[b]<=0)throw Error("only stride 1 allowed on non-range indexing.");f=f&&c.strides[b]===1;let C=!!(c.beginMask&1<=w)throw Error(`slice index ${c.begin[b]} of dimension ${b} out of bounds.`)}else c.begin[b]=Y1(c.begin[b],0,c.strides[b],w,I,T),c.end[b]=Y1(c.end[b],1,c.strides[b],w,I,T);let R=c.strides[b]===1&&c.begin[b]===0&&c.end[b]===w;h=h&&R,m=m&&(b===0&&c.strides[b]===1||R)}else h=h&&c.strides[b]===1&&C,m=m&&(b===0&&c.strides[b]===1||C);let E,A=!1;if(c.beginValid&&c.endValid?(E=c.end[b]-c.begin[b],A=!0):x?(E=1,A=!0):C&&w>=0&&(c.strides[b]<0?E=-w:E=w,A=!0),A){let R;E===0||E<0!=c.strides[b]<0?R=0:R=Math.trunc(E/c.strides[b])+(E%c.strides[b]!==0?1:0),g.push(R)}else g.push(-1)}for(let b=0;b=0?y.push(g[x]):x===Fb&&y.push(1)}return{finalShapeSparse:y.filter((b,x)=>c.finalShapeGatherIndices[x]!==Fb),finalShape:y,isIdentity:h,sliceDim0:m,isSimpleSlice:f,begin:c.begin,end:c.end,strides:c.strides}}function sM(e,t){t.beginMask=0,t.endMask=0,t.shrinkAxisMask=0;let n=0;t.beginValid=e.begin!=null,t.endValid=e.end!=null,t.begin=new Array(t.dims),t.end=new Array(t.dims),t.strides=new Array(t.dims),t.finalShapeGatherIndices=[],t.finalShapeGatherIndicesSparse=[],t.inputShapeGatherIndicesSparse=new Array(t.dims);for(let a=0;a0?s[t]:s[t+1&1];{let i=e<0?a+e:e;return is[1]?s[1]:i}}var ne={};Ae(ne,{Serializable:()=>IS,SerializationMap:()=>Bs,registerClass:()=>gs});var IS=class{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}},Bs=class{constructor(){this.classNameMap={}}static getMap(){return Bs.instance==null&&(Bs.instance=new Bs),Bs.instance}static register(e){Bs.getMap().classNameMap[e.className]=[e,e.fromConfig]}};function gs(e){$(e.className!=null,()=>"Class being registered does not have the static className property defined."),$(typeof e.className=="string",()=>"className is required to be a string, but got type "+typeof e.className),$(e.className.length>0,()=>"Class being registered has an empty-string as its className, which is disallowed."),Bs.register(e)}var SS={};Ae(SS,{TEST_EPSILON_FLOAT16:()=>TS,createVideoElement:()=>hM,encodeStrings:()=>NS,expectArrayBuffersEqual:()=>dM,expectArraysClose:()=>oM,expectArraysEqual:()=>uM,expectNumbersClose:()=>pM,expectPromiseToFail:()=>lM,expectValuesInRange:()=>cM,play:()=>mM,testEpsilon:()=>zx});var iM=.001,TS=.1;function oM(e,t,n){return n==null&&(n=zx()),Db(e,t,(a,r)=>Wx(a,r,n))}function zx(){return O.backend.floatPrecision()===32?iM:TS}function Db(e,t,n){let a=!0;if((hn(e)||hn(t))&&(a=!1),hn(e)&&hn(t)&&(a=!0),a){let i=e.constructor.name,o=t.constructor.name;if(i!==o)throw new Error(`Arrays are of different type. Actual: ${i}. Expected: ${o}`)}if(Array.isArray(e)&&Array.isArray(t)){let i=ir(e),o=ir(t);if(!ps(i,o))throw new Error(`Arrays have different shapes. Actual: [${i}]. Expected: [${o}]`)}let r=hn(e)?e:Zs(e),s=hn(t)?t:Zs(t);if(r.length!==s.length)throw new Error(`Arrays have different lengths actual: ${r.length} vs expected: ${s.length}.
-Actual: ${r}.
-Expected: ${s}.`);for(let i=0;it.fail(),()=>t()),typeof expect!="undefined"&&expect().nothing()}function uM(e,t){let n=typeof t=="string"||typeof t=="number"||typeof t=="boolean"?[t]:t;return Kr(e)||Kr(e[0])||Kr(t)||Kr(t[0])?Db(e,n,(a,r)=>a==r):Db(e,t,(a,r)=>Wx(a,r,0))}function pM(e,t,n){if(n==null&&(n=zx()),!Wx(e,t,n))throw new Error(`Numbers differ: actual === ${e}, expected === ${t}`);typeof expect!="undefined"&&expect().nothing()}function Wx(e,t,n){return!isFinite(e)&&!isFinite(t)?!0:!(isNaN(e)||isNaN(t)||Math.abs(e-t)>n)}function cM(e,t,n){for(let a=0;an)throw new Error(`Value out of range:${e[a]} low: ${t}, high: ${n}`)}function dM(e,t){let n=new Float32Array(e),a=new Float32Array(t);if(n.length!==a.length)throw new Error(`Expected ArrayBuffer to be of length ${a.length}, but it was ${n.length}`);for(let r=0;r{t.addEventListener("loadeddata",a=>n(t)),t.load()})}async function mM(e){await e.play(),"requestVideoFrameCallback"in e&&await new Promise(t=>{e.requestVideoFrameCallback(t)})}var fM="4.0.0";function gM(e,t){let n=_(e,"a","add"),a=_(t,"b","add");[n,a]=_t(n,a);let r={a:n,b:a};return O.runKernel(cs,r)}var Y=L({add_:gM});function yM(e,t){let n=_(e,"a","floorDiv"),a=_(t,"b","floorDiv");[n,a]=_t(n,a);let r={a:n,b:a};return O.runKernel(Ai,r)}var Am=L({floorDiv_:yM});function bM(e,t){let n=_(e,"a","div"),a=_(t,"b","div");if([n,a]=_t(n,a),n.dtype==="int32"&&a.dtype==="int32")return Am(n,a);let r={a:n,b:a},s={};return O.runKernel(Ni,r,s)}var he=L({div_:bM});function xM(e,t){let n=_(e,"a","mul"),a=_(t,"b","mul");[n,a]=_t(n,a);let r={a:n,b:a};return O.runKernel(Ui,r)}var z=L({mul_:xM});function vM(e){let t=_(e,"x","abs");if(t.dtype==="complex64"){let n={x:t};return O.runKernel(oc,n)}else{let n={x:t};return O.runKernel(wl,n)}}var Lt=L({abs_:vM});function wM(e){let t={x:_(e,"x","acos")};return O.runKernel(kl,t)}var Bx=L({acos_:wM});function kM(e){let t={x:_(e,"x","acosh")};return O.runKernel(Il,t)}var Vx=L({acosh_:kM});function IM(e){$(Array.isArray(e),()=>"The argument passed to tf.addN() must be a list of tensors"),$(e.length>=1,()=>`Must pass at least one tensor to tf.addN(), but got ${e.length}`);let t=e.map((r,s)=>_(r,`tensors${s}`,"addN")),n=t[0];t.forEach(r=>{if(r.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),t.forEach(r=>{if(!ps(r.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});let a=t;return O.runKernel(mi,a)}var CS=L({addN_:IM});function SM(e,t=null,n=!1){let a={x:_(e,"x","all","bool")},r={axis:t,keepDims:n};return O.runKernel(Sl,a,r)}var $m=L({all_:SM});function TM(e,t=null,n=!1){let a={x:_(e,"x","any","bool")},r={axis:t,keepDims:n};return O.runKernel(Tl,a,r)}var qp=L({any_:TM});function NM(e,t=0){let n={x:_(e,"x","argMax")},a={axis:t};return O.runKernel(fi,n,a)}var ai=L({argMax_:NM});function CM(e,t=0){let n={x:_(e,"x","argMin")},a={axis:t};return O.runKernel(sc,n,a)}var Ux=L({argMin_:CM});function _M(e){let t={x:_(e,"x","asin")};return O.runKernel(Nl,t)}var Gx=L({asin_:_M});function EM(e){let t={x:_(e,"x","asinh")};return O.runKernel(Cl,t)}var Hx=L({asinh_:EM});function AM(e){let t={x:_(e,"x","atan")};return O.runKernel(_l,t)}var jx=L({atan_:AM});function $M(e,t){let n=_(e,"a","atan2"),a=_(t,"b","atan2");[n,a]=_t(n,a);let r={a:n,b:a};return O.runKernel(Al,r)}var qx=L({atan2_:$M});function FM(e){let t={x:_(e,"x","atanh")};return O.runKernel(El,t)}var Kx=L({atanh_:FM});function DM(e,t,n,a,r="NHWC",s){let i=e[3],o=[...t,i],l=AS(r);return Ec(e,o,n,s,a,null,null,l)}function _S(e,t,n,a,r,s,i="channelsLast"){let[o,l]=Ih(t),u;if(i==="channelsLast")u=[o,l,e[3],e[3]];else if(i==="channelsFirst")u=[o,l,e[1],e[1]];else throw new Error(`Unknown dataFormat ${i}`);return Ec(e,u,n,a,r,s,!1,i)}function RM(e,t,n,a,r,s,i="NDHWC"){let[o,l,u]=Rb(t),p,d;if(i==="NDHWC")d="channelsLast",p=[o,l,u,e[4],e[4]];else if(i==="NCDHW")d="channelsFirst",p=[o,l,u,e[1],e[1]];else throw new Error(`Unknown dataFormat ${i}`);return ES(e,p,n,a,r,!1,d,s)}function Ec(e,t,n,a,r,s,i=!1,o="channelsLast"){let[l,u,p,d]=[-1,-1,-1,-1];if(o==="channelsLast")[l,u,p,d]=e;else if(o==="channelsFirst")[l,d,u,p]=e;else throw new Error(`Unknown dataFormat ${o}`);let[c,h,,m]=t,[f,g]=Ih(n),[y,b]=Ih(a),x=Qo(c,y),w=Qo(h,b),{padInfo:I,outHeight:T,outWidth:C}=OM(r,u,p,f,g,x,w,s,o),E=i?m*d:m,A;return o==="channelsFirst"?A=[l,E,T,C]:o==="channelsLast"&&(A=[l,T,C,E]),{batchSize:l,dataFormat:o,inHeight:u,inWidth:p,inChannels:d,outHeight:T,outWidth:C,outChannels:E,padInfo:I,strideHeight:f,strideWidth:g,filterHeight:c,filterWidth:h,effectiveFilterHeight:x,effectiveFilterWidth:w,dilationHeight:y,dilationWidth:b,inShape:e,outShape:A,filterShape:t}}function ES(e,t,n,a,r,s=!1,i="channelsLast",o){let[l,u,p,d,c]=[-1,-1,-1,-1,-1];if(i==="channelsLast")[l,u,p,d,c]=e;else if(i==="channelsFirst")[l,c,u,p,d]=e;else throw new Error(`Unknown dataFormat ${i}`);let[h,m,f,,g]=t,[y,b,x]=Rb(n),[w,I,T]=Rb(a),C=Qo(h,w),E=Qo(m,I),A=Qo(f,T),{padInfo:R,outDepth:F,outHeight:S,outWidth:M}=LM(r,u,p,d,y,b,x,C,E,A,o),B=s?g*c:g,U;return i==="channelsFirst"?U=[l,B,F,S,M]:i==="channelsLast"&&(U=[l,F,S,M,B]),{batchSize:l,dataFormat:i,inDepth:u,inHeight:p,inWidth:d,inChannels:c,outDepth:F,outHeight:S,outWidth:M,outChannels:B,padInfo:R,strideDepth:y,strideHeight:b,strideWidth:x,filterDepth:h,filterHeight:m,filterWidth:f,effectiveFilterDepth:C,effectiveFilterHeight:E,effectiveFilterWidth:A,dilationDepth:w,dilationHeight:I,dilationWidth:T,inShape:e,outShape:U,filterShape:t}}function MM(e,t,n,a,r){a==null&&(a=Xx(e,t,n));let s=e[0],i=e[1],o=qs((s-t+2*a)/n+1,r),l=qs((i-t+2*a)/n+1,r);return[o,l]}function PM(e,t,n,a,r,s){r==null&&(r=Xx(e,t,a));let i=e[0],o=e[1],l=e[2],u=qs((i-t+2*r)/a+1,s),p=qs((o-t+2*r)/a+1,s),d=qs((l-t+2*r)/a+1,s);return[u,p,d,n]}function Xx(e,t,n,a=1){let r=Qo(t,a);return Math.floor((e[0]*(n-1)-n+r)/2)}function Ih(e){return typeof e=="number"?[e,e,e]:e.length===2?[e[0],e[1],1]:e}function Rb(e){return typeof e=="number"?[e,e,e]:e}function Qo(e,t){return t<=1?e:e+(e-1)*(t-1)}function OM(e,t,n,a,r,s,i,o,l){let u,p,d;if(typeof e=="number"){u={top:e,bottom:e,left:e,right:e,type:e===0?"VALID":"NUMBER"};let c=MM([t,n],s,a,e,o);p=c[0],d=c[1]}else if(e==="same"){p=Math.ceil(t/a),d=Math.ceil(n/r);let c=Math.max(0,(p-1)*a+s-t),h=Math.max(0,(d-1)*r+i-n),m=Math.floor(c/2),f=c-m,g=Math.floor(h/2),y=h-g;u={top:m,bottom:f,left:g,right:y,type:"SAME"}}else if(e==="valid")u={top:0,bottom:0,left:0,right:0,type:"VALID"},p=Math.ceil((t-s+1)/a),d=Math.ceil((n-i+1)/r);else if(typeof e=="object"){let c=l==="channelsLast"?e[1][0]:e[2][0],h=l==="channelsLast"?e[1][1]:e[2][1],m=l==="channelsLast"?e[2][0]:e[3][0],f=l==="channelsLast"?e[2][1]:e[3][1];u={top:c,bottom:h,left:m,right:f,type:c===0&&h===0&&m===0&&f===0?"VALID":"EXPLICIT"},p=qs((t-s+c+h)/a+1,o),d=qs((n-i+m+f)/r+1,o)}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:u,outHeight:p,outWidth:d}}function LM(e,t,n,a,r,s,i,o,l,u,p){let d,c,h,m;if(typeof e=="number"){d={top:e,bottom:e,left:e,right:e,front:e,back:e,type:e===0?"VALID":"NUMBER"};let f=PM([t,n,a,1],o,1,r,e,p);c=f[0],h=f[1],m=f[2]}else if(e==="same"){c=Math.ceil(t/r),h=Math.ceil(n/s),m=Math.ceil(a/i);let f=(c-1)*r+o-t,g=(h-1)*s+l-n,y=(m-1)*i+u-a,b=Math.floor(f/2),x=f-b,w=Math.floor(g/2),I=g-w,T=Math.floor(y/2),C=y-T;d={top:w,bottom:I,left:T,right:C,front:b,back:x,type:"SAME"}}else if(e==="valid")d={top:0,bottom:0,left:0,right:0,front:0,back:0,type:"VALID"},c=Math.ceil((t-o+1)/r),h=Math.ceil((n-l+1)/s),m=Math.ceil((a-u+1)/i);else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:d,outDepth:c,outHeight:h,outWidth:m}}function qs(e,t){if(!t)return Math.trunc(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 ns(e){let[t,n,a]=Ih(e);return t===1&&n===1&&a===1}function ur(e,t){return ns(e)||ns(t)}function AS(e){if(e==="NHWC")return"channelsLast";if(e==="NCHW")return"channelsFirst";throw new Error(`Unknown dataFormat ${e}`)}function Tn(e,t,n){if(n!=null){if(typeof t=="string")throw Error(`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${t}.`);if(typeof t=="number")$(tl(t),()=>`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${t}.`);else if(typeof t=="object")t.forEach(a=>{a.forEach(r=>{$(tl(r),()=>`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${r}.`)})});else throw Error(`Error in ${e}: Unknown padding parameter: ${t}`)}}function zM(e,t){let n={x:_(e,"x","reshape","string_or_numeric")},a={shape:t};return O.runKernel(lu,n,a)}var W=L({reshape_:zM});function WM(e,t,n,a,r){let s=_(e,"x","avgPool","float32"),i=1;$(ur(n,i),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${n} and dilations '${i}'`);let o=s,l=!1;s.rank===3&&(l=!0,o=W(s,[1,s.shape[0],s.shape[1],s.shape[2]])),$(o.rank===4,()=>`Error in avgPool: x must be rank 4 but got rank ${o.rank}.`),Tn("avgPool",a,r);let u={x:o},p={filterSize:t,strides:n,pad:a,dimRoundingMode:r},d=O.runKernel(gi,u,p);return d=oe(d,s.dtype),l?W(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var ga=L({avgPool_:WM});function BM(e,t,n,a,r,s="NDHWC"){let i=_(e,"x","avgPool3d","float32"),o=i,l=!1;i.rank===4&&(l=!0,o=W(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),$(o.rank===5,()=>`Error in avgPool3d: x must be rank 5 but got rank ${o.rank}.`),$(s==="NDHWC",()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${s}`),Tn("avgPool3d",a,r);let u={x:o},p={filterSize:t,strides:n,pad:a,dimRoundingMode:r,dataFormat:s},d=O.runKernel(ic,u,p);return d=oe(d,o.dtype),l?W(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}var Yx=L({avgPool3d_:BM});function VM(e,t=0){$(e.length>=1,()=>"Pass at least one tensor to concat");let n=jp(e,"tensors","concat","string_or_numeric");if(n[0].dtype==="complex64"&&n.forEach(s=>{if(s.dtype!=="complex64")throw new Error(`Cannot concatenate complex64 tensors with a tensor
- with dtype ${s.dtype}. `)}),n.length===1)return rr(n[0]);let a=n,r={axis:t};return O.runKernel(Fl,a,r)}var Ze=L({concat_:VM});function UM(e){let t={x:_(e,"x","sigmoid","float32")};return O.runKernel(ao,t)}var da=L({sigmoid_:UM});function GM(e,t,n){let a=_(e,"x","slice","string_or_numeric");if(a.rank===0)throw new Error("Slicing scalar is not possible");let r={x:a},s={begin:t,size:n};return O.runKernel(du,r,s)}var Be=L({slice_:GM});function HM(e){let t={x:_(e,"x","tanh","float32")};return O.runKernel(po,t)}var ri=L({tanh_:HM});function jM(e,t,n,a,r,s){let i=_(e,"forgetBias","basicLSTMCell"),o=_(t,"lstmKernel","basicLSTMCell"),l=_(n,"lstmBias","basicLSTMCell"),u=_(a,"data","basicLSTMCell"),p=_(r,"c","basicLSTMCell"),d=_(s,"h","basicLSTMCell"),c=Ze([u,d],1),h=Fe(c,o),m=Y(h,l),f=m.shape[0],g=m.shape[1]/4,y=[f,g],b=Be(m,[0,0],y),x=Be(m,[0,g],y),w=Be(m,[0,g*2],y),I=Be(m,[0,g*3],y),T=Y(z(da(b),ri(x)),z(p,da(Y(i,w)))),C=z(ri(T),da(I));return[T,C]}var $S=L({basicLSTMCell_:jM});function qM(e,t,n){let a=_(e,"x","batchToSpaceND"),r=t.reduce((o,l)=>o*l);$(a.rank>=1+t.length,()=>`input rank is ${a.rank} but should be > than blockShape.length ${t.length}`),$(n.length===t.length,()=>`crops.length is ${n.length} but should be equal to blockShape.length ${t.length}`),$(a.shape[0]%r===0,()=>`input tensor batch is ${a.shape[0]} but is not divisible by the product of the elements of blockShape ${t.join(" * ")} === ${r}`);let s={x:a},i={blockShape:t,crops:n};return O.runKernel($l,s,i)}var Ac=L({batchToSpaceND_:qM});function KM(e){let t;return e.rank===0||e.rank===1?t=W(e,[1,1,1,e.size]):e.rank===2?t=W(e,[1,1,e.shape[0],e.shape[1]]):e.rank===3?t=W(e,[1,e.shape[0],e.shape[1],e.shape[2]]):t=e,t}function XM(e,t,n,a,r,s){s==null&&(s=.001);let i=_(e,"x","batchNorm"),o=_(t,"mean","batchNorm"),l=_(n,"variance","batchNorm"),u;r!=null&&(u=_(r,"scale","batchNorm"));let p;a!=null&&(p=_(a,"offset","batchNorm")),$(o.rank===l.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),$(p==null||o.rank===p.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),$(u==null||o.rank===u.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let d={x:KM(i),scale:u,offset:p,mean:o,variance:l},c={varianceEpsilon:s},h=O.runKernel($i,d,c);return W(h,i.shape)}var ys=L({batchNorm_:XM});function YM(e,t,n,a,r,s){let i=_(e,"x","batchNorm"),o=_(t,"mean","batchNorm"),l=_(n,"variance","batchNorm"),u;r!=null&&(u=_(r,"scale","batchNorm"));let p;return a!=null&&(p=_(a,"offset","batchNorm")),$(i.rank===2,()=>`Error in batchNorm2D: x must be rank 2 but got rank ${i.rank}.`),$(o.rank===2||o.rank===1,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${o.rank}.`),$(l.rank===2||l.rank===1,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${l.rank}.`),u!=null&&$(u.rank===2||u.rank===1,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${u.rank}.`),p!=null&&$(p.rank===2||p.rank===1,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${p.rank}.`),ys(i,o,l,p,u,s)}var Zx=L({batchNorm2d_:YM});function ZM(e,t,n,a,r,s){let i=_(e,"x","batchNorm"),o=_(t,"mean","batchNorm"),l=_(n,"variance","batchNorm"),u;r!=null&&(u=_(r,"scale","batchNorm"));let p;return a!=null&&(p=_(a,"offset","batchNorm")),$(i.rank===3,()=>`Error in batchNorm3D: x must be rank 3 but got rank ${i.rank}.`),$(o.rank===3||o.rank===1,()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${o.rank}.`),$(l.rank===3||l.rank===1,()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${l.rank}.`),u!=null&&$(u.rank===3||u.rank===1,()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${u.rank}.`),p!=null&&$(p.rank===3||p.rank===1,()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${p.rank}.`),ys(i,o,l,p,u,s)}var Jx=L({batchNorm3d_:ZM});function JM(e,t,n,a,r,s){let i=_(e,"x","batchNorm"),o=_(t,"mean","batchNorm"),l=_(n,"variance","batchNorm"),u;r!=null&&(u=_(r,"scale","batchNorm"));let p;return a!=null&&(p=_(a,"offset","batchNorm")),$(i.rank===4,()=>`Error in batchNorm4D: x must be rank 4 but got rank ${i.rank}.`),$(o.rank===4||o.rank===1,()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${o.rank}.`),$(l.rank===4||l.rank===1,()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${l.rank}.`),u!=null&&$(u.rank===4||u.rank===1,()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${u.rank}.`),p!=null&&$(p.rank===4||p.rank===1,()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${p.rank}.`),ys(i,o,l,p,u,s)}var Qx=L({batchNorm4d_:JM});function QM(e,t,n){let a=_(e,"x","bincount"),r=_(t,"weights","bincount");$(a.dtype==="int32",()=>`Error in bincount: input dtype must be int32, but got ${a.dtype}`),$(n>=0,()=>`size must be non-negative, but got ${n}.`),$(r.size===a.size||r.size===0,()=>`Error in bincount: weights must have the same size as input or0-length, but got input shape: ${a.shape}, weights shape: ${r.shape}.`);let s={x:a,weights:r},i={size:n};return O.runKernel(Zh,s,i)}var ev=L({bincount_:QM});function eP(e,t){let n=_(e,"s0","broadcastArgs","int32"),a=_(t,"s1","broadcastArgs","int32");if(n.rank!==1)throw new Error(`broadcastArgs(): first input must be a vector (rank=1). Has rank ${n.rank}`);if(a.rank!==1)throw new Error(`broadcastArgs(): second input must be a vector (rank=1). Has rank ${a.rank}`);let r={s0:n,s1:a};return O.runKernel(Jh,r)}var FS=L({broadcastArgs_:eP});function tP(e,t){let n=_(e,"broadcastTo","x"),a=n.shape;if(t.some(l=>!(l>0)||l%1!==0))throw new Error(`broadcastTo(): Invalid broadcast shape [${t}].`);if(t.lengthn.rank){let l=n.shape.slice();for(;l.length=0;l--)if(r[l]===t[l])s[l]=1;else if(n.shape[l]!==1)throw new Error(`broadcastTo(): [${a}] cannot be broadcast to [${t}].`);if(s.map((l,u)=>l>1?u:-1).filter(l=>l>=0).length===0)return rr(n);let i={x:n},o={reps:s};return O.runKernel(hs,i,o)}var Ks=L({broadcastTo_:tP});function nP(e){let t={x:_(e,"x","ceil","float32")};return O.runKernel(xi,t)}var tv=L({ceil_:nP});function gn(e,t,n){let a={shape:e,value:t,dtype:n};return O.runKernel(pc,{},a)}function aP(e,t,n){let a=_(e,"x","clipByValue");if($(t<=n,()=>`Error in clip: min (${t}) must be less than or equal to max (${n}).`),t===n)return gn(a.shape,t,a.dtype);let r={x:a},s={clipValueMin:t,clipValueMax:n};return O.runKernel(ds,r,s)}var en=L({clipByValue_:aP});function rP(e){return Ze(e,0)}var nv=L({concat1d_:rP});function sP(e,t){return Ze(e,t)}var av=L({concat2d_:sP});function iP(e,t){return Ze(e,t)}var rv=L({concat3d_:iP});function oP(e,t){return Ze(e,t)}var sv=L({concat4d_:oP});function lP(e,t,n,a,r="NHWC",s=[1,1],i){let o=_(e,"x","conv2d","float32"),l=_(t,"filter","conv2d","float32"),u=o,p=!1;o.rank===3&&(p=!0,u=W(o,[1,o.shape[0],o.shape[1],o.shape[2]])),$(u.rank===4,()=>`Error in conv2d: input must be rank 4, but got rank ${u.rank}.`),$(l.rank===4,()=>`Error in conv2d: filter must be rank 4, but got rank ${l.rank}.`),Tn("conv2d",a,i);let d=r==="NHWC"?u.shape[3]:u.shape[1];$(d===l.shape[2],()=>`Error in conv2d: depth of input (${d}) must match input depth for filter ${l.shape[2]}.`),$(ur(n,s),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`);let c={x:u,filter:l},h={strides:n,pad:a,dataFormat:r,dilations:s,dimRoundingMode:i},m=O.runKernel(vi,c,h);return p?W(m,[m.shape[1],m.shape[2],m.shape[3]]):m}var $t=L({conv2d_:lP});function uP(e,t,n,a,r="NWC",s=1,i){let o=_(e,"x","conv1d"),l=_(t,"filter","conv1d"),u=o,p=!1;o.rank===2&&(p=!0,u=W(o,[1,o.shape[0],o.shape[1]])),$(u.rank===3,()=>`Error in conv1d: input must be rank 3, but got rank ${u.rank}.`),$(l.rank===3,()=>`Error in conv1d: filter must be rank 3, but got rank ${l.rank}.`),Tn("conv1d",a,i),$(u.shape[2]===l.shape[1],()=>`Error in conv1d: depth of input (${u.shape[2]}) must match input depth for filter ${l.shape[1]}.`),$(ur(n,s),()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${n} and dilation '${s}'`),$(r==="NWC",()=>`Error in conv1d: got dataFormat of ${r} but only NWC is currently supported.`);let d=W(l,[1,l.shape[0],l.shape[1],l.shape[2]]),c=W(u,[u.shape[0],1,u.shape[1],u.shape[2]]),h=$t(c,d,[1,n],a,"NHWC",[1,s],i);return p?W(h,[h.shape[2],h.shape[3]]):W(h,[h.shape[0],h.shape[2],h.shape[3]])}var Fm=L({conv1d_:uP});function pP(e,t,n,a,r,s="NHWC",i){$(e.length===t.rank,()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);let o=e,l=t,u=!1;t.rank===3&&(u=!0,l=W(t,[1,t.shape[0],t.shape[1],t.shape[2]]),o=[1,e[0],e[1],e[2]]),$(o.length===4,()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${o.length}.`),$(l.rank===4,()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${l.rank}`),$(n.rank===4,()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${n.rank}`);let p=s==="NHWC"?o[3]:o[1],d=s==="NHWC"?l.shape[3]:l.shape[1];$(p===n.shape[2],()=>`Error in conv2dDerInput: depth of input (${p}) must match input depth for filter ${n.shape[2]}.`),$(d===n.shape[3],()=>`Error in conv2dDerInput: depth of output (${d}) must match output depth for filter ${n.shape[3]}.`),Tn("conv2dDerInput",r,i);let c={dy:l,filter:n},h={strides:a,pad:r,dataFormat:s,dimRoundingMode:i,inputShape:o},m=O.runKernel(wi,c,h);return u?W(m,[m.shape[1],m.shape[2],m.shape[3]]):m}var iv=L({conv2DBackpropInput_:pP});function cP(e,t,n,a,r,s){let i=_(e,"x","conv2dTranspose"),o=_(t,"filter","conv2dTranspose");return iv(n,i,o,a,r,"NHWC",s)}var Dm=L({conv2dTranspose_:cP});function dP(e,t,n,a,r="NDHWC",s=[1,1,1]){let i=_(e,"x","conv3d"),o=_(t,"filter","conv3d"),l=i,u=!1;i.rank===4&&(u=!0,l=W(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),$(l.rank===5,()=>`Error in conv3d: input must be rank 5, but got rank ${l.rank}.`),$(o.rank===5,()=>`Error in conv3d: filter must be rank 5, but got rank ${o.rank}.`),$(l.shape[4]===o.shape[3],()=>`Error in conv3d: depth of input (${l.shape[4]}) must match input depth for filter ${o.shape[3]}.`),$(ur(n,s),()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`),$(r==="NDHWC",()=>`Error in conv3d: got dataFormat of ${r} but only NDHWC is currently supported.`);let p={x:l,filter:o},d={strides:n,pad:a,dataFormat:r,dilations:s},c=O.runKernel(lc,p,d);return u?W(c,[c.shape[1],c.shape[2],c.shape[3],c.shape[4]]):c}var ov=L({conv3d_:dP});function hP(e,t,n,a,r){$(e.length===t.rank,()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);let s=e,i=t,o=!1;t.rank===4&&(o=!0,i=W(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]]),s=[1,e[0],e[1],e[2],e[3]]);let l=s[4],u=i.shape[4];$(s.length===5,()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${s.length}.`),$(i.rank===5,()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${i.rank}`),$(n.rank===5,()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${n.rank}`),$(l===n.shape[3],()=>`Error in conv3dDerInput: depth of input (${l}) must match input depth for filter ${n.shape[3]}.`),$(u===n.shape[4],()=>`Error in conv3dDerInput: depth of output (${u}) must match output depth for filter ${n.shape[4]}.`);let p={dy:i,filter:n},d={pad:r,strides:a,inputShape:s},c=O.runKernel(nm,p,d);return o?W(c,[c.shape[1],c.shape[2],c.shape[3],c.shape[4]]):c}var DS=L({conv3DBackpropInput_:hP});function mP(e,t,n,a,r){let s=_(e,"x","conv3dTranspose"),i=_(t,"filter","conv3dTranspose");return DS(n,s,i,a,r)}var lv=L({conv3dTranspose_:mP});function fP(e){let t={x:_(e,"x","cos","float32")};return O.runKernel(ki,t)}var $c=L({cos_:fP});function gP(e){let t={x:_(e,"x","cosh","float32")};return O.runKernel(Ii,t)}var Rm=L({cosh_:gP});function yP(e,t=0,n=!1,a=!1){let r={x:_(e,"x","cumprod")},s={axis:t,exclusive:n,reverse:a};return O.runKernel(Dl,r,s)}var Kp=L({cumprod_:yP});function bP(e,t=0,n=!1,a=!1){let r={x:_(e,"x","cumsum")},s={axis:t,exclusive:n,reverse:a};return O.runKernel(Si,r,s)}var Mm=L({cumsum_:bP});function xP(e,t,n,a=!1){let r=_(e,"x","denseBincount"),s=_(t,"weights","denseBincount");$(r.dtype==="int32",()=>`Error in denseBincount: input dtype must be int32, but got ${r.dtype}`),$(r.rank<=2,()=>`Error in denseBincount: input must be at most rank 2, but got rank ${r.rank}.`),$(n>=0,()=>`size must be non-negative, but got ${n}.`),$(s.size===r.size||s.size===0,()=>`Error in denseBincount: weights must have the same shape as x or 0-length, but got x shape: ${r.shape}, weights shape: ${s.shape}.`);let i={x:r,weights:s},o={size:n,binaryOutput:a};return O.runKernel(am,i,o)}var Sh=L({denseBincount_:xP});function vP(e,t,n="NHWC"){let a=_(e,"x","depthToSpace","float32"),r=n==="NHWC"?a.shape[1]:a.shape[2],s=n==="NHWC"?a.shape[2]:a.shape[3],i=n==="NHWC"?a.shape[3]:a.shape[1];$(t>1,()=>`blockSize should be > 1 for depthToSpace, but was: ${t}`),$(r*t>=0,()=>`Negative dimension size caused by overflow when multiplying
- ${r} and ${t} for depthToSpace with input shape
- ${a.shape}`),$(s*t>=0,()=>`Negative dimension size caused by overflow when multiplying
- ${s} and ${t} for depthToSpace with input shape
- ${a.shape}`),$(i%(t*t)===0,()=>`Dimension size must be evenly divisible by ${t*t} but is ${i} for depthToSpace with input shape ${a.shape}`);let o={x:a},l={blockSize:t,dataFormat:n};return O.runKernel(Ml,o,l)}var uv=L({depthToSpace_:vP});function wP(e,t,n,a,r="NHWC",s=[1,1],i){let o=_(e,"x","depthwiseConv2d","float32"),l=_(t,"filter","depthwiseConv2d","float32"),u=o,p=!1;o.rank===3&&(p=!0,u=W(o,[1,o.shape[0],o.shape[1],o.shape[2]])),$(u.rank===4,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${u.rank}.`),$(l.rank===4,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${l.rank}.`);let d=r==="NHWC"?u.shape[3]:u.shape[1];$(d===l.shape[2],()=>`Error in depthwiseConv2d: number of input channels (${d}) must match the inChannels dimension in filter ${l.shape[2]}.`),Tn("depthwiseConv2d",a,i);let c={x:u,filter:l},h={strides:n,pad:a,dataFormat:r,dilations:s,dimRoundingMode:i},m=O.runKernel(Ti,c,h);return p?W(m,[m.shape[1],m.shape[2],m.shape[3]]):m}var bs=L({depthwiseConv2d_:wP});function kP(e){let t={x:_(e,"x","diag")};return O.runKernel(im,t)}var RS=L({diag_:kP});function IP(e,t,n,a,r=[1,1],s="NHWC"){let i=_(e,"x","dilation2d"),o=_(t,"filter","dilation2d");$(i.rank===3||i.rank===4,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${i.rank}.`),$(o.rank===3,()=>`Error in dilation2d: filter must be rank 3, but got rank ${o.rank}.`),$(s==="NHWC",()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${s}`);let l=i,u=!1;i.rank===3&&(l=W(i,[1,i.shape[0],i.shape[1],i.shape[2]]),u=!0);let p={x:l,filter:o},d={strides:n,pad:a,dilations:r},c=O.runKernel(uc,p,d);return u?W(c,[c.shape[1],c.shape[2],c.shape[3]]):c}var pv=L({dilation2d_:IP});function SP(e,t){let n=_(e,"a","equal","string_or_numeric"),a=_(t,"b","equal","string_or_numeric");[n,a]=_t(n,a),lt(n.shape,a.shape);let r={a:n,b:a};return O.runKernel(Ol,r)}var Qn=L({equal_:SP});function TP(e,t,n){let a=_(t,"a","where"),r=_(n,"b","where"),s=_(e,"condition","where","bool"),i=lt(lt(s.shape,a.shape),r.shape),o=Ks(s,i),l=Ks(a,i),u=Ks(r,i),p={condition:o,t:l,e:u};return O.runKernel(pu,p)}var mn=L({where_:TP});function NP(e){let t={x:_(e,"x","zerosLike")};return O.runKernel(Iu,t)}var qe=L({zerosLike_:NP});function CP(e,t){let n=_(e,"a","div"),a=_(t,"b","div");[n,a]=_t(n,a);let r=he(n,a),s=qe(r),i=Qn(a,s);return mn(i,s,r)}var cv=L({divNoNan_:CP});function _P(e,t){let n=_(e,"t1","dot"),a=_(t,"t2","dot");$((n.rank===1||n.rank===2)&&(a.rank===1||a.rank===2),()=>`Error in dot: inputs must all be rank 1 or 2, but got ranks ${n.rank} and ${a.rank}.`);let r=n.rank===1?n.size:n.shape[1],s=a.rank===1?a.size:a.shape[0];if($(r===s,()=>`Error in dot: inner dimensions of inputs must match, but got ${r} and ${s}.`),n.rank===1&&a.rank===1){let i=W(n,[1,-1]),o=W(a,[-1,1]),l=Fe(i,o);return W(l,[])}else if(n.rank===1&&a.rank===2){let i=W(n,[1,-1]),o=W(a,[a.shape[0],a.shape[1]]),l=Fe(i,o);return W(l,[l.size])}else if(n.rank===2&&a.rank===1){let i=W(a,[-1,1]),o=Fe(n,i);return W(o,[o.size])}else{let i=W(a,[a.shape[0],a.shape[1]]);return Fe(n,i)}}var dv=L({dot_:_P});function EP(e,...t){let n=t.map((r,s)=>_(r,`tensors${s}`,"einsum")),a={equation:e};return O.runKernel(om,n,a)}var MS=L({einsum_:EP});function AP(e){let t={x:_(e,"x","elu","float32")};return O.runKernel(Ci,t)}var Nu=L({elu_:AP});function $P(e){let t=_(e,"x","erf");$(t.dtype==="int32"||t.dtype==="float32",()=>"Input dtype must be `int32` or `float32`."),t.dtype==="int32"&&(t=oe(t,"float32"));let n={x:t};return O.runKernel(Pl,n)}var hv=L({erf_:$P});function mv(e,t){for(let n=0;ne[s]);return[n,r]}function si(e,t){let n=t.map(a=>1);return PS(e,n,t)}function FP(e,t,n){$(mv(t,n),()=>`${e} supports only inner-most axes for now. Got axes ${t} and rank-${n} input.`)}function LS(e,t){if(mv(e,t))return null;let n=[];for(let a=0;an.push(a)),n}function fv(e){return e.map((t,n)=>[n,t]).sort((t,n)=>t[1]-n[1]).map(t=>t[0])}function DP(e,t){let n=[];for(let a=t-e;a"Axis must be <= rank of the tensor");let a={input:n},r={dim:t};return O.runKernel(Ll,a,r)}var Zt=L({expandDims_:UP});function GP(e){let t={x:_(e,"x","expm1")};return O.runKernel(zl,t)}var yv=L({expm1_:GP});function HP(e,t){let n=_(e,"x","tile","string_or_numeric");$(n.rank===t.length,()=>`Error in transpose: rank of input ${n.rank} must match length of reps ${t}.`);let a={x:n},r={reps:t};return O.runKernel(hs,a,r)}var Ln=L({tile_:HP});function jP(e,t,n,a="float32"){t==null&&(t=e);let r=Pe([e,t],a),s=e<=t?e:t;for(let o=0;o`Error in localResponseNormalization: x must be rank 3 or 4 but got
- rank ${s.rank}.`),$(tl(t),()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`);let i=s,o=!1;s.rank===3&&(o=!0,i=W(s,[1,s.shape[0],s.shape[1],s.shape[2]]));let l={x:i},u={depthRadius:t,bias:n,alpha:a,beta:r},p=O.runKernel(cc,l,u);return o?W(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var wv=L({localResponseNormalization_:aO});function rO(e){let t={x:_(e,"x","log","float32")};return O.runKernel(Mi,t)}var ea=L({log_:rO});function sO(e){let t={x:_(e,"x","log1p")};return O.runKernel(Xl,t)}var Dc=L({log1p_:sO});function iO(e){return $(es(e),()=>"The f passed in grad(f) must be a function"),(t,n)=>{let a=_(t,"x","tf.grad","string_or_numeric"),r=n!=null?_(n,"dy","tf.grad"):null;return O.tidy(()=>{let{value:s,grads:i}=O.gradients(()=>e(a),[a],r);return r!=null&&Sn(s.shape,r.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),Lm(i),i[0]})}}function oO(e){return $(es(e),()=>"The f passed in grads(f) must be a function"),(t,n)=>{$(Array.isArray(t),()=>"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s");let a=jp(t,"args","tf.grads","string_or_numeric"),r=n!=null?_(n,"dy","tf.grads"):null;return O.tidy(()=>{let{value:s,grads:i}=O.gradients(()=>e(...a),a,r);return r!=null&&Sn(s.shape,r.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Lm(i),i})}}function lO(e){return $(es(e),()=>"The f passed in valueAndGrad(f) must be a function"),(t,n)=>{$(t instanceof Te,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),$(n==null||n instanceof Te,()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");let{grads:a,value:r}=O.gradients(()=>e(t),[t],n);return Lm(a),{grad:a[0],value:r}}}function uO(e){return $(es(e),()=>"The f passed in valueAndGrads(f) must be a function"),(t,n)=>{$(Array.isArray(t)&&t.every(r=>r instanceof Te),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),$(n==null||n instanceof Te,()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");let a=O.gradients(()=>e(...t),t,n);return n!=null&&Sn(a.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Lm(a.grads),a}}function BS(e,t){$(es(e),()=>"The f passed in variableGrads(f) must be a function"),$(t==null||Array.isArray(t)&&t.every(u=>u instanceof ts),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");let n=t!=null;if(!n){t=[];for(let u in O.registeredVariables)t.push(O.registeredVariables[u])}let a=n?t.filter(u=>!u.trainable):null,r=t.length;t=t.filter(u=>u.trainable),$(t.length>0,()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${r} variables is trainable.`);let s=!0,{value:i,grads:o}=O.gradients(e,t,null,s);$(o.some(u=>u!=null),()=>"Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize()."),$(i.rank===0,()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${i.rank} tensor`);let l={};return t.forEach((u,p)=>{o[p]!=null&&(l[u.name]=o[p])}),a!=null&&a.forEach(u=>l[u.name]=null),{value:i,grads:l}}function or(e){return O.customGrad(e)}function Lm(e){if(e.filter(t=>t==null).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.`)}function pO(e){let t={x:_(e,"x","softplus")};return O.runKernel(fu,t)}var ho=L({softplus_:pO});function cO(e){let t=_(e,"x","logSigmoid");return or(n=>({value:bt(ho(bt(n))),gradFunc:a=>z(a,da(bt(n)))}))(t)}var kv=L({logSigmoid_:cO});function dO(e,t){let n=_(e,"a","sub"),a=_(t,"b","sub");[n,a]=_t(n,a);let r={a:n,b:a};return O.runKernel(lo,r)}var pe=L({sub_:dO});function hO(e,t=-1){let n=_(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}`);return or((a,r)=>{let s=ha(a,t,!0),i=pe(a,s),o=pe(oe(i,"float32"),ea(fe(fn(i),t,!0)));return r([o]),{value:o,gradFunc:(l,u)=>{let[p]=u,d=!0,c=fn(p);return pe(l,z(fe(l,t,d),c))}}})(n)}var zm=L({logSoftmax_:hO});function mO(e,t=null,n=!1){let a=_(e,"x","logSumExp"),r=Aa(t,a.shape),s=ha(a,r,!0),i=pe(a,s),o=fn(i),l=fe(o,r),u=ea(l),p=Y(W(s,u.shape),u);if(n){let d=si(p.shape,r);return W(p,d)}return p}var Wm=L({logSumExp_:mO});function fO(e,t){let n=_(e,"a","logicalAnd","bool"),a=_(t,"b","logicalAnd","bool");lt(n.shape,a.shape);let r={a:n,b:a};return O.runKernel(Yl,r)}var Ea=L({logicalAnd_:fO});function gO(e){let t={x:_(e,"x","logicalNot","bool")};return O.runKernel(Zl,t)}var Rc=L({logicalNot_:gO});function yO(e,t){let n=_(e,"a","logicalOr","bool"),a=_(t,"b","logicalOr","bool");lt(n.shape,a.shape);let r={a:n,b:a};return O.runKernel(Jl,r)}var Bm=L({logicalOr_:yO});function bO(e,t){let n=_(e,"a","logicalXor","bool"),a=_(t,"b","logicalXor","bool");return lt(n.shape,a.shape),Ea(Bm(e,t),Rc(Ea(e,t)))}var Iv=L({logicalXor_:bO}),Hd=2147483648;function xO(e,t,n="left"){let a=_(e,"sortedSequence","searchSorted"),r=_(t,"values","searchSorted"),s=a.shape[a.shape.length-1],i=r.shape[r.shape.length-1],o=W(a,[-1,s]),l=W(r,[-1,i]);if(o.rank<2)throw new Error("Sorted input argument must be at least 2-dimensional");if(o.shape[0]!==l.shape[0])throw new Error("Leading dimension of 'sortedSequence' and 'values' must match.");if(mt(l.shape)>=Hd)throw new Error(`values tensor size must less than ${Hd}`);if(o.shape[1]>=Hd)throw new Error(`trailing dim_size must less than ${Hd} for int32 output type, was ${o.shape[1]}`);let u={sortedSequence:o,values:l},p={side:n};return O.runKernel(Sm,u,p)}var Vm=L({searchSorted_:xO});function VS(e,t){return Vm(e,t,"left")}function vO(e,t,n,a,r){let s=_(e,"x","maxPool"),i=1,o=s,l=!1;s.rank===3&&(l=!0,o=W(s,[1,s.shape[0],s.shape[1],s.shape[2]])),$(o.rank===4,()=>`Error in maxPool: input must be rank 4 but got rank ${o.rank}.`),$(ur(n,i),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${n} and dilations '${i}'`),Tn("maxPool",a,r);let u={x:o},p={filterSize:t,strides:n,pad:a,dimRoundingMode:r},d=O.runKernel(Li,u,p);return l?W(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var Dt=L({maxPool_:vO});function wO(e,t=[1,1,1],n,a,r,s="NDHWC"){let i=_(e,"x","maxPool3d"),o=i,l=!1;i.rank===4&&(l=!0,o=W(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),$(o.rank===5,()=>`Error in maxPool3d: x must be rank 5 but got rank ${o.rank}.`),$(s==="NDHWC",()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${s}`),Tn("maxPool3d",a,r);let u={x:o},p={filterSize:t,strides:n,pad:a,dimRoundingMode:r,dataFormat:s},d=O.runKernel(dc,u,p);return l?W(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}var Sv=L({maxPool3d_:wO});function kO(e,t,n,a,r=!1){let s={x:_(e,"x","maxPoolWithArgmax")},i={filterSize:t,strides:n,pad:a,includeBatchInIndex:r},o=O.runKernel(gm,s,i);return{result:o[0],indexes:o[1]}}var US=L({maxPoolWithArgmax_:kO});function IO(e,t){let n=_(e,"a","maximum"),a=_(t,"b","maximum");[n,a]=_t(n,a),n.dtype==="bool"&&(n=oe(n,"int32"),a=oe(a,"int32")),lt(n.shape,a.shape);let r={a:n,b:a};return O.runKernel(Oi,r)}var pr=L({maximum_:IO});function SO(e,t=null,n=!1){let a={x:_(e,"x","mean")},r={axis:t,keepDims:n};return O.runKernel(zi,a,r)}var Nt=L({mean_:SO});function It(e,t="float32"){if(t==="complex64"){let a=It(e,"float32"),r=It(e,"float32");return Cr(a,r)}let n=Kh(mt(e),t);return O.makeTensor(n,e,t)}function Zn(e,t="float32"){if(t==="complex64"){let a=Zn(e,"float32"),r=It(e,"float32");return Cr(a,r)}let n=vx(mt(e),t);return O.makeTensor(n,e,t)}function GS(e,t,{indexing:n="xy"}={}){if(n!=="xy"&&n!=="ij")throw new TypeError(`${n} is not a valid third argument to meshgrid`);if(e===void 0)return[];let a=_(e,"x","meshgrid",e instanceof Te?e.dtype:"float32");if(t===void 0)return[a];let r=_(t,"y","meshgrid",t instanceof Te?t.dtype:"float32"),s=mt(a.shape),i=mt(r.shape);return n==="xy"?(a=W(a,[1,-1]),r=W(r,[-1,1]),[Fe(Zn([i,1],a.dtype),a),Fe(r,Zn([1,s],r.dtype))]):(a=W(a,[-1,1]),r=W(r,[1,-1]),[Fe(a,Zn([1,i],a.dtype)),Fe(Zn([s,1],r.dtype),r)])}function TO(e,t){let n=_(e,"a","minimum"),a=_(t,"b","minimum");[n,a]=_t(n,a),n.dtype==="bool"&&(n=oe(n,"int32"),a=oe(a,"int32")),lt(n.shape,a.shape);let r={a:n,b:a};return O.runKernel(Bi,r)}var Au=L({minimum_:TO});function NO(e,t,n){$(n==="reflect"||n==="symmetric",()=>`Invalid mode. Mode must be either reflect or symmetric. Got ${n}.`);let a=_(e,"x","mirrorPad");if(a.rank===0)throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");$(t.length===a.rank,()=>`Padding doesn't match input. Must be ${a.rank}. Got ${t.length}.`);let r=n==="reflect"?1:0;for(let o=0;o"Invalid number of paddings. Must be length of 2 each."),$(t[o][0]>=0&&t[o][0]<=a.shape[o]-r&&t[o][1]>=0&&t[o][1]<=a.shape[o]-r,()=>`Padding in dimension ${o} cannot be greater than or equal to ${a.shape[o]-r} or less than 0 for input of shape ${a.shape}`);let s={paddings:t,mode:n},i={x:a};return O.runKernel(Vi,i,s)}var Tv=L({mirrorPad_:NO});function CO(e,t){let n=_(e,"a","mod"),a=_(t,"b","mod");[n,a]=_t(n,a);let r={a:n,b:a};return O.runKernel(Ql,r)}var Nv=L({mod_:CO});function _O(e,t=null,n=!1){e=_(e,"x","moments");let a=Aa(t,e.shape),r=Nt(e,a,n),s=r.shape;n||(s=si(r.shape,a));let i=ot(pe(oe(e,"float32"),W(r,s))),o=Nt(i,a,n);return{mean:r,variance:o}}var Mc=L({moments_:_O});function EO(e,t,n,a){let r=_(t,"data","multiRNNCell"),s=jp(n,"c","multiRNNCell"),i=jp(a,"h","multiRNNCell"),o=r,l=[];for(let d=0;d2)throw new Error(`Rank of probabilities must be 1 or 2, but is ${i}`);n=n||Math.random();let o={logits:i===1?W(r,[1,-1]):r},l={numSamples:t,seed:n,normalized:a},u=O.runKernel(ym,o,l);return i===1?W(u,[u.size]):u}var jS=L({multinomial_:AO});function $O(e,t){let n=_(e,"a","notEqual","string_or_numeric"),a=_(t,"b","notEqual","string_or_numeric");[n,a]=_t(n,a),lt(n.shape,a.shape);let r={a:n,b:a};return O.runKernel(tu,r)}var ii=L({notEqual_:$O});function FO(e){let t={x:_(e,"x","onesLike")};return O.runKernel(su,t)}var ta=L({onesLike_:FO});function DO(e,t){let n=_(e,"v1","outerProduct"),a=_(t,"v2","outerProduct");$(n.rank===1&&a.rank===1,()=>`Error in outerProduct: inputs must be rank 1, but got ranks ${n.rank} and ${a.rank}.`);let r=W(n,[-1,1]),s=W(a,[1,-1]);return Fe(r,s)}var qS=L({outerProduct_:DO});function RO(e,t,n=0){let a=_(e,"x","pad");if(a.rank===0)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");let r={paddings:t,constantValue:n},s={x:a};return O.runKernel(Hi,s,r)}var ya=L({pad_:RO});function MO(e,t,n=0){return $(t.length===2,()=>"Invalid number of paddings. Must be length of 2."),ya(e,[t],n)}var KS=L({pad1d_:MO});function PO(e,t,n=0){return $(t.length===2&&t[0].length===2&&t[1].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),ya(e,t,n)}var XS=L({pad2d_:PO});function OO(e,t,n=0){return $(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."),ya(e,t,n)}var YS=L({pad3d_:OO});function LO(e,t,n=0){return $(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."),ya(e,t,n)}var ZS=L({pad4d_:LO});function zO(e,t,n){let a=_(e,"x","spaceToBatchND");$(a.rank>=1+t.length,()=>`input rank ${a.rank} should be > than [blockShape] ${t.length}`),$(n.length===t.length,()=>`paddings.shape[0] ${n.length} must be equal to [blockShape] ${t.length}`),$(a.shape.reduce((i,o,l)=>l>0&&l<=t.length?i&&(o+n[l-1][0]+n[l-1][1])%t[l-1]===0:i,!0),()=>`input spatial dimensions ${a.shape.slice(1)} with paddings ${n.toString()} must be divisible by blockShapes ${t.toString()}`);let r={x:a},s={blockShape:t,paddings:n};return O.runKernel(gu,r,s)}var Pc=L({spaceToBatchND_:zO});function WO(e,t,n,a,r,s,i){r==null&&(r=[1,1]),s==null&&(s=1),a===0&&(a="valid");let o=_(e,"x","maxPool"),l=o,u=!1;o.rank===3&&(u=!0,l=W(o,[1,o.shape[0],o.shape[1],o.shape[2]])),$(ur(s,r),()=>`Error in pool: Either strides or dilations must be 1. Got strides ${s} and dilations '${r}'`);let p=_S(l.shape,t,s,r,a),d=[p.dilationHeight,p.dilationWidth],c;a==="same"?c=VO([p.filterHeight,p.filterWidth],d):c=[[0,0],[0,0]];let h=d[0]===1&&d[1]===1,[m,f]=BO([p.inHeight,p.inWidth],d,c),g=h?a:"valid",y=h?l:Pc(l,d,m),b=(n==="avg"?()=>ga(y,t,s,g,i):()=>Dt(y,t,s,g,i))(),x=h?b:Ac(b,d,f);return u?W(x,[x.shape[1],x.shape[2],x.shape[3]]):x}function BO(e,t,n){let a=n.map(p=>p[0]),r=n.map(p=>p[1]),s=e.concat(a,r),i=t.map((p,d)=>(p-s[d]%p)%p),o=r.map((p,d)=>p+i[d]),l=t.map((p,d)=>[a[d],o[d]]),u=t.map((p,d)=>[0,i[d]]);return[l,u]}function VO(e,t){let n=e.map((s,i)=>s+(s-1)*(t[i]-1)).map(s=>s-1),a=n.map(s=>Math.floor(s/2)),r=n.map((s,i)=>s-a[i]);return n.map((s,i)=>[a[i],r[i]])}var Cv=L({pool_:WO});function UO(e,t){let n=_(e,"x","prelu"),a=_(t,"alpha","prelu"),r={x:n,alpha:a};return O.runKernel(qi,r)}var Oc=L({prelu_:UO});function GO(e,t=null,n=!1){let a=_(e,"x","prod");a.dtype==="bool"&&(a=oe(a,"int32"));let r={x:a},s={axis:t,keepDims:n};return O.runKernel(Ki,r,s)}var _v=L({prod_:GO});function HO(e,t,n,a){let r=e.map((p,d)=>_(p,`tensors${d}`,"raggedGather","int32")),s=_(t,"paramsDenseValues","raggedGather"),i=_(n,"indices","raggedGather","int32"),o={paramsNestedSplits:r,paramsDenseValues:s,indices:i},l={outputRaggedRank:a},u=O.runKernel(bm,o,l);return{outputNestedSplits:u.slice(0,u.length-1),outputDenseValues:u[u.length-1]}}var JS=L({raggedGather_:HO});function jO(e,t,n){let a=_(e,"starts","raggedRange"),r=_(t,"limits","raggedRange",a.dtype),s=_(n,"deltas","raggedRange",a.dtype),i={starts:a,limits:r,deltas:s},o=O.runKernel(xm,i);return{rtNestedSplits:o[0],rtDenseValues:o[1]}}var QS=L({raggedRange_:jO});function qO(e,t,n,a,r){let s=_(e,"shape","raggedTensorToTensor","int32"),i=_(t,"values","raggedTensorToTensor"),o=_(n,"defaultValue","raggedTensorToTensor",i.dtype),l=a.map((d,c)=>_(d,`tensors${c}`,"raggedTensorToTensor","int32")),u={shape:s,values:i,defaultValue:o,rowPartitionTensors:l},p={rowPartitionTypes:r};return O.runKernel(vm,u,p)}var eT=L({raggedTensorToTensor_:qO});function KO(e,t,n){let a=mt(e),r=null;if(n==null||n==="float32")r=new Float32Array(a);else if(n==="int32")r=new Int32Array(a);else if(n==="bool")r=new Uint8Array(a);else throw new Error(`Unknown data type ${n}`);for(let s=0;s=1||s===0);let i=Math.sqrt(-2*Math.log(s)/s);e=this.mean+this.stdDev*a*i,t=this.mean+this.stdDev*r*i,(!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}},XO=class{constructor(e,t,n,a){this.alpha=e,this.beta=1/t,this.dtype=n;let r=a||Math.random();this.randu=Ev.alea(r.toString()),this.randn=new Av(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,a,r,s;for(;;){do a=this.randn.nextValue(),s=1+this.c*a;while(s<=0);if(s*=s*s,e=a*a,t=1-.331*e*e,n=.5*e+this.d*(1-s+Math.log(s)),r=this.randu(),rthis.dtype==null||this.dtype==="float32",this.min=e,this.range=t-e,this.dtype=n,a==null&&(a=Math.random()),typeof a=="number"&&(a=a.toString()),!this.canReturnFloat()&&this.range<=1)throw new Error(`The difference between ${e} - ${t} <= 1 and dtype is not float`);this.random=Ev.alea(a)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}};function ZO(e,t,n=1,a="float32",r){if(n==null&&(n=1),a==null&&(a="float32"),a!=="float32"&&a!=="int32")throw new Error(`Unsupported data type ${a}`);let s=new XO(t,n,a,r),i=Pe(e,a);for(let o=0;o`Error in reverse1D: x must be rank 1 but got rank ${t.rank}.`),fa(t,0)}var rT=L({reverse1d_:s3});function i3(e,t){let n=_(e,"x","reverse");return $(n.rank===2,()=>`Error in reverse2D: x must be rank 2 but got rank ${n.rank}.`),fa(n,t)}var sT=L({reverse2d_:i3});function o3(e,t){let n=_(e,"x","reverse");return $(n.rank===3,()=>`Error in reverse3D: x must be rank 3 but got rank ${n.rank}.`),fa(n,t)}var iT=L({reverse3d_:o3});function l3(e,t){let n=_(e,"x","reverse");return $(n.rank===4,()=>`Error in reverse4D: x must be rank 4 but got rank ${n.rank}.`),fa(n,t)}var oT=L({reverse4d_:l3});function u3(e){let t={x:_(e,"x","round")};return O.runKernel(eo,t)}var Hm=L({round_:u3});function p3(e){let t={x:_(e,"x","rsqrt","float32")};return O.runKernel(to,t)}var jm=L({rsqrt_:p3});function c3(e){let t={x:_(e,"x","selu")};return O.runKernel(cu,t)}var qm=L({selu_:c3});function d3(e,t,n,a,r,s=[1,1],i="NHWC"){let o=_(e,"x","separableConv2d"),l=_(t,"depthwiseFilter","separableConv2d"),u=_(n,"pointwiseFilter","separableConv2d"),p=o,d=!1;if(o.rank===3&&(d=!0,p=W(o,[1,o.shape[0],o.shape[1],o.shape[2]])),i==="NCHW")throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");$(p.rank===4,()=>`Error in separableConv2d: input must be rank 4, but got rank ${p.rank}.`),$(l.rank===4,()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${l.rank}.`),$(u.rank===4,()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${l.rank}.`),$(u.shape[0]===1,()=>`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${u.shape[0]}.`),$(u.shape[1]===1,()=>`Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${u.shape[1]}.`);let c=l.shape[2],h=l.shape[3];$(u.shape[2]===c*h,()=>`Error in separableConv2d: the third dimension of pointwise filter must be ${c*h}, but got ${u.shape[2]}.`);let m=bs(p,l,a,r,i,s),f=$t(m,u,1,"valid",i);return d?W(f,[f.shape[1],f.shape[2],f.shape[3]]):f}var vs=L({separableConv2d_:d3});async function h3(e,t){let n=_(e,"x","setdiff1d"),a=_(t,"y","setdiff1d");$(n.dtype===a.dtype,()=>`x and y should have the same dtype, but got x (${n.dtype}) and y (${a.dtype}).`),$(n.rank===1,()=>`x should be 1D tensor, but got x (${n.shape}).`),$(a.rank===1,()=>`y should be 1D tensor, but got y (${a.shape}).`);let r=await n.data(),s=await a.data(),i=new Set(s),o=0;for(let p=0;p`slice1d expects a rank-1 tensor, but got a rank-${a.rank} tensor`),Be(a,[t],[n])}var Lc=L({slice1d_:y3});function b3(e,t,n){let a=_(e,"x","slice2d");return $(a.rank===2,()=>`slice2d expects a rank-2 tensor, but got a rank-${a.rank} tensor`),Be(a,t,n)}var Ym=L({slice2d_:b3});function x3(e,t,n){let a=_(e,"x","slice3d");return $(a.rank===3,()=>`slice3d expects a rank-3 tensor, but got a rank-${a.rank} tensor`),Be(a,t,n)}var mo=L({slice3d_:x3});function v3(e,t,n){let a=_(e,"x","slice4d");return $(a.rank===4,()=>`slice4d expects a rank-4 tensor, but got a rank-${a.rank} tensor`),Be(a,t,n)}var ll=L({slice4d_:v3});function w3(e,t=-1){let n=_(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}`);let a={logits:n},r={dim:t};return O.runKernel(io,a,r)}var Ka=L({softmax_:w3});function k3(e){$(e.dtype==="complex64",()=>`The dtype for tf.spectral.fft() must be complex64 but got ${e.dtype}.`);let t={input:e};return O.runKernel(um,t)}var zc=L({fft_:k3});function I3(e){$(e.dtype==="complex64",()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${e.dtype}.`);let t={input:e};return O.runKernel(pm,t)}var ul=L({ifft_:I3});function S3(e){let t=e.shape[e.shape.length-1],n=e.size/t,a;if(t<=2){let r=W(e,[n,t]);a=ul(r)}else{let r=[n,2*(t-1)],s=W(sl(e),[n,t]),i=W(Cc(e),[n,t]),o=fa(Be(s,[0,1],[n,t-2]),1),l=z(fa(Be(i,[0,1],[n,t-2]),1),be(-1)),u=Ze([s,o],1),p=Ze([i,l],1),d=W(Cr(u,p),[r[0],r[1]]);a=ul(d)}if(a=sl(a),e.rank===3&&e.shape[0]!==0){let r=a,s=e.shape[0];a=W(a,[s,a.shape[0]/s,a.shape[1]]),r.dispose()}return a}var Zm=L({irfft_:S3});function T3(e,t,n=0){let a={x:_(e,"x","split")},r={numOrSizeSplits:t,axis:n};return O.runKernel(yu,a,r)}var zn=L({split_:T3});function N3(e,t){$(e.dtype==="float32",()=>`The dtype for rfft() must be real value but got ${e.dtype}`);let n=e.shape[e.shape.length-1],a=e.size/n,r;if(t!=null&&t0),f=e.shape.map(g=>g);f[e.shape.length-1]=t,r=Be(e,m,f),n=t}else if(t!=null&&t>n){let m=e.shape.map(f=>f);m[e.shape.length-1]=t-n,r=Ze([e,It(m)],e.shape.length-1),n=t}else r=e;let s=qe(r),i=W(Cr(r,s),[a,n]),o=zc(i),l=Math.floor(n/2)+1,u=sl(o),p=Cc(o),d=zn(u,[l,n-l],u.shape.length-1),c=zn(p,[l,n-l],p.shape.length-1),h=r.shape.slice();return h[r.shape.length-1]=l,W(Cr(d[0],c[0]),h)}var Wc=L({rfft_:N3});function C3(e,t){let n=_(e,"a","squaredDifference"),a=_(t,"b","squaredDifference");[n,a]=_t(n,a),lt(n.shape,a.shape);let r={a:n,b:a},s={};return O.runKernel(oo,r,s)}var Jm=L({squaredDifference_:C3});function _3(e,t){let n=_(e,"x","squeeze","string_or_numeric");return W(n,II(n.shape,t).newShape)}var ws=L({squeeze_:_3});function E3(e,t=0){let n=jp(e,"tensors","stack","string_or_numeric");$(n.length>=1,()=>"Pass at least one tensor to tf.stack"),n.length>0&&$(t<=n[0].rank,()=>"Axis must be <= rank of the tensor");let a=n,r={axis:t};return O.runKernel(iu,a,r)}var Ft=L({stack_:E3});function A3(e,t=0){let n={x:_(e,"x","step")},a={alpha:t};return O.runKernel(ms,n,a)}var fo=L({step_:A3});function $3(e,t,n,a,r=0,s=0,i=0,o=0,l=0){let u={x:_(e,"x","stridedSlice","string_or_numeric")},p={begin:t,end:n,strides:a,beginMask:r,endMask:s,ellipsisMask:i,newAxisMask:o,shrinkAxisMask:l};return O.runKernel(xu,u,p)}var Dv=L({stridedSlice_:$3});function F3(e){let t={x:_(e,"x","tan","float32")};return O.runKernel(uo,t)}var Rv=L({tan_:F3});function Ke(e,t){hi(e);let n=ir(e,t);if(n.length!==1)throw new Error("tensor1d() requires values to be a flat/TypedArray");return fs(e,null,n,t)}function _a(e,t,n){if(hi(e),t!=null&&t.length!==2)throw new Error("tensor2d() requires shape to have two numbers");let a=ir(e,n);if(a.length!==2&&a.length!==1)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(a.length===1&&t==null)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return fs(e,t,a,n)}function $a(e,t,n){if(hi(e),t!=null&&t.length!==4)throw new Error("tensor4d() requires shape to have four numbers");let a=ir(e,n);if(a.length!==4&&a.length!==1)throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");if(a.length===1&&t==null)throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");return fs(e,t,a,n)}function uT(e,t,n){if(hi(e),t!=null&&t.length!==5)throw new Error("tensor5d() requires shape to have five numbers");let a=ir(e,n);if(a.length!==5&&a.length!==1)throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray");if(a.length===1&&t==null)throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");return fs(e,t,a,n)}function pT(e,t,n){if(hi(e),t!=null&&t.length!==6)throw new Error("tensor6d() requires shape to have six numbers");let a=ir(e,n);if(a.length!==6&&a.length!==1)throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray");if(a.length===1&&t==null)throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");return t=t||a,fs(e,t,a,n)}function D3(e,t=1,n=!0){let a=_(e,"x","topk");if(a.rank===0)throw new Error("topk() expects the input to be of rank 1 or higher");let r=a.shape[a.shape.length-1];if(t<0)throw new Error(`'k' passed to topk() must be >= 0 but got ${t}`);if(t>r)throw new Error(`'k' passed to topk() must be <= the last dimension (${r}) but got ${t}`);let s={x:a},i={k:t,sorted:n},[o,l]=O.runKernel(vu,s,i);return{values:o,indices:l}}var Mv=L({topk_:D3});function R3(e,t=0,n=1,a,r){if(a!=null&&a==="bool")throw new Error("Unsupported data type $ { dtype }");let s=new Av(t,n,a,!0,r),i=Pe(e,a);for(let o=0;o0,()=>"The input tensor must be at least 1D");let a={x:n},r={axis:t},[s,i]=O.runKernel(Nm,a,r);return{values:s,indices:i}}var Pv=L({unique_:M3});function P3(e,t,n){let a=_(e,"x","unsortedSegmentSum"),r=_(t,"segmentIds","unsortedSegmentSum","int32");$(tl(n),()=>"numSegments must be of dtype int");let s={x:a,segmentIds:r},i={numSegments:n};return O.runKernel(wc,s,i)}var ef=L({unsortedSegmentSum_:P3});function O3(e,t=0){let n=_(e,"x","unstack","string_or_numeric");$(t>=-n.shape.length&&t`Axis = ${t} is not in [-${n.shape.length}, ${n.shape.length})`);let a={value:n},r={axis:t};return O.runKernel(ku,a,r)}var ct=L({unstack_:O3});function cT(e,t){return Vm(e,t,"right")}function Ov(e,t=!0,n,a){return O.makeVariable(e,t,n,a)}function dT(e,t){let n=[];for(let s=0;s0,()=>"mask cannot be scalar"),Sn(o.slice(s,s+i),r.shape,"mask's shape must match the first K dimensions of tensor's shape,");let l=1;for(let f=s;f"Shape mismatch in v and x");let l=be(1),u=pe(l,o),p=z(pe(i,s),u);if(r){$(a!=null,()=>"When using zeroDebias: true, step is required.");let d=_(a,"step","movingAverage");p=he(p,pe(l,_r(o,d)))}return Y(s,p)}var mT=L({movingAverage_:W3});function B3(e,t,n){let a=_(e,"indices","scatterND","int32"),r=_(t,"updates","scatterND");Lx(r,a,n);let s={indices:a,updates:r},i={shape:n};return O.runKernel(uu,s,i)}var fT=L({scatterND_:B3});function V3(e,t,n,a){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}.`);let r=e.rank>0?e.shape[0]:1,s=e.rank>1?e.shape[1]:1;if(n.length!==s)throw new Error(`outputShape has incorrect number of elements:, ${n.length}, should be: ${s}.`);let i=t.size;if(!(t.rank===0||t.rank===1&&i===r))throw new Error(`sparseValues has incorrect shape ${t.shape}, should be [] or [${r}]`);if(t.dtype!==a.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}function U3(e,t,n,a=0){let r=_(e,"sparseIndices","sparseToDense","int32"),s=_(t,"sparseValues","sparseToDense","string_or_numeric"),i=_(a,"defaultValue","sparseToDense",s.dtype);V3(r,s,n,i);let o={sparseIndices:r,sparseValues:s,defaultValue:i},l={outputShape:n};return O.runKernel(Tm,o,l)}var gT=L({sparseToDense_:U3});function G3(e,t){let n=_(t,"indices","gatherND","int32"),a={params:_(e,"x","gatherND","string_or_numeric"),indices:n};return O.runKernel(Vl,a)}var yT=L({gatherND_:G3});function H3(e,t){if(t==null)return e.shape.slice();if(ps(e.shape,t))return t;if(e.shape.length===t.length){let n=[];for(let a=0;a`x has to be a floating point tensor since it's going to be scaled, but got a ${r.dtype} tensor instead.`),$(t>=0&&t<1,()=>`rate must be a float in the range [0, 1), but got ${t}.`),t===0)return e instanceof Te?r.clone():r;let s=H3(r,n),i=1-t,o=he(_u(Y($u(s,0,1,"float32",a),i)),i);return z(r,o)}var zv=L({dropout_:j3});function Wv(e){return Math.floor(Math.pow(2,Math.ceil(Math.log(e)/Math.log(2))))}function tf(e,t,n){let a=1-e%2,r=new Float32Array(e);for(let s=0;s1,()=>`inTopK() expects the predictions to be of rank 2 or higher, but got ${a.rank}`),$(a.rank-1===r.rank,()=>`predictions rank should be 1 larger than targets rank, but got predictions rank ${a.rank} and targets rank ${r.rank}`),Sn(a.shape.slice(0,a.shape.length-1),r.shape,"predictions's shape should be align with the targets' shape, except the last dimension.");let s=a.shape[a.shape.length-1];$(n>0&&n<=s,()=>`'k' passed to inTopK() must be > 0 && <= the predictions last dimension (${s}), but got ${n}`);let i=await a.data(),o=await r.data(),[l,u]=[i.length/s,s],p=SI("bool",l);for(let d=0;dg.value-f.value),p[d]=0;for(let f=0;fY3,depthwiseConv2d:()=>eL,matMul:()=>nL});function K3(e,t,n,a,r,s="NHWC",i){let o=e;e.rank===3&&(o=W(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;l.rank===3&&(l=W(t,[1,t.shape[0],t.shape[1],t.shape[2]])),$(o.rank===4,()=>`Error in conv2dDerFilter: input must be rank 4, but got shape ${o.shape}.`),$(l.rank===4,()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${l.shape}.`),$(n.length===4,()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${n}.`);let u=s==="NHWC"?o.shape[3]:o.shape[1],p=s==="NHWC"?l.shape[3]:l.shape[1];$(u===n[2],()=>`Error in conv2dDerFilter: depth of input ${u}) must match input depth in filter (${n[2]}.`),$(p===n[3],()=>`Error in conv2dDerFilter: depth of dy (${p}) must match output depth for filter (${n[3]}).`),Tn("conv2dDerFilter",r,i);let d={x:o,dy:l},c={strides:a,pad:r,dataFormat:s,dimRoundingMode:i,filterShape:n};return O.runKernel(em,d,c)}var Bv=L({conv2DBackpropFilter_:K3});function nf(e,t,n){if(n==null||n==="linear")return e;if(n==="relu")return z(e,fo(t));throw new Error(`Cannot compute gradient for fused activation ${n}.`)}function af(e,t){let n=t,a=Wt(e.shape,t.shape);return a.length>0&&(n=fe(n,a)),W(n,e.shape)}function rf(e,t,n,a){if(t==="linear")return e;if(t==="relu")return Xe(e);if(t==="elu")return Nu(e);if(t==="relu6")return Gm(e);if(t==="prelu")return Oc(e,n);if(t==="leakyrelu")return Fc(e,a);if(t==="sigmoid")return da(e);throw new Error(`Unknown fused activation ${t}.`)}var sf=(e,t)=>!(e>0)||t==="linear";function X3({x:e,filter:t,strides:n,pad:a,dataFormat:r="NHWC",dilations:s=[1,1],dimRoundingMode:i,bias:o,activation:l="linear",preluActivationWeights:u,leakyreluAlpha:p}){if(l=l||"linear",sf(O.state.gradientDepth,l)===!1){$(r==="NHWC",()=>`Error in fused conv2d: got dataFormat of ${r} but only NHWC is currently supported for the case of gradient depth is 0 and the activation is not linear.`);let T=$t(e,t,n,a,r,s,i);return o!=null&&(T=Y(T,o)),rf(T,l,u,p)}let d=_(e,"x","conv2d","float32"),c=_(t,"filter","conv2d","float32"),h=d,m=!1;d.rank===3&&(m=!0,h=W(d,[1,d.shape[0],d.shape[1],d.shape[2]])),$(h.rank===4,()=>`Error in fused conv2d: input must be rank 4, but got rank ${h.rank}.`),$(c.rank===4,()=>`Error in fused conv2d: filter must be rank 4, but got rank ${c.rank}.`),Tn("fused conv2d",a,i);let f=r==="NHWC"?h.shape[3]:h.shape[1];$(c.shape[2]===f,()=>`Error in conv2d: depth of input (${f}) must match input depth for filter ${c.shape[2]}.`),$(ur(n,s),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`);let g=Ec(h.shape,c.shape,n,s,a,i),y;o!=null&&(y=_(o,"bias","fused conv2d"),[y]=_t(y,d),r==="NHWC"?lt(g.outShape,y.shape):($(y.shape.length<=1,()=>`Error in fused conv2d: only supports scalar or 1-D Tensor bias for NCHW format but got the bias of rank-${y.shape.length}.`),$(y.shape.length===0||y.shape[0]===g.outChannels||y.shape[0]===1,()=>`Error in fused conv2d: bias shape (${y.shape}) is not compatible with the number of output channels (${g.outChannels})`)));let b;if(u!=null){let T=u.shape;if($(T.length<=1||T.length===3,()=>`Error in fused conv2d: only supports scalar, 1-D Tensor or 3-D Tensor PReLU activation weights but got a tensor of rank-${T.length}.`),T.length===1)$(T[0]===1||T[0]===g.outChannels,()=>`Error in fused conv2d: PReLU activation weights (${T}) is not compatible with the number of output channels (${g.outChannels}).`);else if(T.length===3)try{lt(T,g.outShape)}catch(C){let E=`Error in fused conv2d: PReLU activation weights (${T}) is not compatible with the output shape of the conv2d (${g.outShape}).`;throw Error(E)}b=_(u,"prelu weights","fused conv2d")}let x=(T,C)=>{$(r==="NHWC",()=>`Error in gradient of fused conv2D: got dataFormat of ${r} but only NHWC is currently supported.`);let[E,A,R,F]=C,S=nf(T,R,l);$(ns(s),()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`);let M=iv(A.shape,S,E,n,a),B=Bv(A,S,E.shape,n,a),U=[M,B];if(F!=null){let G=af(F,S);U.push(G)}return U},w={x:h,filter:c,bias:y,preluActivationWeights:b},I={strides:n,pad:a,dataFormat:r,dilations:s,dimRoundingMode:i,activation:l,leakyreluAlpha:p};return o==null?or((T,C,E)=>{let A=O.runKernel(Qs,w,I);return E([C,T,A]),m&&(A=W(A,[A.shape[1],A.shape[2],A.shape[3]])),{value:A,gradFunc:x}})(h,c):or((T,C,E,A)=>{let R=O.runKernel(Qs,w,I);return A([C,T,R,E]),m&&(R=W(R,[R.shape[1],R.shape[2],R.shape[3]])),{value:R,gradFunc:x}})(h,c,y)}var Y3=L({fusedConv2d_:X3});function Z3(e,t,n,a,r,s=[1,1],i){let o=e;e.rank===3&&(o=W(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;l.rank===3&&(l=W(t,[1,t.shape[0],t.shape[1],t.shape[2]]));let u={x:o,dy:l},p={strides:a,pad:r,dimRoundingMode:i,dilations:s,filterShape:n};return O.runKernel(rm,u,p)}var xT=L({depthwiseConv2dNativeBackpropFilter_:Z3});function J3(e,t,n,a,r,s=[1,1],i){let o=t,l=!1;t.rank===3&&(l=!0,o=W(t,[1,t.shape[0],t.shape[1],t.shape[2]]));let u={dy:o,filter:n},p={strides:a,pad:r,dimRoundingMode:i,dilations:s,inputShape:e},d=O.runKernel(sm,u,p);return l?W(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var vT=L({depthwiseConv2dNativeBackpropInput_:J3});function Q3({x:e,filter:t,strides:n,pad:a,dataFormat:r="NHWC",dilations:s=[1,1],dimRoundingMode:i,bias:o,activation:l="linear",preluActivationWeights:u,leakyreluAlpha:p}){if(sf(O.state.gradientDepth,l)===!1){let I=bs(e,t,n,a,r,s,i);return o!=null&&(I=Y(I,o)),rf(I,l,u,p)}let d=_(e,"x","depthwiseConv2d","float32"),c=_(t,"filter","depthwiseConv2d","float32"),h=d,m=!1;d.rank===3&&(m=!0,h=W(d,[1,d.shape[0],d.shape[1],d.shape[2]])),$(h.rank===4,()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${h.rank}.`),$(c.rank===4,()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${c.rank}.`),$(h.shape[3]===c.shape[2],()=>`Error in fused depthwiseConv2d: number of input channels (${h.shape[3]}) must match the inChannels dimension in filter ${c.shape[2]}.`),s==null&&(s=[1,1]),$(ur(n,s),()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`),Tn("fused depthwiseConv2d",a,i);let f=Ec(h.shape,c.shape,n,s,a,i,!0),g;o!=null&&(g=_(o,"bias","fused conv2d"),[g]=_t(g,d),lt(f.outShape,g.shape));let y;u!=null&&(y=_(u,"prelu weights","fused depthwiseConv2d"));let b=(I,T)=>{$(ns(s),()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${s}'`);let[C,E,A,R]=T,F=nf(I,A,l),S=vT(E.shape,F,C,n,a,s,i),M=xT(E,F,C.shape,n,a,s,i);if(R!=null){let B=af(g,F);return[S,M,B]}return[S,M]},x={x:h,filter:c,bias:g,preluActivationWeights:y},w={strides:n,pad:a,dataFormat:r,dilations:s,dimRoundingMode:i,activation:l,leakyreluAlpha:p};return o==null?or((I,T,C)=>{let E=O.runKernel(ei,x,w);return C([T,I,E]),m&&(E=W(E,[E.shape[1],E.shape[2],E.shape[3]])),{value:E,gradFunc:b}})(h,c):or((I,T,C,E)=>{let A=O.runKernel(ei,x,w);return E([T,I,A,C]),m&&(A=W(A,[A.shape[1],A.shape[2],A.shape[3]])),{value:A,gradFunc:b}})(h,c,g)}var eL=L({fusedDepthwiseConv2d_:Q3});function tL({a:e,b:t,transposeA:n=!1,transposeB:a=!1,bias:r,activation:s="linear",preluActivationWeights:i,leakyreluAlpha:o=.2}){if(sf(O.state.gradientDepth,s)===!1){let R=Fe(e,t,n,a);return r!=null&&(R=Y(R,r)),rf(R,s,i,o)}let l=_(e,"a","fused matMul"),u=_(t,"b","fused matMul");[l,u]=_t(l,u);let p=n?l.shape[l.rank-2]:l.shape[l.rank-1],d=a?u.shape[u.rank-1]:u.shape[u.rank-2],c=n?l.shape[l.rank-1]:l.shape[l.rank-2],h=a?u.shape[u.rank-2]:u.shape[u.rank-1],m=l.shape.slice(0,-2),f=u.shape.slice(0,-2),g=mt(m),y=mt(f);$(p===d,()=>`Error in fused matMul: inner shapes (${p}) and (${d}) of Tensors with shapes ${l.shape} and ${u.shape} and transposeA=${n} and transposeB=${a} must match.`);let b=lt(l.shape.slice(0,-2),u.shape.slice(0,-2)).concat([c,h]),x=n?W(l,[g,p,c]):W(l,[g,c,p]),w=a?W(u,[y,h,d]):W(u,[y,d,h]),I;r!=null&&(I=_(r,"bias","fused matMul"),[I]=_t(I,l),lt(b,I.shape));let T;i!=null&&(T=_(i,"prelu weights","fused matMul"));let C=(R,F)=>{let[S,M,B,U]=F,G=nf(W(R,B.shape),B,s),q,K;if(!n&&!a?(q=Fe(G,M,!1,!0),K=Fe(S,G,!0,!1)):!n&&a?(q=Fe(G,M,!1,!1),K=Fe(G,S,!0,!1)):n&&!a?(q=Fe(M,G,!1,!0),K=Fe(S,G,!1,!1)):(q=Fe(M,G,!0,!0),K=Fe(G,S,!0,!0)),r!=null){let Z=af(U,G);return[q,K,Z]}else return[q,K]},E={a:x,b:w,bias:I,preluActivationWeights:T},A={transposeA:n,transposeB:a,activation:s,leakyreluAlpha:o};return r==null?or((R,F,S)=>{let M=O.runKernel(Js,E,A);return S([R,F,M]),{value:W(M,b),gradFunc:C}})(x,w):or((R,F,S,M)=>{let B=O.runKernel(Js,E,A);return M([R,F,B,S]),{value:W(B,b),gradFunc:C}})(x,w,I)}var nL=L({fusedMatMul_:tL});function aL(e){return tf(e,.54,.46)}var rL=L({hammingWindow_:aL});function sL(e){return tf(e,.5,.5)}var wT=L({hannWindow_:sL});function iL(e,t,n,a=!1,r=0){let s=0,i=[];for(;s+t<=e.size;)i.push(Be(e,s,t)),s+=n;if(a)for(;s`Error in cropAndResize: image must be rank 4,but got rank ${i.rank}.`),$(o.rank===2&&o.shape[1]===4,()=>`Error in cropAndResize: boxes must be have size [${u},4] but had shape ${o.shape}.`),$(l.rank===1&&l.shape[0]===u,()=>`Error in cropAndResize: boxInd must be have size [${u}] but had shape ${o.shape}.`),$(a.length===2,()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${a.length}.`),$(a[0]>=1&&a[1]>=1,()=>`cropSize must be atleast [1,1], but was ${a}`),$(r==="bilinear"||r==="nearest",()=>`method must be bilinear or nearest, but was ${r}`);let p={image:i,boxes:o,boxInd:l},d={method:r,extrapolationValue:s,cropSize:a};return O.runKernel(Rl,p,d)}var pL=L({cropAndResize_:uL});function cL(e){let t=_(e,"image","flipLeftRight","float32");$(t.rank===4,()=>`Error in flipLeftRight: image must be rank 4,but got rank ${t.rank}.`);let n={image:t};return O.runKernel(Wl,n,{})}var dL=L({flipLeftRight_:cL});function hL(e){let t=_(e,"image","grayscaleToRGB"),n=t.rank-1,a=t.shape[n];$(t.rank>=2,()=>`Error in grayscaleToRGB: images must be at least rank 2, but got rank ${t.rank}.`),$(a===1,()=>`Error in grayscaleToRGB: last dimension of a grayscale image should be size 1, but got size ${a}.`);let r=new Array(t.rank);return r.fill(1,0,n),r[n]=3,Ln(t,r)}var mL=L({grayscaleToRGB_:hL});function fL(e,t,n=0,a=.5){let r=_(e,"image","rotateWithOffset","float32");$(r.rank===4,()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${r.rank}.`);let s={image:r},i={radians:t,fillValue:n,center:a};return O.runKernel(Su,s,i)}var gL=L({rotateWithOffset_:fL});function Fu(e,t,n,a,r,s){a==null&&(a=.5),r==null&&(r=Number.NEGATIVE_INFINITY),s==null&&(s=0);let i=e.shape[0];return n=Math.min(n,i),$(0<=a&&a<=1,()=>`iouThreshold must be in [0, 1], but was '${a}'`),$(e.rank===2,()=>`boxes must be a 2D tensor, but was of rank '${e.rank}'`),$(e.shape[1]===4,()=>`boxes must have 4 columns, but 2nd dimension was ${e.shape[1]}`),$(t.rank===1,()=>"scores must be a 1D tensor"),$(t.shape[0]===i,()=>`scores has incompatible shape with boxes. Expected ${i}, but was ${t.shape[0]}`),$(0<=s&&s<=1,()=>`softNmsSigma must be in [0, 1], but was '${s}'`),{maxOutputSize:n,iouThreshold:a,scoreThreshold:r,softNmsSigma:s}}function yL(e,t,n,a=.5,r=Number.NEGATIVE_INFINITY){let s=_(e,"boxes","nonMaxSuppression","float32"),i=_(t,"scores","nonMaxSuppression","float32"),o=Fu(s,i,n,a,r);n=o.maxOutputSize,a=o.iouThreshold,r=o.scoreThreshold;let l={maxOutputSize:n,iouThreshold:a,scoreThreshold:r};return O.runKernel(nu,{boxes:s,scores:i},l)}var bL=L({nonMaxSuppression_:yL});function xL(e,t,n){let a=vL(e,t,n),r=a<0?-(a+1):a;e.splice(r,0,t)}function vL(e,t,n){return kL(e,t,n||wL)}function wL(e,t){return e>t?1:e>>1);let o=n(t,e[s]);o>0?a=s+1:(r=s,i=!o)}return i?a:-a-1}function IT(e,t,n,a,r){return Vv(e,t,n,a,r,0)}function ST(e,t,n,a,r,s){return Vv(e,t,n,a,r,0,!1,s,!0)}function TT(e,t,n,a,r,s){return Vv(e,t,n,a,r,s,!0)}function Vv(e,t,n,a,r,s,i=!1,o=!1,l=!1){let u=[];for(let g=0;gr&&u.push({score:t[g],boxIndex:g,suppressBeginIndex:0});u.sort(Z1);let p=s>0?-.5/s:0,d=[],c=[];for(;d.length0;){let g=u.pop(),{score:y,boxIndex:b,suppressBeginIndex:x}=g;if(y=x;--I){let T=IL(e,b,d[I]);if(T>=a){w=!0;break}if(g.score=g.score*SL(a,p,T),g.score<=r)break}g.suppressBeginIndex=d.length,w||(g.score===y?(d.push(b),c.push(g.score)):g.score>r&&xL(u,g,Z1))}let h=d.length,m=n-h;o&&m>0&&(d.push(...new Array(m).fill(0)),c.push(...new Array(m).fill(0)));let f={selectedIndices:d};return i&&(f.selectedScores=c),l&&(f.validOutputs=h),f}function IL(e,t,n){let a=e.subarray(t*4,t*4+4),r=e.subarray(n*4,n*4+4),s=Math.min(a[0],a[2]),i=Math.min(a[1],a[3]),o=Math.max(a[0],a[2]),l=Math.max(a[1],a[3]),u=Math.min(r[0],r[2]),p=Math.min(r[1],r[3]),d=Math.max(r[0],r[2]),c=Math.max(r[1],r[3]),h=(o-s)*(l-i),m=(d-u)*(c-p);if(h<=0||m<=0)return 0;let f=Math.max(s,u),g=Math.max(i,p),y=Math.min(o,d),b=Math.min(l,c),x=Math.max(y-f,0)*Math.max(b-g,0);return x/(h+m-x)}function SL(e,t,n){let a=Math.exp(t*n*n);return n<=e?a:0}function Z1(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex}async function TL(e,t,n,a=.5,r=Number.NEGATIVE_INFINITY){let s=_(e,"boxes","nonMaxSuppressionAsync"),i=_(t,"scores","nonMaxSuppressionAsync"),o=Fu(s,i,n,a,r);n=o.maxOutputSize,a=o.iouThreshold,r=o.scoreThreshold;let l=await Promise.all([s.data(),i.data()]),u=l[0],p=l[1],{selectedIndices:d}=IT(u,p,n,a,r);return s!==e&&s.dispose(),i!==t&&i.dispose(),Ke(d,"int32")}var NL=TL;function CL(e,t,n,a=.5,r=Number.NEGATIVE_INFINITY,s=0){let i=_(e,"boxes","nonMaxSuppression"),o=_(t,"scores","nonMaxSuppression"),l=Fu(i,o,n,a,r,s);n=l.maxOutputSize,a=l.iouThreshold,r=l.scoreThreshold,s=l.softNmsSigma;let u={boxes:i,scores:o},p={maxOutputSize:n,iouThreshold:a,scoreThreshold:r,softNmsSigma:s},d=O.runKernel(ru,u,p);return{selectedIndices:d[0],selectedScores:d[1]}}var _L=L({nonMaxSuppressionWithScore_:CL});async function EL(e,t,n,a=.5,r=Number.NEGATIVE_INFINITY,s=0){let i=_(e,"boxes","nonMaxSuppressionAsync"),o=_(t,"scores","nonMaxSuppressionAsync"),l=Fu(i,o,n,a,r,s);n=l.maxOutputSize,a=l.iouThreshold,r=l.scoreThreshold,s=l.softNmsSigma;let u=await Promise.all([i.data(),o.data()]),p=u[0],d=u[1],{selectedIndices:c,selectedScores:h}=TT(p,d,n,a,r,s);return i!==e&&i.dispose(),o!==t&&o.dispose(),{selectedIndices:Ke(c,"int32"),selectedScores:Ke(h)}}var AL=EL;function $L(e,t,n,a=.5,r=Number.NEGATIVE_INFINITY,s=!1){let i=_(e,"boxes","nonMaxSuppression"),o=_(t,"scores","nonMaxSuppression"),l=Fu(i,o,n,a,r,null),u=l.maxOutputSize,p=l.iouThreshold,d=l.scoreThreshold,c={boxes:i,scores:o},h={maxOutputSize:u,iouThreshold:p,scoreThreshold:d,padToMaxOutputSize:s},m=O.runKernel(au,c,h);return{selectedIndices:m[0],validOutputs:m[1]}}var FL=L({nonMaxSuppressionPadded_:$L});async function DL(e,t,n,a=.5,r=Number.NEGATIVE_INFINITY,s=!1){let i=_(e,"boxes","nonMaxSuppressionAsync"),o=_(t,"scores","nonMaxSuppressionAsync"),l=Fu(i,o,n,a,r,null),u=l.maxOutputSize,p=l.iouThreshold,d=l.scoreThreshold,[c,h]=await Promise.all([i.data(),o.data()]),{selectedIndices:m,validOutputs:f}=ST(c,h,u,p,d,s);return i!==e&&i.dispose(),o!==t&&o.dispose(),{selectedIndices:Ke(m,"int32"),validOutputs:be(f,"int32")}}var RL=DL;function ML(e,t,n=!1,a=!1){let r=_(e,"images","resizeBilinear");$(r.rank===3||r.rank===4,()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${r.rank}.`),$(t.length===2,()=>`Error in resizeBilinear: new shape must 2D, but got shape ${t}.`),$(a===!1||n===!1,()=>"Error in resizeBilinear: If halfPixelCenters is true, alignCorners must be false.");let s=r,i=!1;r.rank===3&&(i=!0,s=W(r,[1,r.shape[0],r.shape[1],r.shape[2]]));let[]=t,o={images:s},l={alignCorners:n,halfPixelCenters:a,size:t},u=O.runKernel(Zi,o,l);return i?W(u,[u.shape[1],u.shape[2],u.shape[3]]):u}var NT=L({resizeBilinear_:ML});function PL(e,t,n=!1,a=!1){let r=_(e,"images","resizeNearestNeighbor");$(r.rank===3||r.rank===4,()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${r.rank}.`),$(t.length===2,()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${t}.`),$(r.dtype==="float32"||r.dtype==="int32",()=>"`images` must have `int32` or `float32` as dtype"),$(a===!1||n===!1,()=>"Error in resizeNearestNeighbor: If halfPixelCenters is true, alignCorners must be false.");let s=r,i=!1;r.rank===3&&(i=!0,s=W(r,[1,r.shape[0],r.shape[1],r.shape[2]]));let[]=t,o={images:s},l={alignCorners:n,halfPixelCenters:a,size:t},u=O.runKernel(Yi,o,l);return i?W(u,[u.shape[1],u.shape[2],u.shape[3]]):u}var CT=L({resizeNearestNeighbor_:PL});function OL(e,t="binary",n=!1,a=.5){let r=_(e,"image","threshold"),s=.2989,i=.587,o=.114,l=r.shape[0]*r.shape[1],u=z(Ke([a]),255),p,d,c,h;if($(r.rank===3,()=>`Error in threshold: image must be rank 3,but got rank ${r.rank}.`),$(r.shape[2]===3||r.shape[2]===1,()=>`Error in threshold: image color channel must be equal to 3 or 1but got ${r.shape[2]}.`),$(r.dtype==="int32"||r.dtype==="float32",()=>`Error in dtype: image dtype must be int32 or float32,but got dtype ${r.dtype}.`),$(t==="otsu"||t==="binary",()=>`Method must be binary or otsu, but was ${t}`),r.shape[2]===3){[p,d,c]=zn(r,[1,1,1],-1);let f=z(p,s),g=z(d,i),y=z(c,o);h=Y(Y(f,g),y)}else h=e;if(t==="otsu"){let f=ev(oe(Hm(h),"int32"),kn([]),256);u=LL(f,l)}let m=n?xs(h,u):Nn(h,u);return oe(z(m,255),"int32")}function LL(e,t){let n=Ke([-1]),a=Ke([0]),r=Ke([0]),s,i,o,l,u,p;for(let d=0;d`Error in transform: image must be rank 4,but got rank ${i.rank}.`),$(o.rank===2&&(o.shape[0]===i.shape[0]||o.shape[0]===1)&&o.shape[1]===8,()=>"Error in transform: Input transform should be batch x 8 or 1 x 8"),$(s==null||s.length===2,()=>`Error in transform: outputShape must be [height, width] or null, but got ${s}.`);let l={image:i,transforms:o},u={interpolation:n,fillMode:a,fillValue:r,outputShape:s};return O.runKernel(wu,l,u)}var BL=L({transform_:WL});function VL(e,t,n){$(t%1===0,()=>`bandPart(): numLower must be an integer, got ${t}.`),$(n%1===0,()=>`bandPart(): numUpper must be an integer, got ${n}.`);let a=_(e,"a","bandPart");$(a.rank>=2,()=>`bandPart(): Rank must be at least 2, got ${a.rank}.`);let r=a.shape,[s,i]=a.shape.slice(-2);if(!(t<=s))throw new Error(`bandPart(): numLower (${t}) must not be greater than the number of rows (${s}).`);if(!(n<=i))throw new Error(`bandPart(): numUpper (${n}) must not be greater than the number of columns (${i}).`);t<0&&(t=s),n<0&&(n=i);let o=W(ol(0,s,1,"int32"),[-1,1]),l=ol(0,i,1,"int32"),u=pe(o,l),p=Ea(xs(u,be(+t,"int32")),Er(u,be(-n,"int32"))),d=It([s,i],a.dtype);return W(Ft(ct(W(a,[-1,s,i])).map(c=>mn(p,c,d))),r)}var UL=L({bandPart_:VL});function GL(e){let t;if(Array.isArray(e)){t=!1,$(e!=null&&e.length>0,()=>"Gram-Schmidt process: input must not be null, undefined, or empty");let r=e[0].shape[0];for(let s=1;s`Gram-Schmidt: Non-unique lengths found in the input vectors: (${e[s].shape[0]} vs. ${r})`)}else t=!0,e=zn(e,e.shape[0],0).map(r=>ws(r,[0]));$(e.length<=e[0].shape[0],()=>`Gram-Schmidt: Number of vectors (${e.length}) exceeds number of dimensions (${e[0].shape[0]}).`);let n=[],a=e;for(let r=0;r{let s=a[r];if(r>0)for(let i=0;i=2,()=>`qr() requires input tensor to have a rank >= 2, but got rank ${e.rank}`),e.rank===2)return J1(e,t);{let n=e.shape.slice(0,e.shape.length-2).reduce((l,u)=>l*u),a=ct(W(e,[n,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),r=[],s=[];a.forEach(l=>{let[u,p]=J1(l,t);r.push(u),s.push(p)});let i=W(Ft(r,0),e.shape),o=W(Ft(s,0),e.shape);return[i,o]}}function J1(e,t=!1){return O.tidy(()=>{$(e.shape.length===2,()=>`qr2d() requires a 2D Tensor, but got a ${e.shape.length}D Tensor.`);let n=e.shape[0],a=e.shape[1],r=Pm(n),s=rr(e),i=_a([[1]],[1,1]),o=rr(i),l=n>=a?a:n;for(let u=0;u{let h=Be(s,[u,u],[n-u,1]),m=Cu(h),f=Be(s,[u,u],[1,1]),g=mn(Nn(f,0),_a([[-1]]),_a([[1]])),y=pe(f,z(g,m)),b=he(h,y);b.shape[0]===1?o=rr(i):o=Ze([i,Be(b,[1,0],[b.shape[0]-1,b.shape[1]])],0);let x=bt(he(Fe(g,y),m)),w=Be(s,[u,0],[n-u,a]),I=z(x,o),T=Ee(o);if(u===0)s=pe(w,Fe(I,Fe(T,w)));else{let A=pe(w,Fe(I,Fe(T,w)));s=Ze([Be(s,[0,0],[u,a]),A],0)}let C=Ee(I),E=Be(r,[0,u],[n,r.shape[1]-u]);if(u===0)r=pe(E,Fe(Fe(E,o),C));else{let A=pe(E,Fe(Fe(E,o),C));r=Ze([Be(r,[0,0],[n,u]),A],1)}return[o,s,r]}),_e([p,d,c])}return!t&&n>a&&(r=Be(r,[0,0],[n,a]),s=Be(s,[0,0],[a,a])),[r,s]})}var qL=L({qr_:jL}),xn;(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"})(xn||(xn={}));function KL(e,t,n=xn.SUM_BY_NONZERO_WEIGHTS){let a=_(e,"losses","computeWeightedLoss"),r=null;t!=null&&(r=_(t,"weights","computeWeightedLoss"));let s=r==null?a:z(a,r);if(n===xn.NONE)return s;if(n===xn.SUM)return fe(s);if(n===xn.MEAN){if(r==null)return Nt(s);{let i=a.size/r.size,o=he(fe(s),fe(r));return i>1?he(o,be(i)):o}}if(n===xn.SUM_BY_NONZERO_WEIGHTS){if(r==null)return he(fe(s),be(a.size));{let i=z(r,Zn(a.shape)),o=oe(fe(ii(i,be(0))),"float32");return he(fe(s),o)}}throw Error(`Unknown reduction: ${n}`)}var Ar=L({computeWeightedLoss_:KL});function XL(e,t,n,a=xn.SUM_BY_NONZERO_WEIGHTS){let r=_(e,"labels","absoluteDifference"),s=_(t,"predictions","absoluteDifference"),i=null;n!=null&&(i=_(n,"weights","absoluteDifference")),Sn(r.shape,s.shape,"Error in absoluteDifference: ");let o=Lt(pe(r,s));return Ar(o,i,a)}var YL=L({absoluteDifference_:XL});function ZL(e,t,n,a,r=xn.SUM_BY_NONZERO_WEIGHTS){let s=_(e,"labels","cosineDistance"),i=_(t,"predictions","cosineDistance"),o=null;a!=null&&(o=_(a,"weights","cosineDistance")),Sn(s.shape,i.shape,"Error in cosineDistance: ");let l=be(1),u=pe(l,fe(z(s,i),n,!0));return Ar(u,o,r)}var JL=L({cosineDistance_:ZL});function QL(e,t,n,a=xn.SUM_BY_NONZERO_WEIGHTS){let r=_(e,"labels","hingeLoss"),s=_(t,"predictions","hingeLoss"),i=null;n!=null&&(i=_(n,"weights","hingeLoss")),Sn(r.shape,s.shape,"Error in hingeLoss: ");let o=be(1);r=pe(z(be(2),r),o);let l=Xe(pe(o,z(r,s)));return Ar(l,i,a)}var ez=L({hingeLoss_:QL});function tz(e,t,n,a=1,r=xn.SUM_BY_NONZERO_WEIGHTS){let s=_(e,"labels","huberLoss"),i=_(t,"predictions","huberLoss"),o=null;n!=null&&(o=_(n,"weights","huberLoss")),Sn(s.shape,i.shape,"Error in huberLoss: ");let l=be(a),u=Lt(pe(i,s)),p=Au(u,l),d=pe(u,p),c=Y(z(be(.5),ot(p)),z(l,d));return Ar(c,o,r)}var nz=L({huberLoss_:tz});function az(e,t,n,a=1e-7,r=xn.SUM_BY_NONZERO_WEIGHTS){let s=_(e,"labels","logLoss"),i=_(t,"predictions","logLoss"),o=null;n!=null&&(o=_(n,"weights","logLoss")),Sn(s.shape,i.shape,"Error in logLoss: ");let l=be(1),u=be(a),p=bt(z(s,ea(Y(i,u)))),d=z(pe(l,s),ea(Y(pe(l,i),u))),c=pe(p,d);return Ar(c,o,r)}var rz=L({logLoss_:az});function sz(e,t,n,a=xn.SUM_BY_NONZERO_WEIGHTS){let r=_(e,"labels","meanSquaredError"),s=_(t,"predictions","meanSquaredError"),i=null;n!=null&&(i=_(n,"weights","meanSquaredError")),Sn(r.shape,s.shape,"Error in meanSquaredError: ");let o=Jm(r,s);return Ar(o,i,a)}var iz=L({meanSquaredError_:sz});function oz(e,t){let n=_(e,"labels","sigmoidCrossEntropyWithLogits"),a=_(t,"logits","sigmoidCrossEntropyWithLogits");Sn(n.shape,a.shape,"Error in sigmoidCrossEntropyWithLogits: ");let r=Xe(a),s=z(a,n),i=Dc(fn(bt(Lt(a))));return Y(pe(r,s),i)}function lz(e,t,n,a=0,r=xn.SUM_BY_NONZERO_WEIGHTS){let s=_(e,"multiClassLabels","sigmoidCrossEntropy"),i=_(t,"logits","sigmoidCrossEntropy"),o=null;if(n!=null&&(o=_(n,"weights","sigmoidCrossEntropy")),Sn(s.shape,i.shape,"Error in sigmoidCrossEntropy: "),a>0){let u=be(a),p=be(1),d=be(.5);s=Y(z(s,pe(p,u)),z(d,u))}let l=oz(s,i);return Ar(l,o,r)}var uz=L({sigmoidCrossEntropy_:lz});function pz(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}`);return or((a,r,s)=>{let i=Wm(r,[n],!0),o=pe(oe(r,"float32"),i);s([a,o]);let l=bt(z(o,a));return{value:fe(l,[n]),gradFunc:(u,p)=>{let[d,c]=p,h=si(u.shape,[n]);return[z(W(u,h),pe(oe(d,"float32"),fn(c))),z(W(u,h),pe(fn(c),oe(d,"float32")))]}}})(e,t)}function cz(e,t,n,a=0,r=xn.SUM_BY_NONZERO_WEIGHTS){let s=_(e,"onehotLabels","softmaxCrossEntropy"),i=_(t,"logits","softmaxCrossEntropy"),o=null;if(n!=null&&(o=_(n,"weights","softmaxCrossEntropy")),Sn(s.shape,i.shape,"Error in softmaxCrossEntropy: "),a>0){let u=be(a),p=be(1),d=be(s.shape[1]);s=Y(z(s,pe(p,u)),he(u,d))}let l=pz(s,i);return Ar(l,o,r)}var dz=L({softmaxCrossEntropy_:cz});function hz(e,t,n,a){let r=_(e,"indices","sparseFillEmptyRows","int32"),s=_(t,"values","sparseFillEmptyRows"),i=_(n,"denseShape","sparseFillEmptyRows","int32"),o=_(a,"defaultValue","sparseFillEmptyRows",s.dtype);if(r.rank!==2)throw new Error(`Indices should be Tensor2D but received shape
- ${r.shape}`);if(s.rank!==1)throw new Error(`Values should be Tensor1D but received shape ${s.shape}`);if(i.rank!==1)throw new Error(`Dense shape should be Tensor1D but received shape ${i.shape}`);if(o.rank!==0)throw new Error(`Default value should be a scalar but received shape ${o.shape}`);let l={indices:r,values:s,denseShape:i,defaultValue:o},u=O.runKernel(mc,l);return{outputIndices:u[0],outputValues:u[1],emptyRowIndicator:u[2],reverseIndexMap:u[3]}}var mz=L({sparseFillEmptyRows_:hz});function fz(e,t,n){let a=_(e,"inputIndices","sparseReshape","int32"),r=_(t,"inputShape","sparseReshape","int32"),s=_(n,"newShape","sparseReshape","int32");if(a.rank!==2)throw new Error(`Input indices should be Tensor2D but received shape
- ${a.shape}`);if(r.rank!==1)throw new Error(`Input shape should be Tensor1D but received shape ${r.shape}`);if(s.rank!==1)throw new Error(`New shape should be Tensor1D but received shape ${s.shape}`);let i={inputIndices:a,inputShape:r,newShape:s},o=O.runKernel(bu,i);return{outputIndices:o[0],outputShape:o[1]}}var gz=L({sparseReshape_:fz});function yz(e,t,n){let a=_(e,"data","sparseSegmentMean"),r=_(t,"indices","sparseSegmentMean","int32"),s=_(n,"segmentIds","sparseSegmentMean","int32");if(a.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(r.rank!==1)throw new Error(`Indices should be Tensor1D but received shape
- ${r.shape}`);if(s.rank!==1)throw new Error(`Segment ids should be Tensor1D but received shape
- ${s.shape}`);let i={data:a,indices:r,segmentIds:s};return O.runKernel(fc,i)}var bz=L({sparseSegmentMean_:yz});function xz(e,t,n){let a=_(e,"data","sparseSegmentSum"),r=_(t,"indices","sparseSegmentSum","int32"),s=_(n,"segmentIds","sparseSegmentSum","int32");if(a.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(r.rank!==1)throw new Error(`Indices should be Tensor1D but received shape
- ${r.shape}`);if(s.rank!==1)throw new Error(`Segment ids should be Tensor1D but received shape
- ${s.shape}`);let i={data:a,indices:r,segmentIds:s};return O.runKernel(gc,i)}var vz=L({sparseSegmentSum_:xz});function wz(e,t,n,a,r,s,i,o){let l=_(e,"data","stringNGrams","string");if(l.dtype!=="string")throw new Error("Data must be of datatype string");if(l.shape.length!==1)throw new Error(`Data must be a vector, saw: ${l.shape}`);let u=_(t,"dataSplits","stringNGrams");if(u.dtype!=="int32")throw new Error("Data splits must be of datatype int32");let p={separator:n,nGramWidths:a,leftPad:r,rightPad:s,padWidth:i,preserveShortSequences:o},d={data:l,dataSplits:u},c=O.runKernel(bc,d,p);return{nGrams:c[0],nGramsSplits:c[1]}}var kz=L({stringNGrams_:wz});function Iz(e,t,n=!0){let a=_(e,"input","stringSplit","string"),r=_(t,"delimiter","stringSplit","string");if(a.rank!==1)throw new Error(`Input should be Tensor1D but received shape ${a.shape}`);if(r.rank!==0)throw new Error(`Delimiter should be a scalar but received shape ${r.shape}`);let s={skipEmpty:n},i={input:a,delimiter:r},o=O.runKernel(xc,i,s);return{indices:o[0],values:o[1],shape:o[2]}}var Sz=L({stringSplit_:Iz});function Tz(e,t){let n=_(e,"input","stringToHashBucketFast","string"),a={numBuckets:t};if(t<=0)throw new Error("Number of buckets must be at least 1");let r={input:n};return O.runKernel(vc,r,a)}var Nz=L({stringToHashBucketFast_:Tz}),_T={fft:zc,ifft:ul,rfft:Wc,irfft:Zm},ET={hammingWindow:rL,hannWindow:wT,frame:kT,stft:lL},za={flipLeftRight:dL,grayscaleToRGB:mL,resizeNearestNeighbor:CT,resizeBilinear:NT,rotateWithOffset:gL,cropAndResize:pL,nonMaxSuppression:bL,nonMaxSuppressionAsync:NL,nonMaxSuppressionWithScore:_L,nonMaxSuppressionWithScoreAsync:AL,nonMaxSuppressionPadded:FL,nonMaxSuppressionPaddedAsync:RL,threshold:zL,transform:BL},Uv={bandPart:UL,gramSchmidt:HL,qr:qL},AT={absoluteDifference:YL,computeWeightedLoss:Ar,cosineDistance:JL,hingeLoss:ez,huberLoss:nz,logLoss:rz,meanSquaredError:iz,sigmoidCrossEntropy:uz,softmaxCrossEntropy:dz},$T={sparseFillEmptyRows:mz,sparseReshape:gz,sparseSegmentMean:bz,sparseSegmentSum:vz},FT={stringNGrams:kz,stringSplit:Sz,stringToHashBucketFast:Nz},$r=class extends IS{minimize(e,t=!1,n){let{value:a,grads:r}=this.computeGradients(e,n);if(n!=null){let s=n.map(i=>({name:i.name,tensor:r[i.name]}));this.applyGradients(s)}else this.applyGradients(r);return _e(r),t?a:(a.dispose(),null)}get iterations(){return this.iterations_==null&&(this.iterations_=0),this.iterations_}incrementIterations(){this.iterations_=this.iterations+1}computeGradients(e,t){return BS(e,t)}dispose(){this.iterations_!=null&&_e(this.iterations_)}async saveIterations(){return this.iterations_==null&&(this.iterations_=0),{name:"iter",tensor:be(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($r,Symbol.hasInstance,{value:e=>e.minimize!=null&&e.computeGradients!=null&&e.applyGradients!=null});var of=class extends $r{constructor(e,t,n=null){super(),this.learningRate=e,this.rho=t,this.epsilon=n,this.accumulatedGrads=[],this.accumulatedUpdates=[],n==null&&(this.epsilon=O.backend.epsilon())}applyGradients(e){(Array.isArray(e)?e.map(t=>t.name):Object.keys(e)).forEach((t,n)=>{let a=O.registeredVariables[t],r=!1;this.accumulatedGrads[n]==null&&(this.accumulatedGrads[n]={originalName:`${t}/accum_grad`,variable:P(()=>qe(a).variable(r))}),this.accumulatedUpdates[n]==null&&(this.accumulatedUpdates[n]={originalName:`${t}/accum_var`,variable:P(()=>qe(a).variable(r))});let s=Array.isArray(e)?e[n].tensor:e[t];if(s==null)return;let i=this.accumulatedGrads[n].variable,o=this.accumulatedUpdates[n].variable;P(()=>{let l=Y(z(i,this.rho),z(ot(s),1-this.rho)),u=z(he(ln(Y(o,this.epsilon)),ln(Y(i,this.epsilon))),s),p=Y(z(o,this.rho),z(ot(u),1-this.rho));i.assign(l),o.assign(p);let d=Y(z(u,-this.learningRate),a);a.assign(d)})}),this.incrementIterations()}dispose(){this.accumulatedUpdates!=null&&(_e(this.accumulatedGrads.map(e=>e.variable)),_e(this.accumulatedUpdates.map(e=>e.variable)))}async getWeights(){let 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);let t=e.length/2,n=!1;this.accumulatedGrads=e.slice(0,t).map(a=>({originalName:a.name,variable:a.tensor.variable(n)})),this.accumulatedUpdates=e.slice(t,t*2).map(a=>({originalName:a.name,variable:a.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)}};of.className="Adadelta";gs(of);var lf=class extends $r{constructor(e,t=.1){super(),this.learningRate=e,this.initialAccumulatorValue=t,this.accumulatedGrads=[]}applyGradients(e){(Array.isArray(e)?e.map(t=>t.name):Object.keys(e)).forEach((t,n)=>{let a=O.registeredVariables[t];this.accumulatedGrads[n]==null&&(this.accumulatedGrads[n]={originalName:`${t}/accumulator`,variable:P(()=>gn(a.shape,this.initialAccumulatorValue).variable(!1))});let r=Array.isArray(e)?e[n].tensor:e[t];if(r==null)return;let s=this.accumulatedGrads[n].variable;P(()=>{let i=Y(s,ot(r));s.assign(i);let o=Y(z(he(r,ln(Y(i,O.backend.epsilon()))),-this.learningRate),a);a.assign(o)})}),this.incrementIterations()}dispose(){this.accumulatedGrads!=null&&_e(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);let 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)}};lf.className="Adagrad";gs(lf);var uf=class extends $r{constructor(e,t,n,a=null){super(),this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=a,this.accumulatedFirstMoment=[],this.accumulatedSecondMoment=[],P(()=>{this.accBeta1=be(t).variable(),this.accBeta2=be(n).variable()}),a==null&&(this.epsilon=O.backend.epsilon())}applyGradients(e){let t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);P(()=>{let n=pe(1,this.accBeta1),a=pe(1,this.accBeta2);t.forEach((r,s)=>{let i=O.registeredVariables[r],o=!1;this.accumulatedFirstMoment[s]==null&&(this.accumulatedFirstMoment[s]={originalName:`${r}/m`,variable:P(()=>qe(i).variable(o))}),this.accumulatedSecondMoment[s]==null&&(this.accumulatedSecondMoment[s]={originalName:`${r}/v`,variable:P(()=>qe(i).variable(o))});let l=Array.isArray(e)?e[s].tensor:e[r];if(l==null)return;let u=this.accumulatedFirstMoment[s].variable,p=this.accumulatedSecondMoment[s].variable,d=Y(z(u,this.beta1),z(l,1-this.beta1)),c=Y(z(p,this.beta2),z(ot(l),1-this.beta2)),h=he(d,n),m=he(c,a);u.assign(d),p.assign(c);let f=Y(z(he(h,Y(ln(m),this.epsilon)),-this.learningRate),i);i.assign(f)}),this.accBeta1.assign(z(this.accBeta1,this.beta1)),this.accBeta2.assign(z(this.accBeta2,this.beta2))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.accBeta2.dispose(),this.accumulatedFirstMoment!=null&&_e(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedSecondMoment!=null&&_e(this.accumulatedSecondMoment.map(e=>e.variable))}async getWeights(){let 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),P(()=>{this.accBeta1.assign(_r(this.beta1,this.iterations_+1)),this.accBeta2.assign(_r(this.beta2,this.iterations_+1))});let t=e.length/2,n=!1;this.accumulatedFirstMoment=e.slice(0,t).map(a=>({originalName:a.name,variable:a.tensor.variable(n)})),this.accumulatedSecondMoment=e.slice(t,t*2).map(a=>({originalName:a.name,variable:a.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)}};uf.className="Adam";gs(uf);var pf=class extends $r{constructor(e,t,n,a=null,r=0){super(),this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=a,this.decay=r,this.accumulatedFirstMoment=[],this.accumulatedWeightedInfNorm=[],P(()=>{this.iteration=be(0).variable(),this.accBeta1=be(t).variable()}),a==null&&(this.epsilon=O.backend.epsilon())}applyGradients(e){let t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);P(()=>{let n=pe(1,this.accBeta1),a=he(-this.learningRate,Y(z(this.iteration,this.decay),1));t.forEach((r,s)=>{let i=O.registeredVariables[r],o=!1;this.accumulatedFirstMoment[s]==null&&(this.accumulatedFirstMoment[s]={originalName:`${r}/m`,variable:qe(i).variable(o)}),this.accumulatedWeightedInfNorm[s]==null&&(this.accumulatedWeightedInfNorm[s]={originalName:`${r}/v`,variable:qe(i).variable(o)});let l=Array.isArray(e)?e[s].tensor:e[r];if(l==null)return;let u=this.accumulatedFirstMoment[s].variable,p=this.accumulatedWeightedInfNorm[s].variable,d=Y(z(u,this.beta1),z(l,1-this.beta1)),c=z(p,this.beta2),h=Lt(l),m=pr(c,h);u.assign(d),p.assign(m);let f=Y(z(he(a,n),he(d,Y(m,this.epsilon))),i);i.assign(f)}),this.iteration.assign(Y(this.iteration,1)),this.accBeta1.assign(z(this.accBeta1,this.beta1))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.iteration.dispose(),this.accumulatedFirstMoment!=null&&_e(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedWeightedInfNorm!=null&&_e(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)}};pf.className="Adamax";gs(pf);var Bc=class extends $r{constructor(e){super(),this.learningRate=e,this.setLearningRate(e)}applyGradients(e){(Array.isArray(e)?e.map(t=>t.name):Object.keys(e)).forEach((t,n)=>{let a=Array.isArray(e)?e[n].tensor:e[t];if(a==null)return;let r=O.registeredVariables[t];P(()=>{let s=Y(z(this.c,a),r);r.assign(s)})}),this.incrementIterations()}setLearningRate(e){this.learningRate=e,this.c!=null&&this.c.dispose(),this.c=Jt(be(-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)}};Bc.className="SGD";gs(Bc);var cf=class extends Bc{constructor(e,t,n=!1){super(e),this.learningRate=e,this.momentum=t,this.useNesterov=n,this.accumulations=[],this.m=be(this.momentum)}applyGradients(e){(Array.isArray(e)?e.map(t=>t.name):Object.keys(e)).forEach((t,n)=>{let a=O.registeredVariables[t];this.accumulations[n]==null&&(this.accumulations[n]={originalName:`${t}/momentum`,variable:P(()=>qe(a).variable(!1))});let r=this.accumulations[n].variable,s=Array.isArray(e)?e[n].tensor:e[t];s!=null&&P(()=>{let i,o=Y(z(this.m,r),s);this.useNesterov?i=Y(z(this.c,Y(s,z(o,this.m))),a):i=Y(z(this.c,o),a),r.assign(o),a.assign(i)})}),this.incrementIterations()}dispose(){this.m.dispose(),this.accumulations!=null&&_e(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);let 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)}};cf.className="Momentum";gs(cf);var df=class extends $r{constructor(e,t=.9,n=0,a=null,r=!1){if(super(),this.learningRate=e,this.decay=t,this.momentum=n,this.epsilon=a,this.accumulatedMeanSquares=[],this.accumulatedMoments=[],this.accumulatedMeanGrads=[],this.centered=r,a==null&&(this.epsilon=O.backend.epsilon()),e==null)throw new Error("learningRate for RMSPropOptimizer must be defined.")}applyGradients(e){(Array.isArray(e)?e.map(t=>t.name):Object.keys(e)).forEach((t,n)=>{let a=O.registeredVariables[t],r=!1;this.accumulatedMeanSquares[n]==null&&(this.accumulatedMeanSquares[n]={originalName:`${t}/rms`,variable:P(()=>qe(a).variable(r))}),this.accumulatedMoments[n]==null&&(this.accumulatedMoments[n]={originalName:`${t}/momentum`,variable:P(()=>qe(a).variable(r))}),this.accumulatedMeanGrads[n]==null&&this.centered&&(this.accumulatedMeanGrads[n]={originalName:`${t}/mg`,variable:P(()=>qe(a).variable(r))});let s=Array.isArray(e)?e[n].tensor:e[t];if(s==null)return;let i=this.accumulatedMeanSquares[n].variable,o=this.accumulatedMoments[n].variable;P(()=>{let l=Y(z(i,this.decay),z(ot(s),1-this.decay));if(this.centered){let u=this.accumulatedMeanGrads[n].variable,p=Y(z(u,this.decay),z(s,1-this.decay)),d=he(z(s,this.learningRate),ln(pe(l,Y(ot(p),this.epsilon)))),c=Y(z(o,this.momentum),d);i.assign(l),u.assign(p),o.assign(c);let h=pe(a,c);a.assign(h)}else{let u=Y(z(i,this.decay),z(ot(s),1-this.decay)),p=Y(z(o,this.momentum),he(z(s,this.learningRate),ln(Y(u,this.epsilon))));i.assign(u),o.assign(p);let d=pe(a,p);a.assign(d)}})}),this.incrementIterations()}dispose(){this.accumulatedMeanSquares!=null&&_e(this.accumulatedMeanSquares.map(e=>e.variable)),this.accumulatedMeanGrads!=null&&this.centered&&_e(this.accumulatedMeanGrads.map(e=>e.variable)),this.accumulatedMoments!=null&&_e(this.accumulatedMoments.map(e=>e.variable))}async getWeights(){let 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);let t=this.centered?e.length/3:e.length/2,n=!1;this.accumulatedMeanSquares=e.slice(0,t).map(a=>({originalName:a.name,variable:a.tensor.variable(n)})),this.accumulatedMoments=e.slice(t,t*2).map(a=>({originalName:a.name,variable:a.tensor.variable(n)})),this.centered&&(this.accumulatedMeanGrads=e.slice(t*2,t*3).map(a=>({originalName:a.name,variable:a.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)}};df.className="RMSProp";gs(df);var Hr=class{static sgd(e){return new Bc(e)}static momentum(e,t,n=!1){return new cf(e,t,n)}static rmsprop(e,t=.9,n=0,a=null,r=!1){return new df(e,t,n,a,r)}static adam(e=.001,t=.9,n=.999,a=null){return new uf(e,t,n,a)}static adadelta(e=.001,t=.95,n=null){return new of(e,t,n)}static adamax(e=.002,t=.9,n=.999,a=null,r=0){return new pf(e,t,n,a,r)}static adagrad(e,t=.1){return new lf(e,t)}},zs={sgd:Hr.sgd,momentum:Hr.momentum,adadelta:Hr.adadelta,adagrad:Hr.adagrad,rmsprop:Hr.rmsprop,adamax:Hr.adamax,adam:Hr.adam},Cz=(()=>typeof requestAnimationFrame!="undefined"?requestAnimationFrame:typeof setImmediate!="undefined"?setImmediate:e=>e())();function Gv(){return new Promise(e=>Cz(()=>e()))}var N={};Ae(N,{ERF_A1:()=>Vz,ERF_A2:()=>Uz,ERF_A3:()=>Gz,ERF_A4:()=>Hz,ERF_A5:()=>jz,ERF_P:()=>Bz,PARALLELIZE_THRESHOLD:()=>Hv,RowPartitionType:()=>er,SELU_SCALE:()=>RT,SELU_SCALEALPHA:()=>DT,applyActivation:()=>rf,assertAndGetBroadcastShape:()=>lt,assertAxesAreInnerMostDims:()=>FP,assertParamsConsistent:()=>_z,assignToTypedArray:()=>Jz,axesAreInnerMostDims:()=>mv,calculateShapes:()=>hS,checkEinsumDimSizes:()=>rW,checkPadOnDimRoundingMode:()=>Tn,combineLocations:()=>PS,combineRaggedTensorToTensorShapes:()=>Az,complexWithEvenIndex:()=>Xz,complexWithOddIndex:()=>Yz,computeConv2DInfo:()=>Ec,computeConv3DInfo:()=>ES,computeDefaultPad:()=>Xx,computeDilation2DInfo:()=>DM,computeOptimalWindowSize:()=>Rz,computeOutAndReduceShapes:()=>OS,computeOutShape:()=>Ez,computePool2DInfo:()=>_S,computePool3DInfo:()=>RM,convertConv2DDataFormat:()=>AS,decodeEinsumEquation:()=>nW,eitherStridesOrDilationsAreOne:()=>ur,expandShapeToKeepDim:()=>si,exponent:()=>eW,exponents:()=>Qz,fromStringArrayToUint8:()=>TW,fromUint8ToStringArray:()=>SW,getAxesPermutation:()=>LS,getBroadcastDims:()=>pS,getComplexWithIndex:()=>Zz,getEinsumComputePath:()=>sW,getEinsumPermutation:()=>aW,getFusedBiasGradient:()=>af,getFusedDyActivation:()=>nf,getImageCenter:()=>Mz,getInnerMostAxes:()=>DP,getPermuted:()=>Oz,getRaggedRank:()=>Fz,getReductionAxes:()=>Wt,getReshaped:()=>Pz,getReshapedPermuted:()=>Lz,getRowPartitionTypesHelper:()=>$z,getSliceBeginCoords:()=>zz,getSliceSize:()=>Wz,getSparseFillEmptyRowsIndicesDenseShapeMismatch:()=>uW,getSparseFillEmptyRowsNegativeIndexErrorMessage:()=>pW,getSparseFillEmptyRowsOutOfRangeIndexErrorMessage:()=>cW,getSparseReshapeEmptyTensorZeroOutputDimErrorMessage:()=>mW,getSparseReshapeInputOutputMismatchErrorMessage:()=>gW,getSparseReshapeInputOutputMultipleErrorMessage:()=>fW,getSparseReshapeMultipleNegativeOneOutputDimErrorMessage:()=>dW,getSparseReshapeNegativeOutputDimErrorMessage:()=>hW,getSparseSegmentReductionIndicesOutOfRangeErrorMessage:()=>vW,getSparseSegmentReductionNegativeSegmentIdsErrorMessage:()=>yW,getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage:()=>bW,getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage:()=>xW,getUndoAxesPermutation:()=>fv,isIdentityPermutation:()=>iW,log:()=>YF,mergeRealAndImagArrays:()=>qz,prepareAndValidate:()=>dS,prepareSplitSize:()=>lW,segment_util:()=>MT,shouldFuse:()=>sf,slice_util:()=>jt,splitRealAndImagArrays:()=>Kz,tupleValuesAreOne:()=>ns,upcastType:()=>ma,validateDefaultValueShape:()=>Dz,validateInput:()=>Lx,validateUpdateShape:()=>Ox,warn:()=>qr});function _z(e,t){let n=e[0].length;e.forEach((r,s)=>{$(r.length===n,()=>`Error in concat${n}D: rank of tensors[${s}] must be the same as the rank of the rest (${n})`)}),$(t>=0&&t`Error in concat${n}D: axis must be between 0 and ${n-1}.`);let a=e[0];e.forEach((r,s)=>{for(let i=0;i`Error in concat${n}D: Shape of tensors[${s}] (${r}) does not match the shape of the rest (${a}) along the non-concatenated axis ${s}.`)})}function Ez(e,t){let n=e[0].slice();for(let a=1;a=0)if(o>=0){if(o!==s)throw new Error(`rt input.shape and shape=${t} are incompatible: rt input.shape[${r+e}] = ${s} but shape[${r+e}] = ${o}`)}else a[i]=s}return a}function $z(e){let t={FIRST_DIM_SIZE:er.FIRST_DIM_SIZE,VALUE_ROWIDS:er.VALUE_ROWIDS,ROW_LENGTHS:er.ROW_LENGTHS,ROW_SPLITS:er.ROW_SPLITS,ROW_LIMITS:er.ROW_LIMITS,ROW_STARTS:er.ROW_STARTS},n=[];for(let a of e)if(a in t)n.push(t[a]);else break;return n}function Fz(e){return e.length===0?0:e[0]===er.FIRST_DIM_SIZE?e.length-1:e.length}function Dz(e,t){if(e==null||t==null)return;let n=e.length,a=t.length;if(n>=a)throw new Error(`defaultValue.shape=${e} and ragged tensor flatValues.shape=${t}, are incompatible: defaultValue.rank = ${n} must be less than ragged tensor input flatValues.rank = ${a})`);for(let r=0;r=0&&i>=0&&s!==1&&s!==i)throw new Error(`defaultValue.shape=${e}, and ragged tensor input flatValues.shape=${t} are incompatible: defaultValue.shape[${r-e.length}] = ${s} but ragged tensor input.flatValues.shape[${r-e.length}] = ${i}`)}}var Hv=30;function Rz(e){return e<=Hv?e:mh(e,Math.floor(Math.sqrt(e)))}function Mz(e,t,n){let a=n*(typeof e=="number"?e:e[0]),r=t*(typeof e=="number"?e:e[1]);return[a,r]}function Pz(e,t,n,a=!0){let r=[];if(a)r=r.concat(t.slice(0)),r.push(e[0]/n),r=r.concat(e.slice(1));else{r=r.concat(e[0]);let s=t.length;for(let i=0;i=t*2+1||i%2===1?s.push(i):r.push(i);a.push(...r),a.push(0),a.push(...s)}return a}function Lz(e,t,n,a=!0){let r=[];a?r.push(e[0]/n):r.push(e[0]*n);for(let s=1;s/g,Q1=",",ek="...";function nW(e,t){e=e.replace(/\s/g,"");let n=(e.length-e.replace(tW,"").length)/ub.length;if(n<1)throw new Error("Equations without an arrow are not supported.");if(n>1)throw new Error(`Equation must contain exactly one arrow ("${ub}").`);let[a,r]=e.split(ub);$(a.indexOf(ek)===-1,()=>`The ellipsis notation ("${ek}") is not supported yet.`);let s=a.split(Q1),i=s.length;if(t!==i)throw new Error(`Expected ${i} input tensors, received ${t}`);if(i>2)throw new Error("Support for more than 2 input tensors is not implemented yet.");let o=[];for(let c=0;cm.indexOf(h)!==-1))throw new Error(`Output subscripts contain the label ${h} not present in the input subscripts.`);o.indexOf(h)===-1&&o.push(h)}for(let c=0;cr!==-1),{permutationIndices:n,expandDims:a}}function rW(e,t,n){let a=new Array(e);for(let r=0;r`Expected dimension ${a[t[r][i]]} at axis ${i} of input shaped ${JSON.stringify(s)}, but got dimension ${s[i]}`)}}function sW(e,t){let n=e,a=[],r=0;e.length===0&&n.push(-1),r=e.length+1;for(let i=0;it===n)}function oW(e,t){let n=[];for(let a=0;a"Number of splits must evenly divide the axis."),a=new Array(t).fill(e.shape[n]/t);else{let r=t.reduce((i,o)=>(o===-1&&(i+=1),i),0);$(r<=1,()=>"There should be only one negative value in split array.");let s=t.indexOf(-1);if(s!==-1){let i=t.reduce((o,l)=>l>0?o+l:o);t[s]=e.shape[n]-i}$(e.shape[n]===t.reduce((i,o)=>i+o),()=>"The sum of sizes must match the size of the axis dimension."),a=t}return a}function uW(e){return`Received SparseTensor with denseShape[0] = 0 but
- indices.shape[0] = ${e}`}function pW(e,t){return`indices(${e}, 0) is invalid: ${t} < 0`}function cW(e,t,n){return`indices(${e}, 0) is invalid: ${t} >= ${n}`}function dW(e,t){return`only one output dimension may be -1, not both ${e} and ${t}`}function hW(e,t){return`size ${e} must be non-negative, not ${t}`}function mW(){return"reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero"}function fW(e,t){let n=mt(e),a=mt(t);return`Input to reshape is a SparseTensor with ${n}
- dense values, but the requested shape requires a multiple of ${a}. inputShape=${e} outputShape= ${t}`}function gW(e,t){let n=mt(e),a=mt(t);return`Input to reshape is a tensor with ${n} dense values, but the requested shape has ${a}. inputShape=${e} outputShape=${t}`}function yW(){return"segment ids must be >= 0"}function bW(){return"segment ids are not increasing"}function xW(e,t){return`Segment id ${e} out of range [0, ${t}), possibly because segmentIds input is not sorted.`}function vW(e,t,n){return`Bad: indices[${e}] == ${t} out of range [0, ${n})`}var MT={};Ae(MT,{collectGatherOpShapeInfo:()=>IW,computeOutShape:()=>kW,segOpComputeOptimalWindowSize:()=>wW});function wW(e,t){let n=!1,a;for(e<=Hv?(a=e,n=!0):a=mh(e,Math.floor(Math.sqrt(e)));!n;)a>t||a===e?n=!0:a=mh(e,a+1);return a}function kW(e,t,n){let a=[],r=e.length;for(let s=0;sr))throw new Error(`Expect batchDims in the range of [-${r}, ${r}], but got ${a}`);if(a<0&&(a+=r),a>s)throw new Error(`batchDims (${a}) must be less than rank(x) (
- ${s}).`);if(nvh(t))}catch(t){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${t}`)}}function TW(e){return e.map(t=>Sc(t))}var cr={};Ae(cr,{nonMaxSuppressionV3Impl:()=>IT,nonMaxSuppressionV4Impl:()=>ST,nonMaxSuppressionV5Impl:()=>TT,whereImpl:()=>dT});var PT={kernelName:wl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>z(e,fo(oe(n,"float32"),-1))}}},NW={kernelName:kl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let a=ot(oe(n,"float32")),r=ln(pe(be(1),a));return bt(he(e,r))}}}},CW={kernelName:Il,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let a=ln(pe(ot(oe(n,"float32")),1));return he(e,a)}}}},_W={kernelName:cs,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t,r=lt(n.shape,a.shape);return{a:()=>{let s=e,i=Wt(n.shape,r);return i.length>0&&(s=fe(s,i)),W(s,n.shape)},b:()=>{let s=e,i=Wt(a.shape,r);return i.length>0&&(s=fe(s,i)),W(s,a.shape)}}}},EW={kernelName:mi,saveAllInputs:!0,gradFunc:(e,t)=>{let n={};return t.forEach((a,r)=>{n[r]=()=>e.clone()}),n}},AW={kernelName:fi,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>qe(n)}}},$W={kernelName:sc,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>qe(n)}}},FW={kernelName:Nl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>he(e,ln(pe(be(1),ot(oe(n,"float32")))))}}},DW={kernelName:Cl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let a=ln(Y(be(1),ot(oe(n,"float32"))));return he(e,a)}}}},RW={kernelName:Al,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t,r=lt(n.shape,a.shape);return{a:()=>{let s=Y(ot(n),ot(a)),i=z(e,he(a,s)),o=Wt(n.shape,r);return o.length>0&&(i=fe(i,o)),W(i,n.shape)},b:()=>{let s=Y(ot(n),ot(a)),i=bt(z(e,he(n,s))),o=Wt(a.shape,r);return o.length>0&&(i=fe(i,o)),W(i,a.shape)}}}},MW={kernelName:_l,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>he(e,Y(ot(oe(n,"float32")),1))}}},PW={kernelName:El,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>he(e,pe(be(1),ot(oe(n,"float32"))))}}};function OW(e,t,n,a,r,s){let i=_(e,"dy","avgPool3dGrad"),o=_(t,"input","avgPool3dGrad"),l=i,u=o,p=!1;o.rank===4&&(p=!0,l=W(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]]),u=W(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),$(l.rank===5,()=>`Error in avgPool3dGrad: dy must be rank 5 but got rank ${l.rank}.`),$(u.rank===5,()=>`Error in avgPool3dGrad: input must be rank 5 but got rank ${u.rank}.`),Tn("avgPool3dGrad",r,s);let d={dy:l,input:u},c={filterSize:n,strides:a,pad:r,dimRoundingMode:s},h=O.runKernel(Yh,d,c);return p?W(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}var LW=L({avgPool3dGrad_:OW}),zW={kernelName:ic,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,{filterSize:r,strides:s,pad:i,dimRoundingMode:o}=n;return{x:()=>LW(e,a,r,s,i,o)}}};function WW(e,t,n,a,r){let s=_(e,"dy","avgPoolGrad"),i=_(t,"input","avgPoolGrad");$(i.rank===s.rank,()=>`Rank of input (${i.rank}) does not match rank of dy (${s.rank})`);let o=i,l=s,u=!1;i.rank===3&&(u=!0,o=W(i,[1,i.shape[0],i.shape[1],i.shape[2]]),l=W(s,[1,s.shape[0],s.shape[1],s.shape[2]])),$(l.rank===4,()=>`Error in avgPoolGrad: dy must be rank 4 but got rank ${l.rank}.`),$(o.rank===4,()=>`Error in avgPoolGrad: input must be rank 4 but got rank ${o.rank}.`);let p={dy:l,input:o},d={filterSize:n,strides:a,pad:r},c=O.runKernel(Xh,p,d);return u?W(c,[c.shape[1],c.shape[2],c.shape[3]]):c}var BW=L({avgPoolGrad_:WW}),VW={kernelName:gi,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,{filterSize:r,strides:s,pad:i}=n;return{x:()=>BW(e,a,r,s,i)}}},UW={kernelName:yi,inputsToSave:["a","b"],gradFunc:(e,t,n)=>{let[a,r]=t,{transposeA:s,transposeB:i}=n;return!s&&!i?{a:()=>Fe(e,r,!1,!0),b:()=>Fe(a,e,!0,!1)}:!s&&i?{a:()=>Fe(e,r,!1,!1),b:()=>Fe(e,a,!0,!1)}:s&&!i?{a:()=>Fe(r,e,!1,!0),b:()=>Fe(a,e,!1,!1)}:{a:()=>Fe(r,e,!0,!0),b:()=>Fe(e,a,!0,!0)}}},GW={kernelName:$l,gradFunc:(e,t,n)=>{let{blockShape:a,crops:r}=n;return{x:()=>Pc(e,a,r)}}},HW={kernelName:RI,gradFunc:(e,t,n)=>{let a=n,r=a.inputShape,s=a.shape,i=Array.from(s);for(let l=r.length-1;l>=0;l--)if(r[l]===s[l])i[l]=1;else if(r[l]!==1)throw new Error(`broadcastTo(): [${r}] cannot be broadcast to [${s}].`);let o=[];for(let l=0;l1&&o.push(l);return{x:()=>fe(e,o,!0)}}},jW={kernelName:bi,gradFunc:e=>({x:()=>e.clone()})},qW={kernelName:xi,gradFunc:e=>({x:()=>qe(e)})},KW={kernelName:ds,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,{clipValueMin:r,clipValueMax:s}=n;return{x:()=>mn(Ea(Er(a,r),xs(a,s)),e,qe(e))}}},XW={kernelName:oc,inputsToSave:["x"],gradFunc:PT.gradFunc},YW={kernelName:Fl,saveAllInputs:!0,gradFunc:(e,t,n)=>{let a=t.map(o=>o.shape),{axis:r}=n,s=Aa(r,t[0].shape)[0],i=a.map(o=>o[s]);return zn(e,i,s).map(o=>()=>o)}},ZW={kernelName:vi,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{let[a,r]=t,{dilations:s,strides:i,pad:o,dataFormat:l}=n;return $(ns(s),()=>`Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`),{x:()=>iv(a.shape,e,r,i,o,l),filter:()=>Bv(a,e,r.shape,i,o,l)}}},JW={kernelName:wi,inputsToSave:["dy","filter"],gradFunc:(e,t,n)=>{let[a,r]=t,{strides:s,pad:i,dataFormat:o,dimRoundingMode:l}=n;return{dy:()=>$t(e,r,s,i,o,1,l),filter:()=>Bv(e,a,r.shape,s,i,o,l)}}};function QW(e,t,n,a,r){let s=e;e.rank===4&&(s=W(e,[1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]]));let i=t;i.rank===4&&(i=W(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]])),$(s.rank===5,()=>`Error in conv3dDerFilter: input must be rank 5, but got shape ${s.shape}.`),$(i.rank===5,()=>`Error in conv3dDerFilter: dy must be rank 5, but got shape ${i.shape}.`),$(n.length===5,()=>`Error in conv3dDerFilter: filterShape must be length 5, but got ${n}.`),$(s.shape[4]===n[3],()=>`Error in conv3dDerFilter: depth of input ${s.shape[4]}) must match input depth in filter (${n[3]}.`),$(i.shape[4]===n[4],()=>`Error in conv3dDerFilter: depth of dy (${i.shape[4]}) must match output depth for filter (${n[4]}).`);let o={x:s,dy:i},l={strides:a,pad:r,filterShape:n};return O.runKernel(tm,o,l)}var eB=L({conv3DBackpropFilter_:QW}),tB={kernelName:lc,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{let{dilations:a,strides:r,pad:s}=n;$(ns(a),()=>`Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${a}'`);let[i,o]=t;return{x:()=>DS(i.shape,e,o,r,s),filter:()=>eB(i,e,o.shape,r,s)}}},nB={kernelName:ki,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>z(bt(Km(oe(n,"float32"))),e)}}},aB={kernelName:Ii,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>z(Xm(oe(n,"float32")),e)}}},rB={kernelName:Si,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,{axis:r,exclusive:s,reverse:i}=n;return{x:()=>{let o=LS([r],a.rank),l=Mm(e,r,s,!i);return o!=null&&(l=Ee(l,o)),l}}}},sB={kernelName:Ti,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{let{dilations:a,strides:r,pad:s,dimRoundingMode:i}=n,o=a==null?[1,1]:a;$(ns(o),()=>`Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations '${o}'`);let[l,u]=t;return $(l.rank===4,()=>`Error in gradient of depthwiseConv2dNative: input must be rank 4, but got rank ${l.rank}.`),$(u.rank===4,()=>`Error in gradient of depthwiseConv2dNative: filter must be rank 4, but got rank ${u.rank}.`),$(l.shape[3]===u.shape[2],()=>`Error in gradient of depthwiseConv2d: number of input channels (${l.shape[3]}) must match the inChannels dimension in filter ${u.shape[2]}.`),$(ur(r,o),()=>`Error in gradient of depthwiseConv2d: Either strides or dilations must be 1. Got strides ${r} and dilations '${o}'.`),Tn("depthwiseConv2d",s,i),{x:()=>vT(l.shape,e,u,r,s,o,i),filter:()=>xT(l,e,u.shape,r,s,o,i)}}},iB={kernelName:uc,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{let[a,r]=t,s={x:a,filter:r,dy:e},i={x:a,filter:r,dy:e};return{x:()=>O.runKernel(fh,s,n),filter:()=>O.runKernel(gh,i,n)}}},oB={kernelName:Ci,outputsToSave:[!0],gradFunc:(e,t)=>{let[n]=t,a={dy:e,y:n};return{x:()=>O.runKernel(lm,a)}}},lB={kernelName:Pl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t,a=z(fn(bt(ot(n))),2/Math.sqrt(Math.PI));return{x:()=>z(e,a)}}},uB={kernelName:_i,outputsToSave:[!0],gradFunc:(e,t)=>{let[n]=t;return{x:()=>z(e,n)}}},pB={kernelName:Ll,inputsToSave:["input"],gradFunc:(e,t)=>{let[n]=t;return{input:()=>W(e,n.shape)}}},cB={kernelName:zl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>z(e,fn(n))}}},dB={kernelName:Ei,gradFunc:e=>({x:()=>qe(e)})},hB={kernelName:Ai,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t,r=lt(n.shape,a.shape);return{a:()=>{let s=he(e,oe(a,"float32")),i=Wt(n.shape,r);return i.length>0?W(fe(s,i),n.shape):s},b:()=>{let s=z(e,oe(n,"float32")),i=Wt(a.shape,r);i.length>0&&(s=W(fe(s,i),a.shape));let o=ot(a);return bt(he(s,oe(o,"float32")))}}}},mB={kernelName:$i,inputsToSave:["x","mean","variance","scale"],gradFunc:(e,t,n)=>{let{varianceEpsilon:a}=n,[r,s,i,o]=t,l=o==null?be(1):o,u=Wt(s.shape,r.shape),p=[];if(s.rank===1){for(let f=0;fs.rank===1?W(z(z(e,Ln(W(h,[1,1,1,s.shape[0]]),p)),l),r.shape):W(z(z(e,h),l),r.shape),mean:()=>{let f=z(z(h,be(-1)),c);return s.rank===1&&(f=fe(f,u)),W(f,s.shape)},variance:()=>{let f=z(z(m,d),c);return s.rank===1&&(f=fe(f,u)),W(f,s.shape)},scale:()=>{let f=z(d,h),g=z(e,f);return s.rank===1&&(g=fe(g,u)),W(g,s.shape)},offset:()=>{let f=e;return s.rank===1&&(f=fe(f,u)),W(f,s.shape)}}}},fB={kernelName:Bl,inputsToSave:["x","indices"],gradFunc:(e,t,n)=>{let[a,r]=t,{axis:s}=n,i=Aa(s,a.shape)[0];return{x:()=>{let o=a.shape,l=r.size,u=o.slice(0,i),p=u.length,d=o.slice(s,o.length).slice(1),c=d.length,h=tk(0,p),m=tk(p+1,p+1+c),f=nk([u,[l],d]),g=W(e,f),y=W(r,[l]),b=nk([[p],h,m]),x=Ee(g,b),w=ef(x,y,a.shape[i]),I=fv(b);return w=Ee(w,I),w},indices:()=>r}}};function tk(e,t){let n=[];for(let a=e;a{let[n,a]=t;return{a:()=>qe(n),b:()=>qe(a)}}},yB={kernelName:Di,gradFunc:e=>({x:()=>oe(e,"float32")})},bB={kernelName:Gl,gradFunc:e=>({x:()=>qe(e)})},xB={kernelName:Hl,gradFunc:e=>({x:()=>qe(e)})},vB={kernelName:jl,gradFunc:e=>({x:()=>qe(e)})},wB={kernelName:Ri,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,{alpha:r}=n,s=Nn(a,0);return{x:()=>mn(s,e,z(e,r))}}},kB={kernelName:Xl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>he(e,Y(n,1))}}},IB={kernelName:Mi,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>he(e,oe(n,"float32"))}}},SB={kernelName:PI,inputsToSave:[],outputsToSave:[!0],gradFunc:(e,t,n)=>{let[a]=t,{axis:r}=n;return{logits:()=>{let s=fn(a);return pe(e,z(fe(e,r,!0),s))}}}};function TB(e,t,n,a=5,r=1,s=1,i=.5){let o={x:e,y:t,dy:n},l={depthRadius:a,bias:r,alpha:s,beta:i};return O.runKernel(hm,o,l)}var NB=L({localResponseNormalizationBackprop_:TB}),CB={kernelName:cc,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let[a,r]=t,{depthRadius:s,bias:i,alpha:o,beta:l}=n;return{x:()=>NB(a,r,e,s,i,o,l)}}};function OT(e,t,n,a){return t.rankz(e,oe(Qn(n,t),e.dtype))}}var ak={kernelName:Pi,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let a=n,{reductionIndices:r}=a,s=t[0],i=t[1],o=Aa(r,s.shape),l=OT(e,i,s,o);return{x:()=>l.x()}}},_B={kernelName:Oi,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t;return{a:()=>z(e,oe(Er(n,a),"float32")),b:()=>z(e,oe(Om(n,a),"float32"))}}};function EB(e,t,n,a,r,s,i){let o=_(e,"dy","maxPool3dGrad"),l=_(t,"input","maxPool3dGrad"),u=_(n,"output","maxPool3dGrad"),p=o,d=l,c=u,h=!1;l.rank===4&&(h=!0,p=W(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]]),d=W(l,[1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]]),c=W(u,[1,u.shape[0],u.shape[1],u.shape[2],u.shape[3]])),$(p.rank===5,()=>`Error in maxPool3dGrad: dy must be rank 5 but got rank ${p.rank}.`),$(d.rank===5,()=>`Error in maxPool3dGrad: input must be rank 5 but got rank ${d.rank}.`),$(c.rank===5,()=>`Error in maxPool3dGrad: output must be rank 5 but got rank ${c.rank}.`),Tn("maxPool3dGrad",s,i);let m={dy:p,input:d,output:c},f={filterSize:a,strides:r,pad:s,dimRoundingMode:i},g=O.runKernel(fm,m,f);return h?W(g,[g.shape[1],g.shape[2],g.shape[3],g.shape[4]]):g}var AB=L({maxPool3dGrad_:EB}),$B={kernelName:dc,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let[a,r]=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=n;return{x:()=>AB(e,a,r,s,i,o,l)}}};function FB(e,t,n,a,r,s,i){let o=_(e,"dy","maxPoolGrad"),l=_(t,"input","maxPoolGrad"),u=_(n,"output","maxPoolGrad");$(l.rank===o.rank,()=>`Rank of input (${l.rank}) does not match rank of dy (${o.rank})`),$(o.rank===4,()=>`Error in maxPoolGrad: dy must be rank 4 but got rank ${o.rank}.`),$(l.rank===4,()=>`Error in maxPoolGrad: input must be rank 4 but got rank ${l.rank}.`),Tn("maxPoolGrad",s,i);let p={dy:o,input:l,output:u},d={filterSize:a,strides:r,pad:s,dimRoundingMode:i};return O.runKernel(mm,p,d)}var DB=L({maxPoolGrad_:FB}),RB={kernelName:Li,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let[a,r]=t,{filterSize:s,strides:i,pad:o}=n;return{x:()=>DB(e,a,r,s,i,o)}}},MB={kernelName:zi,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,{axis:r}=n,s=Aa(r,a.shape),i=OS(a.shape,s)[1],o=mt(i);return{x:()=>{let l=a.shape.slice();s.forEach(p=>{l[p]=1});let u=W(e,l);return he(z(u,Zn(a.shape,"float32")),o)}}}},PB={kernelName:Wi,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let a=n,{axis:r}=a,[s,i]=t,o=Aa(r,s.shape),l=OT(e,i,s,o);return{x:()=>l.x()}}},OB={kernelName:Bi,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t;return{a:()=>z(e,oe(xs(n,a),"float32")),b:()=>z(e,oe(Nn(n,a),"float32"))}}},LB={kernelName:Vi,inputsToSave:["x"],gradFunc:(e,t,n)=>{let a=t[0],{paddings:r}=n,s=r.map(i=>i[0]);return{x:()=>Be(e,s,a.shape)}}},zB={kernelName:Ql,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t,r=lt(n.shape,a.shape);return{a:()=>{let s=Wt(n.shape,r);return s.length>0?W(fe(e,s),n.shape):e},b:()=>{let s=z(e,bt(_u(he(n,a)))),i=Wt(a.shape,r);return i.length>0?W(fe(s,i),a.shape):s}}}},WB={kernelName:Ui,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t,r=lt(n.shape,a.shape);return{a:()=>{let s=z(e,oe(a,"float32")),i=Wt(n.shape,r);return i.length>0?W(fe(s,i),n.shape):s},b:()=>{let s=z(e,oe(n,"float32")),i=Wt(a.shape,r);return i.length>0?W(fe(s,i),a.shape):s}}}},BB={kernelName:eu,gradFunc:e=>({x:()=>bt(e)})},VB={kernelName:Gi,inputsToSave:["indices"],gradFunc:(e,t)=>{let n=t[0];return{indices:()=>It(n.shape,"float32")}}},UB={kernelName:su,gradFunc:e=>({x:()=>qe(e)})},GB={kernelName:iu,saveAllInputs:!0,gradFunc:(e,t,n)=>{let{axis:a}=n;return ct(e,a).map(r=>()=>r)}},rk={kernelName:Hi,inputsToSave:["x"],gradFunc:(e,t,n)=>{let a=t[0],{paddings:r}=n,s=r.map(i=>i[0]);return{x:()=>Be(e,s,a.shape)}}},HB={kernelName:ji,inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:(e,t)=>{let[n,a,r]=t,s=n,i=a,o=lt(s.shape,i.shape);return{a:()=>{let l=oe(i,"float32"),u=z(e,z(l,_r(s,pe(l,be(1))))),p=Wt(s.shape,o);return p.length>0&&(u=fe(u,p)),W(u,s.shape)},b:()=>{let l=Nn(s,0),u=mn(l,ea(s),qe(s)),p=z(e,z(r,u)),d=Wt(i.shape,o);return d.length>0&&(p=fe(p,d)),W(p,i.shape)}}}},jB={kernelName:qi,inputsToSave:["x","alpha"],gradFunc:(e,t)=>{let[n,a]=t,r=Nn(n,0);return{x:()=>mn(r,e,z(e,a)),alpha:()=>{let s=mn(r,qe(e),z(e,n)),i=Wt(a.shape,e.shape);return i.length>0&&(s=fe(s,i)),W(s,a.shape)}}}};function qB(e,t,n){let a=e.shape.slice();a[n]=1;let r=W(t,a),s=Kp(e,n,!0,!1),i=Kp(e,n,!0,!0),o=z(s,i);return z(r,o)}function KB(e,t,n){let a=e.shape.length,r=a-n.length,s=N.getAxesPermutation(n,a),i=e;s!=null&&(i=Ee(e,s));let o=i.shape.slice(),l=o.splice(a-n.length,n.length).reduce((d,c)=>d*c,1);o.push(l);let u=i.reshape(o),p=qB(u,t,r);if(p=p.reshape(i.shape),s!=null){let d=N.getUndoAxesPermutation(s);p=Ee(p,d)}return p}var XB={kernelName:Ki,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,{axis:r}=n,s=[];return r==null?s=a.shape.map((i,o)=>o):typeof r=="number"?s=[r]:s=r,{x:()=>KB(a,e,s)}}},YB={kernelName:Ni,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t,r=lt(n.shape,a.shape);return{a:()=>{let s=he(e,oe(a,"float32")),i=Wt(n.shape,r);return i.length>0?W(fe(s,i),n.shape):s},b:()=>{let s=z(e,oe(n,"float32")),i=Wt(a.shape,r);i.length>0&&(s=W(fe(s,i),a.shape));let o=ot(a);return bt(he(s,oe(o,"float32")))}}}},ZB={kernelName:ou,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>he(e,bt(ot(n)))}}},JB={kernelName:Ji,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t,a=z(xs(n,6),fo(n));return{x:()=>z(e,oe(a,"float32"))}}},QB={kernelName:Xi,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>z(e,oe(fo(n),"float32"))}}},e4={kernelName:lu,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>W(e,n.shape)}}},t4={kernelName:Zi,inputsToSave:["images"],gradFunc:(e,t,n)=>{let[a]=t,r={dy:e,images:a};return{images:()=>O.runKernel(Im,r,n)}}},n4={kernelName:Yi,inputsToSave:["images"],gradFunc:(e,t,n)=>{let[a]=t,r={dy:e,images:a};return{images:()=>O.runKernel(km,r,n)}}},a4={kernelName:Qi,gradFunc:(e,t,n)=>{let{dims:a}=n,r=Aa(a,e.shape);return{x:()=>fa(e,r)}}},r4={kernelName:eo,gradFunc:e=>({x:()=>qe(e)})},s4={kernelName:to,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>bt(he(e,z(_r(n,1.5),2)))}}},i4={kernelName:pu,inputsToSave:["condition"],gradFunc:(e,t)=>{let[n]=t;return{condition:()=>oe(qe(n),"float32"),t:()=>z(e,oe(n,e.dtype)),e:()=>z(e,oe(Rc(n),e.dtype))}}},o4={kernelName:cu,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let a=Nn(n,be(0)),r=be(DT),s=be(RT),i=z(e,s),o=z(z(e,r),fn(oe(n,"float32")));return mn(a,i,o)}}}},l4={kernelName:ao,outputsToSave:[!0],gradFunc:(e,t)=>{let[n]=t;return{x:()=>z(e,z(n,pe(be(1),n)))}}},u4={kernelName:mu,gradFunc:e=>({x:()=>qe(e)})},p4={kernelName:no,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>z($c(oe(n,"float32")),e)}}},c4={kernelName:hu,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>z(Rm(oe(n,"float32")),e)}}},d4={kernelName:du,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,{begin:r,size:s}=n,i=a.shape,[o,l]=kS(a,r,s),u=[];for(let p=0;pya(e,u)}}},h4={kernelName:io,outputsToSave:[!0],gradFunc:(e,t,n)=>{let[a]=t,{dim:r}=n,s=!0,i=z(e,a);return{logits:()=>pe(i,z(fe(i,[r],s),a))}}},m4={kernelName:fu,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>z(e,da(n))}}},sk={kernelName:gu,gradFunc:(e,t,n)=>{let{blockShape:a,paddings:r}=n;return{x:()=>Ac(e,a,r)}}},ik={kernelName:yu,gradFunc:(e,t,n)=>{let{axis:a}=n;return{x:()=>Ze(e,a)}}},f4={kernelName:ro,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>he(e,z(ln(oe(n,"float32")),2))}}},g4={kernelName:yc,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>z(e,z(oe(n,"float32"),2))}}},y4={kernelName:oo,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t,r=be(2);return{a:()=>z(e,z(r,pe(n,a))),b:()=>z(e,z(r,pe(a,n)))}}},b4={kernelName:ms,gradFunc:e=>({x:()=>qe(e)})},x4={kernelName:lo,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t,r=lt(n.shape,a.shape);return{a:()=>{let s=e,i=Wt(n.shape,r);return i.length>0&&(s=fe(s,i)),W(s,n.shape)},b:()=>{let s=e,i=Wt(a.shape,r);return i.length>0&&(s=fe(s,i)),W(bt(s),a.shape)}}}},v4={kernelName:so,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,r=a.shape.slice(),{axis:s}=n;Aa(s,a.shape).forEach(l=>{r[l]=1});let i=W(e,r),o=z(i,Zn(a.shape,"float32"));return{x:()=>o}}},w4={kernelName:uo,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>he(e,ot($c(n)))}}},k4={kernelName:po,outputsToSave:[!0],gradFunc:(e,t)=>{let[n]=t;return{x:()=>z(pe(be(1),ot(n)),e)}}},I4={kernelName:hs,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,{reps:r}=n;return{x:()=>{let s=qe(a);if(a.rank===1)for(let i=0;i{let a=n,{perm:r}=a,s=fv(r);return{x:()=>Ee(e,s)}}},T4={kernelName:ku,gradFunc:(e,t,n)=>{let a=n,{axis:r}=a;return{value:()=>Ft(e,r)}}},N4={kernelName:wc,inputsToSave:["segmentIds"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>C4(e,n)}}};function C4(e,t){let n=pr(t,qe(t)),a=Eu(e,n),r=Er(t,be(0,"int32")),s=a.rank-r.rank;for(let o=0;o({x:()=>qe(e)})},E4=[PT,NW,CW,_W,EW,AW,$W,FW,DW,RW,MW,PW,zW,VW,UW,GW,HW,jW,qW,KW,XW,YW,JW,ZW,tB,nB,aB,rB,sB,iB,YB,oB,lB,uB,pB,cB,hB,dB,mB,fB,gB,yB,bB,xB,vB,wB,kB,IB,SB,CB,ak,ak,_B,$B,RB,MB,PB,OB,LB,zB,WB,BB,VB,UB,GB,rk,rk,HB,jB,XB,ZB,JB,QB,e4,t4,n4,a4,r4,s4,i4,o4,l4,u4,p4,c4,d4,h4,m4,sk,sk,ik,ik,f4,y4,g4,b4,x4,v4,w4,k4,I4,S4,T4,N4,_4];for(let e of E4)OI(e);J().prototype.abs=function(){return this.throwIfDisposed(),Lt(this)};J().prototype.acos=function(){return this.throwIfDisposed(),Bx(this)};J().prototype.acosh=function(){return this.throwIfDisposed(),Vx(this)};J().prototype.add=function(e){return this.throwIfDisposed(),Y(this,e)};J().prototype.all=function(e,t){return this.throwIfDisposed(),$m(this,e,t)};J().prototype.any=function(e,t){return this.throwIfDisposed(),qp(this,e,t)};J().prototype.argMax=function(e){return this.throwIfDisposed(),ai(this,e)};J().prototype.argMin=function(e){return this.throwIfDisposed(),Ux(this,e)};J().prototype.asScalar=function(){return this.throwIfDisposed(),$(this.size===1,()=>"The array must have only 1 element."),W(this,[])};J().prototype.asType=function(e){return this.throwIfDisposed(),oe(this,e)};J().prototype.as1D=function(){return this.throwIfDisposed(),W(this,[this.size])};J().prototype.as2D=function(e,t){return this.throwIfDisposed(),W(this,[e,t])};J().prototype.as3D=function(e,t,n){return this.throwIfDisposed(),W(this,[e,t,n])};J().prototype.as4D=function(e,t,n,a){return this.throwIfDisposed(),W(this,[e,t,n,a])};J().prototype.as5D=function(e,t,n,a,r){return this.throwIfDisposed(),W(this,[e,t,n,a,r])};J().prototype.asin=function(){return this.throwIfDisposed(),Gx(this)};J().prototype.asinh=function(){return this.throwIfDisposed(),Hx(this)};J().prototype.atan=function(){return this.throwIfDisposed(),jx(this)};J().prototype.atan2=function(e){return this.throwIfDisposed(),qx(this,e)};J().prototype.atanh=function(){return this.throwIfDisposed(),Kx(this)};J().prototype.avgPool=function(e,t,n,a){return this.throwIfDisposed(),ga(this,e,t,n,a)};J().prototype.batchToSpaceND=function(e,t){return this.throwIfDisposed(),Ac(this,e,t)};J().prototype.batchNorm=function(e,t,n,a,r){return this.throwIfDisposed(),ys(this,e,t,n,a,r)};J().prototype.broadcastTo=function(e){return this.throwIfDisposed(),Ks(this,e)};J().prototype.cast=function(e){return this.throwIfDisposed(),oe(this,e)};J().prototype.ceil=function(){return this.throwIfDisposed(),tv(this)};J().prototype.clipByValue=function(e,t){return this.throwIfDisposed(),en(this,e,t)};J().prototype.concat=function(e,t){return this.throwIfDisposed(),e instanceof Te&&(e=[e]),Ze([this,...e],t)};J().prototype.conv1d=function(e,t,n,a,r,s){return this.throwIfDisposed(),Fm(this,e,t,n,a,r,s)};J().prototype.conv2dTranspose=function(e,t,n,a,r){return this.throwIfDisposed(),Dm(this,e,t,n,a,r)};J().prototype.conv2d=function(e,t,n,a,r,s){return this.throwIfDisposed(),$t(this,e,t,n,a,r,s)};J().prototype.cos=function(){return this.throwIfDisposed(),$c(this)};J().prototype.cosh=function(){return this.throwIfDisposed(),Rm(this)};J().prototype.cumprod=function(e,t,n){return this.throwIfDisposed(),Kp(this,e,t,n)};J().prototype.cumsum=function(e,t,n){return this.throwIfDisposed(),Mm(this,e,t,n)};J().prototype.depthToSpace=function(e,t){return this.throwIfDisposed(),uv(this,e,t)};J().prototype.depthwiseConv2d=function(e,t,n,a,r,s){return this.throwIfDisposed(),bs(this,e,t,n,a,r,s)};J().prototype.dilation2d=function(e,t,n,a,r){return this.throwIfDisposed(),pv(this,e,t,n,a,r)};J().prototype.divNoNan=function(e){return this.throwIfDisposed(),cv(this,e)};J().prototype.div=function(e){return this.throwIfDisposed(),he(this,e)};J().prototype.dot=function(e){return this.throwIfDisposed(),dv(this,e)};J().prototype.elu=function(){return this.throwIfDisposed(),Nu(this)};J().prototype.equal=function(e){return this.throwIfDisposed(),Qn(this,e)};J().prototype.erf=function(){return this.throwIfDisposed(),hv(this)};J().prototype.euclideanNorm=function(e,t){return this.throwIfDisposed(),gv(this,e,t)};J().prototype.exp=function(){return this.throwIfDisposed(),fn(this)};J().prototype.expandDims=function(e){return this.throwIfDisposed(),Zt(this,e)};J().prototype.expm1=function(){return this.throwIfDisposed(),yv(this)};J().prototype.fft=function(){return this.throwIfDisposed(),zc(this)};J().prototype.flatten=function(){return this.throwIfDisposed(),W(this,[this.size])};J().prototype.floor=function(){return this.throwIfDisposed(),_u(this)};J().prototype.floorDiv=function(e){return this.throwIfDisposed(),Am(this,e)};J().prototype.gather=function(e,t){return this.throwIfDisposed(),Eu(this,e,t)};J().prototype.greaterEqual=function(e){return this.throwIfDisposed(),Er(this,e)};J().prototype.greater=function(e){return this.throwIfDisposed(),Nn(this,e)};J().prototype.ifft=function(){return this.throwIfDisposed(),ul(this)};J().prototype.irfft=function(){return this.throwIfDisposed(),Zm(this)};J().prototype.isFinite=function(){return this.throwIfDisposed(),bv(this)};J().prototype.isInf=function(){return this.throwIfDisposed(),xv(this)};J().prototype.isNaN=function(){return this.throwIfDisposed(),vv(this)};J().prototype.leakyRelu=function(e){return this.throwIfDisposed(),Fc(this,e)};J().prototype.lessEqual=function(e){return this.throwIfDisposed(),xs(this,e)};J().prototype.less=function(e){return this.throwIfDisposed(),Om(this,e)};J().prototype.localResponseNormalization=function(e,t,n,a){return this.throwIfDisposed(),wv(this,e,t,n,a)};J().prototype.logSigmoid=function(){return this.throwIfDisposed(),kv(this)};J().prototype.logSoftmax=function(e){return this.throwIfDisposed(),zm(this,e)};J().prototype.logSumExp=function(e,t){return this.throwIfDisposed(),Wm(this,e,t)};J().prototype.log=function(){return this.throwIfDisposed(),ea(this)};J().prototype.log1p=function(){return this.throwIfDisposed(),Dc(this)};J().prototype.logicalAnd=function(e){return this.throwIfDisposed(),Ea(this,e)};J().prototype.logicalNot=function(){return this.throwIfDisposed(),Rc(this)};J().prototype.logicalOr=function(e){return this.throwIfDisposed(),Bm(this,e)};J().prototype.logicalXor=function(e){return this.throwIfDisposed(),Iv(this,e)};J().prototype.matMul=function(e,t,n){return this.throwIfDisposed(),Fe(this,e,t,n)};J().prototype.maxPool=function(e,t,n,a){return this.throwIfDisposed(),Dt(this,e,t,n,a)};J().prototype.max=function(e,t){return this.throwIfDisposed(),ha(this,e,t)};J().prototype.maximum=function(e){return this.throwIfDisposed(),pr(this,e)};J().prototype.mean=function(e,t){return this.throwIfDisposed(),Nt(this,e,t)};J().prototype.min=function(e,t){return this.throwIfDisposed(),il(this,e,t)};J().prototype.minimum=function(e){return this.throwIfDisposed(),Au(this,e)};J().prototype.mirrorPad=function(e,t){return this.throwIfDisposed(),Tv(this,e,t)};J().prototype.mod=function(e){return this.throwIfDisposed(),Nv(this,e)};J().prototype.mul=function(e){return this.throwIfDisposed(),z(this,e)};J().prototype.neg=function(){return this.throwIfDisposed(),bt(this)};J().prototype.norm=function(e,t,n){return this.throwIfDisposed(),Cu(this,e,t,n)};J().prototype.notEqual=function(e){return this.throwIfDisposed(),ii(this,e)};J().prototype.oneHot=function(e,t=1,n=0){return this.throwIfDisposed(),rl(this,e,t,n)};J().prototype.onesLike=function(){return this.throwIfDisposed(),ta(this)};J().prototype.pad=function(e,t){return this.throwIfDisposed(),ya(this,e,t)};J().prototype.pool=function(e,t,n,a,r,s){return this.throwIfDisposed(),Cv(this,e,t,n,a,r,s)};J().prototype.pow=function(e){return this.throwIfDisposed(),_r(this,e)};J().prototype.prelu=function(e){return this.throwIfDisposed(),Oc(this,e)};J().prototype.prod=function(e,t){return this.throwIfDisposed(),_v(this,e,t)};J().prototype.reciprocal=function(){return this.throwIfDisposed(),$v(this)};J().prototype.relu=function(){return this.throwIfDisposed(),Xe(this)};J().prototype.relu6=function(){return this.throwIfDisposed(),Gm(this)};J().prototype.reshapeAs=function(e){return this.throwIfDisposed(),W(this,e.shape)};J().prototype.reshape=function(e){return this.throwIfDisposed(),W(this,e)};J().prototype.resizeBilinear=function(e,t,n){return this.throwIfDisposed(),NT(this,e,t,n)};J().prototype.resizeNearestNeighbor=function(e,t,n){return this.throwIfDisposed(),CT(this,e,t,n)};J().prototype.reverse=function(e){return this.throwIfDisposed(),fa(this,e)};J().prototype.rfft=function(){return this.throwIfDisposed(),Wc(this)};J().prototype.round=function(){return this.throwIfDisposed(),Hm(this)};J().prototype.rsqrt=function(){return this.throwIfDisposed(),jm(this)};J().prototype.selu=function(){return this.throwIfDisposed(),qm(this)};J().prototype.separableConv2d=function(e,t,n,a,r,s){return this.throwIfDisposed(),vs(this,e,t,n,a,r,s)};J().prototype.sigmoid=function(){return this.throwIfDisposed(),da(this)};J().prototype.sign=function(){return this.throwIfDisposed(),Fv(this)};J().prototype.sin=function(){return this.throwIfDisposed(),Km(this)};J().prototype.sinh=function(){return this.throwIfDisposed(),Xm(this)};J().prototype.slice=function(e,t){return this.throwIfDisposed(),Be(this,e,t)};J().prototype.softmax=function(e){return this.throwIfDisposed(),Ka(this,e)};J().prototype.softplus=function(){return this.throwIfDisposed(),ho(this)};J().prototype.spaceToBatchND=function(e,t){return this.throwIfDisposed(),Pc(this,e,t)};J().prototype.split=function(e,t){return this.throwIfDisposed(),zn(this,e,t)};J().prototype.sqrt=function(){return this.throwIfDisposed(),ln(this)};J().prototype.square=function(){return this.throwIfDisposed(),ot(this)};J().prototype.squaredDifference=function(e){return this.throwIfDisposed(),Jm(this,e)};J().prototype.squeeze=function(e){return this.throwIfDisposed(),ws(this,e)};J().prototype.stack=function(e,t){this.throwIfDisposed();let n=e instanceof Te?[this,e]:[this,...e];return Ft(n,t)};J().prototype.step=function(e){return this.throwIfDisposed(),fo(this,e)};J().prototype.stridedSlice=function(e,t,n,a,r,s,i,o){return this.throwIfDisposed(),Dv(this,e,t,n,a,r,s,i,o)};J().prototype.sub=function(e){return this.throwIfDisposed(),pe(this,e)};J().prototype.sum=function(e,t){return this.throwIfDisposed(),fe(this,e,t)};J().prototype.tan=function(){return this.throwIfDisposed(),Rv(this)};J().prototype.tanh=function(){return this.throwIfDisposed(),ri(this)};J().prototype.tile=function(e){return this.throwIfDisposed(),Ln(this,e)};J().prototype.toBool=function(){return this.throwIfDisposed(),oe(this,"bool")};J().prototype.toFloat=function(){return this.throwIfDisposed(),oe(this,"float32")};J().prototype.toInt=function(){return this.throwIfDisposed(),oe(this,"int32")};J().prototype.topk=function(e,t){return this.throwIfDisposed(),Mv(this,e,t)};J().prototype.transpose=function(e){return this.throwIfDisposed(),Ee(this,e)};J().prototype.unique=function(e){return this.throwIfDisposed(),Pv(this,e)};J().prototype.unsortedSegmentSum=function(e,t){return this.throwIfDisposed(),ef(this,e,t)};J().prototype.unstack=function(e){return this.throwIfDisposed(),ct(this,e)};J().prototype.where=function(e,t){return this.throwIfDisposed(),mn(e,this,t)};J().prototype.zerosLike=function(){return this.throwIfDisposed(),qe(this)};var vr=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,vr.prototype)}},Wa=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,Wa.prototype)}},V=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,V.prototype)}},Re=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,Re.prototype)}},LT=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,LT.prototype)}},zT=class{constructor(e){this.maxEntries=e||100,this.cache=new Map}get(e){let t;return this.cache.has(e)&&(t=this.cache.get(e),this.cache.delete(e),this.cache.set(e,t)),t}put(e,t){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.maxEntries){let n=this.cache.keys().next().value;this.cache.delete(n)}this.cache.set(e,t)}getMaxEntries(){return this.maxEntries}setMaxEntries(e){if(e<0)throw new Error(`The maxEntries of LRU caches must be at least 0, but got ${e}.`);if(this.maxEntries>e)for(let t=0;tn.toUpperCase())}var ka={};function jv(e){if(e==null)return null;let t={};return t.className=e.getClassName(),t.config=e.getConfig(),t}function Mb(e){if(!(e==null||typeof e!="object"))if(Array.isArray(e))e.forEach(t=>Mb(t));else{let t=Object.keys(e);for(let n of t){let a=e[n];a!=null&&typeof a=="object"&&(!Array.isArray(a)&&a.type==="ndarray"&&typeof a.value=="number"?e[n]=a.value:Mb(a))}}}function Vc(e,t={},n={},a="object",r=!1){if(typeof e=="string"){let s=e,i;if(s in n)i=n[s];else if(s in ka)i=ka[s];else if(i=t[s],i==null)throw new V(`Unknown ${a}: ${e}. This may be due to one of the following reasons:
-1. The ${a} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
-2. The custom ${a} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);return i}else{let s=e;if(s.className==null||s.config==null)throw new V(`${a}: Improper config format: ${JSON.stringify(s)}.
-'className' and 'config' must set.`);let i=s.className,o,l;if(i in n?[o,l]=n[i]:i in ka?[o,l]=ka.className:i in t&&([o,l]=t[i]),o==null)throw new V(`Unknown ${a}: ${i}. This may be due to one of the following reasons:
-1. The ${a} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
-2. The custom ${a} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);if(l!=null){let u={};for(let h of Object.keys(ka))u[h]=ka[h];for(let h of Object.keys(n))u[h]=n[h];let p=s.config;p.customObjects=u;let d=Object.assign({},ka);for(let h of Object.keys(n))ka[h]=n[h];Mb(s.config);let c=l(o,s.config,n,r);return ka=Object.assign({},d),c}else{let u=Object.assign({},ka);for(let d of Object.keys(n))ka[d]=n[d];let p=new o(s.config);return ka=Object.assign({},u),p}}}function A4(e,t){return et?1:0}function jd(e,t){return-1*A4(e,t)}function Jr(e){if(e==null)return e;let t=[];for(let n of e)t.indexOf(n)===-1&&t.push(n);return t}function $4(e){if(e==null)throw new V(`Invalid value in obj: ${JSON.stringify(e)}`);for(let t in e)if(e.hasOwnProperty(t))return!1;return!0}function go(e,t,n){if(n!=null&&e.indexOf(n)<0)throw new V(`${n} is not a valid ${t}. Valid values are ${e} or null/undefined.`)}function qv(e,t,n=0,a=1/0){return tr(n>=0),tr(a>=n),Array.isArray(e)&&e.length>=n&&e.length<=a&&e.every(r=>typeof r===t)}function Qt(e,t){Array.isArray(e)?(v.assert(e.length>0,()=>`${t} is unexpectedly an empty array.`),e.forEach((n,a)=>Qt(n,`element ${a+1} of ${t}`))):v.assert(Number.isInteger(e)&&e>0,()=>`Expected ${t} to be a positive integer, but got ${WT(e)}.`)}function WT(e){return e===null?"null":Array.isArray(e)?"["+e.map(t=>WT(t)).join(",")+"]":typeof e=="string"?`"${e}"`:`${e}`}function F4(e,t,n){let a=n!=null?n():v.now(),r;return(...s)=>{let i=n!=null?n():v.now();return i-a0){let n=`${e}_${t}`;return Ho.set(n,1),n}else return e}var B4=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function jT(e){return!!e.match(B4)}function V4(e){return e===parseInt(e.toString(),10)}function Qr(e,t,n){t==null&&(t=0),n==null&&(n=e.length);let a=1;for(let r=t;rt&&(t=a)}return t}function Ha(e,t){if(t{if(e.shape.length!==2)throw new V(`repeat() expects a rank-2 tensor, but received a rank-${e.shape.length} tensor.`);let n=Uc(e,1);return Pb(n,[1,t,1])})}function G4(e){let t=[Qr(e.shape)];return W(e,t)}function H4(e){if(e.rank<=1)throw new V(`batchFlatten requires a minimum rank of 2. Got rank: ${e.rank}.`);let t=[e.shape[0],Qr(e.shape,1)];return W(e,t)}function Ys(e,t,n){return P(()=>{switch(e.rank){case 1:return Lc(e,t,n);case 2:return Ym(e,[t,0],[n,e.shape[1]]);case 3:return mo(e,[t,0,0],[n,e.shape[1],e.shape[2]]);case 4:return ll(e,[t,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3]]);case 5:return Be(e,[t,0,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3],e.shape[4]]);case 6:return Be(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 V(`sliceAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}})}function cb(e,t,n){return P(()=>{switch(e.rank){case 1:return Lc(e,t,n);case 2:return Ym(e,[0,t],[e.shape[0],n]);case 3:return mo(e,[0,0,t],[e.shape[0],e.shape[1],n]);case 4:return ll(e,[0,0,0,t],[e.shape[0],e.shape[1],e.shape[2],n]);default:throw new V(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}})}function Kd(e,t,n,a){return P(()=>{switch(e.rank){case 1:return Lc(e,t,n);case 2:switch(a){case 1:return Ys(e,t,n);case 2:return cb(e,t,n);default:throw new V(`The axis is not within the rank of the tensor ${a}`)}case 3:switch(a){case 1:return Ys(e,t,n);case 2:return mo(e,[0,t,0],[e.shape[0],n,e.shape[2]]);case 3:return cb(e,t,n);default:throw new V(`The axis is not within the rank of the tensor ${a}`)}case 4:switch(a){case 1:return Ys(e,t,n);case 2:return ll(e,[0,t,0,0],[e.shape[0],n,e.shape[2],e.shape[3]]);case 3:return ll(e,[0,0,t,0],[e.shape[0],e.shape[1],n,e.shape[3]]);case 4:return cb(e,t,n);default:throw new V(`The axis is not within the rank of the tensor ${a}`)}default:throw new V(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}})}function Kv(e,t=-1){let n;return t<0&&(n=e[0].rank,n!==0?t=n:t=0),t===e[0].rank&&(t=-1),Ze(e,t)}function uk(e,t){switch(e.rank){case 1:return nv([e,t]);case 2:return av([e,t],0);case 3:return rv([e,t],0);case 4:return sv([e,t],0);default:throw new V(`concatAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}}function Pb(e,t){if(Array.isArray(t)||(t=[t]),e.rank!==t.length)throw new V(`The length of input n (${t.length}) does not match the number of dimensions in input x (${e.rank})`);return Ln(e,t)}function mf(e,t=0,n=1,a,r){return Um(e,t,n,a,r)}function sr(e,t,n,a){if(e.rank<2||t.rank<2)throw new Re(`dot requires both inputs to be rank >= 2 but got x shape = ${e.shape} and y shape = ${t.shape}`);if(t.rank>=3){let r=e.shape.slice(-1)[0],s=t.shape.slice(-2)[0];if(r!==s)throw new Re(`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)return pl.matMul({a:e,b:t,transposeA:!1,transposeB:!1,bias:a?Ob(e.rank,a,ja()):null,activation:n});{let r=e.shape.slice(),s=r.pop();e=W(e,[-1,s]);let i=t.shape.slice(),o=i.pop(),l=i.pop(),u=[...i,o],p=Array.from({length:t.rank},(m,f)=>f===0?t.rank-2:f<=t.rank-2?f-1:f);t=W(Ee(t,p),[l,-1]);let d=[...r,...u],c=!1,h=!1;return W(pl.matMul({a:e,b:t,transposeA:c,transposeB:h,bias:a?Ob(e.rank,a,ja()):null,activation:n}),d)}}function qT(e,t,n){return P(()=>(Array.isArray(t)?t=Ke(t,"int32"):t=oe(t,"int32"),Eu(e,t,n)))}function Gc(e){return z(e,e)}function Ob(e,t,n){let a=t.shape;if(t.rank!==1&&t.rank!==e)throw new V(`Unexpected bias dimensions: ${t.rank}; expected it to be 1 or ${e}`);if(e===5){if(n==="channelsFirst")return a.length===1?W(t,[1,a[0],1,1,1]):W(t,[1,a[3],a[0],a[1],a[2]]);if(n==="channelsLast")return a.length===1?W(t,[1,1,1,1,a[0]]):W(t,[1].concat(a))}else if(e===4){if(n==="channelsFirst")return a.length===1?W(t,[1,a[0],1,1]):W(t,[1,a[2],a[0],a[1]]);if(n==="channelsLast")return a.length===1?W(t,[1,1,1,a[0]]):W(t,[1].concat(a))}else if(e===3){if(n==="channelsFirst")return a.length===1?W(t,[1,a[0],1]):W(t,[1,a[1],a[0]]);if(n==="channelsLast")return a.length===1?W(t,[1,1,a[0]]):W(t,[1].concat(a))}else if(e<3)return t;throw new V(`Unsupported input rank by biasAdd: ${t.rank}`)}function Xa(e,t,n){return P(()=>(n==null&&(n=ja()),Rt(n),Y(e,Ob(e.rank,t,n))))}function j4(e,t=1){if(t!==1)throw new Re(`Support for alpha values other than 1 (${t}) is not implemented yet.`);return Nu(e)}function q4(e){return P(()=>he(e,Y(Lt(e),1)))}function KT(e,t,n,a){return P(()=>zv(e,t,n,a))}function K4(e){return P(()=>{let t=Y(.5,z(.2,e));return en(t,0,1)})}function Hc(e,t,n=!1){return n?e():t()}var X4=["fanIn","fanOut","fanAvg"],Y4=["normal","uniform","truncatedNormal"];function Z4(e){go(X4,"FanMode",e)}function J4(e){go(Y4,"Distribution",e)}var Fa=class extends ne.Serializable{fromConfigUsesCustomObjects(){return!1}getConfig(){return{}}},Xv=class extends Fa{apply(e,t){return It(e,t)}};Xv.className="Zeros";ne.registerClass(Xv);var ff=class extends Fa{apply(e,t){return Zn(e,t)}};ff.className="Ones";ne.registerClass(ff);var Yv=class extends Fa{constructor(e){if(super(),typeof e!="object")throw new V(`Expected argument of type ConstantConfig but got ${e}`);if(e.value===void 0)throw new V(`config must have value set but got ${e}`);this.value=e.value}apply(e,t){return P(()=>z(be(this.value),Zn(e,t)))}getConfig(){return{value:this.value}}};Yv.className="Constant";ne.registerClass(Yv);var Zv=class extends Fa{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 $u(e,this.minval,this.maxval,t)}getConfig(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}}};Zv.className="RandomUniform";ne.registerClass(Zv);var Jv=class extends Fa{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 Re(`randomNormal does not support dType ${t}.`);return mf(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}};Jv.className="RandomNormal";ne.registerClass(Jv);var Qv=class extends Fa{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 Re(`truncatedNormal does not support dType ${t}.`);return Qm(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}};Qv.className="TruncatedNormal";ne.registerClass(Qv);var ew=class extends Fa{constructor(e){super(),this.gain=e.gain!=null?e.gain:1}apply(e,t){return P(()=>{if(e.length!==2||e[0]!==e[1])throw new V("Identity matrix initializer can only be used for 2D square matrices.");return z(this.gain,Pm(e[0]))})}getConfig(){return{gain:this.gain}}};ew.className="Identity";ne.registerClass(ew);function Q4(e,t="channelsLast"){let n,a;if(Rt(t),e.length===2)n=e[0],a=e[1];else if([3,4,5].indexOf(e.length)!==-1){if(t==="channelsFirst"){let r=Qr(e,2);n=e[1]*r,a=e[0]*r}else if(t==="channelsLast"){let r=Qr(e,0,e.length-2);n=e[e.length-2]*r,a=e[e.length-1]*r}}else{let r=Qr(e);n=Math.sqrt(r),a=Math.sqrt(r)}return[n,a]}var Bn=class extends Fa{constructor(e){if(super(),e.scale<0)throw new V(`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,Z4(this.mode),this.distribution=e.distribution==null?"normal":e.distribution,J4(this.distribution),this.seed=e.seed}apply(e,t){let n=Q4(e),a=n[0],r=n[1],s=this.scale;if(this.mode==="fanIn"?s/=Math.max(1,a):this.mode==="fanOut"?s/=Math.max(1,r):s/=Math.max(1,(a+r)/2),this.distribution==="normal"){let i=Math.sqrt(s);if(t=t||"float32",t!=="float32"&&t!=="int32")throw new Re(`${this.getClassName()} does not support dType ${t}.`);return Qm(e,0,i,t,this.seed)}else{let i=Math.sqrt(3*s);return $u(e,-i,i,t)}}getConfig(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}}};Bn.className="VarianceScaling";ne.registerClass(Bn);var gf=class extends Bn{constructor(e){super({scale:1,mode:"fanAvg",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return Bn.className}};gf.className="GlorotUniform";ne.registerClass(gf);var yf=class extends Bn{constructor(e){super({scale:1,mode:"fanAvg",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return Bn.className}};yf.className="GlorotNormal";ne.registerClass(yf);var bf=class extends Bn{constructor(e){super({scale:2,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return Bn.className}};bf.className="HeNormal";ne.registerClass(bf);var xf=class extends Bn{constructor(e){super({scale:2,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return Bn.className}};xf.className="HeUniform";ne.registerClass(xf);var vf=class extends Bn{constructor(e){super({scale:1,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return Bn.className}};vf.className="LeCunNormal";ne.registerClass(vf);var wf=class extends Bn{constructor(e){super({scale:1,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return Bn.className}};wf.className="LeCunNormal";ne.registerClass(wf);var tw=class extends Fa{constructor(e){if(super(),this.DEFAULT_GAIN=1,this.gain=e.gain==null?this.DEFAULT_GAIN:e.gain,this.seed=e.seed,this.seed!=null)throw new Re("Random seed is not implemented for Orthogonal Initializer yet.")}apply(e,t){return P(()=>{if(e.length<2)throw new Re("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.`);let n=e[0]>e[1]?[e[1],e[0]]:e,a=mf(n,0,1,"float32"),r=Uv.gramSchmidt(a);return e[0]>e[1]&&(r=Ee(r)),z(this.gain,r)})}getConfig(){return{gain:this.gain,seed:this.seed}}};tw.className="Orthogonal";ne.registerClass(tw);var pk={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 ck(e,t={}){return Vc(e,ne.SerializationMap.getMap().classNameMap,t,"initializer")}function Ct(e){return jv(e)}function St(e){if(typeof e=="string"){let t=e in pk?pk[e]:e;if(t==="GlorotNormal")return new yf;if(t==="GlorotUniform")return new gf;if(t==="HeNormal")return new bf;if(t==="HeUniform")return new xf;if(t==="LeCunNormal")return new vf;if(t==="LeCunUniform")return new wf;{let n={};return n.className=t,n.config={},ck(n)}}else return e instanceof Fa?e:ck(e)}function Lb(e){return Array.isArray(e)&&Array.isArray(e[0])}function Th(e){return e.length===0?[]:Array.isArray(e[0])?e:[e]}function Ne(e){let t;if(Array.isArray(e)){if(e.length!==1)throw new V(`Expected Tensor length to be 1; got ${e.length}`);t=e[0]}else t=e;return t}function Qe(e){if(Array.isArray(e)&&Array.isArray(e[0])){if(e.length===1)return e=e,e[0];throw new V(`Expected exactly 1 Shape; got ${e.length}`)}else return e}function Nh(e){let t=0;for(let n of e)n.shape.length===0?t+=1:t+=n.shape.reduce((a,r)=>a*r);return t}var dk="Variable",XT=class{constructor(e,t="float32",n=dk,a=!0,r=null){this.dtype=t==null?"float32":t,this.shape=e.shape,this.id=VT(),n=n==null?dk:n,this.originalName=GT(n),this.name=HT(this.originalName),this.trainable_=a,this.constraint=r,this.val=Ov(e,this.trainable_,this.name,this.dtype)}read(){return this.assertNotDisposed(),this.val}write(e){return this.assertNotDisposed(),eV(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 eV(e,t){if(e.shape.toString()!==t.shape.toString())throw new Error("Shape mismatch: "+JSON.stringify(e.shape)+" vs. "+JSON.stringify(t.shape))}function zb(e){return e.map(t=>t.read())}function nw(e){e.forEach(t=>{t[0].write(t[1])})}var zt=class{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||{}}},Ba=class{constructor(e,t,n,a,r,s,i){this.dtype=e,this.shape=t,this.sourceLayer=n,this.inputs=a,this.callArgs=r,this.outputTensorIndex=i,this.id=VT(),s!=null&&(this.originalName=GT(s),this.name=HT(this.originalName)),this.rank=t.length}},tV=0,kf=class{constructor(e,t){this.callArgs=t,this.id=tV++,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(let n of e.inboundLayers)n!=null&&n.outboundNodes.push(this);e.outboundLayer.inboundNodes.push(this)}getConfig(){let e=[];for(let 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}}},nV=0,Ge=class extends ne.Serializable{constructor(e={}){super(),this._callHook=null,this._addedWeightNames=[],this._stateful=!1,this.id=nV++,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){let n=this.getClassName();t=wr(n)+"_"+hf(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 r=null;e.batchSize!=null&&(r=e.batchSize),n=[r].concat(e.inputShape)}this.batchInputShape=n;let a=e.dtype;a==null&&(a=e.inputDType),a==null&&(a="float32"),this.dtype=a}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 Wa(`The layer has never been called and thus has no defined ${t}.`);if(this.inboundNodes.length<=e)throw new V(`Asked to get ${t} at node ${e}, but the layer has only ${this.inboundNodes.length} inbound nodes.`);return this.inboundNodes[e]}getInputAt(e){return On(this.getNodeAtIndex(e,"input").inputTensors)}getOutputAt(e){return On(this.getNodeAtIndex(e,"output").outputTensors)}get input(){if(this.inboundNodes.length>1)throw new vr(`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 vr(`Layer ${this.name} is not connected, no input to return.`);return On(this.getNodeAtIndex(0,"input").inputTensors)}get output(){if(this.inboundNodes.length===0)throw new vr(`Layer ${this.name} has no inbound nodes.`);if(this.inboundNodes.length>1)throw new vr(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use \`getOutputAt(nodeIndex)\` instead.`);return On(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=yt(e),this.inputSpec==null||this.inputSpec.length===0)return;let t=yt(this.inputSpec);if(e.length!==t.length)throw new V(`Layer ${this.name} expects ${t.length} inputs, but it received ${e.length} input tensors. Input received: ${e}`);for(let n=0;nr.maxNDim)throw new V(`Input ${n} is incompatible with layer ${this.name}: expected max_ndim=${r.maxNDim}, found ndim=${s}`);if(r.minNDim!=null&&s=0?i[l]:i[i.length+l];if(u!=null&&[u,null].indexOf(p)===-1)throw new V(`Input ${n} is incompatible with layer ${this.name}: expected axis ${l} of input shape to have value ${u} but got shape ${i}.`)}}if(r.shape!=null)for(let i=0;i{if(!this.built){this.assertInputCompatibility(e);let s=[];for(let i of yt(e))s.push(i.shape);this.build(On(s)),this.built=!0,this.initialWeights&&this.setWeights(this.initialWeights),this._refCount===null&&r&&(this._refCount=1)}if(this.assertInputCompatibility(e),r){let s=this.call(e,t),i=yt(s),o=[];for(let l of i)n.indexOf(l)!==-1&&(l=l.clone()),o.push(l);if(s=On(o),this.activityRegularizer!=null)throw new Re("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return s}else{let s=aV(e),i=this.computeOutputShape(s),o,l=rV(e);if(this.warnOnIncompatibleInputShape(Array.isArray(e)?s[0]:s),i!=null&&i.length>0&&Array.isArray(i[0])?o=i.map((u,p)=>new Ba(l,u,this,yt(e),t,this.name,p)):o=new Ba(l,i,this,yt(e),t,this.name),this.addInboundNode(e,o,null,null,s,i,t),this._refCount++,this.activityRegularizer!=null)throw new Re("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return o}})}warnOnIncompatibleInputShape(e){if(this.batchInputShape!=null)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,a)=>{n!=null&&e[a]!=null&&e[a]!==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 vr(`The layer ${this.name} has never been called and thus has no defined output shape.`);let e=[];for(let t of this.inboundNodes){let n=JSON.stringify(t.outputShapes);e.indexOf(n)===-1&&e.push(n)}if(e.length===1){let t=this.inboundNodes[0].outputShapes;return Array.isArray(t)&&Array.isArray(t[0])&&t.length===1?t[0]:t}else throw new vr(`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 Wa(`You tried to call countParams() on ${this.name}, but the layer is not built yet. Build it first by calling build(batchInputShape).`);return Nh(this.weights)}build(e){this.built=!0}getWeights(e=!1){return zb(e?this.trainableWeights:this.weights)}setWeights(e){P(()=>{let t=this.weights;if(t.length!==e.length)throw new V(`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;let n=[],a=zb(t);for(let r=0;rr.apply(u.read())),s==null&&(s=!0),s?this._trainableWeights.push(u):this._nonTrainableWeights.push(u),u}setFastWeightInitDuringBuild(e){this.fastWeightInitDuringBuild=e}addLoss(e){e==null||Array.isArray(e)&&e.length===0||(e=yt(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,a,r,s,i=null){let o=yt(e);t=yt(t),n=yt(n),a=yt(a),r=Th(r),s=Th(s);let l=[],u=[],p=[];for(let d of o)l.push(d.sourceLayer),u.push(d.nodeIndex),p.push(d.tensorIndex);new kf({outboundLayer:this,inboundLayers:l,nodeIndices:u,tensorIndices:p,inputTensors:o,outputTensors:t,inputMasks:n,outputMasks:a,inputShapes:r,outputShapes:s},i);for(let d=0;de.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 aV(e){e=yt(e);let t=[];for(let n of e)t.push(n.shape);return On(t)}function rV(e){return"float32"}function YT(e,t,n){if((t==null||n!=null&&n>0)&&(t=e.sourceLayer,n=e.nodeIndex),t.inboundNodes.length===0)return[e];{let a=t.inboundNodes[n];if(a.inboundLayers.length===0)return a.inputTensors;{let r=[];for(let s=0;sm.name),l=[],u=t.names();for(let m of o)u.indexOf(m)!==-1?l.push(t.getValue(m)):l.push(null);a!=null&&(a.maxNumTensors=-1/0,a.minNumTensors=1/0);let p=o.join(",")+"|"+t.names().sort().join(","),d=Ch.get(p),c;if(d==null){let m=oV(i,t);d=m.sorted,c=m.recipientCounts,Ch.put(p,d),_h.put(p,c)}c={},r||Object.assign(c,_h.get(p));let h=new Hs(t);for(let m=0;ma.maxNumTensors&&(a.maxNumTensors=A),A0,()=>"Expected at least one fetch, got none");let n=[],a={};if(e.length===1){let r=hk(e[0],t);n=r.sorted,a=r.recipientMap}else{let r=new Set;for(let s of e){let{sorted:i,recipientMap:o}=hk(s,t);for(let l of i)r.has(l.name)||(n.push(l),r.add(l.name));for(let l in o)a[l]==null&&(a[l]=new Set),o[l].forEach(u=>a[l].add(u))}}return{sorted:n,recipientCounts:lV(a)}}function lV(e){let t={};for(let n in e)t[n]=e[n].size;return t}function hk(e,t){let n=new Set,a=[],r={};for(let o of t.names())n.add(o);let s=[],i=[];for(s.push(e);s.length>0;){let o=s[s.length-1];if(n.has(o.name)){s.pop();continue}let l=i[i.length-1]===s.length-1;if(o.inputs.length===0||l)s.pop(),a.push(o),n.add(o.name),l&&i.pop();else{i.push(s.length-1);for(let u of o.inputs)r[u.name]==null&&(r[u.name]=new Set),r[u.name].add(o.name),!n.has(u.name)&&s.push(u)}}return{sorted:a,recipientMap:r}}function uV(e){let t;if(e.sourceLayer.inboundNodes.length===1)t=e.sourceLayer.output;else{let n=null;for(let a=0;a100,iV);var JT={};Ae(JT,{maxNorm:()=>cV,minMaxNorm:()=>mV,nonNeg:()=>hV,unitNorm:()=>dV});function aw(e,t){return P(()=>ln(fe(z(e,e),t,!0)))}var jc=class extends ne.Serializable{getConfig(){return{}}},rw=class extends jc{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 P(()=>{let t=aw(e,this.axis),n=en(t,0,this.maxValue);return z(e,he(n,Y(Gt(),t)))})}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}};rw.className="MaxNorm";ne.registerClass(rw);var sw=class extends jc{constructor(e){super(),this.defaultAxis=0,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return P(()=>he(e,Y(Gt(),aw(e,this.axis))))}getConfig(){return{axis:this.axis}}};sw.className="UnitNorm";ne.registerClass(sw);var iw=class extends jc{apply(e){return Xe(e)}};iw.className="NonNeg";ne.registerClass(iw);var ow=class extends jc{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 P(()=>{let t=aw(e,this.axis),n=Y(z(this.rate,en(t,this.minValue,this.maxValue)),z(1-this.rate,t));return z(e,he(n,Y(Gt(),t)))})}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}};ow.className="MinMaxNorm";ne.registerClass(ow);var mk={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function qt(e){return jv(e)}function fk(e,t={}){return Vc(e,ne.SerializationMap.getMap().classNameMap,t,"constraint")}function Kt(e){if(e==null)return null;if(typeof e=="string"){let t={className:e in mk?mk[e]:e,config:{}};return fk(t)}else return e instanceof jc?e:fk(e)}function cV(e){return new rw(e)}function dV(e){return new sw(e)}function hV(){return new iw}function mV(e){return new ow(e)}var QT={};Ae(QT,{constant:()=>yV,glorotNormal:()=>SV,glorotUniform:()=>IV,heNormal:()=>TV,heUniform:()=>NV,identity:()=>wV,leCunNormal:()=>CV,leCunUniform:()=>_V,ones:()=>gV,orthogonal:()=>EV,randomNormal:()=>xV,randomUniform:()=>bV,truncatedNormal:()=>vV,varianceScaling:()=>kV,zeros:()=>fV});function fV(){return new Xv}function gV(){return new ff}function yV(e){return new Yv(e)}function bV(e){return new Zv(e)}function xV(e){return new Jv(e)}function vV(e){return new Qv(e)}function wV(e){return new ew(e)}function kV(e){return new Bn(e)}function IV(e){return new gf(e)}function SV(e){return new yf(e)}function TV(e){return new bf(e)}function NV(e){return new xf(e)}function CV(e){return new vf(e)}function _V(e){return new wf(e)}function EV(e){return new tw(e)}var eN={};Ae(eN,{Layer:()=>Ge,RNN:()=>dr,RNNCell:()=>Zc,activation:()=>nG,add:()=>cG,alphaDropout:()=>KG,average:()=>dG,averagePooling1d:()=>y0,averagePooling2d:()=>b0,averagePooling3d:()=>x0,avgPool1d:()=>wG,avgPool2d:()=>IG,avgPool3d:()=>TG,avgPooling1d:()=>kG,avgPooling2d:()=>SG,avgPooling3d:()=>NG,batchNormalization:()=>bG,bidirectional:()=>WG,categoryEncoding:()=>JG,concatenate:()=>hG,conv1d:()=>qU,conv2d:()=>KU,conv2dTranspose:()=>XU,conv3d:()=>YU,conv3dTranspose:()=>ZU,convLstm2d:()=>PG,convLstm2dCell:()=>OG,cropping2D:()=>QU,dense:()=>aG,depthwiseConv2d:()=>tG,dot:()=>yG,dropout:()=>rG,elu:()=>BU,embedding:()=>pG,flatten:()=>iG,gaussianDropout:()=>qG,gaussianNoise:()=>jG,globalAveragePooling1d:()=>CG,globalAveragePooling2d:()=>_G,globalMaxPool1d:()=>VG,globalMaxPool2d:()=>UG,globalMaxPooling1d:()=>HN,globalMaxPooling2d:()=>jN,gru:()=>AG,gruCell:()=>$G,input:()=>bN,inputLayer:()=>WU,layerNormalization:()=>xG,leakyReLU:()=>UU,lstm:()=>FG,lstmCell:()=>DG,masking:()=>XG,maxPool1d:()=>GG,maxPool2d:()=>HG,maxPooling1d:()=>qN,maxPooling2d:()=>KN,maxPooling3d:()=>EG,maximum:()=>mG,minimum:()=>fG,multiply:()=>gG,permute:()=>uG,prelu:()=>GU,reLU:()=>VU,repeatVector:()=>oG,rescaling:()=>YG,reshape:()=>lG,resizing:()=>ZG,rnn:()=>LG,separableConv2d:()=>JU,simpleRNN:()=>RG,simpleRNNCell:()=>MG,softmax:()=>HU,spatialDropout1d:()=>sG,stackedRNNCells:()=>zG,thresholdedReLU:()=>jU,timeDistributed:()=>BG,upSampling2d:()=>eG,zeroPadding2d:()=>vG});async function jr(e){if(e==null)return;let t=[],n=[],a=[];for(let r in e){let s=e[r];if(typeof s!="number"){let i=s;t.push(i.data()),n.push(r),a.push(i)}}if(t.length>0){let r=await Promise.all(t);for(let s=0;sY(this.totals[a],z(r,n)));this.totals[a]=i,s!=null&&s.dispose()}}}async onEpochEnd(e,t){if(t!=null)for(let n of this.params.metrics)this.totals[n]!=null&&(typeof this.totals[n]=="number"?t[n]=this.totals[n]/this.seen:P(()=>{let a=z(he(1,this.seen),this.totals[n]);t[n]=a,this.totals[n].dispose(),Jt(t[n])}))}},aN=class extends dl{async onTrainBegin(e){this.epoch=[],this.history={}}async onEpochEnd(e,t){t==null&&(t={}),this.epoch.push(e);for(let n in t)this.history[n]==null&&(this.history[n]=[]),this.history[n].push(t[n])}async syncData(){let e=[],t=[],n=[];for(let r in this.history){let s=this.history[r];for(let i=0;inew rN(n,t))}var Ta=class{constructor(){}static registerCallbackConstructor(e,t){v.assert(e>=0&&Number.isInteger(e),()=>`Verbosity level is expected to be an integer >= 0, but got ${e}`),Ta.checkForDuplicate(t),Ta.constructors[e]==null&&(Ta.constructors[e]=[]),Ta.constructors[e].push(t)}static checkForDuplicate(e){for(let t in Ta.constructors)Ta.constructors[+t].forEach(n=>{if(n===e)throw new V("Duplicate callback constructor.")})}static clear(){Ta.constructors={}}static createCallbacks(e){let t=[];for(let n in Ta.constructors){let a=+n;e>=a&&t.push(...Ta.constructors[a])}return t.map(n=>new n)}};Ta.constructors={};function iN(e,t,n,a,r,s,i,o,l){let u=new aN,p=[new $V,...Ta.createCallbacks(t)];e!=null&&p.push(...e),p.push(u);let d=new nN(p);return d.setParams({epochs:n,initialEpoch:a,samples:r,steps:s,batchSize:i,verbose:t,doValidation:o,metrics:l}),{callbackList:d,history:u}}function Ua(e,t={},n=!1){return Vc(e,ne.SerializationMap.getMap().classNameMap,t,"layer",n)}function Eh(e,t){return P(()=>{e.dtype!=="float32"&&(e=oe(e,"float32"));let n=fe(Gc(e),t,!0),a=gn(n.shape,Gt()),r=ln(pr(n,a));return he(e,r)})}function bo(e,t){return P(()=>Nt(Gc(pe(t,e)),-1))}function If(e,t){return P(()=>Nt(Lt(pe(t,e)),-1))}function Ru(e,t){return P(()=>{let n=pe(e,t),a=en(Lt(e),Gt(),Number.MAX_VALUE),r=Lt(he(n,a));return z(100,Nt(r,-1))})}function FV(e,t){return P(()=>{let n=en(t,Gt(),Number.MAX_VALUE),a=ea(Y(1,n)),r=en(e,Gt(),Number.MAX_VALUE),s=ea(Y(1,r));return Nt(Gc(pe(a,s)),-1)})}function DV(e,t){return P(()=>{let n=pr(0,pe(1,z(e,t)));return Nt(Gc(n),-1)})}function RV(e,t){return P(()=>{let n=pr(0,pe(1,z(e,t)));return Nt(n,-1)})}function MV(e,t){return P(()=>{let n=fe(z(e,t),-1),a=ha(z(pe(1,e),t),-1);return pr(0,Y(1,pe(a,n)))})}function PV(e,t){return P(()=>{let n=Math.log(2),a=pe(t,e),r=pe(Y(a,ho(z(-2,a))),n);return Nt(r,-1)})}function Xp(e,t,n=!1){return P(()=>{if(n)t=Ka(t);else{let a=fe(t,t.shape.length-1,!0);t=he(t,a)}return t=en(t,Gt(),1-Gt()),bt(fe(z(oe(e,"float32"),ea(t)),t.shape.length-1))})}function Ah(e,t,n=!1){return P(()=>{let a=oe(_u(G4(e)),"int32");t=en(t,Gt(),1-Gt());let r=t.shape,s=W(rl(a,r[r.length-1]),r);return Xp(s,t,n)})}function OV(e,t){if(!v.arraysEqual(e.shape,t.shape))throw new V(`logits and labels must have the same shape, but got shapes ${JSON.stringify(e.shape)} and ${JSON.stringify(t.shape)}`);return P(()=>{let n=Xe(t),a=bt(Lt(t));return Y(pe(n,z(t,e)),Dc(fn(a)))})}function Sf(e,t){return P(()=>{let n;return n=en(t,Gt(),1-Gt()),n=ea(he(n,pe(1,n))),Nt(OV(e,n),-1)})}function LV(e,t){return P(()=>{let n=en(e,Gt(),1),a=en(t,Gt(),1);return fe(z(e,ea(he(n,a))),-1)})}function zV(e,t){return P(()=>{let n=ea(Y(Gt(),t));return Nt(pe(t,z(e,n)),-1)})}function lw(e,t){return P(()=>{let n=Eh(e,-1),a=Eh(t,-1),r=z(n,a);return bt(fe(r,-1))})}var $h={meanSquaredError:bo,meanAbsoluteError:If,meanAbsolutePercentageError:Ru,meanSquaredLogarithmicError:FV,squaredHinge:DV,hinge:RV,categoricalHinge:MV,logcosh:PV,categoricalCrossentropy:Xp,sparseCategoricalCrossentropy:Ah,binaryCrossentropy:Sf,kullbackLeiblerDivergence:LV,poisson:zV,cosineProximity:lw};function db(e){if(typeof e=="string"){if(e in $h)return $h[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 V(t)}else return e}function uw(e,t){return P(()=>{let n=z(.5,ta(t)),a=yo(Nn(t,n),e.dtype);return Nt(Qn(e,a),-1)})}function pw(e,t){return P(()=>yo(Qn(ai(e,-1),ai(t,-1)),"float32"))}function oN(e,t){return P(()=>oe(fe(Ea(Qn(e,1),Qn(t,1))),"float32"))}function WV(e,t){return P(()=>oe(fe(Ea(Qn(e,1),Qn(t,0))),"float32"))}function BV(e,t){return P(()=>oe(fe(Ea(Qn(e,0),Qn(t,1))),"float32"))}function lN(e,t){return P(()=>{let n=oN(e,t),a=BV(e,t),r=Y(n,a);return oe(mn(Nn(r,0),he(n,r),0),"float32")})}function VV(e,t){return P(()=>{let n=oN(e,t),a=WV(e,t),r=Y(n,a);return oe(mn(Nn(r,0),he(n,r),0),"float32")})}function uN(e,t){return Sf(e,t)}function pN(e,t){return e.rank===t.rank&&(e=ws(e,[e.rank-1])),t=ai(t,-1),t.dtype!==e.dtype&&(t=oe(t,e.dtype)),oe(Qn(e,t),"float32")}var UV=bo,GV=bo,HV=If,jV=If,qV=Ru,KV=Ru,cw=Xp,XV=lw,cN=Ah,Fh={binaryAccuracy:uw,categoricalAccuracy:pw,precision:lN,categoricalCrossentropy:cw,sparseCategoricalCrossentropy:cN,mse:UV,MSE:GV,mae:HV,MAE:jV,mape:qV,MAPE:KV,cosine:XV};function YV(e){if(typeof e=="string"&&e in Fh)return Fh[e];if(typeof e!="string"&&e!=null)return e;throw new V(`Unknown metric ${e}`)}function Xd(e){if(tr(e!==null,`Unknown LossOrMetricFn ${e}`),typeof e=="string")return e;{let t;for(let n of Object.keys($h))if($h[n]===e){t=n;break}if(t!==void 0)return t;for(let n of Object.keys(Fh))if(Fh[n]===e){t=n;break}return t!==void 0?t:e.name}}function ZV(e){let t={Adagrad:()=>zs.adagrad(.01),Adadelta:()=>zs.adadelta(1,.95,Gt()),Adam:()=>zs.adam(.001,.9,.999,Gt()),Adamax:()=>zs.adamax(.002,.9,.999,Gt(),0),RMSProp:()=>zs.rmsprop(.001,.9,0,Gt()),SGD:()=>zs.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 V(`Unknown Optimizer ${e}`)}function yk(e,t,n=!1){if(e==null||typeof e!="object"||Object.getPrototypeOf(e)!==Object.prototype||!Wb(e))throw new Error("User-defined metadata is expected to be a JSON object, but is not.");if(n){let a=JSON.stringify(e);a.length>1048576&&console.warn(`User-defined metadata of model "${t}" is too large in size (length=${a.length} when serialized). It is not recommended to store such large objects in user-defined metadata. Please make sure its serialized length is <= ${1048576}.`)}}function Wb(e){if(e===null)return!0;if(typeof e=="object")if(Object.getPrototypeOf(e)===Object.prototype){let t=Object.keys(e);for(let n of t)if(typeof n!="string"||!Wb(e[n]))return!1;return!0}else if(Array.isArray(e)){for(let t of e)if(!Wb(t))return!1;return!0}else return!1;else{let t=typeof e;return t==="string"||t==="number"||t==="boolean"}}function JV(e,t,n,a=console.log){let r=eU(e),s=["Layer (type)","Input Shape","Output shape","Param #"];r?(t=t||90,n=n||[.32,.61,.89,1]):(t=t||115,n=n||[.24,.48,.7,.8,1]),n[n.length-1]<=1&&(n=n.map(p=>Math.floor(t*p)));let i;if(!r){s.push("Receives inputs"),i=[];for(let p in e.nodesByDepth)i.push(...e.nodesByDepth[p])}a("_".repeat(t)),Dh(s,n,a),a("=".repeat(t));let o=e.layers;for(let p=0;p1||r.length===1&&r[0].inboundLayers.length>1){t=!1;break}a.push(...r)}if(t)for(let r of e.layers){let s=!1;for(let i of r.inboundNodes)if(a.indexOf(i)!==-1)if(s){t=!1;break}else s=!0;if(!t)break}return t}function Dh(e,t,n=console.log){let a="";for(let r=0;r0&&(a=a.slice(0,a.length-1)+" "),a+=e[r],a=a.slice(0,t[r]),a+=" ".repeat(t[r]-a.length);n(a)}function tU(e,t,n){let a,r;try{r=e.inboundNodes.map(l=>JSON.stringify(l.inputShapes)).join(",")}catch(l){r="multiple"}try{a=JSON.stringify(e.outputShape)}catch(l){a="multiple"}let s=e.name,i=e.getClassName(),o=[`${s} (${i})`,r,a,e.countParams().toString()];Dh(o,t,n)}function nU(e,t,n,a){let r,s;try{s=e.inboundNodes.map(d=>JSON.stringify(d.inputShapes)).join(",")}catch(d){s="multiple"}try{r=JSON.stringify(e.outputShape)}catch(d){r="multiple"}let i=[];for(let d of e.inboundNodes)if(!(n!=null&&n.length>0&&n.indexOf(d)===-1))for(let c=0;cy.name)}`);Jr(this.outputs).length!==this.outputs.length&&console.warn(`The list of outputs passed to the model is redundant. All outputs should only appear once. Found: ${this.outputs.map(y=>y.name)}`),this.inputLayers=[],this.inputLayersNodeIndices=[],this.inputLayersTensorIndices=[],this.outputLayers=[],this.outputLayersNodeIndices=[],this.outputLayersTensorIndices=[],this.layers=[],this.internalContainerRefs=[];for(let y of this.outputs){let b=y.sourceLayer,x=y.nodeIndex,w=y.tensorIndex;this.outputLayers.push(b),this.outputLayersNodeIndices.push(x),this.outputLayersTensorIndices.push(w)}for(let y of this.inputs){let b=y.sourceLayer,x=y.nodeIndex,w=y.tensorIndex;tr(x===0,"input layer has >1 nodes"),tr(w===0,"input layer has >1 tensors"),this.inputLayers.push(b),this.inputLayersNodeIndices.push(x),this.inputLayersTensorIndices.push(w)}this.inputNames=[],this.outputNames=[],this.feedInputShapes=[],this.feedInputNames=[],this.feedOutputNames=[];for(let y=0;yy.shape),this.internalOutputShapes=this.outputs.map(y=>y.shape);let t={},n={},a={},r={},s={},i=[],o=(y,b,x,w,I,T)=>{(w==null||I==null||T==null)&&(w=y.sourceLayer,I=y.nodeIndex,T=y.tensorIndex);let C=w.inboundNodes[I];if(x.indexOf(C)!==-1)throw new Wa(`The tensor ${y.name} at layer "${w.name}" is part of a cycle.`);if(b.indexOf(C)!==-1)return;this.containerNodes.add(Qa.nodeKey(w,I)),w.id in s||(s[w.id]=Object.keys(s).length),x.indexOf(C)===-1&&x.push(C);let E=C.inboundLayers.length;for(let A=0;A=0;)x.splice(x.indexOf(C),1);i.push(C)},l=[],u=[];for(let y of this.outputs)o(y,l,u);let p=i.slice().reverse();for(let y of p){n[y.id]=y,y.id in t||(t[y.id]=0);let b=t[y.id],x=a[y.outboundLayer.id]==null?0:a[y.outboundLayer.id];b=Math.max(b,x),a[y.outboundLayer.id]=b,r[y.outboundLayer.id]=y.outboundLayer,t[y.id]=b;for(let w=0;wparseInt(y,10)).sort(jd);this.layers=[];for(let y of h){let b=c[y];b.sort((x,w)=>{let I=s[x.id],T=s[w.id];return IT?1:0});for(let x of b)x instanceof Qa&&this.internalContainerRefs.push(x),this.layers.push(x)}this.layersByDepth=c,h=Object.keys(d).map(y=>parseInt(y,10)).sort(jd);let m=this.inputs.slice(),f=[];for(let y of h)for(let b of d[y]){let x=b.outboundLayer;if(x!=null){for(let w of b.inputTensors)if(m.indexOf(w)===-1)throw new Wa(`Graph disconnected: cannot obtain value for tensor ${w} at layer "${x.name}". The following previous layers were accessed without issue: ${f}`);for(let w of b.outputTensors)m.push(w);f.push(x.name)}}this.nodesByDepth=d;let g=this.layers.map(y=>y.name);for(let y of g){let b=g.filter(x=>x===y).length;if(b!==1)throw new Wa(`The name "${y}" is used ${b} times in the model. All layer names should be unique. Layer names: `+JSON.stringify(g))}this.outboundNodes=[],this.inboundNodes=[],new kf({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:this.inputs.map(y=>null),outputMasks:this.outputs.map(y=>null),inputShapes:this.inputs.map(y=>y.shape),outputShapes:this.outputs.map(y=>y.shape)}),this.built=!0,this._refCount=1}assertNotDisposed(){if(this._refCount===0)throw new Error(`Container '${this.name}' is already disposed.`)}dispose(){this.assertNotDisposed();let e={refCountAfterDispose:null,numDisposedVariables:0};if(--this._refCount===0){for(let t of this.layers)e.numDisposedVariables+=t.dispose().numDisposedVariables;for(let 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 V("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(let t of this.layers)e=e.concat(t.trainableWeights);return e}get nonTrainableWeights(){let e=[];for(let t of this.layers)e.push(...t.nonTrainableWeights);if(!this.trainable){let t=[];for(let 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){let n={},a=0;for(let s of this.layers)for(let i of s.weights){if(n[i.originalName]!=null)throw new V(`Duplicate weight name: ${i.originalName}`);n[i.originalName]=i,a++}let r=[];for(let s in e){let i=s;if(n[s]==null){let o=s.split("/");i=o.slice(0,-2).concat([o[o.length-1]]).join("/")}if(n[i]!=null)r.push([n[i],e[s]]);else if(t)throw new V(`Provided weight data has no target variable: ${s}`);delete n[i]}if(t){let s=[];for(let i in n)s.push(i);if(s.length>0)throw new V(`${s.length} of ${a} weights are not set: ${s}`)}nw(r)}updatedConfig(){let e=this.getConfig(),t={};return t.className=this.getClassName(),t.config=e,t.kerasVersion=`tfjs-layers ${dw}`,t.backend="TensorFlow.js",t}toJSON(e,t=!0){let n=Bb(this.updatedConfig());return t?JSON.stringify(n):n}call(e,t){return P(()=>{e=yt(e);let n=new Hs;for(let a=0;a{e=yt(e);let n;return t==null?n=oi(null,e.length):n=yt(t),this.runInternalGraph(e,n)[1]})}computeOutputShape(e){let t=Th(e);if(t.length!==this.inputLayers.length)throw new V(`Invalid inputShape argument ${e}: model has ${this.inputLayers.length} tensor inputs.`);let n={};for(let i=0;iparseInt(i,10)).sort(jd);if(a.length>1)for(let i of a){let o=this.nodesByDepth[i];for(let l of o){let u=l.outboundLayer;if(this.inputLayers.map(m=>m.id).indexOf(u.id)!==-1)continue;let p=[];for(let m=0;mparseInt(o,10)).sort(jd);for(let o of a){let l=this.nodesByDepth[o];for(let u of l){let p=u.outboundLayer,d=u.inputTensors,c=u.outputTensors,h=new Array;for(let m of d)m.id in n&&h.push(n[m.id]);if(h.length===d.length){let m={},f,g,y,b;if(u.callArgs!=null&&(m=u.callArgs),h.length===1){let[x,w]=h[0];m.mask==null&&(m.mask=w),y=yt(p.call(x,m)),b=yt(p.computeMask(x,w)),f=[x],g=[w]}else f=h.map(x=>x[0]),g=h.map(x=>x[1]),m.mask==null&&(m.mask=g),y=yt(p.call(f,m)),b=yt(p.computeMask(f,g));if(p.activityRegularizer)throw new Re("LayersModel invocation with concrete Tensor value(s) in the presence of activity regularizer(s) is not supported yet.");for(let x=0;x{let e=[];for(let t of this.layers)for(let n=0;n0){let m=[];for(let f=0;f0&&f.apply(On(y),b)}function l(f){let g=f.name,y=Ua(f,t.customObjects!=null?t.customObjects:{});y.setFastWeightInitDuringBuild(a),r[g]=y,f.inboundNodes.forEach(b=>{if(!(b instanceof Array))throw new V(`Corrupted configuration, expected array for nodeData: ${b}`);i(y,b)})}let u=t.name,p=t.layers;for(let f of p)l(f);for(;!$4(s);)for(let f of p){let g=r[f.name];if(g.name in s){let y=s[g.name];delete s[g.name];for(let b of y)o(g,b)}}let d=[],c=[],h=t.inputLayers;for(let f of h){let g=f[0],y=f[1],b=f[2];tr(g in r);let x=r[g].inboundNodes[y].outputTensors;d.push(x[b])}let m=t.outputLayers;for(let f of m){let g=f[0],y=f[1],b=f[2];tr(g in r);let x=r[g].inboundNodes[y].outputTensors;c.push(x[b])}return new e({inputs:d,outputs:c,name:u})}get stateful(){if(this._stateful)throw new V("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(let e of this.layers)if(e.stateful)return!0;return!1}resetStates(){P(()=>{this.layers.forEach(e=>{e.stateful&&e.resetStates()})})}};function aU(e,t,n){let a=t.length;if(e==null||Array.isArray(e)&&e.length===0)return t.map(r=>null);if(a===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!==a)throw new Error(`Provided ${n} is an array of ${e.length} element(s), but the model has ${a} 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"){let r=[];return t.forEach(s=>{s in e?r.push(e[s]):r.push(null)}),r}else throw new Error(`The model has multiple (${a}) outputs, so ${n} must be either an array with ${a} elements or an object with ${t} keys. Provided ${n} not understood: ${JSON.stringify(e)}`)}function hN(e,t){return aU(e,t,"classWeight")}async function mN(e,t,n,a){if(t!=null||a!=null)throw new Error("Support sampleWeight is not implemented yet");if(n!=null){let r=P(()=>{if(e.shape.length===1)return rr(e);if(e.shape.length===2){if(e.shape[1]>1)return ai(e,1);if(e.shape[1]===1)return W(e,[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.`)}),s=Array.from(await r.data());_e(r);let i=[];return s.forEach(o=>{if(n[o]==null)throw new Error(`classWeight must contain all classes in the training data. The class ${o} exists in the data but not in classWeight`);i.push(n[o])}),Ke(i,"float32")}else return null}function rU(e,t){return z(e,t)}var sU=32;function fN(e,t){let n,a,r=t;n=r.xs,a=r.ys,v.assert(n!=null&&a!=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}`);let s=bk("input",e.inputNames,n),i=bk("output",e.outputNames,a),o=s[0].shape[0];v.assert(s.length===e.inputs.length,()=>`LayersModel has ${e.inputs.length} inputs, but the dataset provides ${s.length} inputs. (Expected input keys: ${JSON.stringify(e.inputNames)})`),v.assert(i.length===e.outputs.length,()=>`LayersModel has ${e.outputs.length} outputs, but the dataset provides ${i.length} outputs. (Expected output keys: ${JSON.stringify(e.outputNames)})`);for(let l=0;l`Batch size mismatch: input ${e.inputNames[l]} has ${s[l].shape[0]}; expected ${o} based on input ${e.inputNames[0]}.`);for(let l=0;l`Batch size mismatch: output ${e.outputNames[l]} has ${i[l].shape[0]}; expected ${o} based on input ${e.inputNames[0]}.`);return{xs:s,ys:i}}function bk(e,t,n){if(n instanceof Te)return[n];if(Array.isArray(n))return v.assert(n.length===t.length,()=>`Received an array of ${n.length} Tensors, but expected ${t.length} to match the ${e} keys ${t}.`),n;{let a=[];for(let r of t){if(n[r]==null)throw new V(`The feature data generated by the dataset lacks the required ${e} key '${r}'.`);a.push(n[r])}return a}}function iU(e){if(e.length===3)throw new Re("Validation with sample weights is not implemented yet.");return{xs:e[0],ys:e[1]}}async function oU(e,t,n){let a=n.batchesPerEpoch!=null;if(v.assert(e.optimizer!=null,()=>"You must compile a model before training/testing. Use LayersModel.compile(modelCompileConfig)."),v.assert(n!=null,()=>"For fitDataset(), the 2nd argument (config) is required, but it is not provided in this call."),v.assert(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}`),v.assert(!a||n.batchesPerEpoch>0&&Number.isInteger(n.batchesPerEpoch),()=>`For fitDataset(), config.batchesPerEpoch is expected to be a positive integer if specified, but got ${n.batchesPerEpoch}`),v.assert(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{let r=n.validationData!=null,s,i;if(r)if(xk(n.validationData))v.assert(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{let g=iU(n.validationData);s=g.xs,i=g.ys}let o=e.makeTrainFunction(),l=e.getDedupedMetricsNames(),u;r?u=l.slice().concat(l.map(g=>"val_"+g)):u=l.slice();let p=sN(n.callbacks,n.yieldEvery),d=n.verbose==null?1:n.verbose,{callbackList:c,history:h}=iN(p,d,n.epochs,null,null,lU(t,n),null,r,u);c.setModel(e),e.history=h,await c.onTrainBegin(),e.stopTraining_=!1;let m=n.initialEpoch==null?0:n.initialEpoch,f=await t.iterator();for(;m=n.batchesPerEpoch:x.done){if(r){let w;xk(n.validationData)?w=yt(await e.evaluateDataset(n.validationData,{batches:n.validationBatches})):w=yt(e.evaluate(s,i,{batchSize:n.validationBatchSize==null?sU:n.validationBatchSize,verbose:0}));for(let I=0;I0)throw new Re("Verbose mode is not implemented yet.");v.assert(!a||n.batches>0&&Number.isInteger(n.batches),()=>`Test loop expects \`batches\` to be a positive integer, but received ${JSON.stringify(n.batches)}`);let i=uU(t)?t:await t.iterator(),o=0,l=0;for(;!a||l{if(u.value){let{xs:p,ys:d}=fN(e,u.value),c=p.concat(d),h=P(()=>r(c));if(_e(c),l===0)for(let f=0;fY(s[f],z(m,g))),l>0&&_e(y)}_e(h),o+=m,++l}return s}),u.done){a&&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 u=0;u0&&Number.isInteger(e),()=>`batchSize is required to be a positive integer, but got ${e}`)}function Ap(e,t,n){return e==null?[null]:Array.isArray(e)?e.map(a=>Ys(a,t,n-t)):Ys(e,t,n-t)}function hw(e,t){return P(()=>e==null?null:Array.isArray(e)?e.map(n=>hw(n,t)):qT(e,t.dtype==="int32"?t:oe(t,"int32")))}function Ub(e,t){let n=[],a=0,r=null;for(;a=e&&(r=e),n.push([a,r]),a=r;return n}async function cU(e,t,n,a,r,s,i,o,l,u,p,d,c,h,m){r==null&&(r=32),s==null&&(s=1),p==null&&(p=!0),c==null&&(c=0);let f=!1;if(l!=null&&u!=null&&(f=!0),m!=null&&(f=!0,h==null))throw new V("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");let g=e.checkNumSamples(n,r,h,"steps_per_epoch"),y;g!=null&&(y=Ha(0,g)),i==null&&(i=1);let{callbackList:b,history:x}=iN(o,i,s,c,g,h,r,f,d);b.setModel(e),e.history=x,await b.onTrainBegin(),e.stopTraining_=!1;for(let w=c;w{let R=C[E][0],F=C[E][1],S=Ys(T,R,F-R);A.batch=E,A.size=F-R;let M=hw(n,S),B=t(M);for(let U=0;U0){if(g=!0,a.validationData.length===2)l=a.validationData[0],u=a.validationData[1];else throw a.validationData.length===3?new Re("validationData including sample weights is not supported yet."):new V(`When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; ${a.validationData} is invalid.`);let E=!0,A=await e.standardizeUserData(l,u,null,null,E,h);p=A[0],d=A[1],y=p.concat(d)}else if(a.validationSplit!=null&&a.validationSplit>0&&a.validationSplit<1){g=!0;let E=Math.floor(r[0].shape[0]*(1-a.validationSplit)),A=r[0].shape[0];p=Ap(r,E,A),i=r,r=Ap(r,0,E),d=Ap(s,E,A),o=s,s=Ap(s,0,E),y=p.concat(d)}else a.validationSteps!=null&&(g=!0);let b=r.concat(s).concat(c);e.checkTrainableWeightsConsistency();let x=e.makeTrainFunction(),w=e.getDedupedMetricsNames(),I,T;g?(e.makeTestFunction(),I=e.testFunction,T=w.slice().concat(w.map(E=>"val_"+E))):(I=null,y=[],T=w.slice());let C=sN(a.callbacks,a.yieldEvery);return await cU(e,x,b,w,h,a.epochs,a.verbose,C,I,y,a.shuffle,T,a.initialEpoch,null,null)}finally{e.isTraining=!1,La(r,t),La(s,n),La(i,t),La(o,n),La(p,l),La(d,u),c!=null&&_e(c)}}function gN(e){let t=[];e instanceof Te&&(e=[e]);for(let n=0;nn.push(r.id));else if(t!=null)for(let r in t){let s=t[r];n.push(s.id)}let a=[];if(e instanceof Te)n.indexOf(e.id)===-1&&a.push(e);else if(Array.isArray(e))e.forEach(r=>{n.indexOf(r.id)===-1&&a.push(r)});else if(e!=null)for(let r in e){let s=e[r];n.indexOf(s.id)===-1&&a.push(s)}a.forEach(r=>{r.isDisposed||r.dispose()})}function hU(e){return e instanceof Te}function Gb(e){return Array.isArray(e)}function vk(e){return!hU(e)&&!Gb(e)}function wk(e,t,n,a=!0,r=""){if(t==null||t.length===0){if(e!=null){let i=!1;if(Gb(e)&&e.length>0)i=!0;else if(vk(e)){for(let o in e)if(e.hasOwnProperty(o)){i=!0;break}}else i=!0;if(i)throw new V(`Error when checking model ${r} expected no data, but got ${e}`)}return[]}if(e==null)return t.map(i=>null);let s;if(vk(e)){e=e,s=[];for(let i of t){if(e[i]==null)throw new V(`No data provided for "${i}". Need data for each key in: ${t}`);s.push(e[i])}}else if(Gb(e)){if(e=e,e.length!==t.length)throw new V(`Error when checking model ${r}: 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}`);s=e}else{if(e=e,t.length>1)throw new V(`The model ${r} expects ${t.length} Tensor(s), but only received one Tensor. Found: Tensor with shape ${e.shape}`);s=[e]}if(s=gN(s),n!=null)for(let i=0;i=0&&u!==p)throw new V(`${r} expected a batch of elements where each example has shape [${n[i].slice(1,n[i].length)}] (i.e.,tensor shape [*,${n[i].slice(1,n[i].length)}]) but the ${r} received an input with ${o.shape[0]} examples, each with shape [${o.shape.slice(1,o.shape.length)}] (tensor shape [${o.shape}])`)}}return s}function mU(e,t,n){let a=Jr(e.map(s=>s.shape[0]));a.sort();let r=Jr(t.map(s=>s.shape[0]));if(r.sort(),a.length>1)throw new V(`All input Tensors (x) should have the same number of samples. Got array shapes: ${JSON.stringify(e.map(s=>s.shape))}`);if(r.length>1)throw new V(`All target Tensors (y) should have the same number of samples. Got array shapes: ${JSON.stringify(t.map(s=>s.shape))}`);if(a.length>0&&r.length>0&&!v.arraysEqual(a,r))throw new V(`Input Tensors should have the same number of samples as target Tensors. Found ${a[0]} input sample(s) and ${r[0]} target sample(s).`)}function fU(e,t,n){let a=[bo,Sf,Xp];for(let r=0;r1)throw new V(`The model expects ${t.length} ${r} Tensors, but only received one Tensor. Found: array with shape ${JSON.stringify(e.shape)}.`);s=[e]}if(n!=null)for(let i=0;i[]);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(a=>n);{let a=[];for(let r of t){let s=n.hasOwnProperty(r)?n[r]:[];Array.isArray(s)||(s=[s]),a.push(s)}return a}}var yU="layers-model",Nr=class extends Qa{constructor(e){super(e),this.isTraining=!1}summary(e,t,n=console.log){if(!this.built)throw new V("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).");JV(this,e,t,n)}compile(e){if(e.loss==null&&(e.loss=[]),this.loss=e.loss,typeof e.optimizer=="string")this.optimizer_=ZV(e.optimizer),this.isOptimizerOwned=!0;else{if(!(e.optimizer instanceof $r))throw new V("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(let s in e.loss)if(this.outputNames.indexOf(s)===-1)throw new V(`Unknown entry in loss dictionary: "${s}". Only expected the following keys: ${this.outputNames}`);for(let s of this.outputNames)e.loss[s]==null&&console.warn(`Output "${s}" is missing from loss dictionary. We assume this was done on purpose, and we will not be expecting data to be passed to ${s} during training`),t.push(db(e.loss[s]))}else if(Array.isArray(e.loss)){if(e.loss.length!==this.outputs.length)throw new V(`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}.`);t=e.loss.map(s=>db(s))}else{let s=db(e.loss);this.outputs.forEach(i=>{t.push(s)})}this.lossFunctions=t,this.feedOutputNames=[],this.feedOutputShapes=[],this.feedLossFns=[];for(let s=0;s{for(let s=0;s1&&(this.metricsTensors.push([i,s]),this.metricsNames.push(this.outputNames[s]+"_loss"))}});let a=gU(e.metrics,this.outputNames),r=(s,i,o)=>{this.outputNames.length>1&&(i=this.outputNames[s]+"_"+i),this.metricsNames.push(i),this.metricsTensors.push([o,s])};Xs("metric",()=>{for(let s=0;s{let l="",u,p,d;for(let c of o){if(typeof c=="string"&&["accuracy","acc","crossentropy","ce"].indexOf(c)!==-1){let m=this.internalOutputShapes[s];m[m.length-1]===1||this.lossFunctions[s]===Sf?["accuracy","acc"].indexOf(c)!==-1?p=uw:["crossentropy","ce"].indexOf(c)!==-1&&(p=uN):this.lossFunctions[s]===Ah?["accuracy","acc"].indexOf(c)!==-1?p=pN:["crossentropy","ce"].indexOf(c)!==-1&&(p=cN):["accuracy","acc"].indexOf(c)!==-1?p=pw:["crossentropy","ce"].indexOf(c)!==-1&&(p=cw);let f;["accuracy","acc"].indexOf(c)!==-1?f="acc":["crossentropy","ce"].indexOf(c)!==-1&&(f="ce"),d=p,u=l+f}else d=YV(c),u=l+Xd(c);let h;Xs(u,()=>{h=d}),r(s,u,h)}})(i)}}),this.collectedTrainableWeights=this.trainableWeights}checkTrainableWeightsConsistency(){this.collectedTrainableWeights!=null&&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={}){let a=n.batchSize==null?32:n.batchSize;Vb(a);let r=!0,s=this.standardizeUserDataXY(e,t,r,a);try{let i=s[0].concat(s[1]);this.makeTestFunction();let o=this.testFunction,l=this.testLoop(o,i,a,n.verbose,n.steps);return On(l)}finally{La(s[0],e),La(s[1],t)}}async evaluateDataset(e,t){return this.makeTestFunction(),pU(this,e,t)}checkNumSamples(e,t,n,a="steps"){let r;if(n!=null){if(r=null,t!=null)throw new V(`If ${a} is set, batchSize must be null or undefined.Got batchSize = ${t}`)}else if(e!=null)Array.isArray(e)?r=e[0].shape[0]:r=e.shape[0];else throw new V(`Either the input data should have a defined shape, or ${a} shoud be specified.`);return r}execute(e,t){if(Array.isArray(t)&&t.length===0)throw new V("`outputs` is an empty Array, which is not allowed.");let n=Array.isArray(t),a=n?t:[t],r=this.retrieveSymbolicTensors(a),s=new Hs;if(e instanceof Te&&(e=[e]),Array.isArray(e)){if(e.length!==this.inputs.length)throw new V(`The number of inputs provided (${e.length}) does not match the number of inputs of this model (${this.inputs.length}).`);for(let o=0;oi.name);for(let i=0;i0){let a=[];throw t.forEach((r,s)=>{r==null&&a.push(e[s])}),new V(`Cannot find SymbolicTensors for output name(s): ${JSON.stringify(a)}`)}return t}predictLoop(e,t=32,n=!1){return P(()=>{let a=this.checkNumSamples(e);if(n)throw new Re("Verbose predictLoop() is not implemented yet.");let r=Ub(a,t),s=this.outputs.map(i=>[]);for(let i=0;i{let o=r[i][0],l=r[i][1],u=Ap(e,o,l),p=[];if(Array.isArray(u))for(let c=0;cs[l].push(o));return On(s.map(i=>Ze(i,0)))})}predict(e,t={}){let n=gN(e);kk(n,this.inputNames,this.feedInputShapes,!1);try{let a=t.batchSize==null?32:t.batchSize;return Vb(a),this.predictLoop(n,a)}finally{La(n,e)}}predictOnBatch(e){kk(e,this.inputNames,this.feedInputShapes,!0);let t=(Array.isArray(e)?e[0]:e).shape[0];return this.predictLoop(e,t)}standardizeUserDataXY(e,t,n=!0,a){if(this.optimizer_==null)throw new Wa("You must compile a model before training/testing. Use LayersModel.compile(modelCompileArgs).");let r=[];for(let s=0;s0&&e[0].shape[0]%a!==0)throw new V(`In a stateful network, you should only pass inputs with a number of samples that is divisible by the batch size ${a}. Found: ${e[0].shape[0]} sample(s).`);return[e,t]}async standardizeUserData(e,t,n,a,r=!0,s){let[i,o]=this.standardizeUserDataXY(e,t,r,s);if(n!=null)throw new Error("sample weight is not supported yet.");let l=null;if(a!=null){let u=hN(a,this.outputNames);l=[];for(let p=0;p{let s=this.checkNumSamples(t,n,r,"steps"),i=[];if(a>0)throw new Re("Verbose mode is not implemented yet.");if(r!=null)throw new Re("steps mode in testLoop() is not implemented yet");{let o=Ub(s,n),l=Ke(Ha(0,s));for(let u=0;u1&&(r+=`_${ok(e.slice(0,n),a)}`),t.push(r)}return t}makeTrainFunction(){return e=>{let t=[],n=e.slice(0,this.inputs.length),a=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),r=e.slice(this.inputs.length+this.outputs.length,this.inputs.length+this.outputs.length*2),s=[],i=()=>{let u=[];for(let h=0;h1&&h{c=Y(c,h)}),c},o=this.collectedTrainableWeights.map(u=>u.read()),l=!0;return[this.optimizer_.minimize(i,l,o)].concat(s)}}makeTestFunction(){this.testFunction=e=>P(()=>{let t=[],n,a=e.slice(0,this.inputs.length),r=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),s=[];for(let l=0;lwr(t))}else{let t=Object.keys(this.loss);e={};let n=this.loss;for(let a of t)if(typeof n[a]=="string")e[a]=wr(n[a]);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[wr(Xd(this.metrics))];if(Array.isArray(this.metrics))return this.metrics.map(e=>wr(Xd(e)));{let e={};for(let t in this.metrics)e[t]=wr(Xd(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.");let t=Yp(e.optimizer_config),n=Ua(t),a;if(typeof e.loss=="string")a=Vs(e.loss);else if(Array.isArray(e.loss))a=e.loss.map(s=>Vs(s));else if(e.loss!=null){a={};for(let s in e.loss)a[s]=Vs(e.loss[s])}let r;if(Array.isArray(e.metrics))r=e.metrics.map(s=>Vs(s));else if(e.metrics!=null){r={};for(let s in e.metrics)r[s]=Vs(e.metrics[s])}this.compile({loss:a,metrics:r,optimizer:n})}async save(e,t){if(typeof e=="string"){let i=Ut.getSaveHandlers(e);if(i.length===0)throw new V(`Cannot find any save handlers for URL '${e}'`);if(i.length>1)throw new V(`Found more than one (${i.length}) save handlers for URL '${e}'`);e=i[0]}if(e.save==null)throw new V("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");let n=await Ut.encodeWeights(this.getNamedWeights(t)),a=!1,r=null,s={modelTopology:this.toJSON(r,a),format:yU,generatedBy:`TensorFlow.js tfjs-layers v${dw}`,convertedBy:null};if((t==null?!1:t.includeOptimizer)&&this.optimizer!=null){s.trainingConfig=this.getTrainingConfig();let i="optimizer",{data:o,specs:l}=await Ut.encodeWeights(await this.optimizer.getWeights(),i);n.specs.push(...l),n.data=Ut.concatenateArrayBuffers([n.data,o])}return this.userDefinedMetadata!=null&&(yk(this.userDefinedMetadata,this.name,!0),s.userDefinedMetadata=this.userDefinedMetadata),s.weightData=n.data,s.weightSpecs=n.specs,e.save(s)}setUserDefinedMetadata(e){yk(e,this.name),this.userDefinedMetadata=e}getUserDefinedMetadata(){return this.userDefinedMetadata}};Nr.className="Model";ne.registerClass(Nr);var yN=class extends Nr{};yN.className="Functional";ne.registerClass(yN);async function bU(e,t){"modelTopology"in e||(e={modelTopology:e}),e=e;let n=e.modelTopology;n.model_config!=null&&(n=n.model_config);let a=Yp(n),r=Ua(a,t);if(e.weightsManifest!=null){let s=await Ut.loadWeights(e.weightsManifest,e.pathPrefix,r.weights.map(o=>o.originalName)),i={};for(let o of r.weights)i[o.originalName]=s[o.originalName];r.loadWeights(i),_e(s)}return r}async function xU(e,t){if(t==null&&(t={}),typeof e=="string"){let n=Ut.getLoadHandlers(e,t);if(n.length===0)n.push(Ut.browserHTTPRequest(e,t));else if(n.length>1)throw new V(`Found more than one (${n.length}) load handlers for URL '${e}'`);e=n[0]}return vU(e,void 0,t)}async function vU(e,t,n){if(n==null&&(n={}),e.load==null)throw new V("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");let a=await e.load(),r=a.modelTopology;r.model_config!=null&&(r=r.model_config);let s=n.strict==null?!0:n.strict,i=a.weightData!=null&&a.weightSpecs!=null&&s,o=Ua(Yp(r),t,i),l=a.trainingConfig;if(l!=null&&o.loadTrainingConfig(l),a.userDefinedMetadata!=null&&o.setUserDefinedMetadata(a.userDefinedMetadata),a.weightData!=null){if(a.weightSpecs==null)throw new V("LayersModel artifacts contains weight data, but not weight specs. Therefore loading of weights cannot proceed.");let{modelWeights:u,optimizerWeights:p}=wU(a.weightData,a.weightSpecs);o.loadWeights(u,s),o.optimizer!=null&&p.length>0&&await o.optimizer.setWeights(p),_e(u),_e(p.map(d=>d.tensor))}return o}function wU(e,t){let n=Ut.decodeWeights(e,t),a={},r=[];return t.forEach(s=>{s.group==="optimizer"?r.push({name:s.name,tensor:n[s.name]}):a[s.name]=n[s.name]}),{modelWeights:a,optimizerWeights:r}}var hl=class extends Nr{constructor(e){if(super({inputs:[],outputs:[]}),e=e||{},this.trainable=!0,this.built=!1,this.name=e.name!=null?e.name:hf("sequential_"),e.layers!=null)for(let t of e.layers)this.add(t)}checkShape(e){if(e.inboundNodes[0].outputTensors[0].shape.some(t=>t<0))throw new V(`Negative dimension size caused by adding layer ${e.name} with input shape [${e.inboundNodes[0].inputTensors[0].shape}]`)}add(e){let t=e instanceof hl||e instanceof Nr,n;if(t){if(n=e,n.outputs.length!==1)throw new V("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 V("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 V("The first layer in a Sequential model must get an `inputShape` or `batchInputShape` argument.");let a=ZT({batchShape:e.batchInputShape,dtype:e.dtype,name:e.name+"_input"});e.apply(a)}if(t)this.outputs=n.outputs,this.inputs=n.inputs;else{if(e.inboundNodes.length!==1)throw new V(`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 V("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=YT(this.outputs[0])}this.inboundNodes=[],new kf({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:oi(null,this.inputs.length),outputMasks:[null],inputShapes:this.inputs.map(a=>a.shape),outputShapes:this.outputs[0].shape})}else{let a=e.apply(this.outputs[0]);if(Array.isArray(a))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=[a],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{let 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(Qe(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 Nr({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 Wa("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 Wa("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 Wa("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 Wa("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={},a=!1){let r,s={};if(t instanceof Array){if(t[0].className==null||t[0].className==="Merge")throw new V("Legacy serialization format not supported yet.");r=t}else v.assert(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."),r=t.layers,delete t.layers,s=t;let i=new e(s);if(!(i instanceof hl))throw new Re(`Sequential.fromConfig called on non-Sequential input: ${i}`);for(let o of r){let l=Ua(o,void 0,a);a&&l.setFastWeightInitDuringBuild(!0),i.add(l)}return i}set stopTraining(e){if(this.model==null)throw new V("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 V("Cannot get the stopTraining property of a sequential model before it is compiled.");return this.model.stopTraining}getConfig(){let e=[];for(let t of this.layers){let n={};n.className=t.getClassName(),n.config=t.getConfig(),e.push(n)}return{name:this.name,layers:e}}};hl.className="Sequential";ne.registerClass(hl);function kU(e){return new Nr(e)}function IU(e){return new hl(e)}function bN(e){return ZT(e)}function SU(e,t){Ta.registerCallbackConstructor(e,t)}var Un=class extends ne.Serializable{getConfig(){return{}}},xN=class extends Un{apply(e,t=1){return j4(e,t)}};xN.className="elu";ne.registerClass(xN);var vN=class extends Un{apply(e){return qm(e)}};vN.className="selu";ne.registerClass(vN);var wN=class extends Un{apply(e){return Xe(e)}};wN.className="relu";ne.registerClass(wN);var kN=class extends Un{apply(e){return P(()=>Au(6,Xe(e)))}};kN.className="relu6";ne.registerClass(kN);var IN=class extends Un{apply(e){return e}};IN.className="linear";ne.registerClass(IN);var SN=class extends Un{apply(e){return da(e)}};SN.className="sigmoid";ne.registerClass(SN);var TN=class extends Un{apply(e){return K4(e)}};TN.className="hardSigmoid";ne.registerClass(TN);var NN=class extends Un{apply(e){return ho(e)}};NN.className="softplus";ne.registerClass(NN);var CN=class extends Un{apply(e){return q4(e)}};CN.className="softsign";ne.registerClass(CN);var _N=class extends Un{apply(e){return ri(e)}};_N.className="tanh";ne.registerClass(_N);var mw=class extends Un{apply(e,t=-1){return Ka(e,t)}};mw.className="softmax";ne.registerClass(mw);var EN=class extends Un{apply(e,t=-1){return zm(e,t)}};EN.className="logSoftmax";ne.registerClass(EN);var AN=class extends Un{apply(e,t=1){return P(()=>z(da(z(e,t)),e))}};AN.className="swish";ne.registerClass(AN);var $N=class extends Un{apply(e){return P(()=>z(e,ri(ho(e))))}};$N.className="mish";ne.registerClass($N);function rs(e){return e.getClassName()}function hb(e,t={}){return Vc(e,ne.SerializationMap.getMap().classNameMap,t,"activation")}function ss(e){if(e==null){let t={};return t.className="linear",t.config={},hb(t)}if(typeof e=="string"){let t={};return t.className=e,t.config={},hb(t)}else return e instanceof Un?e:hb(e)}function fw(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}`)}var FN=class extends ne.Serializable{},qc=class extends FN{constructor(e){super(),fw(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 P(()=>{let t=It([1]);return this.hasL1&&(t=Y(t,fe(z(this.l1,Lt(e))))),this.hasL2&&(t=Y(t,fe(z(this.l2,Gc(e))))),W(t,[])})}getConfig(){return{l1:this.l1,l2:this.l2}}static fromConfig(e,t){return new e({l1:t.l1,l2:t.l2})}};qc.className="L1L2";ne.registerClass(qc);function TU(e){return fw(e),new qc({l1:e!=null?e.l1:null,l2:0})}function NU(e){return fw(e),new qc({l2:e!=null?e.l2:null,l1:0})}var Ik={l1l2:"L1L2"};function pt(e){return jv(e)}function Sk(e,t={}){return Vc(e,ne.SerializationMap.getMap().classNameMap,t,"regularizer")}function Tt(e){if(e==null)return null;if(typeof e=="string"){let t={className:e in Ik?Ik[e]:e,config:{}};return Sk(t)}else return e instanceof FN?e:Sk(e)}var gw=class extends Ge{constructor(e){super(e==null?{}:e),this.supportsMasking=!0,e!=null&&(this.maxValue=e.maxValue)}call(e,t){e=Ne(e);let n=Xe(e);return this.maxValue!=null&&(n=en(n,0,this.maxValue)),n}computeOutputShape(e){return e}getConfig(){let e={maxValue:this.maxValue},t=super.getConfig();return Object.assign(e,t),e}};gw.className="ReLU";ne.registerClass(gw);var yw=class extends Ge{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){let n=Ne(e);return Fc(n,this.alpha)}computeOutputShape(e){return e}getConfig(){let e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}};yw.className="LeakyReLU";ne.registerClass(yw);var bw=class extends Ge{constructor(e){if(super(e==null?{}:e),this.DEFAULT_ALPHA_INITIALIZER="zeros",e==null&&(e={}),this.supportsMasking=!0,this.alphaInitializer=St(e.alphaInitializer||this.DEFAULT_ALPHA_INITIALIZER),this.alphaRegularizer=Tt(e.alphaRegularizer),this.alphaConstraint=Kt(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 V(`Expected sharedAxes to be a number or an array of numbers, but got ${e.sharedAxes}`)}build(e){e=Qe(e);let t=e.slice(1);if(this.sharedAxes!=null)for(let a of this.sharedAxes)t[a-1]=1;this.alpha=this.addWeight("alpha",t,"float32",this.alphaInitializer,this.alphaRegularizer,!0,this.alphaConstraint);let n={};if(this.sharedAxes!=null)for(let a=1;a(Rt(t),t==="channelsFirst"?Ee(e,[0,2,3,1]):e))}function DN(e,t){return P(()=>(Rt(t),t==="channelsFirst"?Ee(e,[0,2,3,4,1]):e))}function CU(e,t,n,a=1,r="valid",s,i=1){return P(()=>{if(s==null&&(s=ja()),Rt(s),e.shape.length!==3)throw new V(`The input of a conv1dWithBias operation should be 3, but is ${e.shape.length} instead.`);if(t.shape.length!==3)throw new V(`The kernel for a conv1dWithBias operation should be 3, but is ${t.shape.length} instead`);if(n!=null&&n.shape.length!==1)throw new V(`The bias for a conv1dWithBias operation should be 1, but is ${t.shape.length} instead`);if(s==="channelsFirst"&&(e=Ee(e,[0,2,1])),r==="causal")throw new Re("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");let o=Fm(e,t,a,r==="same"?"same":"valid","NWC",i);return n!=null&&(o=Xa(o,n)),o})}function Tk(e,t,n,a=[1,1],r="valid",s,i,o=null){return P(()=>{if(s==null&&(s=ja()),Rt(s),e.rank!==3&&e.rank!==4)throw new V(`conv2dWithBiasActivation expects input to be of rank 3 or 4, but received ${e.rank}.`);if(t.rank!==3&&t.rank!==4)throw new V(`conv2dWithBiasActivation expects kernel to be of rank 3 or 4, but received ${e.rank}.`);let l=kw(e,s);if(r==="causal")throw new Re("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");return l=pl.conv2d({x:l,filter:t,strides:a,pad:r==="same"?"same":"valid",dilations:i,dataFormat:"NHWC",bias:n,activation:o}),s==="channelsFirst"&&(l=Ee(l,[0,3,1,2])),l})}function _U(e,t,n,a=[1,1,1],r="valid",s,i){return P(()=>{if(s==null&&(s=ja()),Rt(s),e.rank!==4&&e.rank!==5)throw new V(`conv3dWithBias expects input to be of rank 4 or 5, but received ${e.rank}.`);if(t.rank!==4&&t.rank!==5)throw new V(`conv3dWithBias expects kernel to be of rank 4 or 5, but received ${e.rank}.`);let o=DN(e,s);if(r==="causal")throw new Re("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");return o=ov(o,t,a,r==="same"?"same":"valid","NDHWC",i),n!=null&&(o=Xa(o,n)),s==="channelsFirst"&&(o=Ee(o,[0,4,1,2,3])),o})}var Iw=class extends Ge{constructor(e,t){if(super(t),this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",Iw.verifyArgs(t),this.rank=e,Qt(this.rank,"rank"),this.rank!==1&&this.rank!==2&&this.rank!==3)throw new Re(`Convolution layer for rank other than 1, 2, or 3 (${this.rank}) is not implemented yet.`);if(this.kernelSize=el(t.kernelSize,e,"kernelSize"),this.strides=el(t.strides==null?1:t.strides,e,"strides"),this.padding=t.padding==null?"valid":t.padding,ba(this.padding),this.dataFormat=t.dataFormat==null?"channelsLast":t.dataFormat,Rt(this.dataFormat),this.activation=ss(t.activation),this.useBias=t.useBias==null?!0:t.useBias,this.biasInitializer=St(t.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.biasConstraint=Kt(t.biasConstraint),this.biasRegularizer=Tt(t.biasRegularizer),this.activityRegularizer=Tt(t.activityRegularizer),this.dilationRate=el(t.dilationRate==null?1:t.dilationRate,e,"dilationRate"),this.rank===1&&Array.isArray(this.dilationRate)&&this.dilationRate.length!==1)throw new V(`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 V(`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 V(`dilationRate must be a number or array of three numbers for 3D convolution, but received ${JSON.stringify(this.dilationRate)}`)}}static verifyArgs(e){if(tr("kernelSize"in e,"required key 'kernelSize' not in config"),typeof e.kernelSize!="number"&&!qv(e.kernelSize,"number",1,3))throw new V(`BaseConv expects config.kernelSize to be number or number[] with length 1, 2, or 3, but received ${JSON.stringify(e.kernelSize)}.`)}getConfig(){let e={kernelSize:this.kernelSize,strides:this.strides,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,activation:rs(this.activation),useBias:this.useBias,biasInitializer:Ct(this.biasInitializer),biasRegularizer:pt(this.biasRegularizer),activityRegularizer:pt(this.activityRegularizer),biasConstraint:qt(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}},Kc=class extends Iw{constructor(e,t){super(e,t),this.kernel=null,Kc.verifyArgs(t),this.filters=t.filters,Qt(this.filters,"filters"),this.kernelInitializer=St(t.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.kernelConstraint=Kt(t.kernelConstraint),this.kernelRegularizer=Tt(t.kernelRegularizer)}build(e){e=Qe(e);let t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null)throw new V(`The channel dimension of the input should be defined. Found ${e[t]}`);let n=e[t],a=this.kernelSize.concat([n,this.filters]);this.kernel=this.addWeight("kernel",a,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 P(()=>{e=Ne(e);let n,a=this.bias==null?null:this.bias.read(),r=BT(this.activation.getClassName());if(r!=null&&this.rank===2)n=Tk(e,this.kernel.read(),a,this.strides,this.padding,this.dataFormat,this.dilationRate,r);else{if(this.rank===1)n=CU(e,this.kernel.read(),a,this.strides[0],this.padding,this.dataFormat,this.dilationRate[0]);else if(this.rank===2)n=Tk(e,this.kernel.read(),a,this.strides,this.padding,this.dataFormat,this.dilationRate);else if(this.rank===3)n=_U(e,this.kernel.read(),a,this.strides,this.padding,this.dataFormat,this.dilationRate);else throw new Re("convolutions greater than 3D are not implemented yet.");this.activation!=null&&(n=this.activation.apply(n))}return n})}computeOutputShape(e){e=Qe(e);let t=[],n=this.dataFormat==="channelsLast"?e.slice(1,e.length-1):e.slice(2);for(let r=0;r 0 but got ${JSON.stringify(e.filters)}`)}},Xc=class extends Kc{constructor(e){super(2,e),Xc.verifyArgs(e)}getConfig(){let e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if(typeof e.kernelSize!="number"&&!qv(e.kernelSize,"number",1,2))throw new V(`Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received ${JSON.stringify(e.kernelSize)}.`)}};Xc.className="Conv2D";ne.registerClass(Xc);var Yc=class extends Kc{constructor(e){super(3,e),Yc.verifyArgs(e)}getConfig(){let 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 V(`Conv3D expects config.kernelSize to be number or [number, number, number], but received ${JSON.stringify(e.kernelSize)}.`)}};Yc.className="Conv3D";ne.registerClass(Yc);var Sw=class extends Xc{constructor(e){if(super(e),this.inputSpec=[new zt({ndim:4})],this.padding!=="same"&&this.padding!=="valid")throw new V(`Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(e=Qe(e),e.length!==4)throw new V("Input should have rank 4; Received input shape: "+JSON.stringify(e));let t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null)throw new V("The channel dimension of the inputs should be defined. Found `None`.");let n=e[t],a=this.kernelSize.concat([this.filters,n]);this.kernel=this.addWeight("kernel",a,"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 zt({ndim:4,axes:{[t]:n}})],this.built=!0}call(e,t){return P(()=>{let n=Ne(e);if(n.shape.length!==4)throw new V(`Conv2DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${n.shape.length}`);let a=n.shape,r=a[0],s,i;this.dataFormat==="channelsFirst"?(s=2,i=3):(s=1,i=2);let o=a[s],l=a[i],u=this.kernelSize[0],p=this.kernelSize[1],d=this.strides[0],c=this.strides[1],h=nr(o,d,u,this.padding),m=nr(l,c,p,this.padding),f=[r,h,m,this.filters];this.dataFormat!=="channelsLast"&&(n=Ee(n,[0,2,3,1]));let g=Dm(n,this.kernel.read(),f,this.strides,this.padding);return this.dataFormat!=="channelsLast"&&(g=Ee(g,[0,3,1,2])),this.bias!=null&&(g=Xa(g,this.bias.read(),this.dataFormat)),this.activation!=null&&(g=this.activation.apply(g)),g})}computeOutputShape(e){e=Qe(e);let t=e.slice(),n,a,r;this.dataFormat==="channelsFirst"?(n=1,a=2,r=3):(n=3,a=1,r=2);let s=this.kernelSize[0],i=this.kernelSize[1],o=this.strides[0],l=this.strides[1];return t[n]=this.filters,t[a]=nr(t[a],o,s,this.padding),t[r]=nr(t[r],l,i,this.padding),t}getConfig(){let e=super.getConfig();return delete e.dilationRate,e}};Sw.className="Conv2DTranspose";ne.registerClass(Sw);var Tw=class extends Yc{constructor(e){if(super(e),this.inputSpec=[new zt({ndim:5})],this.padding!=="same"&&this.padding!=="valid")throw new V(`Conv3DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(e=Qe(e),e.length!==5)throw new V("Input should have rank 5; Received input shape: "+JSON.stringify(e));let t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null)throw new V("The channel dimension of the inputs should be defined. Found `None`.");let n=e[t],a=this.kernelSize.concat([this.filters,n]);this.kernel=this.addWeight("kernel",a,"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 zt({ndim:5,axes:{[t]:n}})],this.built=!0}call(e,t){return P(()=>{let n=Ne(e);if(n.shape.length!==5)throw new V(`Conv3DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${n.shape.length}`);let a=n.shape,r=a[0],s,i,o;this.dataFormat==="channelsFirst"?(o=2,s=3,i=4):(o=1,s=2,i=3);let l=a[o],u=a[s],p=a[i],d=this.kernelSize[0],c=this.kernelSize[1],h=this.kernelSize[2],m=this.strides[0],f=this.strides[1],g=this.strides[2],y=nr(l,m,d,this.padding),b=nr(u,f,c,this.padding),x=nr(p,g,h,this.padding),w=[r,y,b,x,this.filters];this.dataFormat!=="channelsLast"&&(n=Ee(n,[0,2,3,4,1]));let I=lv(n,this.kernel.read(),w,this.strides,this.padding);return this.dataFormat!=="channelsLast"&&(I=Ee(I,[0,4,1,2,3])),this.bias!==null&&(I=Xa(I,this.bias.read(),this.dataFormat)),this.activation!==null&&(I=this.activation.apply(I)),I})}computeOutputShape(e){e=Qe(e);let t=e.slice(),n,a,r,s;this.dataFormat==="channelsFirst"?(n=1,a=2,r=3,s=4):(n=4,a=1,r=2,s=3);let i=this.kernelSize[0],o=this.kernelSize[1],l=this.kernelSize[2],u=this.strides[0],p=this.strides[1],d=this.strides[2];return t[n]=this.filters,t[a]=nr(t[a],u,i,this.padding),t[r]=nr(t[r],p,o,this.padding),t[s]=nr(t[s],d,l,this.padding),t}getConfig(){let e=super.getConfig();return delete e.dilationRate,e}};Tw.className="Conv3DTranspose";ne.registerClass(Tw);var RN=class extends Kc{constructor(e,t){if(super(e,t),this.DEFAULT_DEPTHWISE_INITIALIZER="glorotUniform",this.DEFAULT_POINTWISE_INITIALIZER="glorotUniform",this.depthwiseKernel=null,this.pointwiseKernel=null,t.filters==null)throw new V("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(t.kernelInitializer!=null||t.kernelRegularizer!=null||t.kernelConstraint!=null)throw new V("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 V(`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=St(t.depthwiseInitializer||this.DEFAULT_DEPTHWISE_INITIALIZER),this.depthwiseRegularizer=Tt(t.depthwiseRegularizer),this.depthwiseConstraint=Kt(t.depthwiseConstraint),this.pointwiseInitializer=St(t.depthwiseInitializer||this.DEFAULT_POINTWISE_INITIALIZER),this.pointwiseRegularizer=Tt(t.pointwiseRegularizer),this.pointwiseConstraint=Kt(t.pointwiseConstraint)}build(e){if(e=Qe(e),e.length{e=Ne(e);let n;if(this.rank===1)throw new Re("1D separable convolution is not implemented yet.");return this.rank===2&&(this.dataFormat==="channelsFirst"&&(e=Ee(e,[0,2,3,1])),n=vs(e,this.depthwiseKernel.read(),this.pointwiseKernel.read(),this.strides,this.padding,this.dilationRate,"NHWC")),this.useBias&&(n=Xa(n,this.bias.read(),this.dataFormat)),this.activation!=null&&(n=this.activation.apply(n)),this.dataFormat==="channelsFirst"&&(n=Ee(n,[0,3,1,2])),n})}getConfig(){let e=super.getConfig();return delete e.rank,delete e.kernelInitializer,delete e.kernelRegularizer,delete e.kernelConstraint,e.depthwiseInitializer=Ct(this.depthwiseInitializer),e.pointwiseInitializer=Ct(this.pointwiseInitializer),e.depthwiseRegularizer=pt(this.depthwiseRegularizer),e.pointwiseRegularizer=pt(this.pointwiseRegularizer),e.depthwiseConstraint=qt(this.depthwiseConstraint),e.pointwiseConstraint=qt(this.pointwiseConstraint),e}};RN.className="SeparableConv";var Nw=class extends RN{constructor(e){super(2,e)}};Nw.className="SeparableConv2D";ne.registerClass(Nw);var Tf=class extends Kc{constructor(e){super(1,e),Tf.verifyArgs(e),this.inputSpec=[{ndim:3}]}getConfig(){let e=super.getConfig();return delete e.rank,delete e.dataFormat,e}static verifyArgs(e){if(typeof e.kernelSize!="number"&&!qv(e.kernelSize,"number",1,1))throw new V(`Conv1D expects config.kernelSize to be number or number[] with length 1, but received ${JSON.stringify(e.kernelSize)}.`)}};Tf.className="Conv1D";ne.registerClass(Tf);var Cw=class extends Ge{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 P(()=>{if(e=Ne(e),this.dataFormat==="channelsLast"){let n=Kd(e,this.cropping[0][0],e.shape[1]-this.cropping[0][0]-this.cropping[0][1],2);return Kd(n,this.cropping[1][0],e.shape[2]-this.cropping[1][1]-this.cropping[1][0],3)}else{let n=Kd(e,this.cropping[0][0],e.shape[2]-this.cropping[0][0]-this.cropping[0][1],3);return Kd(n,this.cropping[1][0],e.shape[3]-this.cropping[1][1]-this.cropping[1][0],4)}})}getConfig(){let e={cropping:this.cropping,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}};Cw.className="Cropping2D";ne.registerClass(Cw);var _w=class extends Ge{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,Rt(this.dataFormat),this.interpolation=e.interpolation==null?"nearest":e.interpolation,z4(this.interpolation)}computeOutputShape(e){if(this.dataFormat==="channelsFirst"){let 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{let 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 P(()=>{let n=Ne(e),a=n.shape;if(this.dataFormat==="channelsFirst"){n=Ee(n,[0,2,3,1]);let r=this.size[0]*a[2],s=this.size[1]*a[3],i=this.interpolation==="nearest"?za.resizeNearestNeighbor(n,[r,s]):za.resizeBilinear(n,[r,s]);return Ee(i,[0,3,1,2])}else{let r=this.size[0]*a[1],s=this.size[1]*a[2];return this.interpolation==="nearest"?za.resizeNearestNeighbor(n,[r,s]):za.resizeBilinear(n,[r,s])}})}getConfig(){let e={size:this.size,dataFormat:this.dataFormat,interpolation:this.interpolation},t=super.getConfig();return Object.assign(e,t),e}};_w.className="UpSampling2D";ne.registerClass(_w);function EU(e,t,n=[1,1],a="valid",r,s){return P(()=>{r==null&&(r=ja()),Rt(r);let i=kw(e,r);if(e.rank!==4)throw new V(`Input for depthwiseConv2d is required to be 4-D, but is instead ${e.rank}-D`);if(t.rank!==4)throw new V(`depthwiseKernel is required to be 4-D, but is instead ${t.rank}-D`);return i=bs(i,t,n,a==="same"?"same":"valid","NHWC",s),r==="channelsFirst"&&(i=Ee(i,[0,3,1,2])),i})}var Ew=class extends Iw{constructor(e){super(2,e),this.depthwiseKernel=null,this.depthMultiplier=e.depthMultiplier==null?1:e.depthMultiplier,this.depthwiseInitializer=St(e.depthwiseInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.depthwiseConstraint=Kt(e.depthwiseConstraint),this.depthwiseRegularizer=Tt(e.depthwiseRegularizer)}build(e){if(e=Qe(e),e.length<4)throw new V(`Inputs to DepthwiseConv2D should have rank 4. Received input shape: ${JSON.stringify(e)}.`);let t=this.dataFormat==="channelsFirst"?1:3;if(e[t]==null||e[t]<0)throw new V(`The channel dimension of the inputs to DepthwiseConv2D should be defined, but is not (${e[t]}).`);let n=e[t],a=[this.kernelSize[0],this.kernelSize[1],n,this.depthMultiplier];this.depthwiseKernel=this.addWeight("depthwise_kernel",a,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 P(()=>{e=Ne(e);let n=EU(e,this.depthwiseKernel.read(),this.strides,this.padding,this.dataFormat,null);return this.useBias&&(n=Xa(n,this.bias.read(),this.dataFormat)),this.activation!=null&&(n=this.activation.apply(n)),n})}computeOutputShape(e){e=Qe(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],n=this.dataFormat==="channelsFirst"?e[3]:e[2],a=this.dataFormat==="channelsFirst"?e[1]*this.depthMultiplier:e[3]*this.depthMultiplier,r=Ga(t,this.kernelSize[0],this.padding,this.strides[0]),s=Ga(n,this.kernelSize[1],this.padding,this.strides[1]);return this.dataFormat==="channelsFirst"?[e[0],a,r,s]:[e[0],r,s,a]}getConfig(){let e=super.getConfig();return e.depthMultiplier=this.depthMultiplier,e.depthwiseInitializer=Ct(this.depthwiseInitializer),e.depthwiseRegularizer=pt(this.depthwiseRegularizer),e.depthwiseConstraint=qt(this.depthwiseRegularizer),e}};Ew.className="DepthwiseConv2D";ne.registerClass(Ew);function MN(e,t,n,a){if(Array.isArray(e)){if(t!=null||n!=null)throw new V("When inputs is an array, neither initialState or constants should be provided");a!=null&&(n=e.slice(e.length-a,e.length),e=e.slice(0,e.length-a)),e.length>1&&(t=e.slice(1,e.length)),e=e[0]}function r(s){return s==null||Array.isArray(s)?s:[s]}return t=r(t),n=r(n),{inputs:e,initialState:t,constants:n}}function PN(e,t,n,a=!1,r,s,i=!1,o=!1){return P(()=>{let l=t.shape.length;if(l<3)throw new V(`Input should be at least 3D, but is ${l}D.`);let u=[1,0].concat(Ha(2,l));if(t=Ee(t,u),s!=null)throw new Re("The rnn() functoin of the deeplearn.js backend does not support constants yet.");i&&console.warn("Backend rnn(): the unroll = true option is not applicable to the imperative deeplearn.js backend."),r!=null&&(r=oe(oe(r,"bool"),"float32"),r.rank===l-1&&(r=Zt(r,-1)),r=Ee(r,u)),a&&(t=fa(t,0),r!=null&&(r=fa(r,0)));let p=[],d,c=n,h=t.shape[0],m=ct(t),f;r!=null&&(f=ct(r));for(let y=0;ye(b,c));if(r==null)d=x[0],c=x[1];else{let w=P(()=>{let I=f[y],T=pe(ta(I),I),C=Y(z(x[0],I),z(c[0],T)),E=c.map((A,R)=>Y(z(x[1][R],I),z(A,T)));return{output:C,newStates:E}});d=w.output,c=w.newStates}o&&p.push(d)}let g;return o&&(g=Ft(p,1)),[d,g,c]})}var dr=class extends Ge{constructor(e){super(e);let t;if(e.cell==null)throw new V("cell property is missing for the constructor of RNN.");if(Array.isArray(e.cell)?t=new _f({cells:e.cell}):t=e.cell,t.stateSize==null)throw new V("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 zt({ndim:3})],this.stateSpec=null,this.states_=null,this.numConstants=null,this.keptStates=[]}getStates(){if(this.states_==null){let e=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;return Ha(0,e).map(t=>null)}else return this.states_}setStates(e){this.states_=e}computeOutputShape(e){Lb(e)&&(e=e[0]),e=e;let t=this.cell.stateSize;Array.isArray(t)||(t=[t]);let n=t[0],a;if(this.returnSequences?a=[e[0],e[1],n]:a=[e[0],n],this.returnState){let r=[];for(let s of t)r.push([e[0],s]);return[a].concat(r)}else return a}computeMask(e,t){return P(()=>{Array.isArray(t)&&(t=t[0]);let n=this.returnSequences?t:null;if(this.returnState){let a=this.states.map(r=>null);return[n].concat(a)}else return n})}get states(){if(this.states_==null){let e=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1,t=[];for(let n=0;ns.shape[s.shape.length-1]),r))throw new V(`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=r.map(s=>new zt({shape:[null,s]}));this.stateful&&this.resetStates()}resetStates(e,t=!1){P(()=>{if(!this.stateful)throw new vr("Cannot call resetStates() on an RNN Layer that is not stateful.");let n=this.inputSpec[0].shape[0];if(n==null)throw new V("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(a=>It([n,a])):this.states_=[It([n,this.cell.stateSize])];else if(e==null)_e(this.states_),this.keptStates!=null&&(_e(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(a=>It([n,a])):this.states_[0]=It([n,this.cell.stateSize]);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new V(`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()):_e(this.states_);for(let a=0;aJt(a.clone()))})}apply(e,t){let n=t==null?null:t.initialState,a=t==null?null:t.constants;t==null&&(t={});let r=MN(e,n,a,this.numConstants);e=r.inputs,n=r.initialState,a=r.constants;let s=[],i=[];if(n!=null){t.initialState=n,s=s.concat(n),this.stateSpec=[];for(let o of n)this.stateSpec.push(new zt({shape:o.shape}));i=i.concat(this.stateSpec)}if(a!=null&&(t.constants=a,s=s.concat(a),this.numConstants=a.length),s[0]instanceof Ba){let o=[e].concat(s),l=this.inputSpec.concat(i),u=this.inputSpec;this.inputSpec=l;let p=super.apply(o,t);return this.inputSpec=u,p}else return super.apply(e,t)}call(e,t){return P(()=>{let n=t==null?null:t.mask,a=t==null?null:t.training,r=t==null?null:t.initialState;e=Ne(e),r==null&&(this.stateful?r=this.states_:r=this.getInitialState(e));let s=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;if(r.length!==s)throw new V(`RNN Layer has ${s} state(s) but was passed ${r.length} initial state(s).`);this.unroll&&console.warn("Ignoring unroll = true for RNN layer, due to imperative backend.");let i={training:a},o=PN((c,h)=>{let m=this.cell.call([c].concat(h),i);return[m[0],m.slice(1)]},e,r,this.goBackwards,n,null,this.unroll,this.returnSequences),l=o[0],u=o[1],p=o[2];this.stateful&&this.resetStates(p,a);let d=this.returnSequences?u:l;return this.returnState?[d].concat(p):d})}getInitialState(e){return P(()=>{let t=It(e.shape);return t=fe(t,[1,2]),t=Uc(t),Array.isArray(this.cell.stateSize)?this.cell.stateSize.map(n=>n>1?Pb(t,[1,n]):t):this.cell.stateSize>1?[Pb(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(){let 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);let n=this.cell.getConfig();return this.getClassName()===dr.className&&(t.cell={className:this.cell.getClassName(),config:n}),Object.assign(Object.assign(Object.assign({},n),e),t)}static fromConfig(e,t,n={}){let a=t.cell,r=Ua(a,n);return new e(Object.assign(t,{cell:r}))}};dr.className="RNN";ne.registerClass(dr);var Zc=class extends Ge{},Nf=class extends Zc{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,Qt(this.units,"units"),this.activation=ss(e.activation==null?this.DEFAULT_ACTIVATION:e.activation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=St(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=St(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=St(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=Tt(e.kernelRegularizer),this.recurrentRegularizer=Tt(e.recurrentRegularizer),this.biasRegularizer=Tt(e.biasRegularizer),this.kernelConstraint=Kt(e.kernelConstraint),this.recurrentConstraint=Kt(e.recurrentConstraint),this.biasConstraint=Kt(e.biasConstraint),this.dropout=cl([1,as([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=cl([1,as([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=Qe(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 P(()=>{if(e=e,e.length!==2)throw new V(`SimpleRNNCell expects 2 input Tensors, got ${e.length}.`);let n=e[1];e=e[0];let a=t.training==null?!1:t.training;0ta(e),rate:this.dropout,training:a,dropoutFunc:this.dropoutFunc})),0ta(n),rate:this.recurrentDropout,training:a,dropoutFunc:this.dropoutFunc}));let r,s=this.dropoutMask,i=this.recurrentDropoutMask;s!=null?r=sr(z(e,s),this.kernel.read()):r=sr(e,this.kernel.read()),this.bias!=null&&(r=Xa(r,this.bias.read())),i!=null&&(n=z(n,i));let o=Y(r,sr(n,this.recurrentKernel.read()));return this.activation!=null&&(o=this.activation.apply(o)),[o,o]})}getConfig(){let e=super.getConfig(),t={units:this.units,activation:rs(this.activation),useBias:this.useBias,kernelInitializer:Ct(this.kernelInitializer),recurrentInitializer:Ct(this.recurrentInitializer),biasInitializer:Ct(this.biasInitializer),kernelRegularizer:pt(this.kernelRegularizer),recurrentRegularizer:pt(this.recurrentRegularizer),biasRegularizer:pt(this.biasRegularizer),activityRegularizer:pt(this.activityRegularizer),kernelConstraint:qt(this.kernelConstraint),recurrentConstraint:qt(this.recurrentConstraint),biasConstraint:qt(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout};return Object.assign(Object.assign({},e),t)}};Nf.className="SimpleRNNCell";ne.registerClass(Nf);var Aw=class extends dr{constructor(e){e.cell=new Nf(e),super(e)}call(e,t){return P(()=>{this.cell.dropoutMask!=null&&(_e(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(_e(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);let n=t==null?null:t.mask,a=t==null?null:t.training,r=t==null?null:t.initialState;return super.call(e,{mask:n,training:a,initialState:r})})}static fromConfig(e,t){return new e(t)}};Aw.className="SimpleRNN";ne.registerClass(Aw);var Cf=class extends Zc{constructor(e){if(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",e.resetAfter)throw new V("GRUCell does not support reset_after parameter set to true.");this.units=e.units,Qt(this.units,"units"),this.activation=ss(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=ss(e.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=St(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=St(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=St(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=Tt(e.kernelRegularizer),this.recurrentRegularizer=Tt(e.recurrentRegularizer),this.biasRegularizer=Tt(e.biasRegularizer),this.kernelConstraint=Kt(e.kernelConstraint),this.recurrentConstraint=Kt(e.recurrentConstraint),this.biasConstraint=Kt(e.biasConstraint),this.dropout=cl([1,as([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=cl([1,as([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.implementation=e.implementation,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=Qe(e);let 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 P(()=>{if(e=e,e.length!==2)throw new V(`GRUCell expects 2 input Tensors (inputs, h, c), got ${e.length}.`);let n=t.training==null?!1:t.training,a=e[1];e=e[0],0ta(e),rate:this.dropout,training:n,count:3,dropoutFunc:this.dropoutFunc})),0ta(a),rate:this.recurrentDropout,training:n,count:3,dropoutFunc:this.dropoutFunc}));let r=this.dropoutMask,s=this.recurrentDropoutMask,i,o,l;0{this.cell.dropoutMask!=null&&(_e(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(_e(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);let n=t==null?null:t.mask,a=t==null?null:t.training,r=t==null?null:t.initialState;return super.call(e,{mask:n,training:a,initialState:r})})}static fromConfig(e,t){return t.implmentation===0&&(t.implementation=1),new e(t)}};$w.className="GRU";ne.registerClass($w);var Jc=class extends Zc{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,Qt(this.units,"units"),this.activation=ss(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=ss(e.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=St(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=St(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=St(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.unitForgetBias=e.unitForgetBias,this.kernelRegularizer=Tt(e.kernelRegularizer),this.recurrentRegularizer=Tt(e.recurrentRegularizer),this.biasRegularizer=Tt(e.biasRegularizer),this.kernelConstraint=Kt(e.kernelConstraint),this.recurrentConstraint=Kt(e.recurrentConstraint),this.biasConstraint=Kt(e.biasConstraint),this.dropout=cl([1,as([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=cl([1,as([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.implementation=e.implementation,this.stateSize=[this.units,this.units],this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){var t;e=Qe(e);let 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 a;if(this.useBias){if(this.unitForgetBias){let r=this.biasInitializer,s=this.units;a=new(t=class extends Fa{apply(i,o){let l=r.apply([s]),u=new ff().apply([s]),p=r.apply([s*2]);return uk(uk(l,u),p)}},t.className="CustomInit",t)}else a=this.biasInitializer;this.bias=this.addWeight("bias",[this.units*4],null,a,this.biasRegularizer,!0,this.biasConstraint)}else this.bias=null;this.built=!0}call(e,t){return P(()=>{let n=t.training==null?!1:t.training;if(e=e,e.length!==3)throw new V(`LSTMCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);let a=e[1],r=e[2];e=e[0],0ta(e),rate:this.dropout,training:n,count:4,dropoutFunc:this.dropoutFunc})),0ta(a),rate:this.recurrentDropout,training:n,count:4,dropoutFunc:this.dropoutFunc}));let s=this.dropoutMask,i=this.recurrentDropoutMask,o,l,u,p;0{this.cell.dropoutMask!=null&&(_e(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(_e(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);let n=t==null?null:t.mask,a=t==null?null:t.training,r=t==null?null:t.initialState;return super.call(e,{mask:n,training:a,initialState:r})})}static fromConfig(e,t){return t.implmentation===0&&(t.implementation=1),new e(t)}};Fw.className="LSTM";ne.registerClass(Fw);var _f=class extends Zc{constructor(e){super(e),this.cells=e.cells}get stateSize(){let e=[];for(let t of this.cells.slice().reverse())Array.isArray(t.stateSize)?e.push(...t.stateSize):e.push(t.stateSize);return e}call(e,t){return P(()=>{e=e;let n=e.slice(1),a=[];for(let i of this.cells.slice().reverse())Array.isArray(i.stateSize)?a.push(n.splice(0,i.stateSize.length)):a.push(n.splice(0,1));a.reverse();let r=[],s;for(let i=0;i{Xs(`RNNCell_${a}`,()=>{n.build(e),Array.isArray(n.stateSize)?t=n.stateSize[0]:t=n.stateSize,e=[e[0],t]})}),this.built=!0}getConfig(){let e=super.getConfig(),t=a=>({className:a.getClassName(),config:a.getConfig()}),n={cells:this.cells.map(t)};return Object.assign(Object.assign({},e),n)}static fromConfig(e,t,n={}){let a=[];for(let r of t.cells)a.push(Ua(r,n));return new e({cells:a})}get trainableWeights(){if(!this.trainable)return[];let e=[];for(let t of this.cells)e.push(...t.trainableWeights);return e}get nonTrainableWeights(){let e=[];for(let t of this.cells)e.push(...t.nonTrainableWeights);if(!this.trainable){let t=[];for(let n of this.cells)t.push(...n.trainableWeights);return t.concat(e)}return e}getWeights(){let e=[];for(let t of this.cells)e.push(...t.weights);return zb(e)}setWeights(e){let t=[];for(let n of this.cells){let a=n.weights.length,r=e.splice(a);for(let s=0;ss!=null?s(t(),n):KT(t(),n),o=()=>Hc(i,t,a);return!r||r<=1?Jt(o().clone()):Array(r).fill(void 0).map(o).map(l=>Jt(l.clone()))}var AU=function(e,t){var n={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&t.indexOf(a)<0&&(n[a]=e[a]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,a=Object.getOwnPropertySymbols(e);r{if(this.cell.dropoutMask!=null&&(_e(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(_e(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null),t&&t.constants)throw new V("ConvRNN2D cell does not support constants");let n=t==null?null:t.mask,a=t==null?null:t.training,r=t==null?null:t.initialState;return super.call(e,{mask:n,training:a,initialState:r})})}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 P(()=>{let{stateSize:t}=this.cell,n=e.shape,a=this.computeSingleOutputShape(n),r=[a[0],...a.slice(2)],s=It(r);return Array.isArray(t)?Array(t.length).fill(s):[s]})}resetStates(e,t=!1){P(()=>{if(!this.stateful)throw new vr("Cannot call resetStates() on an RNN Layer that is not stateful.");let n=this.inputSpec[0].shape,a=this.computeSingleOutputShape(n),r=[a[0],...a.slice(2)];if(n[0]==null)throw new V("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(()=>It(r)):this.states_=[It(r)];else if(e==null)_e(this.states_),this.keptStates!=null&&(_e(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(()=>It(r)):this.states_[0]=It(r);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new V(`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()):_e(this.states_);for(let s=0;sJt(s.clone()))})}computeSingleOutputShape(e){let{dataFormat:t,filters:n,kernelSize:a,padding:r,strides:s,dilationRate:i}=this.cell,o=t==="channelsFirst",l=e[o?3:2],u=e[o?4:3],p=Ga(l,a[0],r,s[0],i[0]),d=Ga(u,a[1],r,s[1],i[1]);return[...e.slice(0,2),...o?[n,p,d]:[p,d,n]]}};ON.className="ConvRNN2D";var Ef=class extends Jc{constructor(e){let{filters:t,kernelSize:n,strides:a,padding:r,dataFormat:s,dilationRate:i}=e;super(Object.assign(Object.assign({},e),{units:t})),this.filters=t,Qt(this.filters,"filters"),this.kernelSize=el(n,2,"kernelSize"),this.kernelSize.forEach(o=>Qt(o,"kernelSize")),this.strides=el(a||1,2,"strides"),this.strides.forEach(o=>Qt(o,"strides")),this.padding=r||"valid",ba(this.padding),this.dataFormat=s||"channelsLast",Rt(this.dataFormat),this.dilationRate=el(i||1,2,"dilationRate"),this.dilationRate.forEach(o=>Qt(o,"dilationRate"))}build(e){var t;e=Qe(e);let n=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[n]==null)throw new V(`The channel dimension of the input should be defined. Found ${e[n]}`);let a=e[n],r=4,s=this.kernelSize.concat([a,this.filters*r]);this.kernel=this.addWeight("kernel",s,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint);let i=this.kernelSize.concat([this.filters,this.filters*r]);if(this.recurrentKernel=this.addWeight("recurrent_kernel",i,null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias){let o;if(this.unitForgetBias){let l=this.biasInitializer,u=this.filters;o=new(t=class extends Fa{apply(p,d){let c=l.apply([u]),h=Zn([u]),m=l.apply([u*2]);return Kv([c,h,m])}},t.className="CustomInit",t)}else o=this.biasInitializer;this.bias=this.addWeight("bias",[this.filters*r],null,o,this.biasRegularizer,!0,this.biasConstraint)}this.built=!0}call(e,t){return P(()=>{if(e.length!==3)throw new V(`ConvLSTM2DCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);let n=t.training||!1,a=e[0],r=e[1],s=e[2],i=4;0ta(a),rate:this.dropout,training:n,count:i,dropoutFunc:this.dropoutFunc}));let o=this.dropoutMask,l=(Z,Q,ee)=>!Q||!Q[ee]?Z:z(Q[ee],Z),u=l(a,o,0),p=l(a,o,1),d=l(a,o,2),c=l(a,o,3);0ta(r),rate:this.recurrentDropout,training:n,count:i,dropoutFunc:this.dropoutFunc}));let h=this.recurrentDropoutMask,m=l(r,h,0),f=l(r,h,1),g=l(r,h,2),y=l(r,h,3),b=3,[x,w,I,T]=zn(this.kernel.read(),i,b),[C,E,A,R]=this.useBias?zn(this.bias.read(),i):[null,null,null,null];u=this.inputConv(u,x,C,this.padding),p=this.inputConv(p,w,E,this.padding),d=this.inputConv(d,I,A,this.padding),c=this.inputConv(c,T,R,this.padding);let[F,S,M,B]=zn(this.recurrentKernel.read(),i,b);m=this.recurrentConv(m,F),f=this.recurrentConv(f,S),g=this.recurrentConv(g,M),y=this.recurrentConv(y,B);let U=this.recurrentActivation.apply(Y(u,m)),G=this.recurrentActivation.apply(Y(p,f)),q=Y(z(G,s),z(U,this.activation.apply(Y(d,g)))),K=z(this.recurrentActivation.apply(Y(c,y)),this.activation.apply(q));return[K,K,q]})}getConfig(){let e=super.getConfig(),{units:t}=e,n=AU(e,["units"]),a={filters:this.filters,kernelSize:this.kernelSize,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,strides:this.strides};return Object.assign(Object.assign({},n),a)}inputConv(e,t,n,a){let r=$t(e,t,this.strides,a||"valid",this.dataFormat==="channelsFirst"?"NCHW":"NHWC",this.dilationRate);return n?Xa(r,n,this.dataFormat):r}recurrentConv(e,t){return $t(e,t,1,"same",this.dataFormat==="channelsFirst"?"NCHW":"NHWC")}};Ef.className="ConvLSTM2DCell";ne.registerClass(Ef);var Dw=class extends ON{constructor(e){let t=new Ef(e);super(Object.assign(Object.assign({},e),{cell:t}))}static fromConfig(e,t){return new e(t)}};Dw.className="ConvLSTM2D";ne.registerClass(Dw);var Af=class extends Ge{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;let t=e.shape,n=[];for(let a=0;a{this.invokeCallHook(e,t);let n=Ne(e);if(0KT(n,this.rate,r,this.seed),()=>n,a)}return e})}getConfig(){let e={rate:this.rate,noiseShape:this.noiseShape,seed:this.seed},t=super.getConfig();return Object.assign(e,t),e}dispose(){return super.dispose()}};Af.className="Dropout";ne.registerClass(Af);var Rw=class extends Af{constructor(e){super(e),this.inputSpec=[{ndim:3}]}getNoiseShape(e){let t=e.shape;return[t[0],1,t[2]]}};Rw.className="SpatialDropout1D";ne.registerClass(Rw);var Mw=class extends Ge{constructor(e){if(super(e),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,Qt(this.units,"units"),this.activation=ss(e.activation),e.useBias!=null&&(this.useBias=e.useBias),this.kernelInitializer=St(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.biasInitializer=St(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelConstraint=Kt(e.kernelConstraint),this.biasConstraint=Kt(e.biasConstraint),this.kernelRegularizer=Tt(e.kernelRegularizer),this.biasRegularizer=Tt(e.biasRegularizer),this.activityRegularizer=Tt(e.activityRegularizer),this.supportsMasking=!0,this.inputSpec=[{minNDim:2}]}build(e){e=Qe(e);let 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=Qe(e);let t=e.slice();return t[t.length-1]=this.units,t}call(e,t){return P(()=>{this.invokeCallHook(e,t);let n=Ne(e),a=BT(this.activation.getClassName()),r;return a!=null?r=sr(n,this.kernel.read(),a,this.bias?this.bias.read():null):(r=sr(n,this.kernel.read()),this.bias!=null&&(r=Xa(r,this.bias.read())),this.activation!=null&&(r=this.activation.apply(r))),r})}getConfig(){let e={units:this.units,activation:rs(this.activation),useBias:this.useBias,kernelInitializer:Ct(this.kernelInitializer),biasInitializer:Ct(this.biasInitializer),kernelRegularizer:pt(this.kernelRegularizer),biasRegularizer:pt(this.biasRegularizer),activityRegularizer:pt(this.activityRegularizer),kernelConstraint:qt(this.kernelConstraint),biasConstraint:qt(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}};Mw.className="Dense";ne.registerClass(Mw);var Pw=class extends Ge{constructor(e){e=e||{},super(e),this.inputSpec=[{minNDim:3}],this.dataFormat=e.dataFormat}computeOutputShape(e){e=Qe(e);for(let t of e.slice(1))if(t==null)throw new V(`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],Qr(e,1)]}call(e,t){return P(()=>{this.invokeCallHook(e,t);let n=Ne(e);if(this.dataFormat==="channelsFirst"&&n.rank>1){let a=[0];for(let r=2;r{this.invokeCallHook(e,t);let n=Ne(e);return this.activation.apply(n)})}getConfig(){let e={activation:rs(this.activation)},t=super.getConfig();return Object.assign(e,t),e}};Ow.className="Activation";ne.registerClass(Ow);var Lw=class extends Ge{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 P(()=>(e=Ne(e),U4(e,this.n)))}getConfig(){let e={n:this.n},t=super.getConfig();return Object.assign(e,t),e}};Lw.className="RepeatVector";ne.registerClass(Lw);var zw=class extends Ge{constructor(e){super(e),this.targetShape=e.targetShape;for(let t=0;t{this.invokeCallHook(e,t);let n=Ne(e),a=n.shape,r=a.slice(0,1).concat(this.fixUnknownDimension(a.slice(1),this.targetShape));return W(n,r)})}getConfig(){let e={targetShape:this.targetShape},t=super.getConfig();return Object.assign(e,t),e}};zw.className="Reshape";ne.registerClass(zw);var Ww=class extends Ge{constructor(e){if(super(e),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.`);let t=Ha(1,e.dims.length+1);if(!v.arraysEqual(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 zt({ndim:this.dims.length+1})]}computeOutputShape(e){e=Qe(e);let t=e.slice();return this.dims.forEach((n,a)=>{t[a+1]=e[n]}),t}call(e,t){return Ee(Ne(e),this.dimsIncludingBatch)}getConfig(){let e={dims:this.dims},t=super.getConfig();return Object.assign(e,t),e}};Ww.className="Permute";ne.registerClass(Ww);var Bw=class extends Ge{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(){let e=super.getConfig(),t={maskValue:this.maskValue};return Object.assign(t,e),t}computeMask(e,t){let n=Ne(e),a=-1;return qp(ii(n,this.maskValue),a)}call(e,t){return P(()=>{this.invokeCallHook(e,t);let n=Ne(e),a=-1,r=!0,s=qp(ii(n,this.maskValue),a,r);return z(n,oe(s,n.dtype))})}};Bw.className="Masking";ne.registerClass(Bw);var Vw=class extends Ge{constructor(e){if(super(e),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(yt(e.inputLength))}this.inputDim=e.inputDim,Qt(this.inputDim,"inputDim"),this.outputDim=e.outputDim,Qt(this.outputDim,"outputDim"),this.embeddingsInitializer=St(e.embeddingsInitializer||this.DEFAULT_EMBEDDINGS_INITIALIZER),this.embeddingsRegularizer=Tt(e.embeddingsRegularizer),this.activityRegularizer=Tt(e.activityRegularizer),this.embeddingsConstraint=Kt(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 P(()=>this.maskZero?(e=Ne(e),ii(e,qe(e))):null)}computeOutputShape(e){if(e=Qe(e),this.inputLength==null)return[...e,this.outputDim];let t=yt(this.inputLength);if(t.length!==e.length-1)throw new V(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);{let n=0;for(let a=0;a{this.invokeCallHook(e,t);let n=Ne(e);n.dtype!=="int32"&&(n=yo(n,"int32"));let a=qT(this.embeddings.read(),W(n,[n.size]));return W(a,Qe(this.computeOutputShape(n.shape)))})}getConfig(){let e={inputDim:this.inputDim,outputDim:this.outputDim,embeddingsInitializer:Ct(this.embeddingsInitializer),embeddingsRegularizer:pt(this.embeddingsRegularizer),activityRegularizer:pt(this.activityRegularizer),embeddingsConstraint:qt(this.embeddingsConstraint),maskZero:this.maskZero,inputLength:this.inputLength},t=super.getConfig();return Object.assign(e,t),e}};Vw.className="Embedding";ne.registerClass(Vw);var xo=class extends Ge{constructor(e){super(e||{}),this.supportsMasking=!0}mergeFunction(e){throw new Re}computeElementwiseOpOutputShape(e,t){if(e==null||t==null)return null;if(e.length1)throw new V(`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 r=1;rr.length);e.indexOf(null)===-1&&Jr(a).length===1?this.reshapeRequired=!1:this.reshapeRequired=!0}call(e,t){return P(()=>{if(e=e,this.reshapeRequired){let n=[],a=e.map(r=>r.rank);if(a.indexOf(null)===-1){let r=as(a);for(let s of e){let i=s.rank;for(let o=0;o1){let u=Ha(1,l).concat([0]);n.push(Ee(o,u)),r=!0}else n.push(o)}let s=this.mergeFunction(n),i=s.rank;if(r){if(i==null){let o=s.shape,l=o.length,u=o[l-1],p=[u].concat(o.slice(0,o.length-1));s=W(Ee(W(s,[-1,u]),[1,0]),p)}else if(i>1){let o=[i-1].concat(Ha(0,i-1));s=Ee(s,o)}}return s}}else return this.mergeFunction(e)})}computeOutputShape(e){e=e;let t;e[0]==null?t=null:t=e[0].slice(1);for(let a=1;a{if(t==null)return null;if(!Array.isArray(t))throw new V("`mask` should be an Array");if(!Array.isArray(e))throw new V("`inputs` should be an Array");if(t.length!==e.length)throw new V(`The Array 'inputs' and 'mask' are expected to have the same length, but have different lengths (${e.length} vs ${t.length})`);if(t.every(a=>a==null))return null;t=t.map(a=>a==null?a:Zt(a,0));let n=t[0];for(let a=1;a{let t=e[0].clone();for(let n=1;n{let t=e[0].clone();for(let n=1;n{let t=e[0].clone();for(let n=1;n{let t=e[0];for(let n=1;n{let t=e[0];for(let n=1;n1)throw new V("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(e))}mergeFunction(e){return P(()=>Kv(e,this.axis))}computeOutputShape(e){if(!(Array.isArray(e)&&Array.isArray(e[0])))throw new V("A `Concatenate` layer should be called on a list of inputs.");let t=e,n=t[0].slice(),a=this.axis<0?n.length+this.axis:this.axis;for(let r of t.slice(1)){if(n[a]==null||r[a]==null){n[a]=null;break}n[a]+=r[a]}return n}computeMask(e,t){if(t==null)return null;if(!Array.isArray(t))throw new V("`mask` should be an array for Concatenate");if(!Array.isArray(e))throw new V("`inputs` should be an array for Concatenate");if(t.length!==e.length)throw new V(`Mismatch in the length of mask (${t.length}) and the legnth of inputs (${e.length})`);return P(()=>{let n=!0;if(t.forEach(s=>{if(s!=null){n=!1;return}}),n)return null;let a=[];for(let s=0;s3||t.shape.length>3)throw new Re("batchDot is not implemented for tensors of 4D or higher rank yet");if(v.assert(e.shape.length>=2,()=>`batchDot requires the rank of x to be >= 2, but got ${e.shape.length}`),v.assert(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 Re("batchDot is not implemented for complex64-type Tensors yet.");let a=e.shape.length,r=t.shape.length;n==null&&(n=[a-1,r-2]);let s=n;return P(()=>{let i;if(a>r){i=a-r;let l=[];for(let u=0;ua){i=r-a;let l=[];for(let u=0;u0){let l;a>r?l=a+r-3:l=a-1;let u=[];for(let p=l;p"A `Dot` layer should be called on a list of exactly 2 inputs.");let t=e[0],n=e[1];if(t.length>3||n.length>3)throw new Re("Dot layer does not support tensors of 4D or higher rank yet.");let a=this.interpretAxes(t,n);if(t[a[0]]!==n[a[1]])throw new V(`Dimension incompatibility: ${t[a[0]]} !== ${n[a[1]]}`)}mergeFunction(e){if(e.length!==2)throw new V(`A \`Dot\` layer must be called on exactly 2 inputs, but received ${e.length} input(s).`);let t=e[0],n=e[1],a;return Array.isArray(this.axes)?a=this.axes.map((r,s)=>Sp(r,e[s].shape.length)):a=[Sp(this.axes,t.shape.length),Sp(this.axes,n.shape.length)],this.normalize&&(t=Eh(t,a[0]),n=Eh(n,a[1])),$U(t,n,a)}interpretAxes(e,t){let n;return Array.isArray(this.axes)?n=this.axes:n=[Sp(this.axes,e.length),Sp(this.axes,t.length)],n}computeOutputShape(e){v.assert(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.");let t=e[0].slice(),n=e[1].slice();if(t.length>3||n.length>3)throw new Re("Dot layer does not support tensors of 4D or higher rank yet.");let a=this.interpretAxes(t,n);t.splice(a[0],1),n.splice(a[1],1),n.splice(0,1);let r=t.concat(n);return r.length===1&&r.push(1),r}computeMask(e,t){return null}getConfig(){let e={axes:this.axes,normalize:this.normalize},t=super.getConfig();return Object.assign(e,t),e}};Xw.className="Dot";ne.registerClass(Xw);var Yw=class extends Ge{constructor(e){super(e),this.supportsMasking=!0,this.stddev=e.stddev}computeOutputShape(e){return e}getConfig(){let e=super.getConfig(),t={stddev:this.stddev};return Object.assign(t,e),t}call(e,t){return P(()=>{this.invokeCallHook(e,t);let n=Ne(e);return Hc(()=>Y(mf(n.shape,0,this.stddev),n),()=>n,t.training||!1)})}};Yw.className="GaussianNoise";ne.registerClass(Yw);var Zw=class extends Ge{constructor(e){super(e),this.supportsMasking=!0,this.rate=e.rate}computeOutputShape(e){return e}getConfig(){let e=super.getConfig(),t={rate:this.rate};return Object.assign(t,e),t}call(e,t){return P(()=>{this.invokeCallHook(e,t);let n=Ne(e);return this.rate>0&&this.rate<1?Hc(()=>{let a=Math.sqrt(this.rate/(1-this.rate));return z(n,mf(n.shape,1,a))},()=>n,t.training||!1):n})}};Zw.className="GaussianDropout";ne.registerClass(Zw);var Jw=class extends Ge{constructor(e){super(e),this.supportsMasking=!0,this.rate=e.rate,this.noiseShape=e.noiseShape}_getNoiseShape(e){return this.noiseShape||Ne(e).shape}computeOutputShape(e){return e}getConfig(){let e=super.getConfig(),t={rate:this.rate};return Object.assign(t,e),t}call(e,t){return P(()=>{if(this.rate<1&&this.rate>0){let n=this._getNoiseShape(e);return Hc(()=>{let a=Ne(e),r=1.6732632423543772,s=1.0507009873554805,i=-r*s,o=Er($u(n),this.rate);o=yo(o,"float32");let l=((1-this.rate)*(1+this.rate*i**2))**-.5,u=-l*i*this.rate,p=Y(z(a,o),z(Y(o,-1),i));return Y(z(p,l),u)},()=>Ne(e),t.training||!1)}return e})}};Jw.className="AlphaDropout";ne.registerClass(Jw);function Zp(e,t,n,a,r,s=.001){let i;if(e.rank===2)i=Zx(e,t,n,a,r,s);else if(e.rank===3)i=Jx(e,t,n,a,r,s);else if(e.rank===4)i=Qx(e,t,n,a,r,s);else throw new Re(`batchNormalization is not implemented for array of rank ${e.rank} yet`);return i}function FU(e,t,n,a,r=.001){return P(()=>{let s=Mc(e,a),i=s.mean,o=s.variance;return[Zp(e,i,o,n,t,r),i,o]})}function DU(e,t,n,a,r=.001){return P(()=>{let s=Mc(e,a),i=s.mean,o=s.variance,l=[];for(let h of Ha(0,e.rank))a.indexOf(h)!==-1?l.push(1):l.push(e.shape[h]);let u=W(i,l),p=W(o,l),d=t==null?null:W(t,l),c=n==null?null:W(n,l);return[Zp(e,u,p,c,d,r),i,o]})}function RU(e,t,n,a,r=.001){return v.arraysEqual(a.slice().sort(),Ha(0,e.rank-1))?FU(e,t,n,a,r):DU(e,t,n,a,r)}var Qw=class extends Ge{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=St(e.betaInitializer||"zeros"),this.gammaInitializer=St(e.gammaInitializer||"ones"),this.movingMeanInitializer=St(e.movingMeanInitializer||"zeros"),this.movingVarianceInitializer=St(e.movingVarianceInitializer||"ones"),this.betaConstraint=Kt(e.betaConstraint),this.gammaConstraint=Kt(e.gammaConstraint),this.betaRegularizer=Tt(e.betaRegularizer),this.gammaRegularizer=Tt(e.gammaRegularizer)}build(e){e=Qe(e);let t=this.axis>=0?this.axis:this.axis+e.length,n=e[t];if(n==null)throw new V(`Axis ${t} of input tensor should have a defined dimension but the layer received an input with shape ${JSON.stringify(e)}.`);this.inputSpec=[new zt({ndim:e.length,axes:{[t]:n}})];let a=[n];this.scale&&(this.gamma=this.addWeight("gamma",a,null,this.gammaInitializer,this.gammaRegularizer,!0,this.gammaConstraint)),this.center&&(this.beta=this.addWeight("beta",a,null,this.betaInitializer,this.betaRegularizer,!0,this.betaConstraint)),this.movingMean=this.addWeight("moving_mean",a,null,this.movingMeanInitializer,null,!1),this.movingVariance=this.addWeight("moving_variance",a,null,this.movingVarianceInitializer,null,!1),this.built=!0}call(e,t){return P(()=>{let n=t.training==null?!1:t.training,a=Ne(e),r=a.shape,s=r.length,i=Ha(0,s),o=this.axis>=0?this.axis:this.axis+s;i.splice(o,1);let l=oi(1,s);l[o]=r[o];let u=i.slice();u.sort();let p=!v.arraysEqual(u,Ha(0,s).slice(0,s-1)),d=()=>{if(p){let g=W(this.movingMean.read(),l),y=W(this.movingVariance.read(),l),b=this.center?W(this.beta.read(),l):null,x=this.scale?W(this.gamma.read(),l):null;return Zp(a,g,y,b,x,this.epsilon)}else return Zp(a,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 d();let[c,h,m]=RU(a,this.gamma.read(),this.beta.read(),i,this.epsilon),f=(g,y,b)=>{P(()=>{let x=1-b,w=g.read(),I=z(pe(w,y),x);g.write(pe(w,I))})};return f(this.movingMean,h,this.momentum),f(this.movingVariance,m,this.momentum),c})}getConfig(){let e={axis:this.axis,momentum:this.momentum,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:Ct(this.betaInitializer),gammaInitializer:Ct(this.gammaInitializer),movingMeanInitializer:Ct(this.movingMeanInitializer),movingVarianceInitializer:Ct(this.movingVarianceInitializer),betaRegularizer:pt(this.betaRegularizer),gammaRegularizer:pt(this.gammaRegularizer),betaConstraint:qt(this.betaConstraint),gammaConstraint:qt(this.gammaConstraint)},t=super.getConfig();return Object.assign(e,t),e}};Qw.className="BatchNormalization";ne.registerClass(Qw);var e0=class extends Ge{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(let 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=St(e.betaInitializer||"zeros"),this.gammaInitializer=St(e.gammaInitializer||"ones"),this.betaRegularizer=Tt(e.betaRegularizer),this.gammaRegularizer=Tt(e.gammaRegularizer),this.supportsMasking=!0}build(e){e=Qe(e);let t=e.length;typeof this.axis=="number"&&(this.axis=[this.axis]);for(let r=0;r=t)throw new Error(`Invalid axis: ${r}`);if(this.axis.length!==Jr(this.axis).length)throw new Error(`Found duplicate axes in: ${this.axis}`);let n=this.axis.map(r=>e[r]),a=!0;this.scale?this.gamma=this.addWeight("gamma",n,"float32",this.gammaInitializer,this.gammaRegularizer,a):this.gamma=null,this.center?this.beta=this.addWeight("beta",n,"float32",this.betaInitializer,this.betaRegularizer,a):this.beta=null,this.built=!0}call(e,t){let n=Ne(e),a=n.shape,r=a.length;return P(()=>{let{mean:s,variance:i}=Mc(n,this.axis,!0),o=oi(1,r);for(let h of this.axis)o[h]=a[h];let l=h=>h!=null&&h.shape.length!==r?W(h,o):h,u=this.scale?l(this.gamma.read()):null,p=this.center?l(this.beta.read()):null,d=[],c=[];for(let h=0;h{if(e.rank!==4)throw new V(`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 V("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");if(n==null&&(n=ja()),n!=="channelsLast"&&n!=="channelsFirst")throw new V(`Unknown data format: ${n}. Supported data formats are 'channelsLast' and 'channelsFirst.`);let a;return n==="channelsFirst"?a=[[0,0],[0,0],t[0],t[1]]:a=[[0,0],t[0],t[1],[0,0]],ya(e,a)})}var t0=class extends Ge{constructor(e){if(e==null&&(e={}),super(e),this.dataFormat=e.dataFormat==null?ja():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 V(`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 V(`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 V(`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 zt({ndim:4})]}computeOutputShape(e){e=Qe(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 P(()=>MU(Ne(e),this.padding,this.dataFormat))}getConfig(){let e={padding:this.padding,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}};t0.className="ZeroPadding2D";ne.registerClass(t0);function $f(e,t,n,a,r,s){return P(()=>{Rt(r),UT(s),ba(a),n==null&&(n=[1,1]),a==null&&(a="valid"),r==null&&(r=ja()),s==null&&(s="max"),e=kw(e,r);let i,o=a==="same"?"same":"valid";return s==="max"?i=Dt(e,t,n,o):i=ga(e,t,n,o),r==="channelsFirst"&&(i=Ee(i,[0,3,1,2])),i})}function LN(e,t,n,a,r,s){return P(()=>{Rt(r),UT(s),ba(a),n==null&&(n=[1,1,1]),a==null&&(a="valid"),r==null&&(r=ja()),s==null&&(s="max"),e=DN(e,r);let i,o=a==="same"?"same":"valid";return s==="max"?i=Sv(e,t,n,o):i=Yx(e,t,n,o),r==="channelsFirst"&&(i=Ee(i,[0,4,1,2,3])),i})}var zN=class extends Ge{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 V(`poolSize for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.poolSize)}`);if(Qt(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 V(`strides for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.strides)}`);Qt(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,ba(this.padding),this.inputSpec=[new zt({ndim:3})]}computeOutputShape(e){e=Qe(e);let t=Ga(e[1],this.poolSize[0],this.padding,this.strides[0]);return[e[0],t,e[2]]}call(e,t){return P(()=>{this.invokeCallHook(e,t),e=Uc(Ne(e),2);let n=this.poolingFunction(Ne(e),[this.poolSize[0],1],[this.strides[0],1],this.padding,"channelsLast");return ws(n,[2])})}getConfig(){let e={poolSize:this.poolSize,padding:this.padding,strides:this.strides},t=super.getConfig();return Object.assign(e,t),e}},n0=class extends zN{constructor(e){super(e)}poolingFunction(e,t,n,a,r){return Rt(r),ba(a),$f(e,t,n,a,r,"max")}};n0.className="MaxPooling1D";ne.registerClass(n0);var a0=class extends zN{constructor(e){super(e)}poolingFunction(e,t,n,a,r){return Rt(r),ba(a),$f(e,t,n,a,r,"avg")}};a0.className="AveragePooling1D";ne.registerClass(a0);var WN=class extends Ge{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 V(`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];Qt(this.poolSize,"poolSize"),Qt(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Rt(this.dataFormat),ba(this.padding),this.inputSpec=[new zt({ndim:4})]}computeOutputShape(e){e=Qe(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],n=this.dataFormat==="channelsFirst"?e[3]:e[2];return t=Ga(t,this.poolSize[0],this.padding,this.strides[0]),n=Ga(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 P(()=>(this.invokeCallHook(e,t),this.poolingFunction(Ne(e),this.poolSize,this.strides,this.padding,this.dataFormat)))}getConfig(){let e={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}},r0=class extends WN{constructor(e){super(e)}poolingFunction(e,t,n,a,r){return Rt(r),ba(a),$f(e,t,n,a,r,"max")}};r0.className="MaxPooling2D";ne.registerClass(r0);var s0=class extends WN{constructor(e){super(e)}poolingFunction(e,t,n,a,r){return Rt(r),ba(a),$f(e,t,n,a,r,"avg")}};s0.className="AveragePooling2D";ne.registerClass(s0);var BN=class extends Ge{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 V(`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];Qt(this.poolSize,"poolSize"),Qt(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Rt(this.dataFormat),ba(this.padding),this.inputSpec=[new zt({ndim:5})]}computeOutputShape(e){e=Qe(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],n=this.dataFormat==="channelsFirst"?e[3]:e[2],a=this.dataFormat==="channelsFirst"?e[4]:e[3];return t=Ga(t,this.poolSize[0],this.padding,this.strides[0]),n=Ga(n,this.poolSize[1],this.padding,this.strides[1]),a=Ga(a,this.poolSize[2],this.padding,this.strides[2]),this.dataFormat==="channelsFirst"?[e[0],e[1],t,n,a]:[e[0],t,n,a,e[4]]}call(e,t){return P(()=>(this.invokeCallHook(e,t),this.poolingFunction(Ne(e),this.poolSize,this.strides,this.padding,this.dataFormat)))}getConfig(){let e={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}},i0=class extends BN{constructor(e){super(e)}poolingFunction(e,t,n,a,r){return Rt(r),ba(a),LN(e,t,n,a,r,"max")}};i0.className="MaxPooling3D";ne.registerClass(i0);var o0=class extends BN{constructor(e){super(e)}poolingFunction(e,t,n,a,r){return Rt(r),ba(a),LN(e,t,n,a,r,"avg")}};o0.className="AveragePooling3D";ne.registerClass(o0);var VN=class extends Ge{constructor(e){super(e),this.inputSpec=[new zt({ndim:3})]}computeOutputShape(e){return[e[0],e[2]]}call(e,t){throw new Re}},l0=class extends VN{constructor(e){super(e||{})}call(e,t){return P(()=>{let n=Ne(e);return Nt(n,1)})}};l0.className="GlobalAveragePooling1D";ne.registerClass(l0);var u0=class extends VN{constructor(e){super(e||{})}call(e,t){return P(()=>{let n=Ne(e);return ha(n,1)})}};u0.className="GlobalMaxPooling1D";ne.registerClass(u0);var UN=class extends Ge{constructor(e){super(e),this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Rt(this.dataFormat),this.inputSpec=[new zt({ndim:4})]}computeOutputShape(e){return e=e,this.dataFormat==="channelsLast"?[e[0],e[3]]:[e[0],e[1]]}call(e,t){throw new Re}getConfig(){let e={dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}},p0=class extends UN{call(e,t){return P(()=>{let n=Ne(e);return this.dataFormat==="channelsLast"?Nt(n,[1,2]):Nt(n,[2,3])})}};p0.className="GlobalAveragePooling2D";ne.registerClass(p0);var c0=class extends UN{call(e,t){return P(()=>{let n=Ne(e);return this.dataFormat==="channelsLast"?ha(n,[1,2]):ha(n,[2,3])})}};c0.className="GlobalMaxPooling2D";ne.registerClass(c0);var GN=class extends Ge{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(){let 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={}){let a=t.layer,r=Ua(a,n);delete t.layer;let s={layer:r};return Object.assign(s,t),new e(s)}},d0=class extends GN{constructor(e){super(e),this.supportsMasking=!0}build(e){if(e=Qe(e),e.length<3)throw new V(`TimeDistributed layer expects an input shape >= 3D, but received input shape ${JSON.stringify(e)}`);this.inputSpec=[{shape:e}];let t=[e[0]].concat(e.slice(2));this.layer.built||(this.layer.build(t),this.layer.built=!0),super.build(e)}computeOutputShape(e){e=Qe(e);let t=[e[0]].concat(e.slice(2)),n=this.layer.computeOutputShape(t),a=e[1];return[n[0],a].concat(n.slice(1))}call(e,t){return P(()=>(e=Ne(e),PN((n,a)=>[Ne(this.layer.call(n,t)),[]],e,[],!1,null,null,!1,!0)[1]))}};d0.className="TimeDistributed";ne.registerClass(d0);function PU(e){go(L4,"BidirectionalMergeMode",e)}var OU="concat",h0=class extends GN{constructor(e){super(e);let t=e.layer.getConfig(),n={};n.className=e.layer.getClassName(),n.config=t,this.forwardLayer=Ua(n),t.goBackwards=t.goBackwards!==!0;let a={};if(a.className=e.layer.getClassName(),a.config=t,this.backwardLayer=Ua(a),this.forwardLayer.name="forward_"+this.forwardLayer.name,this.backwardLayer.name="backward_"+this.backwardLayer.name,this.mergeMode=e.mergeMode===void 0?OU:e.mergeMode,PU(this.mergeMode),e.weights)throw new Re("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){let 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,a,r;return this.returnState&&(r=t.slice(1)),n=t[0],n=n,this.mergeMode==="concat"?(n[n.length-1]*=2,a=[n]):this.mergeMode==null?a=[n,n.slice()]:a=[n],this.returnState?this.mergeMode==null?a.concat(r).concat(r.slice()):[n].concat(r).concat(r.slice()):On(a)}apply(e,t){let n=t==null?null:t.initialState,a=t==null?null:t.constants;t==null&&(t={});let r=MN(e,n,a,this.numConstants);if(e=r.inputs,n=r.initialState,a=r.constants,Array.isArray(e)&&(n=e.slice(1),e=e[0]),(n==null||n.length===0)&&a==null)return super.apply(e,t);let s=[],i=[];if(n!=null){let l=n.length;if(l%2>0)throw new V("When passing `initialState` to a Bidrectional RNN, the state should be an Array containing the states of the underlying RNNs.");t.initialState=n,s.push(...n);let u=n.map(p=>new zt({shape:p.shape}));this.forwardLayer.stateSpec=u.slice(0,l/2),this.backwardLayer.stateSpec=u.slice(l/2),i.push(...u)}if(a!=null)throw new Re("Support for constants in Bidirectional layers is not implemented yet.");let o=s[0]instanceof Ba;for(let l of s)if(l instanceof Ba!==o)throw new V("The initial state of a Bidirectional layer cannot be specified as a mix of symbolic and non-symbolic tensors");if(o){let l=[e].concat(s),u=this.inputSpec.concat(i),p=this.inputSpec;this.inputSpec=u;let d=super.apply(l,t);return this.inputSpec=p,d}else return super.apply(e,t)}call(e,t){return P(()=>{let n=t.initialState,a,r;if(n==null)a=this.forwardLayer.call(e,t),r=this.backwardLayer.call(e,t);else{let o=n.slice(0,n.length/2),l=n.slice(n.length/2);a=this.forwardLayer.call(e,Object.assign(t,{initialState:o})),r=this.backwardLayer.call(e,Object.assign(t,{initialState:l}))}let s;this.returnState&&(Array.isArray(a)&&(s=a.slice(1).concat(r.slice(1))),a=a[0],r=r[0]),this.returnSequences&&(r=fa(r,1));let i;return this.mergeMode==="concat"?i=Kv([a,r]):this.mergeMode==="sum"?i=Y(a,r):this.mergeMode==="ave"?i=z(.5,Y(a,r)):this.mergeMode==="mul"?i=z(a,r):this.mergeMode==null&&(i=[a,r]),this.returnState?this.mergeMode==null?i.concat(s):[i].concat(s):i})}resetStates(e){this.forwardLayer.resetStates(),this.backwardLayer.resetStates()}build(e){Xs(this.forwardLayer.name,()=>{this.forwardLayer.build(e)}),Xs(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){let a=this.forwardLayer.states.map(r=>null);return Array.isArray(n)?n.concat(a).concat(a):[n].concat(a).concat(a)}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(){let e={mergeMode:this.mergeMode},t=super.getConfig();return Object.assign(e,t),e}static fromConfig(e,t){let n=Ua(t.layer);if(delete t.layer,t.numConstants!=null)throw new Re("Deserialization of a Bidirectional layer with numConstants present is not supported yet.");let a=t;return a.layer=n,new e(a)}};h0.className="Bidirectional";ne.registerClass(h0);var m0=class extends Ge{constructor(e){super(e),this.scale=e.scale,e.offset?this.offset=e.offset:this.offset=0}getConfig(){let e={scale:this.scale,offset:this.offset},t=super.getConfig();return Object.assign(e,t),e}call(e,t){return P(()=>(e=Ne(e),e.dtype!=="float32"&&(e=yo(e,"float32")),Y(z(e,this.scale),this.offset)))}};m0.className="Rescaling";ne.registerClass(m0);var LU=["bilinear","nearest"],Nk=new Set(LU),f0=class extends Ge{constructor(e){if(super(e),this.height=e.height,this.width=e.width,e.interpolation)if(Nk.has(e.interpolation))this.interpolation=e.interpolation;else throw new V(`Invalid interpolation parameter: ${e.interpolation} is not implemented`);else this.interpolation="bilinear";this.cropToAspectRatio=Boolean(e.cropToAspectRatio)}computeOutputShape(e){e=Qe(e);let t=e[2];return[this.height,this.width,t]}getConfig(){let e={height:this.height,width:this.width,interpolation:this.interpolation,cropToAspectRatio:this.cropToAspectRatio},t=super.getConfig();return Object.assign(e,t),e}call(e,t){return P(()=>{let n=[this.height,this.width];if(this.interpolation==="bilinear")return za.resizeBilinear(e,n,!this.cropToAspectRatio);if(this.interpolation==="nearest")return za.resizeNearestNeighbor(e,n,!this.cropToAspectRatio);throw new Error(`Interpolation is ${this.interpolation} but only ${[...Nk]} are supported`)})}};f0.className="Resizing";ne.registerClass(f0);function zU(e,t,n,a){let r=Ne(e);if(r.dtype!=="int32"&&(r=yo(r,"int32")),t==="int")return r;let s=r.shape;if(r.rank===0&&(r=Zt(r,-1)),t==="oneHot"&&r.shape[r.shape.length-1]!==1&&(r=Zt(r,-1)),r.rank>2)throw new V(`When outputMode is not int, maximum output rank is 2 Received outputMode ${t} and input shape ${s} which would result in output rank ${r.rank}.`);let i=["multiHot","oneHot"].includes(t),o=r,l;if(typeof a!="undefined"&&t==="count"?l=Sh(o,a,n,i):l=Sh(o,[],n,i),t!=="tfIdf")return l;if(a)return z(l,a);throw new V("When outputMode is 'tfIdf', weights must be provided.")}var g0=class extends Ge{constructor(e){super(e),this.numTokens=e.numTokens,e.outputMode?this.outputMode=e.outputMode:this.outputMode="multiHot"}getConfig(){let e={numTokens:this.numTokens,outputMode:this.outputMode},t=super.getConfig();return Object.assign(e,t),e}computeOutputShape(e){return e=Qe(e),e==null?[this.numTokens]:this.outputMode==="oneHot"&&e[e.length-1]!==1?(e.push(this.numTokens),e):(e[e.length-1]=this.numTokens,e)}call(e,t){return P(()=>{e=Ne(e),e.dtype!=="int32"&&(e=yo(e,"int32"));let n;if(typeof t.countWeights!="undefined"){if(this.outputMode!=="count")throw new V(`countWeights is not used when outputMode !== count.
- Received countWeights=${t.countWeights}`);n=Ne(t.countWeights)}let a=ha(e),r=il(e),s=Nn(this.numTokens,a).bufferSync().get(0),i=Er(r,0).bufferSync().get(0);if(!(s&&i))throw new V(`Input values must be between 0 < values <= numTokens with numTokens=${this.numTokens}`);return zU(e,this.outputMode,this.numTokens,n)})}};g0.className="CategoryEncoding";ne.registerClass(g0);function WU(e){return new Du(e)}function BU(e){return new xw(e)}function VU(e){return new gw(e)}function UU(e){return new yw(e)}function GU(e){return new bw(e)}function HU(e){return new ww(e)}function jU(e){return new vw(e)}function qU(e){return new Tf(e)}function KU(e){return new Xc(e)}function XU(e){return new Sw(e)}function YU(e){return new Yc(e)}function ZU(e){return new Tw(e)}function JU(e){return new Nw(e)}function QU(e){return new Cw(e)}function eG(e){return new _w(e)}function tG(e){return new Ew(e)}function nG(e){return new Ow(e)}function aG(e){return new Mw(e)}function rG(e){return new Af(e)}function sG(e){return new Rw(e)}function iG(e){return new Pw(e)}function oG(e){return new Lw(e)}function lG(e){return new zw(e)}function uG(e){return new Ww(e)}function pG(e){return new Vw(e)}function cG(e){return new Uw(e)}function dG(e){return new Hw(e)}function hG(e){return new Kw(e)}function mG(e){return new jw(e)}function fG(e){return new qw(e)}function gG(e){return new Gw(e)}function yG(e){return new Xw(e)}function bG(e){return new Qw(e)}function xG(e){return new e0(e)}function vG(e){return new t0(e)}function y0(e){return new a0(e)}function wG(e){return y0(e)}function kG(e){return y0(e)}function b0(e){return new s0(e)}function IG(e){return b0(e)}function SG(e){return b0(e)}function x0(e){return new o0(e)}function TG(e){return x0(e)}function NG(e){return x0(e)}function CG(e){return new l0(e)}function _G(e){return new p0(e)}function HN(e){return new u0(e)}function jN(e){return new c0(e)}function qN(e){return new n0(e)}function KN(e){return new r0(e)}function EG(e){return new i0(e)}function AG(e){return new $w(e)}function $G(e){return new Cf(e)}function FG(e){return new Fw(e)}function DG(e){return new Jc(e)}function RG(e){return new Aw(e)}function MG(e){return new Nf(e)}function PG(e){return new Dw(e)}function OG(e){return new Ef(e)}function LG(e){return new dr(e)}function zG(e){return new _f(e)}function WG(e){return new h0(e)}function BG(e){return new d0(e)}var VG=HN,UG=jN,GG=qN,HG=KN;function jG(e){return new Yw(e)}function qG(e){return new Zw(e)}function KG(e){return new Jw(e)}function XG(e){return new Bw(e)}function YG(e){return new m0(e)}function ZG(e){return new f0(e)}function JG(e){return new g0(e)}var XN={};Ae(XN,{MAPE:()=>uH,MSE:()=>dH,binaryAccuracy:()=>QG,binaryCrossentropy:()=>eH,categoricalAccuracy:()=>nH,categoricalCrossentropy:()=>aH,cosineProximity:()=>iH,mape:()=>pH,meanAbsoluteError:()=>oH,meanAbsolutePercentageError:()=>lH,meanSquaredError:()=>cH,mse:()=>hH,precision:()=>rH,recall:()=>sH,sparseCategoricalAccuracy:()=>tH});function QG(e,t){return uw(e,t)}function eH(e,t){return uN(e,t)}function tH(e,t){return pN(e,t)}function nH(e,t){return pw(e,t)}function aH(e,t){return cw(e,t)}function rH(e,t){return lN(e,t)}function sH(e,t){return VV(e,t)}function iH(e,t){return lw(e,t)}function oH(e,t){return If(e,t)}function lH(e,t){return Ru(e,t)}function uH(e,t){return Ru(e,t)}function pH(e,t){return Ru(e,t)}function cH(e,t){return bo(e,t)}function dH(e,t){return bo(e,t)}function hH(e,t){return bo(e,t)}var YN={};Ae(YN,{modelFromJSON:()=>bU});var ZN={};Ae(ZN,{l1:()=>fH,l1l2:()=>mH,l2:()=>gH});function mH(e){return new qc(e)}function fH(e){return TU(e)}function gH(e){return NU(e)}var JN=class extends dl{constructor(){super(...arguments),this.model=null}setModel(e){if(!(e instanceof Nr))throw new Error("model must be a LayersModel, not some other Container");this.model=e}};function Yd(e,t){return e