/*! For license information please see mindar-image.prod.js.LICENSE.txt */ (()=>{var e={1113:function(e){e.exports=function(e){var t={};function n(r){if(t[r])return t[r].exports;var s=t[r]={i:r,l:!1,exports:{}};return e[r].call(s.exports,s,s.exports,n),s.l=!0,s.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var s in e)n.d(r,s,function(t){return e[t]}.bind(null,s));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=0)}([function(e,t,n){"use strict";n.r(t),n.d(t,"encode",(function(){return E})),n.d(t,"decode",(function(){return U})),n.d(t,"decodeAsync",(function(){return K})),n.d(t,"decodeArrayStream",(function(){return X})),n.d(t,"decodeStream",(function(){return Y})),n.d(t,"Decoder",(function(){return B})),n.d(t,"Encoder",(function(){return T})),n.d(t,"ExtensionCodec",(function(){return I})),n.d(t,"ExtData",(function(){return d})),n.d(t,"EXT_TIMESTAMP",(function(){return g})),n.d(t,"encodeDateToTimeSpec",(function(){return b})),n.d(t,"encodeTimeSpecToTimestamp",(function(){return y})),n.d(t,"decodeTimestampToTimeSpec",(function(){return w})),n.d(t,"encodeTimestampExtension",(function(){return x})),n.d(t,"decodeTimestampExtension",(function(){return v}));var r=function(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,s,a=n.call(e),i=[];try{for(;(void 0===t||t-- >0)&&!(r=a.next()).done;)i.push(r.value)}catch(e){s={error:e}}finally{try{r&&!r.done&&(n=a.return)&&n.call(a)}finally{if(s)throw s.error}}return i},s=function(){for(var e=[],t=0;t=55296&&s<=56319&&r65535&&(h-=65536,i.push(h>>>10&1023|55296),h=56320|1023&h),i.push(h)}else i.push(l);i.length>=4096&&(o+=String.fromCharCode.apply(String,s(i)),i.length=0)}return i.length>0&&(o+=String.fromCharCode.apply(String,s(i))),o}var h=a?new TextDecoder:null,p="undefined"!=typeof process?200:0,d=function(e,t){this.type=e,this.data=t};function f(e,t,n){var r=Math.floor(n/4294967296),s=n;e.setUint32(t,r),e.setUint32(t+4,s)}function m(e,t){return 4294967296*e.getInt32(t)+e.getUint32(t+4)}var g=-1;function y(e){var t,n=e.sec,r=e.nsec;if(n>=0&&r>=0&&n<=17179869183){if(0===r&&n<=4294967295){var s=new Uint8Array(4);return(t=new DataView(s.buffer)).setUint32(0,n),s}var a=n/4294967296,i=4294967295&n;return s=new Uint8Array(8),(t=new DataView(s.buffer)).setUint32(0,r<<2|3&a),t.setUint32(4,i),s}return s=new Uint8Array(12),(t=new DataView(s.buffer)).setUint32(0,r),f(t,4,n),s}function b(e){var t=e.getTime(),n=Math.floor(t/1e3),r=1e6*(t-1e3*n),s=Math.floor(r/1e9);return{sec:n+s,nsec:r-1e9*s}}function x(e){return e instanceof Date?y(b(e)):null}function w(e){var t=new DataView(e.buffer,e.byteOffset,e.byteLength);switch(e.byteLength){case 4:return{sec:t.getUint32(0),nsec:0};case 8:var n=t.getUint32(0);return{sec:4294967296*(3&n)+t.getUint32(4),nsec:n>>>2};case 12:return{sec:m(t,4),nsec:t.getUint32(0)};default:throw new Error("Unrecognized data size for timestamp: "+e.length)}}function v(e){var t=w(e);return new Date(1e3*t.sec+t.nsec/1e6)}var k={type:g,encode:x,decode:v},I=function(){function e(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(k)}return e.prototype.register=function(e){var t=e.type,n=e.encode,r=e.decode;if(t>=0)this.encoders[t]=n,this.decoders[t]=r;else{var s=1+t;this.builtInEncoders[s]=n,this.builtInDecoders[s]=r}},e.prototype.tryToEncode=function(e,t){for(var n=0;n=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},T=function(){function e(e,t,n,r,s,a,i){void 0===e&&(e=I.defaultCodec),void 0===n&&(n=100),void 0===r&&(r=2048),void 0===s&&(s=!1),void 0===a&&(a=!1),void 0===i&&(i=!1),this.extensionCodec=e,this.context=t,this.maxDepth=n,this.initialBufferSize=r,this.sortKeys=s,this.forceFloat32=a,this.ignoreUndefined=i,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}return e.prototype.encode=function(e,t){if(t>this.maxDepth)throw new Error("Too deep objects in depth "+t);null==e?this.encodeNil():"boolean"==typeof e?this.encodeBoolean(e):"number"==typeof e?this.encodeNumber(e):"string"==typeof e?this.encodeString(e):this.encodeObject(e,t)},e.prototype.getUint8Array=function(){return this.bytes.subarray(0,this.pos)},e.prototype.ensureBufferSizeToWrite=function(e){var t=this.pos+e;this.view.byteLength=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):(this.writeU8(211),this.writeI64(e)):this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))},e.prototype.writeStringHeader=function(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else{if(!(e<4294967296))throw new Error("Too long string: "+e+" bytes in UTF-8");this.writeU8(219),this.writeU32(e)}},e.prototype.encodeString=function(e){var t=e.length;if(a&&t>l){var n=i(e);this.ensureBufferSizeToWrite(5+n),this.writeStringHeader(n),u(e,this.bytes,this.pos),this.pos+=n}else n=i(e),this.ensureBufferSizeToWrite(5+n),this.writeStringHeader(n),function(e,t,n){for(var r=e.length,s=n,a=0;a>6&31|192;else{if(i>=55296&&i<=56319&&a>12&15|224,t[s++]=i>>6&63|128):(t[s++]=i>>18&7|240,t[s++]=i>>12&63|128,t[s++]=i>>6&63|128)}t[s++]=63&i|128}else t[s++]=i}}(e,this.bytes,this.pos),this.pos+=n},e.prototype.encodeObject=function(e,t){var n=this.extensionCodec.tryToEncode(e,this.context);if(null!=n)this.encodeExtension(n);else if(Array.isArray(e))this.encodeArray(e,t);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else{if("object"!=typeof e)throw new Error("Unrecognized object: "+Object.prototype.toString.apply(e));this.encodeMap(e,t)}},e.prototype.encodeBinary=function(e){var t=e.byteLength;if(t<256)this.writeU8(196),this.writeU8(t);else if(t<65536)this.writeU8(197),this.writeU16(t);else{if(!(t<4294967296))throw new Error("Too large binary: "+t);this.writeU8(198),this.writeU32(t)}var n=N(e);this.writeU8a(n)},e.prototype.encodeArray=function(e,t){var n,r,s=e.length;if(s<16)this.writeU8(144+s);else if(s<65536)this.writeU8(220),this.writeU16(s);else{if(!(s<4294967296))throw new Error("Too large array: "+s);this.writeU8(221),this.writeU32(s)}try{for(var a=S(e),i=a.next();!i.done;i=a.next()){var o=i.value;this.encode(o,t+1)}}catch(e){n={error:e}}finally{try{i&&!i.done&&(r=a.return)&&r.call(a)}finally{if(n)throw n.error}}},e.prototype.countWithoutUndefined=function(e,t){var n,r,s=0;try{for(var a=S(t),i=a.next();!i.done;i=a.next())void 0!==e[i.value]&&s++}catch(e){n={error:e}}finally{try{i&&!i.done&&(r=a.return)&&r.call(a)}finally{if(n)throw n.error}}return s},e.prototype.encodeMap=function(e,t){var n,r,s=Object.keys(e);this.sortKeys&&s.sort();var a=this.ignoreUndefined?this.countWithoutUndefined(e,s):s.length;if(a<16)this.writeU8(128+a);else if(a<65536)this.writeU8(222),this.writeU16(a);else{if(!(a<4294967296))throw new Error("Too large map object: "+a);this.writeU8(223),this.writeU32(a)}try{for(var i=S(s),o=i.next();!o.done;o=i.next()){var l=o.value,u=e[l];this.ignoreUndefined&&void 0===u||(this.encodeString(l),this.encode(u,t+1))}}catch(e){n={error:e}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}},e.prototype.encodeExtension=function(e){var t=e.data.length;if(1===t)this.writeU8(212);else if(2===t)this.writeU8(213);else if(4===t)this.writeU8(214);else if(8===t)this.writeU8(215);else if(16===t)this.writeU8(216);else if(t<256)this.writeU8(199),this.writeU8(t);else if(t<65536)this.writeU8(200),this.writeU16(t);else{if(!(t<4294967296))throw new Error("Too large extension object: "+t);this.writeU8(201),this.writeU32(t)}this.writeI8(e.type),this.writeU8a(e.data)},e.prototype.writeU8=function(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++},e.prototype.writeU8a=function(e){var t=e.length;this.ensureBufferSizeToWrite(t),this.bytes.set(e,this.pos),this.pos+=t},e.prototype.writeI8=function(e){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,e),this.pos++},e.prototype.writeU16=function(e){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,e),this.pos+=2},e.prototype.writeI16=function(e){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,e),this.pos+=2},e.prototype.writeU32=function(e){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,e),this.pos+=4},e.prototype.writeI32=function(e){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,e),this.pos+=4},e.prototype.writeF32=function(e){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,e),this.pos+=4},e.prototype.writeF64=function(e){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,e),this.pos+=8},e.prototype.writeU64=function(e){this.ensureBufferSizeToWrite(8),function(e,t,n){var r=n/4294967296,s=n;e.setUint32(t,r),e.setUint32(t+4,s)}(this.view,this.pos,e),this.pos+=8},e.prototype.writeI64=function(e){this.ensureBufferSizeToWrite(8),f(this.view,this.pos,e),this.pos+=8},e}(),C={};function E(e,t){void 0===t&&(t=C);var n=new T(t.extensionCodec,t.context,t.maxDepth,t.initialBufferSize,t.sortKeys,t.forceFloat32,t.ignoreUndefined);return n.encode(e,1),n.getUint8Array()}function $(e){return(e<0?"-":"")+"0x"+Math.abs(e).toString(16).padStart(2,"0")}var A=function(){function e(e,t){void 0===e&&(e=16),void 0===t&&(t=16),this.maxKeyLength=e,this.maxLengthPerKey=t,this.caches=[];for(var n=0;n0&&e<=this.maxKeyLength},e.prototype.get=function(e,t,n){var r=this.caches[n-1],s=r.length;e:for(var a=0;a=this.maxLengthPerKey?n[Math.random()*n.length|0]=r:n.push(r)},e.prototype.decode=function(e,t,n){var r=this.get(e,t,n);if(null!=r)return r;var s=c(e,t,n),a=Uint8Array.prototype.slice.call(e,t,t+n);return this.store(a,s),s},e}(),R=function(e,t){var n,r,s,a,i={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return a={next:o(0),throw:o(1),return:o(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function o(a){return function(o){return function(a){if(n)throw new TypeError("Generator is already executing.");for(;i;)try{if(n=1,r&&(s=2&a[0]?r.return:a[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,a[1])).done)return s;switch(r=0,s&&(a=[2&a[0],s.value]),a[0]){case 0:case 1:s=a;break;case 4:return i.label++,{value:a[1],done:!1};case 5:i.label++,r=a[1],a=[0];continue;case 7:a=i.ops.pop(),i.trys.pop();continue;default:if(!((s=(s=i.trys).length>0&&s[s.length-1])||6!==a[0]&&2!==a[0])){i=0;continue}if(3===a[0]&&(!s||a[1]>s[0]&&a[1]1||o(e,t)}))})}function o(e,t){try{(n=s[e](t)).value instanceof F?Promise.resolve(n.value.v).then(l,u):c(a[0][2],n)}catch(e){c(a[0][3],e)}var n}function l(e){o("next",e)}function u(e){o("throw",e)}function c(e,t){e(t),a.shift(),a.length&&o(a[0][0],a[0][1])}},_=new DataView(new ArrayBuffer(0)),O=new Uint8Array(_.buffer),L=function(){try{_.getInt8(0)}catch(e){return e.constructor}throw new Error("never reached")}(),z=new L("Insufficient data"),P=new A,B=function(){function e(e,t,n,r,s,a,i,o){void 0===e&&(e=I.defaultCodec),void 0===n&&(n=4294967295),void 0===r&&(r=4294967295),void 0===s&&(s=4294967295),void 0===a&&(a=4294967295),void 0===i&&(i=4294967295),void 0===o&&(o=P),this.extensionCodec=e,this.context=t,this.maxStrLength=n,this.maxBinLength=r,this.maxArrayLength=s,this.maxMapLength=a,this.maxExtLength=i,this.cachedKeyDecoder=o,this.totalPos=0,this.pos=0,this.view=_,this.bytes=O,this.headByte=-1,this.stack=[]}return e.prototype.setBuffer=function(e){this.bytes=N(e),this.view=function(e){if(e instanceof ArrayBuffer)return new DataView(e);var t=N(e);return new DataView(t.buffer,t.byteOffset,t.byteLength)}(this.bytes),this.pos=0},e.prototype.appendBuffer=function(e){if(-1!==this.headByte||this.hasRemaining()){var t=this.bytes.subarray(this.pos),n=N(e),r=new Uint8Array(t.length+n.length);r.set(t),r.set(n,t.length),this.setBuffer(r)}else this.setBuffer(e)},e.prototype.hasRemaining=function(e){return void 0===e&&(e=1),this.view.byteLength-this.pos>=e},e.prototype.createNoExtraBytesError=function(e){var t=this.view,n=this.pos;return new RangeError("Extra "+(t.byteLength-n)+" byte(s) found at buffer["+e+"]")},e.prototype.decodeSingleSync=function(){var e=this.decodeSync();if(this.hasRemaining())throw this.createNoExtraBytesError(this.pos);return e},e.prototype.decodeSingleAsync=function(e){var t,n,r,s;return function(e,t,n,r){return new(n||(n=Promise))((function(s,a){function i(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,o)}l((r=r.apply(e,t||[])).next())}))}(this,void 0,void 0,(function(){var a,i,o,l,u,c,h,p;return R(this,(function(d){switch(d.label){case 0:a=!1,d.label=1;case 1:d.trys.push([1,6,7,12]),t=M(e),d.label=2;case 2:return[4,t.next()];case 3:if((n=d.sent()).done)return[3,5];if(o=n.value,a)throw this.createNoExtraBytesError(this.totalPos);this.appendBuffer(o);try{i=this.decodeSync(),a=!0}catch(e){if(!(e instanceof L))throw e}this.totalPos+=this.pos,d.label=4;case 4:return[3,2];case 5:return[3,12];case 6:return l=d.sent(),r={error:l},[3,12];case 7:return d.trys.push([7,,10,11]),n&&!n.done&&(s=t.return)?[4,s.call(t)]:[3,9];case 8:d.sent(),d.label=9;case 9:return[3,11];case 10:if(r)throw r.error;return[7];case 11:return[7];case 12:if(a){if(this.hasRemaining())throw this.createNoExtraBytesError(this.totalPos);return[2,i]}throw c=(u=this).headByte,h=u.pos,p=u.totalPos,new RangeError("Insufficient data in parcing "+$(c)+" at "+p+" ("+h+" in the current buffer)")}}))}))},e.prototype.decodeArrayStream=function(e){return this.decodeMultiAsync(e,!0)},e.prototype.decodeStream=function(e){return this.decodeMultiAsync(e,!1)},e.prototype.decodeMultiAsync=function(e,t){return D(this,arguments,(function(){var n,r,s,a,i,o,l,u,c;return R(this,(function(h){switch(h.label){case 0:n=t,r=-1,h.label=1;case 1:h.trys.push([1,13,14,19]),s=M(e),h.label=2;case 2:return[4,F(s.next())];case 3:if((a=h.sent()).done)return[3,12];if(i=a.value,t&&0===r)throw this.createNoExtraBytesError(this.totalPos);this.appendBuffer(i),n&&(r=this.readArraySize(),n=!1,this.complete()),h.label=4;case 4:h.trys.push([4,9,,10]),h.label=5;case 5:return[4,F(this.decodeSync())];case 6:return[4,h.sent()];case 7:return h.sent(),0==--r?[3,8]:[3,5];case 8:return[3,10];case 9:if(!((o=h.sent())instanceof L))throw o;return[3,10];case 10:this.totalPos+=this.pos,h.label=11;case 11:return[3,2];case 12:return[3,19];case 13:return l=h.sent(),u={error:l},[3,19];case 14:return h.trys.push([14,,17,18]),a&&!a.done&&(c=s.return)?[4,F(c.call(s))]:[3,16];case 15:h.sent(),h.label=16;case 16:return[3,18];case 17:if(u)throw u.error;return[7];case 18:return[7];case 19:return[2]}}))}))},e.prototype.decodeSync=function(){e:for(;;){var e=this.readHeadByte(),t=void 0;if(e>=224)t=e-256;else if(e<192)if(e<128)t=e;else if(e<144){if(0!=(r=e-128)){this.pushMapState(r),this.complete();continue e}t={}}else if(e<160){if(0!=(r=e-144)){this.pushArrayState(r),this.complete();continue e}t=[]}else{var n=e-160;t=this.decodeUtf8String(n,0)}else if(192===e)t=null;else if(194===e)t=!1;else if(195===e)t=!0;else if(202===e)t=this.readF32();else if(203===e)t=this.readF64();else if(204===e)t=this.readU8();else if(205===e)t=this.readU16();else if(206===e)t=this.readU32();else if(207===e)t=this.readU64();else if(208===e)t=this.readI8();else if(209===e)t=this.readI16();else if(210===e)t=this.readI32();else if(211===e)t=this.readI64();else if(217===e)n=this.lookU8(),t=this.decodeUtf8String(n,1);else if(218===e)n=this.lookU16(),t=this.decodeUtf8String(n,2);else if(219===e)n=this.lookU32(),t=this.decodeUtf8String(n,4);else if(220===e){if(0!==(r=this.readU16())){this.pushArrayState(r),this.complete();continue e}t=[]}else if(221===e){if(0!==(r=this.readU32())){this.pushArrayState(r),this.complete();continue e}t=[]}else if(222===e){if(0!==(r=this.readU16())){this.pushMapState(r),this.complete();continue e}t={}}else if(223===e){if(0!==(r=this.readU32())){this.pushMapState(r),this.complete();continue e}t={}}else if(196===e){var r=this.lookU8();t=this.decodeBinary(r,1)}else if(197===e)r=this.lookU16(),t=this.decodeBinary(r,2);else if(198===e)r=this.lookU32(),t=this.decodeBinary(r,4);else if(212===e)t=this.decodeExtension(1,0);else if(213===e)t=this.decodeExtension(2,0);else if(214===e)t=this.decodeExtension(4,0);else if(215===e)t=this.decodeExtension(8,0);else if(216===e)t=this.decodeExtension(16,0);else if(199===e)r=this.lookU8(),t=this.decodeExtension(r,1);else if(200===e)r=this.lookU16(),t=this.decodeExtension(r,2);else{if(201!==e)throw new Error("Unrecognized type byte: "+$(e));r=this.lookU32(),t=this.decodeExtension(r,4)}this.complete();for(var s=this.stack;s.length>0;){var a=s[s.length-1];if(0===a.type){if(a.array[a.position]=t,a.position++,a.position!==a.size)continue e;s.pop(),t=a.array}else{if(1===a.type){if(void 0,"string"!=(i=typeof t)&&"number"!==i)throw new Error("The type of key must be string or number but "+typeof t);a.key=t,a.type=2;continue e}if(a.map[a.key]=t,a.readCount++,a.readCount!==a.size){a.key=null,a.type=1;continue e}s.pop(),t=a.map}}return t}var i},e.prototype.readHeadByte=function(){return-1===this.headByte&&(this.headByte=this.readU8()),this.headByte},e.prototype.complete=function(){this.headByte=-1},e.prototype.readArraySize=function(){var e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:if(e<160)return e-144;throw new Error("Unrecognized array type byte: "+$(e))}},e.prototype.pushMapState=function(e){if(e>this.maxMapLength)throw new Error("Max length exceeded: map length ("+e+") > maxMapLengthLength ("+this.maxMapLength+")");this.stack.push({type:1,size:e,key:null,readCount:0,map:{}})},e.prototype.pushArrayState=function(e){if(e>this.maxArrayLength)throw new Error("Max length exceeded: array length ("+e+") > maxArrayLength ("+this.maxArrayLength+")");this.stack.push({type:0,size:e,array:new Array(e),position:0})},e.prototype.decodeUtf8String=function(e,t){var n;if(e>this.maxStrLength)throw new Error("Max length exceeded: UTF-8 byte length ("+e+") > maxStrLength ("+this.maxStrLength+")");if(this.bytes.byteLengthp?function(e,t,n){var r=e.subarray(t,t+n);return h.decode(r)}(this.bytes,s,e):c(this.bytes,s,e),this.pos+=t+e,r},e.prototype.stateIsMapKey=function(){return this.stack.length>0&&1===this.stack[this.stack.length-1].type},e.prototype.decodeBinary=function(e,t){if(e>this.maxBinLength)throw new Error("Max length exceeded: bin length ("+e+") > maxBinLength ("+this.maxBinLength+")");if(!this.hasRemaining(e+t))throw z;var n=this.pos+t,r=this.bytes.subarray(n,n+e);return this.pos+=t+e,r},e.prototype.decodeExtension=function(e,t){if(e>this.maxExtLength)throw new Error("Max length exceeded: ext length ("+e+") > maxExtLength ("+this.maxExtLength+")");var n=this.view.getInt8(this.pos+t),r=this.decodeBinary(e,t+1);return this.extensionCodec.decode(r,n,this.context)},e.prototype.lookU8=function(){return this.view.getUint8(this.pos)},e.prototype.lookU16=function(){return this.view.getUint16(this.pos)},e.prototype.lookU32=function(){return this.view.getUint32(this.pos)},e.prototype.readU8=function(){var e=this.view.getUint8(this.pos);return this.pos++,e},e.prototype.readI8=function(){var e=this.view.getInt8(this.pos);return this.pos++,e},e.prototype.readU16=function(){var e=this.view.getUint16(this.pos);return this.pos+=2,e},e.prototype.readI16=function(){var e=this.view.getInt16(this.pos);return this.pos+=2,e},e.prototype.readU32=function(){var e=this.view.getUint32(this.pos);return this.pos+=4,e},e.prototype.readI32=function(){var e=this.view.getInt32(this.pos);return this.pos+=4,e},e.prototype.readU64=function(){var e,t,n=(e=this.view,t=this.pos,4294967296*e.getUint32(t)+e.getUint32(t+4));return this.pos+=8,n},e.prototype.readI64=function(){var e=m(this.view,this.pos);return this.pos+=8,e},e.prototype.readF32=function(){var e=this.view.getFloat32(this.pos);return this.pos+=4,e},e.prototype.readF64=function(){var e=this.view.getFloat64(this.pos);return this.pos+=8,e},e}(),V={};function U(e,t){void 0===t&&(t=V);var n=new B(t.extensionCodec,t.context,t.maxStrLength,t.maxBinLength,t.maxArrayLength,t.maxMapLength,t.maxExtLength);return n.setBuffer(e),n.decodeSingleSync()}var W=function(e,t){var n,r,s,a,i={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return a={next:o(0),throw:o(1),return:o(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function o(a){return function(o){return function(a){if(n)throw new TypeError("Generator is already executing.");for(;i;)try{if(n=1,r&&(s=2&a[0]?r.return:a[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,a[1])).done)return s;switch(r=0,s&&(a=[2&a[0],s.value]),a[0]){case 0:case 1:s=a;break;case 4:return i.label++,{value:a[1],done:!1};case 5:i.label++,r=a[1],a=[0];continue;case 7:a=i.ops.pop(),i.trys.pop();continue;default:if(!((s=(s=i.trys).length>0&&s[s.length-1])||6!==a[0]&&2!==a[0])){i=0;continue}if(3===a[0]&&(!s||a[1]>s[0]&&a[1]1||o(e,t)}))})}function o(e,t){try{(n=s[e](t)).value instanceof G?Promise.resolve(n.value.v).then(l,u):c(a[0][2],n)}catch(e){c(a[0][3],e)}var n}function l(e){o("next",e)}function u(e){o("throw",e)}function c(e,t){e(t),a.shift(),a.length&&o(a[0][0],a[0][1])}};function j(e){if(null==e)throw new Error("Assertion Failure: value must not be null nor undefined")}function q(e){return null!=e[Symbol.asyncIterator]?e:function(e){return H(this,arguments,(function(){var t,n,r,s;return W(this,(function(a){switch(a.label){case 0:t=e.getReader(),a.label=1;case 1:a.trys.push([1,,9,10]),a.label=2;case 2:return[4,G(t.read())];case 3:return n=a.sent(),r=n.done,s=n.value,r?[4,G(void 0)]:[3,5];case 4:return[2,a.sent()];case 5:return j(s),[4,G(s)];case 6:return[4,a.sent()];case 7:return a.sent(),[3,2];case 8:return[3,10];case 9:return t.releaseLock(),[7];case 10:return[2]}}))}))}(e)}function K(e,t){return void 0===t&&(t=V),function(e,t,n,r){return new(n||(n=Promise))((function(s,a){function i(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,o)}l((r=r.apply(e,t||[])).next())}))}(this,void 0,void 0,(function(){var n;return function(e,t){var n,r,s,a,i={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return a={next:o(0),throw:o(1),return:o(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function o(a){return function(o){return function(a){if(n)throw new TypeError("Generator is already executing.");for(;i;)try{if(n=1,r&&(s=2&a[0]?r.return:a[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,a[1])).done)return s;switch(r=0,s&&(a=[2&a[0],s.value]),a[0]){case 0:case 1:s=a;break;case 4:return i.label++,{value:a[1],done:!1};case 5:i.label++,r=a[1],a=[0];continue;case 7:a=i.ops.pop(),i.trys.pop();continue;default:if(!((s=(s=i.trys).length>0&&s[s.length-1])||6!==a[0]&&2!==a[0])){i=0;continue}if(3===a[0]&&(!s||a[1]>s[0]&&a[1]{"use strict";n.r(t),n.d(t,{Abs:()=>Ye,Acos:()=>Ze,Acosh:()=>Je,AdadeltaOptimizer:()=>Nl,AdagradOptimizer:()=>Tl,AdamOptimizer:()=>$l,AdamaxOptimizer:()=>Ml,Add:()=>Qe,AddN:()=>et,All:()=>tt,Any:()=>nt,ArgMax:()=>rt,ArgMin:()=>st,Asin:()=>at,Asinh:()=>it,Atan:()=>ot,Atan2:()=>ut,Atanh:()=>lt,AvgPool:()=>ct,AvgPool3D:()=>pt,AvgPool3DGrad:()=>dt,AvgPoolGrad:()=>ht,BatchMatMul:()=>ft,BatchToSpaceND:()=>mt,Bincount:()=>gt,BroadcastArgs:()=>bt,BroadcastTo:()=>yt,Callback:()=>bI,CallbackList:()=>bb,Cast:()=>xt,Ceil:()=>wt,ClipByValue:()=>vt,Complex:()=>kt,ComplexAbs:()=>It,Concat:()=>Nt,Conv2D:()=>St,Conv2DBackpropFilter:()=>Tt,Conv2DBackpropInput:()=>Ct,Conv3D:()=>Et,Conv3DBackpropFilterV2:()=>$t,Conv3DBackpropInputV2:()=>At,Cos:()=>Rt,Cosh:()=>Mt,CropAndResize:()=>Dt,Cumsum:()=>Ft,CustomCallback:()=>vb,DataStorage:()=>j,DenseBincount:()=>_t,DepthToSpace:()=>Ot,DepthwiseConv2dNative:()=>Lt,DepthwiseConv2dNativeBackpropFilter:()=>zt,DepthwiseConv2dNativeBackpropInput:()=>Pt,Diag:()=>Bt,Dilation2D:()=>Vt,Dilation2DBackpropFilter:()=>Wt,Dilation2DBackpropInput:()=>Ut,ENV:()=>qe,EarlyStopping:()=>vI,Einsum:()=>Ht,Elu:()=>jt,EluGrad:()=>qt,Environment:()=>We,Equal:()=>Xt,Erf:()=>Kt,Exp:()=>Yt,ExpandDims:()=>Zt,Expm1:()=>Jt,FFT:()=>Qt,Fill:()=>en,FlipLeftRight:()=>tn,Floor:()=>nn,FloorDiv:()=>rn,FromPixels:()=>Zr,FusedBatchNorm:()=>sn,FusedConv2D:()=>es,FusedDepthwiseConv2D:()=>ts,GatherNd:()=>on,GatherV2:()=>an,GraphModel:()=>LN,Greater:()=>ln,GreaterEqual:()=>un,History:()=>wb,IFFT:()=>hn,Identity:()=>cn,Imag:()=>pn,InputSpec:()=>ab,IsFinite:()=>dn,IsInf:()=>fn,IsNan:()=>mn,KernelBackend:()=>q,LRN:()=>Tn,LRNGrad:()=>Cn,LayerVariable:()=>nb,LayersModel:()=>Tx,LeakyRelu:()=>gn,Less:()=>yn,LessEqual:()=>bn,LinSpace:()=>xn,Log:()=>wn,Log1p:()=>vn,LogSoftmax:()=>Sn,LogicalAnd:()=>kn,LogicalNot:()=>In,LogicalOr:()=>Nn,Max:()=>En,MaxPool:()=>An,MaxPool3D:()=>Mn,MaxPool3DGrad:()=>Fn,MaxPoolGrad:()=>Rn,MaxPoolWithArgmax:()=>Dn,Maximum:()=>$n,Mean:()=>_n,Min:()=>On,Minimum:()=>Ln,MirrorPad:()=>zn,Mod:()=>Pn,MomentumOptimizer:()=>Dl,Multinomial:()=>Bn,Multiply:()=>Vn,Neg:()=>Un,NonMaxSuppressionV3:()=>Gn,NonMaxSuppressionV4:()=>Hn,NonMaxSuppressionV5:()=>jn,NotEqual:()=>Wn,OP_SCOPE_SUFFIX:()=>Sa,OneHot:()=>Kn,OnesLike:()=>qn,Optimizer:()=>Il,OptimizerConstructors:()=>Ol,Pack:()=>Xn,PadV2:()=>Yn,Pool:()=>Zn,Pow:()=>Jn,Prelu:()=>Qn,Prod:()=>er,RMSPropOptimizer:()=>_l,RNN:()=>Mw,Range:()=>tr,Rank:()=>Ys,Real:()=>nr,RealDiv:()=>Gt,Reciprocal:()=>rr,Reduction:()=>od,Relu:()=>sr,Relu6:()=>cr,Reshape:()=>ar,ResizeBilinear:()=>lr,ResizeBilinearGrad:()=>ur,ResizeNearestNeighbor:()=>ir,ResizeNearestNeighborGrad:()=>or,Reverse:()=>hr,RotateWithOffset:()=>Jr,Round:()=>pr,Rsqrt:()=>dr,SGDOptimizer:()=>Fl,ScatterNd:()=>fr,Select:()=>mr,Selu:()=>gr,Sequential:()=>$x,Sigmoid:()=>vr,Sign:()=>wr,Sin:()=>br,Sinh:()=>xr,Slice:()=>yr,Softmax:()=>Cr,Softplus:()=>kr,SpaceToBatchND:()=>Sr,SparseFillEmptyRows:()=>Er,SparseReshape:()=>$r,SparseSegmentMean:()=>Ar,SparseSegmentSum:()=>Rr,SparseToDense:()=>Mr,SplitV:()=>Tr,Sqrt:()=>Ir,Square:()=>Dr,SquaredDifference:()=>Fr,Step:()=>Yr,StridedSlice:()=>_r,StringNGrams:()=>Or,StringSplit:()=>Lr,StringToHashBucketFast:()=>zr,Sub:()=>Pr,Sum:()=>Nr,SymbolicTensor:()=>ib,Tan:()=>Br,Tanh:()=>Vr,Tensor:()=>qs,TensorBuffer:()=>Ws,Tile:()=>Ur,TopK:()=>Wr,Transform:()=>Gr,Transpose:()=>Hr,Unique:()=>jr,Unpack:()=>qr,UnsortedSegmentSum:()=>Kr,Variable:()=>Xs,ZerosLike:()=>Xr,_FusedMatMul:()=>Qr,abs:()=>Al,acos:()=>Ll,acosh:()=>zl,add:()=>ll,addN:()=>Pl,all:()=>Bl,any:()=>Vl,argMax:()=>Ul,argMin:()=>Wl,asin:()=>Gl,asinh:()=>Hl,atan:()=>jl,atan2:()=>ql,atanh:()=>Kl,avgPool:()=>cu,avgPool3d:()=>hu,backend:()=>il,backend_util:()=>y,basicLSTMCell:()=>gu,batchNorm:()=>bu,batchNorm2d:()=>xu,batchNorm3d:()=>wu,batchNorm4d:()=>vu,batchToSpaceND:()=>yu,bincount:()=>ku,booleanMaskAsync:()=>hp,broadcastArgs:()=>Iu,broadcastTo:()=>Nu,broadcast_util:()=>l,browser:()=>u,buffer:()=>Ni,callbacks:()=>kI,cast:()=>Si,ceil:()=>Su,clipByValue:()=>Tu,clone:()=>Ti,complex:()=>Ca,concat:()=>pu,concat1d:()=>Cu,concat2d:()=>Eu,concat3d:()=>$u,concat4d:()=>Au,constraints:()=>x,conv1d:()=>Mu,conv2d:()=>Ru,conv2dTranspose:()=>Du,conv3d:()=>_u,conv3dTranspose:()=>Lu,copyRegisteredKernels:()=>ds,cos:()=>zu,cosh:()=>Pu,cosineWindow:()=>wp,cumsum:()=>Bu,customGrad:()=>wl,data:()=>G,denseBincount:()=>Vu,deprecationWarn:()=>Go,depthToSpace:()=>Uu,depthwiseConv2d:()=>Wu,deregisterOp:()=>EI,device_util:()=>a,diag:()=>Gu,dilation2d:()=>Hu,disableDeprecationWarnings:()=>Wo,dispose:()=>Yo,disposeVariables:()=>Ho,div:()=>cl,divNoNan:()=>Ku,dot:()=>Xu,dropout:()=>bp,einsum:()=>Yu,elu:()=>Zu,enableDebugMode:()=>Uo,enableProdMode:()=>Vo,enclosingPowerOfTwo:()=>xp,engine:()=>jo,env:()=>He,equal:()=>ju,erf:()=>Ju,exp:()=>Qu,expandDims:()=>ec,expm1:()=>tc,eye:()=>rc,fft:()=>Vh,fill:()=>Sl,findBackend:()=>rl,findBackendFactory:()=>sl,floor:()=>sc,floorDiv:()=>ul,fused:()=>m,gather:()=>ac,gatherND:()=>yp,gather_util:()=>c,getBackend:()=>tl,getGradient:()=>os,getKernel:()=>is,getKernelsForBackend:()=>ls,grad:()=>ml,grads:()=>gl,greater:()=>ic,greaterEqual:()=>oc,ifft:()=>Uh,imag:()=>lc,image:()=>Td,inTopKAsync:()=>vp,initializers:()=>w,input:()=>Fx,io:()=>i,irfft:()=>Wh,isFinite:()=>uc,isInf:()=>cc,isNaN:()=>hc,keep:()=>Zo,kernel_impls:()=>b,layers:()=>v,leakyRelu:()=>pc,less:()=>dc,lessEqual:()=>fc,linalg:()=>Cd,linspace:()=>mc,loadGraphModel:()=>zN,loadLayersModel:()=>Mx,localResponseNormalization:()=>gc,log:()=>yc,log1p:()=>bc,logSigmoid:()=>vc,logSoftmax:()=>Nc,logSumExp:()=>Fc,logicalAnd:()=>Dc,logicalNot:()=>_c,logicalOr:()=>Oc,logicalXor:()=>Lc,losses:()=>Ed,matMul:()=>Hi,math:()=>o,max:()=>kc,maxPool:()=>zc,maxPool3d:()=>Pc,maxPoolWithArgmax:()=>Bc,maximum:()=>Rl,mean:()=>Vc,memory:()=>qo,meshgrid:()=>Gc,metrics:()=>k,min:()=>Hc,minimum:()=>jc,mirrorPad:()=>qc,mod:()=>Kc,model:()=>Ax,models:()=>I,moments:()=>Xc,movingAverage:()=>fp,mul:()=>hl,multiRNNCell:()=>Yc,multinomial:()=>Zc,neg:()=>xc,nextFrame:()=>Fd,norm:()=>dp,notEqual:()=>Jc,oneHot:()=>ji,ones:()=>Wc,onesLike:()=>Qc,op:()=>Ta,outerProduct:()=>eh,pad:()=>th,pad1d:()=>nh,pad2d:()=>rh,pad3d:()=>sh,pad4d:()=>ah,pool:()=>oh,pow:()=>Cl,prelu:()=>lh,print:()=>Ci,prod:()=>uh,profile:()=>Ko,rand:()=>ch,randomGamma:()=>mh,randomNormal:()=>gh,randomUniform:()=>yh,range:()=>bh,ready:()=>el,real:()=>xh,reciprocal:()=>wh,registerBackend:()=>al,registerCallbackConstructor:()=>Dx,registerGradient:()=>cs,registerKernel:()=>us,registerOp:()=>TI,regularizers:()=>N,relu:()=>vh,relu6:()=>kh,removeBackend:()=>nl,reshape:()=>uu,reverse:()=>Ih,reverse1d:()=>Nh,reverse2d:()=>Sh,reverse3d:()=>Th,reverse4d:()=>Ch,rfft:()=>Hh,round:()=>Eh,rsqrt:()=>$h,scalar:()=>kl,scatterND:()=>mp,scatter_util:()=>h,selu:()=>Ah,separableConv2d:()=>Rh,sequential:()=>Rx,serialization:()=>d,setBackend:()=>Qo,setPlatform:()=>ol,setdiff1dAsync:()=>Mh,sigmoid:()=>du,sign:()=>Fh,signal:()=>Sd,sin:()=>Dh,sinh:()=>_h,slice:()=>fu,slice1d:()=>Oh,slice2d:()=>Lh,slice3d:()=>zh,slice4d:()=>Ph,slice_util:()=>p,softmax:()=>Bh,softplus:()=>wc,spaceToBatchND:()=>ih,sparse:()=>$d,sparseToDense:()=>gp,spectral:()=>Nd,split:()=>Gh,sqrt:()=>pl,square:()=>dl,squaredDifference:()=>jh,squeeze:()=>qh,stack:()=>Kh,step:()=>Xh,stridedSlice:()=>Yh,string:()=>Ad,sub:()=>El,sum:()=>Ic,sumOutType:()=>ra,tan:()=>Zh,tanh:()=>mu,tensor:()=>$a,tensor1d:()=>Jh,tensor2d:()=>Qh,tensor3d:()=>Ji,tensor4d:()=>ep,tensor5d:()=>tp,tensor6d:()=>np,tensor_util:()=>s,test_util:()=>f,tidy:()=>Xo,tile:()=>nc,time:()=>Jo,topk:()=>rp,train:()=>Rd,transpose:()=>qi,truncatedNormal:()=>sp,unique:()=>ap,unregisterGradient:()=>ps,unregisterKernel:()=>hs,unsortedSegmentSum:()=>ip,unstack:()=>op,upcastType:()=>na,util:()=>r,valueAndGrad:()=>yl,valueAndGrads:()=>bl,variable:()=>lp,variableGrads:()=>xl,version:()=>_B,version_converter:()=>PN,version_core:()=>Bo,version_layers:()=>tx,where:()=>qu,whereAsync:()=>cp,zeros:()=>Uc,zerosLike:()=>fl});var r={};n.r(r),n.d(r,{arraysEqual:()=>ue,assert:()=>re,assertNonNegativeIntegerDimensions:()=>Pe,assertNonNull:()=>ae,assertShapesMatch:()=>se,bytesFromStringArray:()=>Te,bytesPerElement:()=>Se,checkConversionForErrors:()=>ve,clamp:()=>Z,computeStrides:()=>Fe,createScalarValue:()=>$s,createShuffledIndices:()=>de,decodeString:()=>Ds,distSquared:()=>ne,encodeString:()=>Fs,fetch:()=>Ms,fingerPrint64:()=>Es,flatten:()=>ie,getArrayFromDType:()=>we,getTypedArrayFromDType:()=>xe,hasEncodingLoss:()=>Ie,hexToLong:()=>ys,indexToLoc:()=>Ve,inferDtype:()=>Ae,inferFromImplicitShape:()=>ge,isBoolean:()=>Ee,isFunction:()=>Re,isInt:()=>ce,isNumber:()=>$e,isPromise:()=>Ue,isScalarShape:()=>le,isString:()=>Ce,isTypedArray:()=>Ne,isValidDtype:()=>ke,locToIndex:()=>Be,makeOnesTypedArray:()=>Oe,makeZerosNestedTypedArray:()=>ze,makeZerosTypedArray:()=>Le,nearestDivisor:()=>Me,nearestLargerEven:()=>J,now:()=>Rs,parseAxisParam:()=>ye,randUniform:()=>te,repeatedTry:()=>me,rightPad:()=>fe,shuffle:()=>X,shuffleCombo:()=>Y,sizeFromShape:()=>oe,sizeToSquarishShape:()=>pe,squeezeShape:()=>be,sum:()=>ee,swap:()=>Q,tanh:()=>he,toNestedArray:()=>_e,toTypedArray:()=>As});var s={};n.r(s),n.d(s,{assertTypesMatch:()=>aa,getTensorsInContainer:()=>oa,isTensorInList:()=>ia,makeTypesMatch:()=>sa});var a={};n.r(a),n.d(a,{isBrowser:()=>ba,isMobile:()=>ya,mockIsMobile:()=>ga});var i={};n.r(i),n.d(i,{browserFiles:()=>Ri,browserHTTPRequest:()=>Bi,concatenateArrayBuffers:()=>Oa,copyModel:()=>wi,decodeWeights:()=>Ma,encodeWeights:()=>Ra,fromMemory:()=>Wi,getLoadHandlers:()=>ja,getModelArtifactsForJSON:()=>Pa,getModelArtifactsInfoForJSON:()=>Ba,getSaveHandlers:()=>Ha,http:()=>Pi,isHTTPScheme:()=>Li,listModels:()=>bi,loadWeights:()=>Di,moveModel:()=>vi,registerLoadRouter:()=>Ga,registerSaveRouter:()=>Wa,removeModel:()=>xi,weightsLoaderFactory:()=>_i,withSaveHandler:()=>Gi});var o={};n.r(o),n.d(o,{confusionMatrix:()=>Ki});var l={};n.r(l),n.d(l,{assertAndGetBroadcastShape:()=>Zi,getBroadcastDims:()=>Xi,getReductionAxes:()=>Yi});var u={};n.r(u),n.d(u,{fromPixels:()=>ro,fromPixelsAsync:()=>to,toPixels:()=>no});var c={};n.r(c),n.d(c,{prepareAndValidate:()=>so});var h={};n.r(h),n.d(h,{calculateShapes:()=>oo,validateInput:()=>io,validateUpdateShape:()=>ao});var p={};n.r(p),n.d(p,{assertParamsValid:()=>lo,computeFlatOffset:()=>ko,computeOutShape:()=>co,getNormalizedAxes:()=>mo,isSliceContinous:()=>vo,maskToAxes:()=>uo,parseSliceParams:()=>Io,sliceInfo:()=>No,startForAxis:()=>xo,startIndicesWithElidedDims:()=>go,stopForAxis:()=>wo,stopIndicesWithElidedDims:()=>yo,stridesForAxis:()=>bo,stridesWithElidedDims:()=>ho});var d={};n.r(d),n.d(d,{Serializable:()=>To,SerializationMap:()=>Co,registerClass:()=>Eo});var f={};n.r(f),n.d(f,{TEST_EPSILON_FLOAT16:()=>$o,encodeStrings:()=>Po,expectArrayBuffersEqual:()=>zo,expectArraysClose:()=>Ao,expectArraysEqual:()=>Do,expectNumbersClose:()=>_o,expectPromiseToFail:()=>Fo,expectValuesInRange:()=>Lo,testEpsilon:()=>Ro});var m={};n.r(m),n.d(m,{conv2d:()=>Cp,depthwiseConv2d:()=>Ap,matMul:()=>Rp});var g={};n.r(g),n.d(g,{collectGatherOpShapeInfo:()=>$f,computeOutShape:()=>Ef,segOpComputeOptimalWindowSize:()=>Cf});var y={};n.r(y),n.d(y,{ERF_A1:()=>qd,ERF_A2:()=>Kd,ERF_A3:()=>Xd,ERF_A4:()=>Yd,ERF_A5:()=>Zd,ERF_P:()=>jd,PARALLELIZE_THRESHOLD:()=>Od,SELU_SCALE:()=>Hd,SELU_SCALEALPHA:()=>Gd,applyActivation:()=>Sp,assertAndGetBroadcastShape:()=>Zi,assertAxesAreInnerMostDims:()=>$c,assertParamsConsistent:()=>Dd,assignToTypedArray:()=>rf,axesAreInnerMostDims:()=>Sc,calculateShapes:()=>oo,checkEinsumDimSizes:()=>cf,checkPadOnDimRoundingMode:()=>lu,combineLocations:()=>Tc,complexWithEvenIndex:()=>ef,complexWithOddIndex:()=>tf,computeConv2DInfo:()=>Jl,computeConv3DInfo:()=>Ql,computeDefaultPad:()=>eu,computeDilation2DInfo:()=>Xl,computeOptimalWindowSize:()=>Ld,computeOutAndReduceShapes:()=>Cc,computeOutShape:()=>_d,computePool2DInfo:()=>Yl,computePool3DInfo:()=>Zl,convertConv2DDataFormat:()=>ou,decodeEinsumEquation:()=>lf,eitherStridesOrDilationsAreOne:()=>iu,expandShapeToKeepDim:()=>Ec,exponent:()=>af,exponents:()=>sf,fromStringArrayToUint8:()=>Rf,fromUint8ToStringArray:()=>Af,getAxesPermutation:()=>Ac,getBroadcastDims:()=>Xi,getComplexWithIndex:()=>nf,getEinsumComputePath:()=>hf,getEinsumPermutation:()=>uf,getFusedBiasGradient:()=>Np,getFusedDyActivation:()=>Ip,getImageCenter:()=>zd,getInnerMostAxes:()=>Mc,getPermuted:()=>Bd,getReductionAxes:()=>Yi,getReshaped:()=>Pd,getReshapedPermuted:()=>Vd,getSliceBeginCoords:()=>Ud,getSliceSize:()=>Wd,getSparseFillEmptyRowsIndicesDenseShapeMismatch:()=>mf,getSparseFillEmptyRowsNegativeIndexErrorMessage:()=>gf,getSparseFillEmptyRowsOutOfRangeIndexErrorMessage:()=>yf,getSparseReshapeEmptyTensorZeroOutputDimErrorMessage:()=>wf,getSparseReshapeInputOutputMismatchErrorMessage:()=>kf,getSparseReshapeInputOutputMultipleErrorMessage:()=>vf,getSparseReshapeMultipleNegativeOneOutputDimErrorMessage:()=>bf,getSparseReshapeNegativeOutputDimErrorMessage:()=>xf,getSparseSegmentReductionIndicesOutOfRangeErrorMessage:()=>Tf,getSparseSegmentReductionNegativeSegmentIdsErrorMessage:()=>If,getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage:()=>Nf,getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage:()=>Sf,getUndoAxesPermutation:()=>Rc,isIdentityPermutation:()=>pf,log:()=>rs,mergeRealAndImagArrays:()=>Jd,prepareAndValidate:()=>so,prepareSplitSize:()=>ff,segment_util:()=>g,shouldFuse:()=>Tp,slice_util:()=>p,splitRealAndImagArrays:()=>Qd,tupleValuesAreOne:()=>au,upcastType:()=>na,validateInput:()=>io,validateUpdateShape:()=>ao,warn:()=>ns});var b={};n.r(b),n.d(b,{nonMaxSuppressionV3Impl:()=>Gp,nonMaxSuppressionV4Impl:()=>Hp,nonMaxSuppressionV5Impl:()=>jp,whereImpl:()=>up});var x={};n.r(x),n.d(x,{maxNorm:()=>Sg,minMaxNorm:()=>Eg,nonNeg:()=>Cg,unitNorm:()=>Tg});var w={};n.r(w),n.d(w,{constant:()=>Dy,glorotNormal:()=>Vy,glorotUniform:()=>By,heNormal:()=>Uy,heUniform:()=>Wy,identity:()=>zy,leCunNormal:()=>Gy,leCunUniform:()=>Hy,ones:()=>Fy,orthogonal:()=>jy,randomNormal:()=>Oy,randomUniform:()=>_y,truncatedNormal:()=>Ly,varianceScaling:()=>Py,zeros:()=>My});var v={};n.r(v),n.d(v,{Layer:()=>cb,RNN:()=>Mw,RNNCell:()=>Fw,activation:()=>Qv,add:()=>lk,alphaDropout:()=>Jk,average:()=>uk,averagePooling1d:()=>bk,averagePooling2d:()=>vk,averagePooling3d:()=>Nk,avgPool1d:()=>xk,avgPool2d:()=>kk,avgPool3d:()=>Sk,avgPooling1d:()=>wk,avgPooling2d:()=>Ik,avgPooling3d:()=>Tk,batchNormalization:()=>mk,bidirectional:()=>Gk,concatenate:()=>ck,conv1d:()=>Gv,conv2d:()=>Hv,conv2dTranspose:()=>jv,conv3d:()=>qv,conv3dTranspose:()=>Kv,convLstm2d:()=>Bk,convLstm2dCell:()=>Vk,cropping2D:()=>Yv,dense:()=>ek,depthwiseConv2d:()=>Jv,dot:()=>fk,dropout:()=>tk,elu:()=>zv,embedding:()=>ok,flatten:()=>rk,gaussianDropout:()=>Zk,gaussianNoise:()=>Yk,globalAveragePooling1d:()=>Ck,globalAveragePooling2d:()=>Ek,globalMaxPool1d:()=>jk,globalMaxPool2d:()=>qk,globalMaxPooling1d:()=>$k,globalMaxPooling2d:()=>Ak,gru:()=>Dk,gruCell:()=>_k,input:()=>Fx,inputLayer:()=>Lv,layerNormalization:()=>gk,leakyReLU:()=>Bv,lstm:()=>Ok,lstmCell:()=>Lk,masking:()=>Qk,maxPool1d:()=>Kk,maxPool2d:()=>Xk,maxPooling1d:()=>Rk,maxPooling2d:()=>Mk,maxPooling3d:()=>Fk,maximum:()=>hk,minimum:()=>pk,multiply:()=>dk,permute:()=>ik,prelu:()=>Vv,reLU:()=>Pv,repeatVector:()=>sk,reshape:()=>ak,rnn:()=>Uk,separableConv2d:()=>Xv,simpleRNN:()=>zk,simpleRNNCell:()=>Pk,softmax:()=>Uv,spatialDropout1d:()=>nk,stackedRNNCells:()=>Wk,thresholdedReLU:()=>Wv,timeDistributed:()=>Hk,upSampling2d:()=>Zv,zeroPadding2d:()=>yk});var k={};n.r(k),n.d(k,{MAPE:()=>cI,MSE:()=>dI,binaryAccuracy:()=>eI,binaryCrossentropy:()=>tI,categoricalAccuracy:()=>rI,categoricalCrossentropy:()=>sI,cosineProximity:()=>oI,mape:()=>hI,meanAbsoluteError:()=>lI,meanAbsolutePercentageError:()=>uI,meanSquaredError:()=>pI,mse:()=>fI,precision:()=>aI,recall:()=>iI,sparseCategoricalAccuracy:()=>nI});var I={};n.r(I),n.d(I,{modelFromJSON:()=>Ex});var N={};n.r(N),n.d(N,{l1:()=>gI,l1l2:()=>mI,l2:()=>yI});var S={};n.r(S),n.d(S,{json:()=>OI});var T={};n.r(T),n.d(T,{json:()=>LI});var C={};n.r(C),n.d(C,{json:()=>zI});var E={};n.r(E),n.d(E,{json:()=>PI});var $={};n.r($),n.d($,{json:()=>BI});var A={};n.r(A),n.d(A,{json:()=>VI});var R={};n.r(R),n.d(R,{json:()=>UI});var M={};n.r(M),n.d(M,{json:()=>WI});var F={};n.r(F),n.d(F,{json:()=>GI});var D={};n.r(D),n.d(D,{json:()=>HI});var _={};n.r(_),n.d(_,{json:()=>jI});var O={};n.r(O),n.d(O,{json:()=>qI});var L={};n.r(L),n.d(L,{json:()=>KI});var z={};n.r(z),n.d(z,{json:()=>XI});var P={};n.r(P),n.d(P,{json:()=>YI});var B={};n.r(B),n.d(B,{json:()=>ZI});var V={};n.r(V),n.d(V,{json:()=>JI});var U={};n.r(U),n.d(U,{json:()=>QI});var W={};n.r(W),n.d(W,{json:()=>eN});var G={};n.r(G),n.d(G,{CSVDataset:()=>CS,Dataset:()=>mS,FileDataSource:()=>PS,TextLineDataset:()=>wS,URLDataSource:()=>BS,array:()=>yS,csv:()=>VS,func:()=>US,generator:()=>WS,microphone:()=>HS,version_data:()=>jS,webcam:()=>GS,zip:()=>bS});var H={};n.r(H),n.d(H,{addImpl:()=>TT,bincountImpl:()=>bC,bincountReduceImpl:()=>xC,ceilImpl:()=>kC,concatImpl:()=>EC,equalImpl:()=>cE,expImpl:()=>vE,expm1Impl:()=>TE,floorImpl:()=>WE,gatherNdImpl:()=>ZE,gatherV2Impl:()=>QE,greaterEqualImpl:()=>s$,greaterImpl:()=>t$,lessEqualImpl:()=>y$,lessImpl:()=>f$,linSpaceImpl:()=>w$,logImpl:()=>k$,maxImpl:()=>L$,maximumImpl:()=>B$,minimumImpl:()=>Y$,multiplyImpl:()=>nE,negImpl:()=>iA,notEqualImpl:()=>fA,prodImpl:()=>CA,rangeImpl:()=>$A,rsqrtImpl:()=>VA,sigmoidImpl:()=>dT,simpleAbsImpl:()=>_T,sliceImpl:()=>fC,sparseFillEmptyRowsImpl:()=>oR,sparseReshapeImpl:()=>uR,sparseSegmentReductionImpl:()=>hR,sqrtImpl:()=>gR,squaredDifferenceImpl:()=>wR,stridedSliceImpl:()=>SR,stringNGramsImpl:()=>ER,stringSplitImpl:()=>RR,stringToHashBucketFastImpl:()=>FR,subImpl:()=>ME,tileImpl:()=>zR,topKImpl:()=>VR,transposeImpl:()=>UT,uniqueImpl:()=>jR});class j{constructor(e,t){this.backend=e,this.dataMover=t,this.data=new WeakMap,this.dataIdsCount=0}get(e){return this.data.has(e)||this.dataMover.moveData(this.backend,e),this.data.get(e)}set(e,t){this.dataIdsCount++,this.data.set(e,t)}has(e){return this.data.has(e)}delete(e){return this.dataIdsCount--,this.data.delete(e)}numDataIds(){return this.dataIdsCount}}class q{refCount(e){return K("refCount")}incRef(e){return K("incRef")}timerAvailable(){return!0}time(e){return K("time")}read(e){return K("read")}readSync(e){return K("readSync")}readToGPU(e,t){return K("readToGPU")}numDataIds(){return K("numDataIds")}disposeData(e,t){return K("disposeData")}write(e,t,n){return K("write")}move(e,t,n,r,s){return K("move")}memory(){return K("memory")}floatPrecision(){return K("floatPrecision")}epsilon(){return 32===this.floatPrecision()?1e-7:1e-4}dispose(){return K("dispose")}}function K(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 X(e){let t=e.length,n=0;for(;t>0;)n=Math.random()*t|0,t--,Q(e,t,n)}function Y(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,r=0;for(;n>0;)r=Math.random()*n|0,n--,Q(e,n,r),Q(t,n,r)}function Z(e,t,n){return Math.max(e,Math.min(t,n))}function J(e){return e%2==0?e:e+1}function Q(e,t,n){const r=e[t];e[t]=e[n],e[n]=r}function ee(e){let t=0;for(let n=0;nn+` Shapes ${e} and ${t} must match`))}function ae(e){re(null!=e,(()=>"The input to the tensor constructor must be a non-null value."))}function ie(e,t=[],n=!1){if(null==t&&(t=[]),Array.isArray(e)||Ne(e)&&!n)for(let r=0;r0),n){return new Promise(((r,s)=>{let a=0;const i=()=>{if(e())return void r();a++;const o=t(a);null!=n&&a>=n?s():setTimeout(i,o)};i()}))}function ge(e,t){let n=1,r=-1;for(let t=0;t=0)n*=e[t];else if(-1===e[t]){if(-1!==r)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${r} and dim ${t}`);r=t}else if(e[t]<0)throw Error(`Shapes can not be < 0. Found ${e[t]} at dim ${t}`);if(-1===r){if(t>0&&t!==n)throw Error(`Size(${t}) must match the product of shape ${e}`);return e}if(0===n)throw Error(`Cannot infer the missing size in [${e}] when there are 0 elements`);if(t%n!=0)throw Error(`The implicit shape can't be a fractional number. Got ${t} / ${n}`);const s=e.slice();return s[r]=t/n,s}function ye(e,t){const n=t.length;return re((e=null==e?t.map(((e,t)=>t)):[].concat(e)).every((e=>e>=-n&&e`All values in axis param must be in range [-${n}, ${n}) but got axis ${e}`)),re(e.every((e=>ce(e))),(()=>`All values in axis param must be integers but got axis ${e}`)),e.map((e=>e<0?n+e:e))}function be(e,t){const n=[],r=[],s=null!=t&&Array.isArray(t)&&0===t.length,a=null==t||s?null:ye(t,e).sort();let i=0;for(let t=0;tt)&&1===e[t]&&(n.push(e[t]),r.push(t)),a[i]<=t&&i++}1!==e[t]&&(n.push(e[t]),r.push(t))}return{newShape:n,keptDims:r}}function xe(e,t){let n=null;if(null==e||"float32"===e)n=new Float32Array(t);else if("int32"===e)n=new Int32Array(t);else{if("bool"!==e)throw new Error(`Unknown data type ${e}`);n=new Uint8Array(t)}return n}function we(e,t){let n=null;if(null==e||"float32"===e)n=new Float32Array(t);else if("int32"===e)n=new Int32Array(t);else if("bool"===e)n=new Uint8Array(t);else{if("string"!==e)throw new Error(`Unknown data type ${e}`);n=new Array(t)}return n}function ve(e,t){for(let n=0;nt+=e.length)),t}function Ce(e){return"string"==typeof e||e instanceof String}function Ee(e){return"boolean"==typeof e}function $e(e){return"number"==typeof e}function Ae(e){return Array.isArray(e)?Ae(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray?"int32":$e(e)?"float32":Ce(e)?"string":Ee(e)?"bool":"float32"}function Re(e){return!!(e&&e.constructor&&e.call&&e.apply)}function Me(e,t){for(let n=t;n=0;--r)n[r]=n[r+1]*e[r+1];return n}function De(e,t,n,r=!1){const s=new Array;if(1===t.length){const a=t[0]*(r?2:1);for(let t=0;te*t))*(r?2:1);for(let t=0;te*t))*(n?2:1);if(0===r)return[];if(r!==t.length)throw new Error(`[${e}] does not match the input size ${t.length}${n?" for a complex tensor":""}.`);return De(0,e,t,n)}function Oe(e,t){const n=Le(e,t);for(let e=0;ee*t),1);if(null==t||"float32"===t)return _e(e,new Float32Array(n));if("int32"===t)return _e(e,new Int32Array(n));if("bool"===t)return _e(e,new Uint8Array(n));throw new Error(`Unknown data type ${t}`)}function Pe(e){e.forEach((t=>{re(Number.isInteger(t)&&t>=0,(()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`))}))}function Be(e,t,n){if(0===t)return 0;if(1===t)return e[0];let r=e[e.length-1];for(let t=0;t{const[t,n]=e.split(":");this.urlFlags[t]=function(e,t){if("true"===(t=t.toLowerCase())||"false"===t)return"true"===t;if(""+ +t===t)return+t;throw new Error(`Could not parse value flag value ${t} for flag ${e}.`)}(t,n)}))}}function Ge(e){const t={};return e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,((e,...n)=>(function(e,t,n){e[decodeURIComponent(t)]=decodeURIComponent(n||"")}(t,n[0],n[1]),n.join("=")))),t}function He(){return qe}let je,qe=null;function Ke(){if(null==je){let e;if("undefined"!=typeof window)e=window;else if(void 0!==n.g)e=n.g;else if("undefined"!=typeof process)e=process;else{if("undefined"==typeof self)throw new Error("Could not find a global object");e=self}je=e}return je}function Xe(e,t){const n=function(){const e=Ke();return null==e._tfGlobals&&(e._tfGlobals=new Map),e._tfGlobals}();if(n.has(e))return n.get(e);{const r=t();return n.set(e,r),n.get(e)}}const Ye="Abs",Ze="Acos",Je="Acosh",Qe="Add",et="AddN",tt="All",nt="Any",rt="ArgMax",st="ArgMin",at="Asin",it="Asinh",ot="Atan",lt="Atanh",ut="Atan2",ct="AvgPool",ht="AvgPoolGrad",pt="AvgPool3D",dt="AvgPool3DGrad",ft="BatchMatMul",mt="BatchToSpaceND",gt="Bincount",yt="BroadcastTo",bt="BroadcastArgs",xt="Cast",wt="Ceil",vt="ClipByValue",kt="Complex",It="ComplexAbs",Nt="Concat",St="Conv2D",Tt="Conv2DBackpropFilter",Ct="Conv2DBackpropInput",Et="Conv3D",$t="Conv3DBackpropFilterV2",At="Conv3DBackpropInputV2",Rt="Cos",Mt="Cosh",Ft="Cumsum",Dt="CropAndResize",_t="DenseBincount",Ot="DepthToSpace",Lt="DepthwiseConv2dNative",zt="DepthwiseConv2dNativeBackpropFilter",Pt="DepthwiseConv2dNativeBackpropInput",Bt="Diag",Vt="Dilation2D",Ut="Dilation2DBackpropInput",Wt="Dilation2DBackpropFilter",Gt="RealDiv",Ht="Einsum",jt="Elu",qt="EluGrad",Kt="Erf",Xt="Equal",Yt="Exp",Zt="ExpandDims",Jt="Expm1",Qt="FFT",en="Fill",tn="FlipLeftRight",nn="Floor",rn="FloorDiv",sn="FusedBatchNorm",an="GatherV2",on="GatherNd",ln="Greater",un="GreaterEqual",cn="Identity",hn="IFFT",pn="Imag",dn="IsFinite",fn="IsInf",mn="IsNan",gn="LeakyRelu",yn="Less",bn="LessEqual",xn="LinSpace",wn="Log",vn="Log1p",kn="LogicalAnd",In="LogicalNot",Nn="LogicalOr",Sn="LogSoftmax",Tn="LRN",Cn="LRNGrad",En="Max",$n="Maximum",An="MaxPool",Rn="MaxPoolGrad",Mn="MaxPool3D",Fn="MaxPool3DGrad",Dn="MaxPoolWithArgmax",_n="Mean",On="Min",Ln="Minimum",zn="MirrorPad",Pn="Mod",Bn="Multinomial",Vn="Multiply",Un="Neg",Wn="NotEqual",Gn="NonMaxSuppressionV3",Hn="NonMaxSuppressionV4",jn="NonMaxSuppressionV5",qn="OnesLike",Kn="OneHot",Xn="Pack",Yn="PadV2",Zn="Pool",Jn="Pow",Qn="Prelu",er="Prod",tr="Range",nr="Real",rr="Reciprocal",sr="Relu",ar="Reshape",ir="ResizeNearestNeighbor",or="ResizeNearestNeighborGrad",lr="ResizeBilinear",ur="ResizeBilinearGrad",cr="Relu6",hr="Reverse",pr="Round",dr="Rsqrt",fr="ScatterNd",mr="Select",gr="Selu",yr="Slice",br="Sin",xr="Sinh",wr="Sign",vr="Sigmoid",kr="Softplus",Ir="Sqrt",Nr="Sum",Sr="SpaceToBatchND",Tr="SplitV",Cr="Softmax",Er="SparseFillEmptyRows",$r="SparseReshape",Ar="SparseSegmentMean",Rr="SparseSegmentSum",Mr="SparseToDense",Fr="SquaredDifference",Dr="Square",_r="StridedSlice",Or="StringNGrams",Lr="StringSplit",zr="StringToHashBucketFast",Pr="Sub",Br="Tan",Vr="Tanh",Ur="Tile",Wr="TopK",Gr="Transform",Hr="Transpose",jr="Unique",qr="Unpack",Kr="UnsortedSegmentSum",Xr="ZerosLike",Yr="Step",Zr="FromPixels",Jr="RotateWithOffset",Qr="_FusedMatMul",es="FusedConv2D",ts="FusedDepthwiseConv2D";function ns(...e){He().getBool("IS_TEST")||He().getBool("PROD")||console.warn(...e)}function rs(...e){He().getBool("IS_TEST")||He().getBool("PROD")||console.log(...e)}const ss=Xe("kernelRegistry",(()=>new Map)),as=Xe("gradRegistry",(()=>new Map));function is(e,t){const n=fs(e,t);return ss.get(n)}function os(e){return as.get(e)}function ls(e){const t=ss.entries(),n=[];for(;;){const{done:r,value:s}=t.next();if(r)break;const[a,i]=s,[o]=a.split("_");o===e&&n.push(i)}return n}function us(e){const{kernelName:t,backendName:n}=e,r=fs(t,n);ss.has(r)&&ns(`The kernel '${t}' for backend '${n}' is already registered`),ss.set(r,e)}function cs(e){const{kernelName:t}=e;as.has(t)&&He().getBool("DEBUG")&&ns(`Overriding the gradient for '${t}'`),as.set(t,e)}function hs(e,t){const n=fs(e,t);if(!ss.has(n))throw new Error(`The kernel '${e}' for backend '${t}' is not registered`);ss.delete(n)}function ps(e){if(!as.has(e))throw new Error(`The gradient '${e}' for backend is not registered`);as.delete(e)}function ds(e,t){ls(e).forEach((e=>{us(Object.assign({},e,{backendName:t}))}))}function fs(e,t){return`${t}_${e}`}var ms=n(3720);const gs=n.n(ms)()||ms;function ys(e){return gs.fromString(e,!0,16)}const bs=ys("c3a5c85c97cb3127"),xs=ys("b492b66fbe98f273"),ws=ys("9ae16a3b2f90404f");function vs(e){return e.xor(e.shru(47))}function ks(e,t,n){const r=e.slice(t,t+n);return gs.fromBytes(Array.from(r),!0,!0)}function Is(e,t){return ks(e,t,8)}function Ns(e,t){return ks(e,t,4)}function Ss(e,t){return 0===t?e:e.shru(t).or(e.shl(64-t))}function Ts(e,t,n=ys("9ddfea08eb382d69")){let r=e.xor(t).mul(n);r=r.xor(r.shru(47));let s=t.xor(r).mul(n);return s=s.xor(s.shru(47)),s=s.mul(n),s}function Cs(e,t,n,r){return function(e,t,n,r,s,a){s=s.add(e),a=Ss(a.add(s).add(r),21);const i=s;return s=(s=s.add(t)).add(n),a=a.add(Ss(s,44)),[s.add(r),a.add(i)]}(Is(e,t),Is(e,t+8),Is(e,t+16),Is(e,t+24),n,r)}function Es(e,t=e.length){const n=gs.fromNumber(81,!0);if(t<=32)return t<=16?function(e,t=e.length){if(t>=8){const n=ws.add(2*t),r=Is(e,0).add(ws),s=Is(e,t-8);return Ts(Ss(s,37).mul(n).add(r),Ss(r,25).add(s).mul(n),n)}if(t>=4){const n=ws.add(2*t);return Ts(Ns(e,0).shl(3).add(t),Ns(e,t-4),n)}if(t>0){const n=e[0]+(e[t>>1]<<8),r=t+(e[t-1]<<2);return vs(ws.mul(n).xor(bs.mul(r))).mul(ws)}return ws}(e,t):function(e,t=e.length){const n=ws.add(2*t),r=Is(e,0).mul(xs),s=Is(e,8),a=Is(e,t-8).mul(n),i=Is(e,t-16).mul(ws);return Ts(Ss(r.add(s),43).add(Ss(a,30)).add(i),r.add(Ss(s.add(ws),18)).add(a),n)}(e,t);if(t<=64)return function(e,t=e.length){const n=ws.add(2*t),r=Is(e,0).mul(ws),s=Is(e,8),a=Is(e,t-8).mul(n),i=Is(e,t-16).mul(ws),o=Ss(r.add(s),43).add(Ss(a,30)).add(i),l=Ts(o,r.add(Ss(s.add(ws),18)).add(a),n),u=Is(e,16).mul(n),c=Is(e,24),h=o.add(Is(e,t-32)).mul(n),p=l.add(Is(e,t-24)).mul(n);return Ts(Ss(u.add(c),43).add(Ss(h,30)).add(p),u.add(Ss(c.add(r),18)).add(h),n)}(e,t);let r=n,s=n.mul(xs).add(113),a=vs(s.mul(ws).add(113)).mul(ws),i=[gs.UZERO,gs.UZERO],o=[gs.UZERO,gs.UZERO];r=r.mul(ws).add(Is(e,0));let l=0;const u=64*(t-1>>6),c=u+(t-1&63)-63;do{r=Ss(r.add(s).add(i[0]).add(Is(e,l+8)),37).mul(xs),s=Ss(s.add(i[1]).add(Is(e,l+48)),42).mul(xs),r=r.xor(o[1]),s=s.add(i[0]).add(Is(e,l+40)),a=Ss(a.add(o[0]),33).mul(xs),i=Cs(e,l,i[1].mul(xs),r.add(o[0])),o=Cs(e,l+32,a.add(o[1]),s.add(Is(e,l+16))),[a,r]=[r,a],l+=64}while(l!==u);const h=xs.add(a.and(255).shl(1));return l=c,o[0]=o[0].add(t-1&63),i[0]=i[0].add(o[0]),o[0]=o[0].add(i[0]),r=Ss(r.add(s).add(i[0]).add(Is(e,l+8)),37).mul(h),s=Ss(s.add(i[1]).add(Is(e,l+48)),42).mul(h),r=r.xor(o[1].mul(9)),s=s.add(i[0].mul(9).add(Is(e,l+40))),a=Ss(a.add(o[0]),33).mul(h),i=Cs(e,l,i[1].mul(h),r.add(o[0])),o=Cs(e,l+32,a.add(o[1]),s.add(Is(e,l+16))),[a,r]=[r,a],Ts(Ts(i[0],o[0],h).add(vs(s).mul(bs)).add(a),Ts(i[1],o[1],h).add(r),h)}function $s(e,t){return"string"===t?Fs(e):As([e],t)}function As(e,t){if("string"===t)throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=ie(e)),He().getBool("DEBUG")&&ve(e,t),function(e,t){return e instanceof Float32Array&&"float32"===t||e instanceof Int32Array&&"int32"===t||e instanceof Uint8Array&&"bool"===t}(e,t))return e;if(null==t||"float32"===t||"complex64"===t)return new Float32Array(e);if("int32"===t)return new Int32Array(e);if("bool"===t){const t=new Uint8Array(e.length);for(let n=0;n{r=n()};let a;const i=Rs();if(this.backendTimer.timerAvailable())a=this.backendTimer.time(s);else{s();for(const e of r)e.dataSync();a=Promise.resolve({kernelMs:Rs()-i})}if(He().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let t=0;t{Os(t,n.dtype,e)}))}return{kernelName:e,outputs:r,inputs:t,timeMs:a.then((e=>e.kernelMs)),extraInfo:a.then((e=>null!=e.getExtraProfileInfo?e.getExtraProfileInfo():""))}}logKernelProfile(e){const{kernelName:t,outputs:n,timeMs:r,inputs:s,extraInfo:a}=e;n.forEach((e=>{Promise.all([e.data(),r,a]).then((n=>{this.logger.logKernelProfile(t,e,n[0],n[1],s,n[2])}))}))}}function Os(e,t,n){if("float32"!==t)return!1;for(let t=0;t0?r:""} `}}console.log(`%c${o}\t%c${i}\t%c${l}D ${c}\t%c${u}\t%c${h}\t%c${a}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}}function zs(e,t,n,r){const s=Fe(t),a=function(e,t,n,r){const s=oe(t),a=r[r.length-1],i=new Array(a).fill(0),o=t.length,l="complex64"===n?Us(e):e;if(o>1)for(let e=0;e" "+e)).join("\n")),l.join("\n")}function Ps(e,t,n){let r;return r=Array.isArray(e)?`${parseFloat(e[0].toFixed(7))} + ${parseFloat(e[1].toFixed(7))}j`:Ce(e)?`'${e}'`:"bool"===n?Bs(e):parseFloat(e.toFixed(7)).toString(),fe(r,t)}function Bs(e){return 0===e?"false":"true"}function Vs(e,t,n,r,s,a=!0){const i="complex64"===n?2:1,o=t[0],l=t.length;if(0===l)return"complex64"===n?[Ps(Us(e)[0],0,n)]:"bool"===n?[Bs(e[0])]:[e[0].toString()];if(1===l){if(o>20){const t=3*i;let r=Array.from(e.slice(0,t)),a=Array.from(e.slice((o-3)*i,o*i));return"complex64"===n&&(r=Us(r),a=Us(a)),["["+r.map(((e,t)=>Ps(e,s[t],n))).join(", ")+", ..., "+a.map(((e,t)=>Ps(e,s[o-3+t],n))).join(", ")+"]"]}return["["+("complex64"===n?Us(e):Array.from(e)).map(((e,t)=>Ps(e,s[t],n))).join(", ")+"]"]}const u=t.slice(1),c=r.slice(1),h=r[0]*i,p=[];if(o>20){for(let t=0;t<3;t++){const r=t*h,a=r+h;p.push(...Vs(e.slice(r,a),u,n,c,s,!1))}p.push("...");for(let t=o-3;t`Length of values '${e}' does not match the size inferred by the shape '${this.size}'.`))}if("complex64"===t)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||we(t,this.size),this.strides=Fe(e)}set(e,...t){0===t.length&&(t=[0]),re(t.length===this.rank,(()=>`The number of provided coordinates (${t.length}) must match the rank (${this.rank})`));const n=this.locToIndex(t);this.values[n]=e}get(...e){0===e.length&&(e=[0]);let t=0;for(const n of e){if(n<0||n>=this.shape[t]){const t=`Requested out of range element at ${e}. Buffer shape=${this.shape}`;throw new Error(t)}t++}let n=e[e.length-1];for(let t=0;tDs(e)))}catch(e){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(),Gs().readToGPU(this.dataId,e)}dataSync(){this.throwIfDisposed();const e=Gs().readSync(this.dataId);if("string"===this.dtype)try{return e.map((e=>Ds(e)))}catch(e){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}return e}async bytes(){this.throwIfDisposed();const e=await Gs().read(this.dataId);return"string"===this.dtype?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(Gs().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return Hs.print(this,e)}clone(){return this.throwIfDisposed(),Hs.clone(this)}toString(e=!1){return zs(this.dataSync(),this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),Hs.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),Gs().makeVariable(this,e,t,n)}}function Ks(){return Xe("Tensor",(()=>qs))}Object.defineProperty(qs,Symbol.hasInstance,{value:e=>!!e&&null!=e.data&&null!=e.dataSync&&null!=e.throwIfDisposed}),Ks();class Xs extends qs{constructor(e,t,n,r){super(e.shape,e.dtype,e.dataId,r),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(!ue(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);Gs().disposeTensor(this),this.dataId=e.dataId,Gs().incRef(this,null)}dispose(){Gs().disposeVariable(this),this.isDisposedInternal=!0}}var Ys,Zs,Js,Qs,ea;Object.defineProperty(Xs,Symbol.hasInstance,{value:e=>e instanceof qs&&null!=e.assign&&e.assign instanceof Function}),function(e){e.R0="R0",e.R1="R1",e.R2="R2",e.R3="R3",e.R4="R4",e.R5="R5",e.R6="R6"}(Ys||(Ys={})),function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"}(Zs||(Zs={})),function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"}(Js||(Js={})),function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"}(Qs||(Qs={})),function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"}(ea||(ea={}));const ta={float32:Qs,int32:Zs,bool:Js,complex64:ea};function na(e,t){if("string"===e||"string"===t){if("string"===e&&"string"===t)return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return ta[e][t]}function ra(e){return na(e,"int32")}function sa(e,t){if(e.dtype===t.dtype)return[e,t];const n=na(e.dtype,t.dtype);return[e.cast(n),t.cast(n)]}function aa(e,t){re(e.dtype===t.dtype,(()=>`The dtypes of the first(${e.dtype}) and second(${t.dtype}) input must match`))}function ia(e,t){return t.some((t=>t.id===e.id))}function oa(e){const t=[];return la(e,t,new Set),t}function la(e,t,n){if(null==e)return;if(e instanceof qs)return void t.push(e);if(r=e,!Array.isArray(r)&&"object"!=typeof r)return;var r;const s=e;for(const e in s){const r=s[e];n.has(r)||(n.add(r),la(r,t,n))}}function ua(e){return null!=e.kernelName}class ca{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(const e in this.registeredVariables)this.registeredVariables[e].dispose()}}class ha{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new ca}async ready(){if(null!=this.pendingBackendInit)return this.pendingBackendInit.then((()=>{}));if(null!=this.backendInstance)return;const e=this.getSortedBackends();for(let t=0;t{null!=e.setupFunc&&e.setupFunc(this.backendInstance)}))}disposeRegisteredKernels(e){ls(e).forEach((t=>{null!=t.disposeFunc&&t.disposeFunc(this.registry[e])}))}initializeBackend(e){const t=this.registryFactory[e];if(null==t)throw new Error(`Cannot initialize backend ${e}, no registration found.`);try{const n=t.factory();if(!n||n instanceof q||"function"!=typeof n.then)return this.registry[e]=n,{success:!0,asyncInit:!1};{const t=++this.pendingBackendInitId,r=n.then((n=>!(t(tthis.registryFactory[t].priority-this.registryFactory[e].priority))}initializeBackendsAndReturnBest(){const e=this.getSortedBackends();for(let t=0;tthis.startScope(r)),(()=>this.endScope(n)),(()=>(n=t(),n instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),n)))}scopedRun(e,t,n){e();try{const e=n();return t(),e}catch(e){throw t(),e}}nextTensorId(){return ha.nextTensorId++}nextVariableId(){return ha.nextVariableId++}clone(e){const t=da.runKernel(cn,{x:e}),n={x:e};return this.addTapeNode(this.state.activeScope.name,n,[t],(e=>({x:()=>{const t={x:e};return da.runKernel(xt,t,{dtype:"float32"})}})),[],{}),t}runKernel(e,t,n){if(null==this.backendName&&this.backend,null==is(e,this.backendName))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){const r=this.backend.numDataIds();let s=0;n.forEach((e=>{s+="complex64"===e.dtype?3:1}));const a=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],i=r-t-s-a;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=[];const r=this.isTapeOn(),s=this.state.numBytes,a=this.state.numTensors;let i,o;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0),null==this.backendName&&this.backend;const l=ua(e)?e.kernelName:null!=this.state.activeScope?this.state.activeScope.name:"";if(ua(e)){const{kernelName:t,inputs:s,attrs:a}=e;null==this.backendName&&this.backend;const l=is(t,this.backendName);re(null!=l,(()=>`Cannot find registered kernel '${t}' for backend '${this.backendName}'`)),i=()=>{const e=this.backend.numDataIds();o=l.kernelFunc({inputs:s,attrs:a,backend:this.backend});const i=Array.isArray(o)?o:[o];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(t,e,i);const u=i.map((e=>{if(null!=e.rank)return e;const{dataId:t,shape:n,dtype:r}=e;return this.makeTensorFromDataId(t,n,r)}));if(r){const e=this.getTensorsForGradient(t,s,u);n=this.saveTensorsForBackwardMode(e)}return u}}else{const{forwardFunc:t}=e,s=e=>{r&&(n=e.map((e=>this.keep(this.clone(e)))))};i=()=>{const e=this.backend.numDataIds();o=this.tidy((()=>t(this.backend,s)));const n=Array.isArray(o)?o:[o];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(l,e,n),n}}const{inputs:u,attrs:c}=e,h=ua(e)?null:e.backwardsFunc;let p;return this.scopedRun((()=>this.state.kernelDepth++),(()=>this.state.kernelDepth--),(()=>{this.ENV.getBool("DEBUG")||this.state.profiling?(p=this.profiler.profileKernel(l,u,(()=>i())),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(p),t=p.outputs):t=i()})),r&&this.addTapeNode(l,u,t,h,n,c),this.state.profiling&&this.state.activeProfile.kernels.push({name:l,bytesAdded:this.state.numBytes-s,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-a,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(u).map((e=>null!=u[e]?u[e].shape:null)),outputShapes:t.map((e=>e.shape)),kernelTimeMs:p.timeMs,extraInfo:p.extraInfo}),Array.isArray(o)?t:t[0]}saveTensorsForBackwardMode(e){return e.map((e=>this.keep(this.clone(e))))}getTensorsForGradient(e,t,n){const r=os(e);if(null!=r){const e=r.inputsToSave||[],s=r.outputsToSave||[];let a;r.saveAllInputs?(re(Array.isArray(t),(()=>"saveAllInputs is true, expected inputs to be an array.")),a=Object.keys(t).map((e=>t[e]))):a=e.map((e=>t[e]));const i=n.filter(((e,t)=>s[t]));return a.concat(i)}return[]}makeTensor(e,t,n,r){if(null==e)throw new Error("Values passed to engine.makeTensor() are null");n=n||"float32",r=r||this.backend;let s=e;"string"===n&&Ce(e[0])&&(s=e.map((e=>Fs(e))));const a=r.write(s,t,n),i=new qs(t,n,a,this.nextTensorId());if(this.trackTensor(i,r),"string"===n){const e=this.state.tensorInfo.get(a),t=Te(s);this.state.numBytes+=t-e.bytes,e.bytes=t}return i}makeTensorFromDataId(e,t,n,r){const s=new qs(t,n=n||"float32",e,this.nextTensorId());return this.trackTensor(s,r),s}makeVariable(e,t=!0,n,r){n=n||this.nextVariableId().toString(),null!=r&&r!==e.dtype&&(e=e.cast(r));const s=new Xs(e,t,n,this.nextTensorId());if(null!=this.state.registeredVariables[s.name])throw new Error(`Variable with name ${s.name} was already registered`);return this.state.registeredVariables[s.name]=s,this.incRef(s,this.backend),s}trackTensor(e,t){this.state.numTensors++,"string"===e.dtype&&this.state.numStringTensors++;let n=0;"complex64"!==e.dtype&&"string"!==e.dtype&&(n=e.size*Se(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 Xs||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;const t=this.state.tensorInfo.get(e.dataId);if(this.state.numTensors--,"string"===e.dtype&&(this.state.numStringTensors--,this.state.numBytes-=t.bytes),"complex64"!==e.dtype&&"string"!==e.dtype){const t=e.size*Se(e.dtype);this.state.numBytes-=t}t.backend.disposeData(e.dataId)&&this.removeDataId(e.dataId,t.backend)}disposeVariables(){for(const e in this.state.registeredVariables){const t=this.state.registeredVariables[e];this.disposeVariable(t)}}disposeVariable(e){this.disposeTensor(e),null!=this.state.registeredVariables[e.name]&&delete this.state.registeredVariables[e.name]}memory(){const e=this.backend.memory();return e.numTensors=this.state.numTensors,e.numDataBuffers=this.state.numDataBuffers,e.numBytes=this.state.numBytes,this.state.numStringTensors>0&&(e.unreliable=!0,null==e.reasons&&(e.reasons=[]),e.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),e}async profile(e){this.state.profiling=!0;const t=this.state.numBytes,n=this.state.numTensors;this.state.activeProfile.kernels=[],this.state.activeProfile.result=await e(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max(...this.state.activeProfile.kernels.map((e=>e.totalBytesSnapshot))),this.state.activeProfile.newBytes=this.state.numBytes-t,this.state.activeProfile.newTensors=this.state.numTensors-n;for(const e of this.state.activeProfile.kernels)e.kernelTimeMs=await e.kernelTimeMs,e.extraInfo=await e.extraInfo;return this.state.activeProfile}isTapeOn(){return this.state.gradientDepth>0&&0===this.state.kernelDepth}addTapeNode(e,t,n,r,s,a){const i={id:this.state.nextTapeNodeId++,kernelName:e,inputs:t,outputs:n,saved:s},o=os(e);null!=o&&(r=o.gradFunc),null!=r&&(i.gradient=e=>(e=e.map(((e,t)=>{if(null==e){const e=n[t],r=Le(e.size,e.dtype);return this.makeTensor(r,e.shape,e.dtype)}return e})),r(e.length>1?e:e[0],s,a))),this.state.activeTape.push(i)}keep(e){return e.kept=!0,e}startTape(){0===this.state.gradientDepth&&(this.state.activeTape=[]),this.state.gradientDepth++}endTape(){this.state.gradientDepth--}startScope(e){const t={track:[],name:"unnamed scope",id:this.state.nextScopeId++};e&&(t.name=e),this.state.scopeStack.push(t),this.state.activeScope=t}endScope(e){const t=oa(e),n=new Set(t.map((e=>e.id)));for(let e=0;e{e.kept||e.scopeId!==r.id||this.track(e)}))}gradients(e,t,n,r=!1){if(re(t.length>0,(()=>"gradients() received an empty list of xs.")),null!=n&&"float32"!==n.dtype)throw new Error(`dy must have 'float32' dtype, but has '${n.dtype}'`);const s=this.scopedRun((()=>this.startTape()),(()=>this.endTape()),(()=>this.tidy("forward",e)));re(s instanceof qs,(()=>"The result y returned by f() must be a tensor."));const a=function(e,t,n){const r={},s={};for(let e=0;er[e.id]=!0)),o=!0,s[a.id]=!0;break}if(o)break}}const a={};a[n.id]=!0;const i={};for(let t=e.length-1;t>=0;t--){const n=e[t],r=n.inputs;for(let e=0;e0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y.");return this.tidy("backward",(()=>{const e={};e[s.id]=null==n?function(e){const t=Oe(oe(e),"float32");return da.makeTensor(t,e,"float32")}(s.shape):n,function(e,t,n,r){for(let s=t.length-1;s>=0;s--){const a=t[s],i=[];if(a.outputs.forEach((t=>{const n=e[t.id];null!=n?i.push(n):i.push(null)})),null==a.gradient)throw new Error(`Cannot compute gradient: gradient function not found for ${a.kernelName}.`);const o=a.gradient(i);for(const t in a.inputs){if(!(t in o))throw new Error(`Cannot backprop through input ${t}. Available gradients found: ${Object.keys(o)}.`);const s=n((()=>o[t]()));if("float32"!==s.dtype)throw new Error(`Error in gradient for op ${a.kernelName}. The gradient of input ${t} must have 'float32' dtype, but has '${s.dtype}'`);const i=a.inputs[t];if(!ue(s.shape,i.shape))throw new Error(`Error in gradient for op ${a.kernelName}. The gradient of input '${t}' has shape '${s.shape}', which does not match the shape of the input '${i.shape}'`);if(null==e[i.id])e[i.id]=s;else{const t=e[i.id];e[i.id]=r(t,s),t.dispose()}}}}(e,a,(e=>this.tidy(e)),fa);const r=t.map((t=>e[t.id]));return 0===this.state.gradientDepth&&(this.state.activeTape.forEach((e=>{for(const t of e.saved)t.dispose()})),this.state.activeTape=null),{value:s,grads:r}}))}customGrad(e){return re(Re(e),(()=>"The f passed in customGrad(f) must be a function.")),(...t)=>{let n;re(t.every((e=>e instanceof qs)),(()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors"));const r={};return t.forEach(((e,t)=>{r[t]=e})),this.runKernelFunc({forwardFunc:(r,s)=>(n=e(...t,s),re(n.value instanceof qs,(()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor")),re(Re(n.gradFunc),(()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function.")),n.value),backwardsFunc:(e,r)=>{const s=n.gradFunc(e,r),a=Array.isArray(s)?s:[s];re(a.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(...).")),re(a.every((e=>e instanceof qs)),(()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors."));const i={};return a.forEach(((e,t)=>{i[t]=()=>e})),i},inputs:r})}}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){const t=Rs(),n=await this.backend.time(e);return n.wallMs=Rs()-t,n}track(e){return null!=this.state.activeScope&&(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 ca;for(const e in this.registry)this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e];this.backendName=null,this.backendInstance=null,this.pendingBackendInit=null}}function pa(){const e=Ke();if(null==e._tfengine){const t=new We(e);e._tfengine=new ha(t)}var t;return t=e._tfengine.ENV,qe=t,Gs=()=>e._tfengine,e._tfengine}ha.nextTensorId=0,ha.nextVariableId=0;const da=pa();function fa(e,t){const n={a:e,b:t};return da.runKernel(Qe,n)}let ma;function ga(e){ma=e}function ya(e){if(void 0!==ma)return ma;if(e||"undefined"!=typeof navigator&&null!=navigator){if(e||(e=navigator),"ReactNative"===e.product)return!0;const t=e.userAgent||e.vendor||("undefined"!=typeof window?window.opera:"");if(!t){const t=e;return t.userAgentData&&t.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 ba(){return"undefined"!=typeof window&&null!=window.document||"undefined"!=typeof WorkerGlobalScope}const xa=He();function wa(e,t){let n=e;if(Ne(e))return"string"===t?[]:[e.length];if(!Array.isArray(e))return[];const r=[];for(;Array.isArray(n)||Ne(n)&&"string"!==t;)r.push(n.length),n=n[0];return Array.isArray(e)&&He().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&va(e,r,[]),r}function va(e,t,n){if(n=n||[],!Array.isArray(e)&&!Ne(e))return void re(0===t.length,(()=>`Element arr[${n.join("][")}] is a primitive, but should be an array/TypedArray of ${t[0]} elements`));re(t.length>0,(()=>`Element arr[${n.join("][")}] should be a primitive, but is an array of ${e.length} elements`)),re(e.length===t[0],(()=>`Element arr[${n.join("][")}] should have ${t[0]} elements, but has ${e.length} elements`));const r=t.slice(1);for(let t=0;t=0&&(s=r),ka(r,s,t,n),null==e||!Ne(e)&&!Array.isArray(e)&&"number"!=typeof e&&"boolean"!=typeof e&&"string"!=typeof e){const r=null==e?"null":e.constructor.name;throw new Error(`Argument '${t}' passed to '${n}' must be a Tensor or TensorLike, but got '${r}'`)}const a=wa(e,s);Ne(e)||Array.isArray(e)||(e=[e]);const i="string"!==s?As(e,s):ie(e,[],!0);return da.makeTensor(i,a,s)}function Na(e,t,n,r="numeric"){if(!Array.isArray(e))throw new Error(`Argument ${t} passed to ${n} must be a \`Tensor[]\` or \`TensorLike[]\``);return e.map(((e,s)=>Ia(e,`${t}[${s}]`,n,r)))}xa.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.")})),xa.registerFlag("IS_BROWSER",(()=>ba())),xa.registerFlag("IS_NODE",(()=>"undefined"!=typeof process&&void 0!==process.versions&&void 0!==process.versions.node)),xa.registerFlag("IS_CHROME",(()=>"undefined"!=typeof navigator&&null!=navigator&&null!=navigator.userAgent&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor))),xa.registerFlag("PROD",(()=>!1)),xa.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",(()=>xa.getBool("DEBUG"))),xa.registerFlag("DEPRECATION_WARNINGS_ENABLED",(()=>!0)),xa.registerFlag("IS_TEST",(()=>!1)),xa.registerFlag("CHECK_COMPUTATION_FOR_ERRORS",(()=>!0)),xa.registerFlag("WRAP_TO_IMAGEBITMAP",(()=>!1));const Sa="__op";function Ta(e){const t=Object.keys(e);if(1!==t.length)throw new Error(`Please provide an object with a single key (operation name) mapping to a function. Got an object with ${t.length} keys.`);let n=t[0];const r=e[n];n.endsWith("_")&&(n=n.substring(0,n.length-1)),n+=Sa;const s=(...e)=>{da.startScope(n);try{const t=r(...e);return Ue(t)&&console.error("Cannot return a Promise inside of tidy."),da.endScope(t),t}catch(e){throw da.endScope(null),e}};return Object.defineProperty(s,"name",{value:n,configurable:!0}),s}const Ca=Ta({complex_:function(e,t){const n=Ia(e,"real","complex"),r=Ia(t,"imag","complex");se(n.shape,r.shape,`real and imag shapes, ${n.shape} and ${r.shape}, must match in call to tf.complex().`);const s={real:n,imag:r};return da.runKernel(kt,s)}});function Ea(e,t,n,r){if(null==r&&(r=Ae(e)),"complex64"===r)throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!Ne(e)&&!Array.isArray(e)&&"number"!=typeof e&&"boolean"!=typeof e&&"string"!=typeof e)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(null!=t){Pe(t);const e=oe(t),r=oe(n);re(e===r,(()=>`Based on the provided shape, [${t}], the tensor should have ${e} values but has ${r}`));for(let e=0;e`Error creating a new Tensor. Inferred shape (${n}) does not match the provided shape (${t}). `))}}return Ne(e)||Array.isArray(e)||(e=[e]),t=t||n,e="string"!==r?As(e,r):ie(e,[],!0),da.makeTensor(e,t,r)}function $a(e,t,n){return Ea(e,t,wa(e,n),n)}const Aa={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8};async function Ra(e,t){const n=[],r=[],s=Array.isArray(e)?e.map((e=>e.name)):Object.keys(e);for(let a=0;a{const t=await o.bytes(),n=t.reduce(((e,t)=>e+t.length),0)+4*t.length,r=new Uint8Array(n);let s=0;for(let e=0;e{if(t+=e.byteLength,n.push(e.byteLength===e.buffer.byteLength?e:new e.constructor(e)),!(e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array))throw new Error(`Unsupported TypedArray subtype: ${e.constructor.name}`)}));const r=new Uint8Array(t);let s=0;return n.forEach((e=>{r.set(new Uint8Array(e.buffer),s),s+=e.byteLength})),r.buffer}const Da="undefined"!=typeof Buffer&&("undefined"==typeof Blob||"undefined"==typeof atob||"undefined"==typeof btoa);function _a(e){return Da?Buffer.byteLength(e):new Blob([e]).size}function Oa(e){if(1===e.length)return e[0];let t=0;e.forEach((e=>{t+=e.byteLength}));const n=new Uint8Array(t);let r=0;return e.forEach((e=>{n.set(new Uint8Array(e),r),r+=e.byteLength})),n.buffer}function La(e){for(e=e.trim();e.endsWith("/");)e=e.slice(0,e.length-1);const t=e.split("/");return t[t.length-1]}function za(e,t){const n={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,weightsManifest:t};return null!=e.signature&&(n.signature=e.signature),null!=e.userDefinedMetadata&&(n.userDefinedMetadata=e.userDefinedMetadata),null!=e.modelInitializer&&(n.modelInitializer=e.modelInitializer),null!=e.trainingConfig&&(n.trainingConfig=e.trainingConfig),n}async function Pa(e,t){const n={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy};if(null!=e.trainingConfig&&(n.trainingConfig=e.trainingConfig),null!=e.weightsManifest){const[r,s]=await t(e.weightsManifest);n.weightSpecs=r,n.weightData=s}return null!=e.signature&&(n.signature=e.signature),null!=e.userDefinedMetadata&&(n.userDefinedMetadata=e.userDefinedMetadata),null!=e.modelInitializer&&(n.modelInitializer=e.modelInitializer),n}function Ba(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("Expected JSON model topology, received ArrayBuffer.");return{dateSaved:new Date,modelTopologyType:"JSON",modelTopologyBytes:null==e.modelTopology?0:_a(JSON.stringify(e.modelTopology)),weightSpecsBytes:null==e.weightSpecs?0:_a(JSON.stringify(e.weightSpecs)),weightDataBytes:null==e.weightData?0:e.weightData.byteLength}}function Va(){const e=function(){const e=e=>{let t=e<<13,n=0;for(;0==(8388608&t);)n-=8388608,t<<=1;return t&=-8388609,n+=947912704,t|n},t=new Uint32Array(2048);t[0]=0;for(let n=1;n<1024;n++)t[n]=e(n);for(let e=1024;e<2048;e++)t[e]=939524096+(e-1024<<13);return t}(),t=function(){const e=new Uint32Array(64);e[0]=0,e[31]=1199570944,e[32]=2147483648,e[63]=3347054592;for(let t=1;t<31;t++)e[t]=t<<23;for(let t=33;t<63;t++)e[t]=2147483648+(t-32<<23);return e}(),n=function(){const e=new Uint32Array(64);for(let t=0;t<64;t++)e[t]=1024;return e[0]=e[32]=0,e}();return r=>{const s=new ArrayBuffer(4*r.length),a=new Uint32Array(s);for(let s=0;s>10]+(1023&i)]+t[i>>10];a[s]=o}return new Float32Array(s)}}class Ua{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return null==Ua.instance&&(Ua.instance=new Ua),Ua.instance}static registerSaveRouter(e){Ua.getInstance().saveRouters.push(e)}static registerLoadRouter(e){Ua.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return Ua.getHandlers(e,"save")}static getLoadHandlers(e,t){return Ua.getHandlers(e,"load",t)}static getHandlers(e,t,n){const r=[];return("load"===t?Ua.getInstance().loadRouters:Ua.getInstance().saveRouters).forEach((t=>{const s=t(e,n);null!==s&&r.push(s)})),r}}const Wa=e=>Ua.registerSaveRouter(e),Ga=e=>Ua.registerLoadRouter(e),Ha=e=>Ua.getSaveHandlers(e),ja=(e,t)=>Ua.getLoadHandlers(e,t),qa="tensorflowjs",Ka="models_store",Xa="model_info_store";function Ya(){if(!He().getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");const e="undefined"==typeof window?self:window,t=e.indexedDB||e.mozIndexedDB||e.webkitIndexedDB||e.msIndexedDB||e.shimIndexedDB;if(null==t)throw new Error("The current browser does not appear to support IndexedDB.");return t}function Za(e){const t=e.result;t.createObjectStore(Ka,{keyPath:"modelPath"}),t.createObjectStore(Xa,{keyPath:"modelPath"})}class Ja{constructor(e){if(this.indexedDB=Ya(),null==e||!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(((e,n)=>{const r=this.indexedDB.open(qa,1);r.onupgradeneeded=()=>Za(r),r.onsuccess=()=>{const s=r.result;if(null==t){const t=s.transaction(Ka,"readonly"),r=t.objectStore(Ka).get(this.modelPath);r.onsuccess=()=>{if(null==r.result)return s.close(),n(new Error(`Cannot find model with path '${this.modelPath}' in IndexedDB.`));e(r.result.modelArtifacts)},r.onerror=e=>(s.close(),n(r.error)),t.oncomplete=()=>s.close()}else{const r=Ba(t),a=s.transaction(Xa,"readwrite");let i=a.objectStore(Xa);const o=i.put({modelPath:this.modelPath,modelArtifactsInfo:r});let l;o.onsuccess=()=>{l=s.transaction(Ka,"readwrite");const o=l.objectStore(Ka).put({modelPath:this.modelPath,modelArtifacts:t,modelArtifactsInfo:r});o.onsuccess=()=>e({modelArtifactsInfo:r}),o.onerror=e=>{i=a.objectStore(Xa);const t=i.delete(this.modelPath);t.onsuccess=()=>(s.close(),n(o.error)),t.onerror=e=>(s.close(),n(o.error))}},o.onerror=e=>(s.close(),n(o.error)),a.oncomplete=()=>{null==l?s.close():l.oncomplete=()=>s.close()}}},r.onerror=e=>n(r.error)}))}}Ja.URL_SCHEME="indexeddb://";const Qa=e=>{return He().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(Ja.URL_SCHEME)?(t=e.slice(Ja.URL_SCHEME.length),new Ja(t)):null;var t};Ua.registerSaveRouter(Qa),Ua.registerLoadRouter(Qa);class ei{constructor(){this.indexedDB=Ya()}async listModels(){return new Promise(((e,t)=>{const n=this.indexedDB.open(qa,1);n.onupgradeneeded=()=>Za(n),n.onsuccess=()=>{const r=n.result,s=r.transaction(Xa,"readonly"),a=s.objectStore(Xa).getAll();a.onsuccess=()=>{const t={};for(const e of a.result)t[e.modelPath]=e.modelArtifactsInfo;e(t)},a.onerror=e=>(r.close(),t(a.error)),s.oncomplete=()=>r.close()},n.onerror=e=>t(n.error)}))}async removeModel(e){var t;return e=(t=e).startsWith(Ja.URL_SCHEME)?t.slice(Ja.URL_SCHEME.length):t,new Promise(((t,n)=>{const r=this.indexedDB.open(qa,1);r.onupgradeneeded=()=>Za(r),r.onsuccess=()=>{const s=r.result,a=s.transaction(Xa,"readwrite"),i=a.objectStore(Xa),o=i.get(e);let l;o.onsuccess=()=>{if(null==o.result)return s.close(),n(new Error(`Cannot find model with path '${e}' in IndexedDB.`));{const r=i.delete(e),a=()=>{l=s.transaction(Ka,"readwrite");const r=l.objectStore(Ka).delete(e);r.onsuccess=()=>t(o.result.modelArtifactsInfo),r.onerror=e=>n(o.error)};r.onsuccess=a,r.onerror=e=>(a(),s.close(),n(o.error))}},o.onerror=e=>(s.close(),n(o.error)),a.oncomplete=()=>{null==l?s.close():l.oncomplete=()=>s.close()}},r.onerror=e=>n(r.error)}))}}const ti="/",ni="tensorflowjs_models",ri="info",si="model_topology",ai="weight_specs",ii="weight_data",oi="model_metadata";function li(e){return{info:[ni,e,ri].join(ti),topology:[ni,e,si].join(ti),weightSpecs:[ni,e,ai].join(ti),weightData:[ni,e,ii].join(ti),modelMetadata:[ni,e,oi].join(ti)}}function ui(e){for(const t of Object.values(e))window.localStorage.removeItem(t)}function ci(e){const t=e.split(ti);if(t.length<3)throw new Error(`Invalid key format: ${e}`);return t.slice(1,t.length-1).join(ti)}class hi{constructor(e){if(!He().getBool("IS_BROWSER")||"undefined"==typeof window||void 0===window.localStorage)throw new Error("The current environment does not support local storage.");if(this.LS=window.localStorage,null==e||!e)throw new Error("For local storage, modelPath must not be null, undefined or empty.");this.modelPath=e,this.keys=li(this.modelPath)}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");{const t=JSON.stringify(e.modelTopology),n=JSON.stringify(e.weightSpecs),r=Ba(e);try{this.LS.setItem(this.keys.info,JSON.stringify(r)),this.LS.setItem(this.keys.topology,t),this.LS.setItem(this.keys.weightSpecs,n),this.LS.setItem(this.keys.weightData,function(e){if(Da)return Buffer.from(e).toString("base64");const t=new Uint8Array(e);let n="";for(let e=0,r=t.length;e{return He().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(hi.URL_SCHEME)?(t=e.slice(hi.URL_SCHEME.length),new hi(t)):null;var t};Ua.registerSaveRouter(pi),Ua.registerLoadRouter(pi);class di{constructor(){re(He().getBool("IS_BROWSER"),(()=>"Current environment is not a web browser")),re("undefined"==typeof window||void 0!==window.localStorage,(()=>"Current browser does not appear to support localStorage")),this.LS=window.localStorage}async listModels(){const e={},t=ni+ti,n=ti+ri;for(let r=0;r"scheme must not be undefined or null.")),e.endsWith(fi)&&(e=e.slice(0,e.indexOf(fi))),re(e.length>0,(()=>"scheme must not be an empty string."));const n=mi.getInstance();re(null==n.managers[e],(()=>`A model store manager is already registered for scheme '${e}'.`)),n.managers[e]=t}static getManager(e){const t=this.getInstance().managers[e];if(null==t)throw new Error(`Cannot find model manager for scheme '${e}'`);return t}static getSchemes(){return Object.keys(this.getInstance().managers)}}function gi(e){if(-1===e.indexOf(fi))throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${mi.getSchemes().join(",")}`);return{scheme:e.split(fi)[0],path:e.split(fi)[1]}}async function yi(e,t,n=!1){re(e!==t,(()=>`Old path and new path are the same: '${e}'`));const r=Ua.getLoadHandlers(e);re(r.length>0,(()=>`Copying failed because no load handler is found for source URL ${e}.`)),re(r.length<2,(()=>`Copying failed because more than one (${r.length}) load handlers for source URL ${e}.`));const s=r[0],a=Ua.getSaveHandlers(t);re(a.length>0,(()=>`Copying failed because no save handler is found for destination URL ${t}.`)),re(a.length<2,(()=>`Copying failed because more than one (${r.length}) save handlers for destination URL ${t}.`));const i=a[0],o=gi(e).scheme,l=gi(e).path,u=o===gi(e).scheme,c=await s.load();n&&u&&await mi.getManager(o).removeModel(l);const h=await i.save(c);return n&&!u&&await mi.getManager(o).removeModel(l),h.modelArtifactsInfo}async function bi(){const e=mi.getSchemes(),t={};for(const n of e){const e=await mi.getManager(n).listModels();for(const r in e)t[n+fi+r]=e[r]}return t}async function xi(e){const t=gi(e);return mi.getManager(t.scheme).removeModel(t.path)}async function wi(e,t){return yi(e,t,!1)}async function vi(e,t){return yi(e,t,!0)}class ki{fetch(e,t){return fetch(e,t)}now(){return performance.now()}encode(e,t){if("utf-8"!==t&&"utf8"!==t)throw new Error(`Browser's encoder only supports utf-8, but got ${t}`);return null==this.textEncoder&&(this.textEncoder=new TextEncoder),this.textEncoder.encode(e)}decode(e,t){return new TextDecoder(t).decode(e)}}if(He().get("IS_BROWSER")){He().setPlatform("browser",new ki);try{mi.registerManager(hi.URL_SCHEME,new di)}catch(e){}try{mi.registerManager(Ja.URL_SCHEME,new ei)}catch(e){}}let Ii;function Ni(e,t="float32",n){return t=t||"float32",Pe(e),new Ws(e,t,n)}He().get("IS_NODE")&&He().setPlatform("node",new class{constructor(){this.util=n(1758),this.textEncoder=new this.util.TextEncoder}fetch(e,t){return null!=He().global.fetch?He().global.fetch(e,t):(null==Ii&&(Ii=n(8352)),Ii(e,t))}now(){const e=process.hrtime();return 1e3*e[0]+e[1]/1e6}encode(e,t){if("utf-8"!==t&&"utf8"!==t)throw new Error(`Node built-in encoder only supports utf-8, but got ${t}`);return this.textEncoder.encode(e)}decode(e,t){return 0===e.length?"":new this.util.TextDecoder(t).decode(e)}});const Si=Ta({cast_:function(e,t){const n=Ia(e,"x","cast");if(!ke(t))throw new Error(`Failed to cast to unknown dtype ${t}`);if("string"===t&&"string"!==n.dtype||"string"!==t&&"string"===n.dtype)throw new Error("Only strings can be casted to strings");const r={x:n},s={dtype:t};return da.runKernel(xt,r,s)}}),Ti=Ta({clone_:function(e){const t={x:Ia(e,"x","clone","string_or_numeric")};return da.runKernel(cn,t)}});function Ci(e,t=!1){console.log(e.toString(t))}function Ei(e){return new Promise((e=>setTimeout(e))).then(e)}pa(),Hs={buffer:Ni,cast:Si,clone:Ti,print:Ci};class $i{constructor(e){if(!He().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith($i.URL_SCHEME)&&(e=e.slice($i.URL_SCHEME.length)),null!=e&&0!==e.length||(e="model"),this.modelJsonFileName=e+".json",this.weightDataFileName=e+".weights.bin"}async save(e){if("undefined"==typeof document)throw new Error("Browser downloads are not supported in this environment since `document` is not present");const t=window.URL.createObjectURL(new Blob([e.weightData],{type:"application/octet-stream"}));if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserDownloads.save() does not support saving model topology in binary formats yet.");{const n=za(e,[{paths:["./"+this.weightDataFileName],weights:e.weightSpecs}]),r=window.URL.createObjectURL(new Blob([JSON.stringify(n)],{type:"application/json"})),s=null==this.modelJsonAnchor?document.createElement("a"):this.modelJsonAnchor;if(s.download=this.modelJsonFileName,s.href=r,await Ei((()=>s.dispatchEvent(new MouseEvent("click")))),null!=e.weightData){const e=null==this.weightDataAnchor?document.createElement("a"):this.weightDataAnchor;e.download=this.weightDataFileName,e.href=t,await Ei((()=>e.dispatchEvent(new MouseEvent("click"))))}return{modelArtifactsInfo:Ba(e)}}}}$i.URL_SCHEME="downloads://";class Ai{constructor(e){if(null==e||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)=>{const n=new FileReader;n.onload=n=>{const r=JSON.parse(n.target.result),s=r.modelTopology;if(null==s)return void t(new Error(`modelTopology field is missing from file ${this.jsonFile.name}`));if(null==r.weightsManifest)return void t(new Error(`weightManifest field is missing from file ${this.jsonFile.name}`));if(0===this.weightsFiles.length)return void e({modelTopology:s});const a=Pa(r,(e=>this.loadWeights(e)));e(a)},n.onerror=e=>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){const t=[],n=[];for(const r of e)t.push(...r.weights),n.push(...r.paths);const r=this.checkManifestAndWeightFiles(e),s=n.map((e=>this.loadWeightsFile(e,r[e])));return Promise.all(s).then((e=>[t,Oa(e)]))}loadWeightsFile(e,t){return new Promise(((n,r)=>{const s=new FileReader;s.onload=e=>{const t=e.target.result;n(t)},s.onerror=t=>r(`Failed to weights data from file of path '${e}'.`),s.readAsArrayBuffer(t)}))}checkManifestAndWeightFiles(e){const t=[],n=this.weightsFiles.map((e=>La(e.name))),r={};for(const s of e)s.paths.forEach((e=>{const s=La(e);if(-1!==t.indexOf(s))throw new Error(`Duplicate file basename found in weights manifest: '${s}'`);if(t.push(s),-1===n.indexOf(s))throw new Error(`Weight file with basename '${s}' is not provided.`);r[e]=this.weightsFiles[n.indexOf(s)]}));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 r}}function Ri(e){return new Ai(e)}function Mi(e,t,n,r){!function(e){re(null!=e&&Array.isArray(e)&&e.length>0,(()=>"promises must be a none empty array"))}(e),function(e,t){re(e>=0&&e<=1,(()=>`Progress fraction must be in range [0, 1], but got startFraction ${e}`)),re(t>=0&&t<=1,(()=>`Progress fraction must be in range [0, 1], but got endFraction ${t}`)),re(t>=e,(()=>`startFraction must be no more than endFraction, but got startFraction ${e} and endFraction ${t}`))}(n=null==n?0:n,r=null==r?1:r);let s=0;return Promise.all(e.map((a=>(a.then((a=>{const i=n+ ++s/e.length*(r-n);return t(i),a})),a))))}async function Fi(e,t){null==t&&(t={});const n=null==t.fetchFunc?He().platform.fetch:t.fetchFunc,r=e.map((e=>n(e,t.requestInit,{isBinary:!0}))),s=(null==t.onProgress?await Promise.all(r):await Mi(r,t.onProgress,0,.5)).map((e=>e.arrayBuffer()));return null==t.onProgress?await Promise.all(s):await Mi(s,t.onProgress,.5,1)}async function Di(e,t="",n,r){return _i((e=>Fi(e,{requestInit:r})))(e,t,n)}function _i(e){return async(t,n="",r)=>{const s=t.map((()=>!1)),a={},i=null!=r?r.map((()=>!1)):[],o=[];if(t.forEach(((e,t)=>{let n=0;e.weights.forEach((e=>{const l="quantization"in e?e.quantization.dtype:e.dtype,u=Aa[l]*oe(e.shape),c=()=>{s[t]=!0,null==a[t]&&(a[t]=[]),a[t].push({manifestEntry:e,groupOffset:n,sizeBytes:u})};null!=r?r.forEach(((t,n)=>{t===e.name&&(c(),i[n]=!0)})):c(),o.push(e.name),n+=u}))})),!i.every((e=>e))){const e=r.filter(((e,t)=>!i[t]));throw new Error(`Could not find weights in manifest with names: ${e.join(", ")}. \nManifest JSON has weights with names: ${o.join(", ")}.`)}const l=s.reduce(((e,t,n)=>(t&&e.push(n),e)),[]),u=[];l.forEach((e=>{t[e].paths.forEach((e=>{const t=n+(n.endsWith("/")?"":"/")+e;u.push(t)}))}));const c=await e(u),h={};let p=0;return l.forEach((e=>{const n=t[e].paths.length;let r=0;for(let e=0;e{const t=Ma(s.slice(e.groupOffset,e.groupOffset+e.sizeBytes),[e.manifestEntry]);for(const e in t)h[e]=t[e]})),p+=n})),h}}Ua.registerSaveRouter((e=>He().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith($i.URL_SCHEME)?function(e="model"){return new $i(e)}(e.slice($i.URL_SCHEME.length)):null));class Oi{constructor(e,t){if(this.DEFAULT_METHOD="POST",null==t&&(t={}),this.weightPathPrefix=t.weightPathPrefix,this.onProgress=t.onProgress,this.weightUrlConverter=t.weightUrlConverter,null!=t.fetchFunc?(re("function"==typeof t.fetchFunc,(()=>"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=He().platform.fetch,re(null!=e&&e.length>0,(()=>"URL path for http must not be null, undefined or empty.")),Array.isArray(e)&&re(2===e.length,(()=>`URL paths for http must have a length of 2, (actual length is ${e.length}).`)),this.path=e,null!=t.requestInit&&null!=t.requestInit.body)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=t.requestInit||{}}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");const t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit);t.body=new FormData;const n=za(e,[{paths:["./model.weights.bin"],weights:e.weightSpecs}]);t.body.append("model.json",new Blob([JSON.stringify(n)],{type:"application/json"}),"model.json"),null!=e.weightData&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:"application/octet-stream"}),"model.weights.bin");const r=await this.fetch(this.path,t);if(r.ok)return{modelArtifactsInfo:Ba(e),responses:[r]};throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${r.status}.`)}async load(){const e=await this.fetch(this.path,this.requestInit);if(!e.ok)throw new Error(`Request to ${this.path} failed with status code ${e.status}. Please verify this URL points to the model JSON of the model to load.`);let t;try{t=await e.json()}catch(e){let t=`Failed to parse model JSON of response from ${this.path}.`;throw this.path.endsWith(".pb")?t+=" 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.":t+=" Please make sure the server is serving valid JSON for this request.",new Error(t)}const n=t.modelTopology,r=t.weightsManifest;if(null==n&&null==r)throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`);return Pa(t,(e=>this.loadWeights(e)))}async loadWeights(e){const t=Array.isArray(this.path)?this.path[1]:this.path,[n,r]=function(e){const t=e.lastIndexOf("/"),n=e.lastIndexOf("?");return[e.substring(0,t)+"/",n>t?e.substring(n):""]}(t),s=this.weightPathPrefix||n,a=[];for(const t of e)a.push(...t.weights);const i=[],o=[];for(const t of e)for(const e of t.paths)null!=this.weightUrlConverter?o.push(this.weightUrlConverter(e)):i.push(s+e+r);return this.weightUrlConverter&&i.push(...await Promise.all(o)),[a,Oa(await Fi(i,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress}))]}}function Li(e){return null!=e.match(Oi.URL_SCHEME_REGEX)}Oi.URL_SCHEME_REGEX=/^https?:\/\//;const zi=(e,t)=>{if("undefined"==typeof fetch&&(null==t||null==t.fetchFunc))return null;{let n=!0;if(n=Array.isArray(e)?e.every((e=>Li(e))):Li(e),n)return Pi(e,t)}return null};function Pi(e,t){return new Oi(e,t)}function Bi(e,t){return Pi(e,t)}Ua.registerSaveRouter(zi),Ua.registerLoadRouter(zi);class Vi{constructor(e){this.modelArtifacts=e}async load(){return this.modelArtifacts}}class Ui{constructor(e){this.saveHandler=e}async save(e){return this.saveHandler(e)}}function Wi(e,t,n,r){return 1===arguments.length?null!=e.modelTopology||null!=e.weightSpecs?new Vi(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 Vi({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 Vi({modelTopology:e,weightSpecs:t,weightData:n,trainingConfig:r}))}function Gi(e){return new Ui(e)}const Hi=Ta({matMul_:function(e,t,n=!1,r=!1){let s=Ia(e,"a","matMul"),a=Ia(t,"b","matMul");[s,a]=sa(s,a);const i={a:s,b:a},o={transposeA:n,transposeB:r};return da.runKernel(ft,i,o)}}),ji=Ta({oneHot_:function(e,t,n=1,r=0){if(t<2)throw new Error(`Error in oneHot: depth must be >=2, but it is ${t}`);const s={indices:Ia(e,"indices","oneHot","int32")},a={depth:t,onValue:n,offValue:r};return da.runKernel(Kn,s,a)}}),qi=Ta({transpose_:function(e,t){const n=Ia(e,"x","transpose");if(null==t&&(t=n.shape.map(((e,t)=>t)).reverse()),re(n.rank===t.length,(()=>`Error in transpose: rank of input ${n.rank} must match length of perm ${t}.`)),t.forEach((e=>{re(e>=0&&e"All entries in 'perm' must be between 0 and "+(n.rank-1)+` but got ${t}`))})),n.rank<=1)return n.clone();const r={x:n},s={perm:t};return da.runKernel(Hr,r,s)}}),Ki=Ta({confusionMatrix_:function(e,t,n){const r=Ia(e,"labels","confusionMatrix"),s=Ia(t,"predictions","confusionMatrix");re(null==n||n>0&&Number.isInteger(n),(()=>`If provided, numClasses must be a positive integer, but got ${n}`)),re(1===r.rank,(()=>`Expected the rank of labels to be 1, but got ${r.rank}`)),re(1===s.rank,(()=>`Expected the rank of predictions to be 1, but got ${s.rank}`)),re(r.shape[0]===s.shape[0],(()=>`Mismatch in the number of examples: ${r.shape[0]} vs. ${s.shape[0]}. Labels and predictions should have the same number of elements.`)),re(n>0&&Number.isInteger(n),(()=>`numClasses is required to be a positive integer, but got ${n}`));const a=ji(Si(r,"int32"),n),i=ji(Si(s,"int32"),n),o=qi(a),l=Hi(o,i);return Si(l,"int32")}});function Xi(e,t){const n=e.length,r=[];for(let s=0;s1&&1===i&&r.unshift(a)}return r}function Yi(e,t){const n=[];for(let r=0;r1)&&n.unshift(a)}return n}function Zi(e,t){const n=[],r=Math.max(e.length,t.length);for(let s=0;s4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");if(null==e)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");let n=!1,r=!1,s=!1,a=!1,i=!1,o=!1;if(e.data instanceof Uint8Array)n=!0;else if("undefined"!=typeof ImageData&&e instanceof ImageData)r=!0;else if("undefined"!=typeof HTMLVideoElement&&e instanceof HTMLVideoElement)s=!0;else if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)a=!0;else if(null!=e.getContext)i=!0;else{if(!("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap))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}`);o=!0}if(s){const t=2;if(s&&e.readyState element.")}if(null!=is(Zr,da.backendName)){const n={pixels:e},r={numChannels:t};return da.runKernel(Zr,n,r)}const[l,u]=s?[e.videoWidth,e.videoHeight]:[e.width,e.height];let c,h;if(i)c=e.getContext("2d").getImageData(0,0,l,u).data;else if(r||n)c=e.data;else if(a||s||o){if(null==Qi)if("undefined"==typeof document){if("undefined"==typeof OffscreenCanvas||"undefined"==typeof OffscreenCanvasRenderingContext2D)throw new Error("Cannot parse input in current context. Reason: OffscreenCanvas Context2D rendering is not supported.");Qi=new OffscreenCanvas(1,1).getContext("2d")}else Qi=document.createElement("canvas").getContext("2d");Qi.canvas.width=l,Qi.canvas.height=u,Qi.drawImage(e,0,0,l,u),c=Qi.getImageData(0,0,l,u).data}if(4===t)h=new Int32Array(c);else{const e=l*u;h=new Int32Array(e*t);for(let n=0;n4||2===a)throw new Error(`toPixels only supports depth of size 1, 3 or 4 but got ${a}`);if("float32"!==n.dtype&&"int32"!==n.dtype)throw new Error(`Unsupported type for toPixels: ${n.dtype}. Please use float32 or int32 tensors.`);const i=await n.data(),o="float32"===n.dtype?255:1,l=new Uint8ClampedArray(s*r*4);for(let e=0;e1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${s}.`)}else if("int32"===n.dtype&&(s<0||s>255))throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${s}.`);1===a?(t[0]=s*o,t[1]=s*o,t[2]=s*o):t[r]=s*o}const r=4*e;l[r+0]=Math.round(t[0]),l[r+1]=Math.round(t[1]),l[r+2]=Math.round(t[2]),l[r+3]=Math.round(t[3])}if(null!=t){t.width=s,t.height=r;const e=t.getContext("2d"),n=new ImageData(l,s,r);e.putImageData(n,0,0)}return n!==e&&n.dispose(),l}const ro=Ta({fromPixels_:eo});function so(e,t){const n=e.shape.length,r=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(r<1)throw new Error(`tf.gatherND() expects the indices to be rank 1 or higher, but the rank was ${r}.`);if("int32"!==t.dtype)throw new Error(`tf.gatherND() expects the indices to be int32 type, but the dtype was ${t.dtype}.`);if(t.shape[r-1]>n)throw new Error(`index innermost dimension length must be <= tensor rank; saw: ${t.shape[r-1]} vs. ${n}`);if(0===oe(e.shape))throw new Error(`Requested more than 0 entries, but input is empty. Input shape: ${e.shape}.`);const s=t.shape,a=s[s.length-1];let i=1;for(let e=0;ee/u)),1].slice(0,a);return[l,i,u,c]}function ao(e,t,n){const r=t.rank>1?t.shape[t.rank-1]:1,s=t.rank>1?t.rank-1:1,a=`Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: ${n.shape}, indices.shape: ${t.shape}, shape: ${e}, sliceDim: ${r}, and batchDim: ${s}.`;if(n.rank1?t.shape[r-1]:1,a=n.length;let i=1;for(let e=s;e`Error in slice${r}D: Length of begin ${t} must match the rank of the array (${r}).`)),re(r===n.length,(()=>`Error in slice${r}D: Length of size ${n} must match the rank of the array (${r}).`));for(let s=0;s`Error in slice${r}D: begin[${s}] + size[${s}] (${t[s]+n[s]}) would overflow input.shape[${s}] (${e.shape[s]})`))}function uo(e){const t=[];let n=0;for(;e>0;)1&e&&t.push(n),e/=2,n++;return t}function co(e,t,n){const r=[];for(let s=0;s0){const l=t[0],u=n+1;c=go(i,l,u,r,e),h=yo(o,l,u,s,e),p=ho(a,l,u,e)}else for(let t=0;t-1)a[s]=0;else{const i=po(t,n,s);let o=r[i];e&1<-1)a[s]=Number.MAX_SAFE_INTEGER;else{const i=po(t,n,s);let o=r[i];e&1<0?Number.MIN_SAFE_INTEGER:Number.MAX_SAFE_INTEGER);const l=r[s];return i<0&&(i+=l),i=Z(0,i,l-1),i}function wo(e,t,n,r,s,a){let i=t[s];const o=n[s]||1;(e&1<0?Number.MAX_SAFE_INTEGER:Number.MIN_SAFE_INTEGER);const l=r[s];return i<0&&(i+=l),i=o>0?Z(0,i,l):Z(-1,i,l-1),i}function vo(e,t,n){let r=n.length;for(let e=0;e1){r=e;break}for(let s=r+1;s0||n[s]!==e[s])return!1;return!0}function ko(e,t){let n=e.length>0?e[e.length-1]:1;for(let r=0;r{re(-1!==e,(()=>"slice() does not support negative begin indexing."))})),a=null==n?new Array(s).fill(-1):"number"==typeof n?[n,...new Array(s-1).fill(-1)]:n.lengtht>=0?t:(re(-1===t,(()=>`Negative size values should be exactly -1 but got ${t} for the slice() size at index ${n}.`)),e.shape[n]-r[n]))),[r,a]}function No(e,t,n,r,s,a,i,o,l){let u;if(null==r?(u=new Array(t.length),u.fill(1)):u=r,null!=i&&0!=(i&i-1))throw new Error("Multiple ellipses in slice is not allowed.");let c=!1;const h={dims:u.length,numAddAxisAfterEllipsis:0,begin:t.slice(),end:n.slice(),strides:u.slice(),beginMask:s,endMask:a,ellipsisMask:i,newAxisMask:o,shrinkAxisMask:l};for(let e=0;e0?0:-1,p.strides[t]>0?r:r-1];if(n&&p.strides[t]<=0)throw Error("only stride 1 allowed on non-range indexing.");m=m&&1===p.strides[t];const i=!!(p.beginMask&1<=r)throw Error(`slice index ${p.begin[t]} of dimension ${t} out of bounds.`)}else p.begin[t]=So(p.begin[t],0,p.strides[t],r,s,a),p.end[t]=So(p.end[t],1,p.strides[t],r,s,a);const e=1===p.strides[t]&&0===p.begin[t]&&p.end[t]===r;d=d&&e,f=f&&(0===t&&1===p.strides[t]||e)}else d=d&&1===p.strides[t]&&i,f=f&&(0===t&&1===p.strides[t]||i);let o,l=!1;if(p.beginValid&&p.endValid?(o=p.end[t]-p.begin[t],l=!0):n?(o=1,l=!0):i&&r>=0&&(o=p.strides[t]<0?-r:r,l=!0),l){let e;e=0===o||o<0!=p.strides[t]<0?0:Math.trunc(o/p.strides[t])+(o%p.strides[t]!=0?1:0),g.push(e)}else g.push(-1)}for(let e=0;e=0?y.push(g[t]):-2===t&&y.push(1)}return{finalShapeSparse:y.filter(((e,t)=>-2!==p.finalShapeGatherIndices[t])),finalShape:y,isIdentity:d,sliceDim0:f,isSimpleSlice:m,begin:p.begin,end:p.end,strides:p.strides}}function So(e,t,n,r,s,a){if(s[t])return n>0?a[t]:a[t+1&1];{const t=e<0?r+e:e;return ta[1]?a[1]:t}}class To{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}}class Co{constructor(){this.classNameMap={}}static getMap(){return null==Co.instance&&(Co.instance=new Co),Co.instance}static register(e){Co.getMap().classNameMap[e.className]=[e,e.fromConfig]}}function Eo(e){re(null!=e.className,(()=>"Class being registered does not have the static className property defined.")),re("string"==typeof e.className,(()=>"className is required to be a string, but got type "+typeof e.className)),re(e.className.length>0,(()=>"Class being registered has an empty-string as its className, which is disallowed.")),Co.register(e)}const $o=.1;function Ao(e,t,n){return null==n&&(n=Ro()),Mo(e,t,((e,t)=>Oo(e,t,n)))}function Ro(){return 32===da.backend.floatPrecision()?.001:$o}function Mo(e,t,n){let r=!0;if((Ne(e)||Ne(t))&&(r=!1),Ne(e)&&Ne(t)&&(r=!0),r){const n=e.constructor.name,r=t.constructor.name;if(n!==r)throw new Error(`Arrays are of different type. Actual: ${n}. Expected: ${r}`)}if(Array.isArray(e)&&Array.isArray(t)){const n=wa(e),r=wa(t);if(!ue(n,r))throw new Error(`Arrays have different shapes. Actual: [${n}]. Expected: [${r}]`)}const s=Ne(e)?e:ie(e),a=Ne(t)?t:ie(t);if(s.length!==a.length)throw new Error(`Arrays have different lengths actual: ${s.length} vs expected: ${a.length}.\nActual: ${s}.\nExpected: ${a}.`);for(let e=0;et.fail()),(()=>t()))}function Do(e,t){const n="string"==typeof t||"number"==typeof t||"boolean"==typeof t?[t]:t;return Ce(e)||Ce(e[0])||Ce(t)||Ce(t[0])?Mo(e,n,((e,t)=>e==t)):Mo(e,t,((e,t)=>Oo(e,t,0)))}function _o(e,t,n){if(null==n&&(n=Ro()),!Oo(e,t,n))throw new Error(`Numbers differ: actual === ${e}, expected === ${t}`)}function Oo(e,t,n){return!isFinite(e)&&!isFinite(t)||!(isNaN(e)||isNaN(t)||Math.abs(e-t)>n)}function Lo(e,t,n){for(let r=0;rn)throw new Error(`Value out of range:${e[r]} low: ${t}, high: ${n}`)}function zo(e,t){const n=new Float32Array(e),r=new Float32Array(t);if(n.length!==r.length)throw new Error(`Expected ArrayBuffer to be of length ${r.length}, but it was ${n.length}`);for(let e=0;ee.dispose()))}function Zo(e){return da.keep(e)}function Jo(e){return da.time(e)}function Qo(e){return da.setBackend(e)}function el(){return da.ready()}function tl(){return da.backendName}function nl(e){da.removeBackend(e)}function rl(e){return da.findBackend(e)}function sl(e){return da.findBackendFactory(e)}function al(e,t,n=1){return da.registerBackend(e,t,n)}function il(){return da.backend}function ol(e,t){He().setPlatform(e,t)}js=Go;const ll=Ta({add_:function(e,t){let n=Ia(e,"a","add"),r=Ia(t,"b","add");[n,r]=sa(n,r);const s={a:n,b:r};return da.runKernel(Qe,s)}}),ul=Ta({floorDiv_:function(e,t){let n=Ia(e,"a","floorDiv"),r=Ia(t,"b","floorDiv");[n,r]=sa(n,r);const s={a:n,b:r};return da.runKernel(rn,s)}}),cl=Ta({div_:function(e,t){let n=Ia(e,"a","div"),r=Ia(t,"b","div");if([n,r]=sa(n,r),"int32"===n.dtype&&"int32"===r.dtype)return ul(n,r);const s={a:n,b:r};return da.runKernel(Gt,s,{})}}),hl=Ta({mul_:function(e,t){let n=Ia(e,"a","mul"),r=Ia(t,"b","mul");[n,r]=sa(n,r);const s={a:n,b:r};return da.runKernel(Vn,s)}}),pl=Ta({sqrt_:function(e){const t={x:Ia(e,"x","sqrt","float32")};return da.runKernel(Ir,t)}}),dl=Ta({square_:function(e){const t=Ia(e,"x","square");return da.runKernel("Square",{x:t},{})}}),fl=Ta({zerosLike_:function(e){const t={x:Ia(e,"x","zerosLike")};return da.runKernel(Xr,t)}});function ml(e){return re(Re(e),(()=>"The f passed in grad(f) must be a function")),(t,n)=>{const r=Ia(t,"x","tf.grad","string_or_numeric"),s=null!=n?Ia(n,"dy","tf.grad"):null;return da.tidy((()=>{const{value:t,grads:n}=da.gradients((()=>e(r)),[r],s);return null!=s&&se(t.shape,s.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),vl(n),n[0]}))}}function gl(e){return re(Re(e),(()=>"The f passed in grads(f) must be a function")),(t,n)=>{re(Array.isArray(t),(()=>"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s"));const r=Na(t,"args","tf.grads","string_or_numeric"),s=null!=n?Ia(n,"dy","tf.grads"):null;return da.tidy((()=>{const{value:t,grads:n}=da.gradients((()=>e(...r)),r,s);return null!=s&&se(t.shape,s.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),vl(n),n}))}}function yl(e){return re(Re(e),(()=>"The f passed in valueAndGrad(f) must be a function")),(t,n)=>{re(t instanceof qs,(()=>"The x passed in valueAndGrad(f)(x) must be a tensor")),re(null==n||n instanceof qs,(()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor"));const{grads:r,value:s}=da.gradients((()=>e(t)),[t],n);return vl(r),{grad:r[0],value:s}}}function bl(e){return re(Re(e),(()=>"The f passed in valueAndGrads(f) must be a function")),(t,n)=>{re(Array.isArray(t)&&t.every((e=>e instanceof qs)),(()=>"The args passed in valueAndGrads(f)(args) must be array of tensors")),re(null==n||n instanceof qs,(()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor"));const r=da.gradients((()=>e(...t)),t,n);return null!=n&&se(r.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),vl(r.grads),r}}function xl(e,t){re(Re(e),(()=>"The f passed in variableGrads(f) must be a function")),re(null==t||Array.isArray(t)&&t.every((e=>e instanceof Xs)),(()=>"The varList passed in variableGrads(f, varList) must be an array of variables"));const n=null!=t;if(!n){t=[];for(const e in da.registeredVariables)t.push(da.registeredVariables[e])}const r=n?t.filter((e=>!e.trainable)):null,s=t.length;re((t=t.filter((e=>e.trainable))).length>0,(()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${s} variables is trainable.`));const{value:a,grads:i}=da.gradients(e,t,null,!0);re(i.some((e=>null!=e)),(()=>"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().")),re(0===a.rank,(()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${a.rank} tensor`));const o={};return t.forEach(((e,t)=>{null!=i[t]&&(o[e.name]=i[t])})),null!=r&&r.forEach((e=>o[e.name]=null)),{value:a,grads:o}}function wl(e){return da.customGrad(e)}function vl(e){if(e.filter((e=>null==e)).length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that\n the f you passed encloses all operations that lead from x to y.")}function kl(e,t){if((Ne(e)&&"string"!==t||Array.isArray(e))&&"complex64"!==t)throw new Error("Error creating a new Scalar: value must be a primitive (number|boolean|string)");if("string"===t&&Ne(e)&&!(e instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return Ea(e,[],[],t)}class Il extends To{minimize(e,t=!1,n){const{value:r,grads:s}=this.computeGradients(e,n);if(null!=n){const e=n.map((e=>({name:e.name,tensor:s[e.name]})));this.applyGradients(e)}else this.applyGradients(s);return Yo(s),t?r:(r.dispose(),null)}get iterations(){return null==this.iterations_&&(this.iterations_=0),this.iterations_}incrementIterations(){this.iterations_=this.iterations+1}computeGradients(e,t){return xl(e,t)}dispose(){null!=this.iterations_&&Yo(this.iterations_)}async saveIterations(){return null==this.iterations_&&(this.iterations_=0),{name:"iter",tensor:kl(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(Il,Symbol.hasInstance,{value:e=>null!=e.minimize&&null!=e.computeGradients&&null!=e.applyGradients});class Nl extends Il{constructor(e,t,n=null){super(),this.learningRate=e,this.rho=t,this.epsilon=n,this.accumulatedGrads=[],this.accumulatedUpdates=[],null==n&&(this.epsilon=da.backend.epsilon())}applyGradients(e){(Array.isArray(e)?e.map((e=>e.name)):Object.keys(e)).forEach(((t,n)=>{const r=da.registeredVariables[t];null==this.accumulatedGrads[n]&&(this.accumulatedGrads[n]={originalName:`${t}/accum_grad`,variable:Xo((()=>fl(r).variable(!1)))}),null==this.accumulatedUpdates[n]&&(this.accumulatedUpdates[n]={originalName:`${t}/accum_var`,variable:Xo((()=>fl(r).variable(!1)))});const s=Array.isArray(e)?e[n].tensor:e[t];if(null==s)return;const a=this.accumulatedGrads[n].variable,i=this.accumulatedUpdates[n].variable;Xo((()=>{const e=ll(hl(a,this.rho),hl(dl(s),1-this.rho)),t=hl(cl(pl(ll(i,this.epsilon)),pl(ll(a,this.epsilon))),s),n=ll(hl(i,this.rho),hl(dl(t),1-this.rho));a.assign(e),i.assign(n);const o=ll(hl(t,-this.learningRate),r);r.assign(o)}))})),this.incrementIterations()}dispose(){null!=this.accumulatedUpdates&&(Yo(this.accumulatedGrads.map((e=>e.variable))),Yo(this.accumulatedUpdates.map((e=>e.variable))))}async getWeights(){const e=[...this.accumulatedGrads,...this.accumulatedUpdates];return[await this.saveIterations()].concat(e.map((e=>({name:e.originalName,tensor:e.variable}))))}async setWeights(e){const t=(e=await this.extractIterations(e)).length/2;this.accumulatedGrads=e.slice(0,t).map((e=>({originalName:e.name,variable:e.tensor.variable(!1)}))),this.accumulatedUpdates=e.slice(t,2*t).map((e=>({originalName:e.name,variable:e.tensor.variable(!1)})))}getConfig(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.rho,t.epsilon)}}function Sl(e,t,n){const r={shape:e,value:t,dtype:n};return da.runKernel(en,{},r)}Nl.className="Adadelta",Eo(Nl);class Tl extends Il{constructor(e,t=.1){super(),this.learningRate=e,this.initialAccumulatorValue=t,this.accumulatedGrads=[]}applyGradients(e){(Array.isArray(e)?e.map((e=>e.name)):Object.keys(e)).forEach(((t,n)=>{const r=da.registeredVariables[t];if(null==this.accumulatedGrads[n]){const e=!1;this.accumulatedGrads[n]={originalName:`${t}/accumulator`,variable:Xo((()=>Sl(r.shape,this.initialAccumulatorValue).variable(e)))}}const s=Array.isArray(e)?e[n].tensor:e[t];if(null==s)return;const a=this.accumulatedGrads[n].variable;Xo((()=>{const e=ll(a,dl(s));a.assign(e);const t=ll(hl(cl(s,pl(ll(e,da.backend.epsilon()))),-this.learningRate),r);r.assign(t)}))})),this.incrementIterations()}dispose(){null!=this.accumulatedGrads&&Yo(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),this.accumulatedGrads=e.map((e=>({originalName:e.name,variable:e.tensor.variable(!1)})))}getConfig(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}}static fromConfig(e,t){return new e(t.learningRate,t.initialAccumulatorValue)}}Tl.className="Adagrad",Eo(Tl);const Cl=Ta({pow_:function(e,t){let n=Ia(e,"base","pow"),r=Ia(t,"exp","pow");[n,r]=sa(n,r);const s={a:n,b:r};return da.runKernel(Jn,s)}}),El=Ta({sub_:function(e,t){let n=Ia(e,"a","sub"),r=Ia(t,"b","sub");[n,r]=sa(n,r);const s={a:n,b:r};return da.runKernel(Pr,s)}});class $l extends Il{constructor(e,t,n,r=null){super(),this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=r,this.accumulatedFirstMoment=[],this.accumulatedSecondMoment=[],Xo((()=>{this.accBeta1=kl(t).variable(),this.accBeta2=kl(n).variable()})),null==r&&(this.epsilon=da.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map((e=>e.name)):Object.keys(e);Xo((()=>{const n=El(1,this.accBeta1),r=El(1,this.accBeta2);t.forEach(((t,s)=>{const a=da.registeredVariables[t];null==this.accumulatedFirstMoment[s]&&(this.accumulatedFirstMoment[s]={originalName:`${t}/m`,variable:Xo((()=>fl(a).variable(!1)))}),null==this.accumulatedSecondMoment[s]&&(this.accumulatedSecondMoment[s]={originalName:`${t}/v`,variable:Xo((()=>fl(a).variable(!1)))});const i=Array.isArray(e)?e[s].tensor:e[t];if(null==i)return;const o=this.accumulatedFirstMoment[s].variable,l=this.accumulatedSecondMoment[s].variable,u=ll(hl(o,this.beta1),hl(i,1-this.beta1)),c=ll(hl(l,this.beta2),hl(dl(i),1-this.beta2)),h=cl(u,n),p=cl(c,r);o.assign(u),l.assign(c);const d=ll(hl(cl(h,ll(pl(p),this.epsilon)),-this.learningRate),a);a.assign(d)})),this.accBeta1.assign(hl(this.accBeta1,this.beta1)),this.accBeta2.assign(hl(this.accBeta2,this.beta2))})),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.accBeta2.dispose(),null!=this.accumulatedFirstMoment&&Yo(this.accumulatedFirstMoment.map((e=>e.variable))),null!=this.accumulatedSecondMoment&&Yo(this.accumulatedSecondMoment.map((e=>e.variable)))}async getWeights(){const e=[...this.accumulatedFirstMoment,...this.accumulatedSecondMoment];return[await this.saveIterations()].concat(e.map((e=>({name:e.originalName,tensor:e.variable}))))}async setWeights(e){e=await this.extractIterations(e),Xo((()=>{this.accBeta1.assign(Cl(this.beta1,this.iterations_+1)),this.accBeta2.assign(Cl(this.beta2,this.iterations_+1))}));const t=e.length/2;this.accumulatedFirstMoment=e.slice(0,t).map((e=>({originalName:e.name,variable:e.tensor.variable(!1)}))),this.accumulatedSecondMoment=e.slice(t,2*t).map((e=>({originalName:e.name,variable:e.tensor.variable(!1)})))}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)}}$l.className="Adam",Eo($l);const Al=Ta({abs_:function(e){const t=Ia(e,"x","abs");if("complex64"===t.dtype){const e={x:t};return da.runKernel(It,e)}{const e={x:t};return da.runKernel(Ye,e)}}}),Rl=Ta({maximum_:function(e,t){let n=Ia(e,"a","maximum"),r=Ia(t,"b","maximum");[n,r]=sa(n,r),"bool"===n.dtype&&(n=Si(n,"int32"),r=Si(r,"int32")),Zi(n.shape,r.shape);const s={a:n,b:r};return da.runKernel($n,s)}});class Ml extends Il{constructor(e,t,n,r=null,s=0){super(),this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=r,this.decay=s,this.accumulatedFirstMoment=[],this.accumulatedWeightedInfNorm=[],Xo((()=>{this.iteration=kl(0).variable(),this.accBeta1=kl(t).variable()})),null==r&&(this.epsilon=da.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map((e=>e.name)):Object.keys(e);Xo((()=>{const n=El(1,this.accBeta1),r=cl(-this.learningRate,ll(hl(this.iteration,this.decay),1));t.forEach(((t,s)=>{const a=da.registeredVariables[t];null==this.accumulatedFirstMoment[s]&&(this.accumulatedFirstMoment[s]={originalName:`${t}/m`,variable:fl(a).variable(!1)}),null==this.accumulatedWeightedInfNorm[s]&&(this.accumulatedWeightedInfNorm[s]={originalName:`${t}/v`,variable:fl(a).variable(!1)});const i=Array.isArray(e)?e[s].tensor:e[t];if(null==i)return;const o=this.accumulatedFirstMoment[s].variable,l=this.accumulatedWeightedInfNorm[s].variable,u=ll(hl(o,this.beta1),hl(i,1-this.beta1)),c=hl(l,this.beta2),h=Al(i),p=Rl(c,h);o.assign(u),l.assign(p);const d=ll(hl(cl(r,n),cl(u,ll(p,this.epsilon))),a);a.assign(d)})),this.iteration.assign(ll(this.iteration,1)),this.accBeta1.assign(hl(this.accBeta1,this.beta1))})),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.iteration.dispose(),null!=this.accumulatedFirstMoment&&Yo(this.accumulatedFirstMoment.map((e=>e.variable))),null!=this.accumulatedWeightedInfNorm&&Yo(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)}}Ml.className="Adamax",Eo(Ml);class Fl extends Il{constructor(e){super(),this.learningRate=e,this.setLearningRate(e)}applyGradients(e){(Array.isArray(e)?e.map((e=>e.name)):Object.keys(e)).forEach(((t,n)=>{const r=Array.isArray(e)?e[n].tensor:e[t];if(null==r)return;const s=da.registeredVariables[t];Xo((()=>{const e=ll(hl(this.c,r),s);s.assign(e)}))})),this.incrementIterations()}setLearningRate(e){this.learningRate=e,null!=this.c&&this.c.dispose(),this.c=Zo(kl(-e))}dispose(){this.c.dispose()}async getWeights(){return[await this.saveIterations()]}async setWeights(e){if(0!==(e=await this.extractIterations(e)).length)throw new Error("SGD optimizer does not have settable weights.")}getConfig(){return{learningRate:this.learningRate}}static fromConfig(e,t){return new e(t.learningRate)}}Fl.className="SGD",Eo(Fl);class Dl extends Fl{constructor(e,t,n=!1){super(e),this.learningRate=e,this.momentum=t,this.useNesterov=n,this.accumulations=[],this.m=kl(this.momentum)}applyGradients(e){(Array.isArray(e)?e.map((e=>e.name)):Object.keys(e)).forEach(((t,n)=>{const r=da.registeredVariables[t];if(null==this.accumulations[n]){const e=!1;this.accumulations[n]={originalName:`${t}/momentum`,variable:Xo((()=>fl(r).variable(e)))}}const s=this.accumulations[n].variable,a=Array.isArray(e)?e[n].tensor:e[t];null!=a&&Xo((()=>{let e;const t=ll(hl(this.m,s),a);e=this.useNesterov?ll(hl(this.c,ll(a,hl(t,this.m))),r):ll(hl(this.c,t),r),s.assign(t),r.assign(e)}))})),this.incrementIterations()}dispose(){this.m.dispose(),null!=this.accumulations&&Yo(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),this.accumulations=e.map((e=>({originalName:e.name,variable:e.tensor.variable(!1)})))}getConfig(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}}static fromConfig(e,t){return new e(t.learningRate,t.momentum,t.useNesterov)}}Dl.className="Momentum",Eo(Dl);class _l extends Il{constructor(e,t=.9,n=0,r=null,s=!1){if(super(),this.learningRate=e,this.decay=t,this.momentum=n,this.epsilon=r,this.accumulatedMeanSquares=[],this.accumulatedMoments=[],this.accumulatedMeanGrads=[],this.centered=s,null==r&&(this.epsilon=da.backend.epsilon()),null==e)throw new Error("learningRate for RMSPropOptimizer must be defined.")}applyGradients(e){(Array.isArray(e)?e.map((e=>e.name)):Object.keys(e)).forEach(((t,n)=>{const r=da.registeredVariables[t],s=!1;null==this.accumulatedMeanSquares[n]&&(this.accumulatedMeanSquares[n]={originalName:`${t}/rms`,variable:Xo((()=>fl(r).variable(s)))}),null==this.accumulatedMoments[n]&&(this.accumulatedMoments[n]={originalName:`${t}/momentum`,variable:Xo((()=>fl(r).variable(s)))}),null==this.accumulatedMeanGrads[n]&&this.centered&&(this.accumulatedMeanGrads[n]={originalName:`${t}/mg`,variable:Xo((()=>fl(r).variable(s)))});const a=Array.isArray(e)?e[n].tensor:e[t];if(null==a)return;const i=this.accumulatedMeanSquares[n].variable,o=this.accumulatedMoments[n].variable;Xo((()=>{const e=ll(hl(i,this.decay),hl(dl(a),1-this.decay));if(this.centered){const t=this.accumulatedMeanGrads[n].variable,s=ll(hl(t,this.decay),hl(a,1-this.decay)),l=cl(hl(a,this.learningRate),pl(El(e,ll(dl(s),this.epsilon)))),u=ll(hl(o,this.momentum),l);i.assign(e),t.assign(s),o.assign(u);const c=El(r,u);r.assign(c)}else{const e=ll(hl(i,this.decay),hl(dl(a),1-this.decay)),t=ll(hl(o,this.momentum),cl(hl(a,this.learningRate),pl(ll(e,this.epsilon))));i.assign(e),o.assign(t);const n=El(r,t);r.assign(n)}}))})),this.incrementIterations()}dispose(){null!=this.accumulatedMeanSquares&&Yo(this.accumulatedMeanSquares.map((e=>e.variable))),null!=this.accumulatedMeanGrads&&this.centered&&Yo(this.accumulatedMeanGrads.map((e=>e.variable))),null!=this.accumulatedMoments&&Yo(this.accumulatedMoments.map((e=>e.variable)))}async getWeights(){const e=[...this.accumulatedMeanSquares,...this.accumulatedMoments];return this.centered&&e.push(...this.accumulatedMeanGrads),[await this.saveIterations()].concat(e.map((e=>({name:e.originalName,tensor:e.variable}))))}async setWeights(e){e=await this.extractIterations(e);const t=this.centered?e.length/3:e.length/2,n=!1;this.accumulatedMeanSquares=e.slice(0,t).map((e=>({originalName:e.name,variable:e.tensor.variable(n)}))),this.accumulatedMoments=e.slice(t,2*t).map((e=>({originalName:e.name,variable:e.tensor.variable(n)}))),this.centered&&(this.accumulatedMeanGrads=e.slice(2*t,3*t).map((e=>({originalName:e.name,variable:e.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)}}_l.className="RMSProp",Eo(_l);class Ol{static sgd(e){return new Fl(e)}static momentum(e,t,n=!1){return new Dl(e,t,n)}static rmsprop(e,t=.9,n=0,r=null,s=!1){return new _l(e,t,n,r,s)}static adam(e=.001,t=.9,n=.999,r=null){return new $l(e,t,n,r)}static adadelta(e=.001,t=.95,n=null){return new Nl(e,t,n)}static adamax(e=.002,t=.9,n=.999,r=null,s=0){return new Ml(e,t,n,r,s)}static adagrad(e,t=.1){return new Tl(e,t)}}const Ll=Ta({acos_:function(e){const t={x:Ia(e,"x","acos")};return da.runKernel(Ze,t)}}),zl=Ta({acosh_:function(e){const t={x:Ia(e,"x","acosh")};return da.runKernel(Je,t)}}),Pl=Ta({addN_:function(e){re(Array.isArray(e),(()=>"The argument passed to tf.addN() must be a list of tensors")),re(e.length>=1,(()=>`Must pass at least one tensor to tf.addN(), but got ${e.length}`));const t=e.map(((e,t)=>Ia(e,`tensors${t}`,"addN"))),n=t[0];t.forEach((e=>{if(e.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")})),t.forEach((e=>{if(!ue(e.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")}));const r=t;return da.runKernel(et,r)}}),Bl=Ta({all_:function(e,t=null,n=!1){const r={x:Ia(e,"x","all","bool")},s={axis:t,keepDims:n};return da.runKernel(tt,r,s)}}),Vl=Ta({any_:function(e,t=null,n=!1){const r={x:Ia(e,"x","any","bool")},s={axis:t,keepDims:n};return da.runKernel(nt,r,s)}}),Ul=Ta({argMax_:function(e,t=0){const n={x:Ia(e,"x","argMax")},r={axis:t};return da.runKernel(rt,n,r)}}),Wl=Ta({argMin_:function(e,t=0){const n={x:Ia(e,"x","argMin")},r={axis:t};return da.runKernel(st,n,r)}}),Gl=Ta({asin_:function(e){const t={x:Ia(e,"x","asin")};return da.runKernel(at,t)}}),Hl=Ta({asinh_:function(e){const t={x:Ia(e,"x","asinh")};return da.runKernel(it,t)}}),jl=Ta({atan_:function(e){const t={x:Ia(e,"x","atan")};return da.runKernel(ot,t)}}),ql=Ta({atan2_:function(e,t){let n=Ia(e,"a","atan2"),r=Ia(t,"b","atan2");[n,r]=sa(n,r);const s={a:n,b:r};return da.runKernel(ut,s)}}),Kl=Ta({atanh_:function(e){const t={x:Ia(e,"x","atanh")};return da.runKernel(lt,t)}});function Xl(e,t,n,r,s="NHWC",a){return Jl(e,[...t,e[3]],n,a,r,null,null,ou(s))}function Yl(e,t,n,r,s,a,i="channelsLast"){const[o,l]=tu(t);let u;if("channelsLast"===i)u=[o,l,e[3],e[3]];else{if("channelsFirst"!==i)throw new Error(`Unknown dataFormat ${i}`);u=[o,l,e[1],e[1]]}return Jl(e,u,n,r,s,a,!1,i)}function Zl(e,t,n,r,s,a,i="NDHWC"){const[o,l,u]=nu(t);let c,h;if("NDHWC"===i)h="channelsLast",c=[o,l,u,e[4],e[4]];else{if("NCDHW"!==i)throw new Error(`Unknown dataFormat ${i}`);h="channelsFirst",c=[o,l,u,e[1],e[1]]}return Ql(e,c,n,r,s,!1,h,a)}function Jl(e,t,n,r,s,a,i=!1,o="channelsLast"){let[l,u,c,h]=[-1,-1,-1,-1];if("channelsLast"===o)[l,u,c,h]=e;else{if("channelsFirst"!==o)throw new Error(`Unknown dataFormat ${o}`);[l,h,u,c]=e}const[p,d,,f]=t,[m,g]=tu(n),[y,b]=tu(r),x=ru(p,y),w=ru(d,b),{padInfo:v,outHeight:k,outWidth:I}=function(e,t,n,r,s,a,i,o,l){let u,c,h;if("number"==typeof e){u={top:e,bottom:e,left:e,right:e,type:0===e?"VALID":"NUMBER"};const s=function(e,t,n,r,s){null==r&&(r=eu(e,t,n));const a=e[1];return[su((e[0]-t+2*r)/n+1,s),su((a-t+2*r)/n+1,s)]}([t,n],a,r,e,o);c=s[0],h=s[1]}else if("same"===e){c=Math.ceil(t/r),h=Math.ceil(n/s);const e=Math.max(0,(c-1)*r+a-t),o=Math.max(0,(h-1)*s+i-n),l=Math.floor(e/2),p=e-l,d=Math.floor(o/2);u={top:l,bottom:p,left:d,right:o-d,type:"SAME"}}else if("valid"===e)u={top:0,bottom:0,left:0,right:0,type:"VALID"},c=Math.ceil((t-a+1)/r),h=Math.ceil((n-i+1)/s);else{if("object"!=typeof e)throw Error(`Unknown padding parameter: ${e}`);{const p="channelsLast"===l?e[1][0]:e[2][0],d="channelsLast"===l?e[1][1]:e[2][1],f="channelsLast"===l?e[2][0]:e[3][0],m="channelsLast"===l?e[2][1]:e[3][1];u={top:p,bottom:d,left:f,right:m,type:0===p&&0===d&&0===f&&0===m?"VALID":"EXPLICIT"},c=su((t-a+p+d)/r+1,o),h=su((n-i+f+m)/s+1,o)}}return{padInfo:u,outHeight:c,outWidth:h}}(s,u,c,m,g,x,w,a,o),N=i?f*h:f;let S;return"channelsFirst"===o?S=[l,N,k,I]:"channelsLast"===o&&(S=[l,k,I,N]),{batchSize:l,dataFormat:o,inHeight:u,inWidth:c,inChannels:h,outHeight:k,outWidth:I,outChannels:N,padInfo:v,strideHeight:m,strideWidth:g,filterHeight:p,filterWidth:d,effectiveFilterHeight:x,effectiveFilterWidth:w,dilationHeight:y,dilationWidth:b,inShape:e,outShape:S,filterShape:t}}function Ql(e,t,n,r,s,a=!1,i="channelsLast",o){let[l,u,c,h,p]=[-1,-1,-1,-1,-1];if("channelsLast"===i)[l,u,c,h,p]=e;else{if("channelsFirst"!==i)throw new Error(`Unknown dataFormat ${i}`);[l,p,u,c,h]=e}const[d,f,m,,g]=t,[y,b,x]=nu(n),[w,v,k]=nu(r),I=ru(d,w),N=ru(f,v),S=ru(m,k),{padInfo:T,outDepth:C,outHeight:E,outWidth:$}=function(e,t,n,r,s,a,i,o,l,u,c){let h,p,d,f;if("number"==typeof e){h={top:e,bottom:e,left:e,right:e,front:e,back:e,type:0===e?"VALID":"NUMBER"};const a=function(e,t,n,r,s,a){null==s&&(s=eu(e,t,r));const i=e[1],o=e[2];return[su((e[0]-t+2*s)/r+1,a),su((i-t+2*s)/r+1,a),su((o-t+2*s)/r+1,a),1]}([t,n,r,1],o,0,s,e,c);p=a[0],d=a[1],f=a[2]}else if("same"===e){p=Math.ceil(t/s),d=Math.ceil(n/a),f=Math.ceil(r/i);const e=(p-1)*s+o-t,c=(d-1)*a+l-n,m=(f-1)*i+u-r,g=Math.floor(e/2),y=e-g,b=Math.floor(c/2),x=c-b,w=Math.floor(m/2);h={top:b,bottom:x,left:w,right:m-w,front:g,back:y,type:"SAME"}}else{if("valid"!==e)throw Error(`Unknown padding parameter: ${e}`);h={top:0,bottom:0,left:0,right:0,front:0,back:0,type:"VALID"},p=Math.ceil((t-o+1)/s),d=Math.ceil((n-l+1)/a),f=Math.ceil((r-u+1)/i)}return{padInfo:h,outDepth:p,outHeight:d,outWidth:f}}(s,u,c,h,y,b,x,I,N,S,o),A=a?g*p:g;let R;return"channelsFirst"===i?R=[l,A,C,E,$]:"channelsLast"===i&&(R=[l,C,E,$,A]),{batchSize:l,dataFormat:i,inDepth:u,inHeight:c,inWidth:h,inChannels:p,outDepth:C,outHeight:E,outWidth:$,outChannels:A,padInfo:T,strideDepth:y,strideHeight:b,strideWidth:x,filterDepth:d,filterHeight:f,filterWidth:m,effectiveFilterDepth:I,effectiveFilterHeight:N,effectiveFilterWidth:S,dilationDepth:w,dilationHeight:v,dilationWidth:k,inShape:e,outShape:R,filterShape:t}}function eu(e,t,n,r=1){const s=ru(t,r);return Math.floor((e[0]*(n-1)-n+s)/2)}function tu(e){return"number"==typeof e?[e,e,e]:2===e.length?[e[0],e[1],1]:e}function nu(e){return"number"==typeof e?[e,e,e]:e}function ru(e,t){return t<=1?e:e+(e-1)*(t-1)}function su(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 au(e){const[t,n,r]=tu(e);return 1===t&&1===n&&1===r}function iu(e,t){return au(e)||au(t)}function ou(e){if("NHWC"===e)return"channelsLast";if("NCHW"===e)return"channelsFirst";throw new Error(`Unknown dataFormat ${e}`)}function lu(e,t,n){if(null!=n){if("string"==typeof t)throw Error(`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${t}.`);if("number"==typeof t)re(ce(t),(()=>`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${t}.`));else{if("object"!=typeof t)throw Error(`Error in ${e}: Unknown padding parameter: ${t}`);t.forEach((t=>{t.forEach((t=>{re(ce(t),(()=>`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${t}.`))}))}))}}}const uu=Ta({reshape_:function(e,t){const n={x:Ia(e,"x","reshape","string_or_numeric")},r={shape:t};return da.runKernel(ar,n,r)}}),cu=Ta({avgPool_:function(e,t,n,r,s){const a=Ia(e,"x","avgPool","float32");re(iu(n,1),(()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${n} and dilations '1'`));let i=a,o=!1;3===a.rank&&(o=!0,i=uu(a,[1,a.shape[0],a.shape[1],a.shape[2]])),re(4===i.rank,(()=>`Error in avgPool: x must be rank 4 but got rank ${i.rank}.`)),lu("avgPool",r,s);const l={x:i},u={filterSize:t,strides:n,pad:r,dimRoundingMode:s};let c=da.runKernel(ct,l,u);return c=Si(c,a.dtype),o?uu(c,[c.shape[1],c.shape[2],c.shape[3]]):c}}),hu=Ta({avgPool3d_:function(e,t,n,r,s,a="NDHWC"){const i=Ia(e,"x","avgPool3d","float32");let o=i,l=!1;4===i.rank&&(l=!0,o=uu(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),re(5===o.rank,(()=>`Error in avgPool3d: x must be rank 5 but got rank ${o.rank}.`)),re("NDHWC"===a,(()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${a}`)),lu("avgPool3d",r,s);const u={x:o},c={filterSize:t,strides:n,pad:r,dimRoundingMode:s,dataFormat:a};let h=da.runKernel(pt,u,c);return h=Si(h,o.dtype),l?uu(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}}),pu=Ta({concat_:function(e,t=0){re(e.length>=1,(()=>"Pass at least one tensor to concat"));const n=Na(e,"tensors","concat","string_or_numeric");if("complex64"===n[0].dtype&&n.forEach((e=>{if("complex64"!==e.dtype)throw new Error(`Cannot concatenate complex64 tensors with a tensor\n with dtype ${e.dtype}. `)})),1===n.length)return Ti(n[0]);const r=n,s={axis:t};return da.runKernel(Nt,r,s)}}),du=Ta({sigmoid_:function(e){const t={x:Ia(e,"x","sigmoid","float32")};return da.runKernel(vr,t)}}),fu=Ta({slice_:function(e,t,n){const r=Ia(e,"x","slice","string_or_numeric");if(0===r.rank)throw new Error("Slicing scalar is not possible");const s={x:r},a={begin:t,size:n};return da.runKernel(yr,s,a)}}),mu=Ta({tanh_:function(e){const t={x:Ia(e,"x","tanh","float32")};return da.runKernel(Vr,t)}}),gu=Ta({basicLSTMCell_:function(e,t,n,r,s,a){const i=Ia(e,"forgetBias","basicLSTMCell"),o=Ia(t,"lstmKernel","basicLSTMCell"),l=Ia(n,"lstmBias","basicLSTMCell"),u=Ia(r,"data","basicLSTMCell"),c=Ia(s,"c","basicLSTMCell"),h=Ia(a,"h","basicLSTMCell"),p=pu([u,h],1),d=Hi(p,o),f=ll(d,l),m=f.shape[0],g=f.shape[1]/4,y=[m,g],b=fu(f,[0,0],y),x=fu(f,[0,g],y),w=fu(f,[0,2*g],y),v=fu(f,[0,3*g],y),k=ll(hl(du(b),mu(x)),hl(c,du(ll(i,w))));return[k,hl(mu(k),du(v))]}}),yu=Ta({batchToSpaceND_:function(e,t,n){const r=Ia(e,"x","batchToSpaceND"),s=t.reduce(((e,t)=>e*t));re(r.rank>=1+t.length,(()=>`input rank is ${r.rank} but should be > than blockShape.length ${t.length}`)),re(n.length===t.length,(()=>`crops.length is ${n.length} but should be equal to blockShape.length ${t.length}`)),re(r.shape[0]%s==0,(()=>`input tensor batch is ${r.shape[0]} but is not divisible by the product of the elements of blockShape ${t.join(" * ")} === ${s}`));const a={x:r},i={blockShape:t,crops:n};return da.runKernel(mt,a,i)}}),bu=Ta({batchNorm_:function(e,t,n,r,s,a){null==a&&(a=.001);const i=Ia(e,"x","batchNorm"),o=Ia(t,"mean","batchNorm"),l=Ia(n,"variance","batchNorm");let u,c;null!=s&&(u=Ia(s,"scale","batchNorm")),null!=r&&(c=Ia(r,"offset","batchNorm")),re(o.rank===l.rank,(()=>"Batch normalization gradient requires mean and variance to have equal ranks.")),re(null==c||o.rank===c.rank,(()=>"Batch normalization gradient requires mean and offset to have equal ranks.")),re(null==u||o.rank===u.rank,(()=>"Batch normalization gradient requires mean and scale to have equal ranks."));const h={x:function(e){let t;return t=0===e.rank||1===e.rank?uu(e,[1,1,1,e.size]):2===e.rank?uu(e,[1,1,e.shape[0],e.shape[1]]):3===e.rank?uu(e,[1,e.shape[0],e.shape[1],e.shape[2]]):e,t}(i),scale:u,offset:c,mean:o,variance:l},p={varianceEpsilon:a},d=da.runKernel(sn,h,p);return uu(d,i.shape)}}),xu=Ta({batchNorm2d_:function(e,t,n,r,s,a){const i=Ia(e,"x","batchNorm"),o=Ia(t,"mean","batchNorm"),l=Ia(n,"variance","batchNorm");let u,c;return null!=s&&(u=Ia(s,"scale","batchNorm")),null!=r&&(c=Ia(r,"offset","batchNorm")),re(2===i.rank,(()=>`Error in batchNorm2D: x must be rank 2 but got rank ${i.rank}.`)),re(2===o.rank||1===o.rank,(()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${o.rank}.`)),re(2===l.rank||1===l.rank,(()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${l.rank}.`)),null!=u&&re(2===u.rank||1===u.rank,(()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${u.rank}.`)),null!=c&&re(2===c.rank||1===c.rank,(()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${c.rank}.`)),bu(i,o,l,c,u,a)}}),wu=Ta({batchNorm3d_:function(e,t,n,r,s,a){const i=Ia(e,"x","batchNorm"),o=Ia(t,"mean","batchNorm"),l=Ia(n,"variance","batchNorm");let u,c;return null!=s&&(u=Ia(s,"scale","batchNorm")),null!=r&&(c=Ia(r,"offset","batchNorm")),re(3===i.rank,(()=>`Error in batchNorm3D: x must be rank 3 but got rank ${i.rank}.`)),re(3===o.rank||1===o.rank,(()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${o.rank}.`)),re(3===l.rank||1===l.rank,(()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${l.rank}.`)),null!=u&&re(3===u.rank||1===u.rank,(()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${u.rank}.`)),null!=c&&re(3===c.rank||1===c.rank,(()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${c.rank}.`)),bu(i,o,l,c,u,a)}}),vu=Ta({batchNorm4d_:function(e,t,n,r,s,a){const i=Ia(e,"x","batchNorm"),o=Ia(t,"mean","batchNorm"),l=Ia(n,"variance","batchNorm");let u,c;return null!=s&&(u=Ia(s,"scale","batchNorm")),null!=r&&(c=Ia(r,"offset","batchNorm")),re(4===i.rank,(()=>`Error in batchNorm4D: x must be rank 4 but got rank ${i.rank}.`)),re(4===o.rank||1===o.rank,(()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${o.rank}.`)),re(4===l.rank||1===l.rank,(()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${l.rank}.`)),null!=u&&re(4===u.rank||1===u.rank,(()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${u.rank}.`)),null!=c&&re(4===c.rank||1===c.rank,(()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${c.rank}.`)),bu(i,o,l,c,u,a)}}),ku=Ta({bincount_:function(e,t,n){const r=Ia(e,"x","bincount"),s=Ia(t,"weights","bincount");re("int32"===r.dtype,(()=>`Error in bincount: input dtype must be int32, but got ${r.dtype}`)),re(n>=0,(()=>`size must be non-negative, but got ${n}.`)),re(s.size===r.size||0===s.size,(()=>`Error in bincount: weights must have the same size as input or0-length, but got input shape: ${r.shape}, weights shape: ${s.shape}.`));const a={x:r,weights:s},i={size:n};return da.runKernel(gt,a,i)}}),Iu=Ta({broadcastArgs_:function(e,t){const n=Ia(e,"s0","broadcastArgs","int32"),r=Ia(t,"s1","broadcastArgs","int32");if(1!==n.rank)throw new Error(`broadcastArgs(): first input must be a vector (rank=1). Has rank ${n.rank}`);if(1!==r.rank)throw new Error(`broadcastArgs(): second input must be a vector (rank=1). Has rank ${r.rank}`);const s={s0:n,s1:r};return da.runKernel(bt,s)}}),Nu=Ta({broadcastTo_:function(e,t){let n=Ia(e,"broadcastTo","x");const r=n.shape;if(t.some((e=>!(e>0)||e%1!=0)))throw new Error(`broadcastTo(): Invalid broadcast shape [${t}].`);if(t.lengthn.rank){const e=n.shape.slice();for(;e.length=0;e--)if(s[e]===t[e])a[e]=1;else if(1!==n.shape[e])throw new Error(`broadcastTo(): [${r}] cannot be broadcast to [${t}].`);if(0===a.map(((e,t)=>e>1?t:-1)).filter((e=>e>=0)).length)return Ti(n);const i={x:n},o={reps:a};return da.runKernel(Ur,i,o)}}),Su=Ta({ceil_:function(e){const t={x:Ia(e,"x","ceil","float32")};return da.runKernel(wt,t)}}),Tu=Ta({clipByValue_:function(e,t,n){const r=Ia(e,"x","clipByValue");re(t<=n,(()=>`Error in clip: min (${t}) must be less than or equal to max (${n}).`));const s={x:r},a={clipValueMin:t,clipValueMax:n};return da.runKernel(vt,s,a)}}),Cu=Ta({concat1d_:function(e){return pu(e,0)}}),Eu=Ta({concat2d_:function(e,t){return pu(e,t)}}),$u=Ta({concat3d_:function(e,t){return pu(e,t)}}),Au=Ta({concat4d_:function(e,t){return pu(e,t)}}),Ru=Ta({conv2d_:function(e,t,n,r,s="NHWC",a=[1,1],i){const o=Ia(e,"x","conv2d","float32"),l=Ia(t,"filter","conv2d","float32");let u=o,c=!1;3===o.rank&&(c=!0,u=uu(o,[1,o.shape[0],o.shape[1],o.shape[2]])),re(4===u.rank,(()=>`Error in conv2d: input must be rank 4, but got rank ${u.rank}.`)),re(4===l.rank,(()=>`Error in conv2d: filter must be rank 4, but got rank ${l.rank}.`)),lu("conv2d",r,i);const h="NHWC"===s?u.shape[3]:u.shape[1];re(h===l.shape[2],(()=>`Error in conv2d: depth of input (${h}) must match input depth for filter ${l.shape[2]}.`)),re(iu(n,a),(()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`));const p={x:u,filter:l},d={strides:n,pad:r,dataFormat:s,dilations:a,dimRoundingMode:i},f=da.runKernel(St,p,d);return c?uu(f,[f.shape[1],f.shape[2],f.shape[3]]):f}}),Mu=Ta({conv1d_:function(e,t,n,r,s="NWC",a=1,i){const o=Ia(e,"x","conv1d"),l=Ia(t,"filter","conv1d");let u=o,c=!1;2===o.rank&&(c=!0,u=uu(o,[1,o.shape[0],o.shape[1]])),re(3===u.rank,(()=>`Error in conv1d: input must be rank 3, but got rank ${u.rank}.`)),re(3===l.rank,(()=>`Error in conv1d: filter must be rank 3, but got rank ${l.rank}.`)),lu("conv1d",r,i),re(u.shape[2]===l.shape[1],(()=>`Error in conv1d: depth of input (${u.shape[2]}) must match input depth for filter ${l.shape[1]}.`)),re(iu(n,a),(()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${n} and dilation '${a}'`)),re("NWC"===s,(()=>`Error in conv1d: got dataFormat of ${s} but only NWC is currently supported.`));const h=uu(l,[1,l.shape[0],l.shape[1],l.shape[2]]),p=uu(u,[u.shape[0],1,u.shape[1],u.shape[2]]),d=Ru(p,h,[1,n],r,"NHWC",[1,a],i);return uu(d,c?[d.shape[2],d.shape[3]]:[d.shape[0],d.shape[2],d.shape[3]])}}),Fu=Ta({conv2DBackpropInput_:function(e,t,n,r,s,a="NHWC",i){re(e.length===t.rank,(()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`));let o=e,l=t,u=!1;3===t.rank&&(u=!0,l=uu(t,[1,t.shape[0],t.shape[1],t.shape[2]]),o=[1,e[0],e[1],e[2]]),re(4===o.length,(()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${o.length}.`)),re(4===l.rank,(()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${l.rank}`)),re(4===n.rank,(()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${n.rank}`));const c="NHWC"===a?o[3]:o[1],h="NHWC"===a?l.shape[3]:l.shape[1];re(c===n.shape[2],(()=>`Error in conv2dDerInput: depth of input (${c}) must match input depth for filter ${n.shape[2]}.`)),re(h===n.shape[3],(()=>`Error in conv2dDerInput: depth of output (${h}) must match output depth for filter ${n.shape[3]}.`)),lu("conv2dDerInput",s,i);const p={dy:l,filter:n},d={strides:r,pad:s,dataFormat:a,dimRoundingMode:i,inputShape:o},f=da.runKernel(Ct,p,d);return u?uu(f,[f.shape[1],f.shape[2],f.shape[3]]):f}}),Du=Ta({conv2dTranspose_:function(e,t,n,r,s,a){const i=Ia(e,"x","conv2dTranspose"),o=Ia(t,"filter","conv2dTranspose");return Fu(n,i,o,r,s,"NHWC",a)}}),_u=Ta({conv3d_:function(e,t,n,r,s="NDHWC",a=[1,1,1]){const i=Ia(e,"x","conv3d"),o=Ia(t,"filter","conv3d");let l=i,u=!1;4===i.rank&&(u=!0,l=uu(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),re(5===l.rank,(()=>`Error in conv3d: input must be rank 5, but got rank ${l.rank}.`)),re(5===o.rank,(()=>`Error in conv3d: filter must be rank 5, but got rank ${o.rank}.`)),re(l.shape[4]===o.shape[3],(()=>`Error in conv3d: depth of input (${l.shape[4]}) must match input depth for filter ${o.shape[3]}.`)),re(iu(n,a),(()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`)),re("NDHWC"===s,(()=>`Error in conv3d: got dataFormat of ${s} but only NDHWC is currently supported.`));const c={x:l,filter:o},h={strides:n,pad:r,dataFormat:s,dilations:a},p=da.runKernel(Et,c,h);return u?uu(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}}),Ou=Ta({conv3DBackpropInput_:function(e,t,n,r,s){re(e.length===t.rank,(()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`));let a=e,i=t,o=!1;4===t.rank&&(o=!0,i=uu(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]]),a=[1,e[0],e[1],e[2],e[3]]);const l=a[4],u=i.shape[4];re(5===a.length,(()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${a.length}.`)),re(5===i.rank,(()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${i.rank}`)),re(5===n.rank,(()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${n.rank}`)),re(l===n.shape[3],(()=>`Error in conv3dDerInput: depth of input (${l}) must match input depth for filter ${n.shape[3]}.`)),re(u===n.shape[4],(()=>`Error in conv3dDerInput: depth of output (${u}) must match output depth for filter ${n.shape[4]}.`));const c={dy:i,filter:n},h={pad:s,strides:r,inputShape:a},p=da.runKernel(At,c,h);return o?uu(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}}),Lu=Ta({conv3dTranspose_:function(e,t,n,r,s){const a=Ia(e,"x","conv3dTranspose"),i=Ia(t,"filter","conv3dTranspose");return Ou(n,a,i,r,s)}}),zu=Ta({cos_:function(e){const t={x:Ia(e,"x","cos","float32")};return da.runKernel(Rt,t)}}),Pu=Ta({cosh_:function(e){const t={x:Ia(e,"x","cosh","float32")};return da.runKernel(Mt,t)}}),Bu=Ta({cumsum_:function(e,t=0,n=!1,r=!1){const s={x:Ia(e,"x","cumsum")},a={axis:t,exclusive:n,reverse:r};return da.runKernel(Ft,s,a)}}),Vu=Ta({denseBincount_:function(e,t,n,r=!1){const s=Ia(e,"x","denseBincount"),a=Ia(t,"weights","denseBincount");re("int32"===s.dtype,(()=>`Error in denseBincount: input dtype must be int32, but got ${s.dtype}`)),re(s.rank<=2,(()=>`Error in denseBincount: input must be at most rank 2, but got rank ${s.rank}.`)),re(n>=0,(()=>`size must be non-negative, but got ${n}.`)),re(a.size===s.size||0===a.size,(()=>`Error in denseBincount: weights must have the same shape as x or 0-length, but got x shape: ${s.shape}, weights shape: ${a.shape}.`));const i={x:s,weights:a},o={size:n,binaryOutput:r};return da.runKernel(_t,i,o)}}),Uu=Ta({depthToSpace_:function(e,t,n="NHWC"){const r=Ia(e,"x","depthToSpace","float32"),s="NHWC"===n?r.shape[1]:r.shape[2],a="NHWC"===n?r.shape[2]:r.shape[3],i="NHWC"===n?r.shape[3]:r.shape[1];re(t>1,(()=>`blockSize should be > 1 for depthToSpace, but was: ${t}`)),re(s*t>=0,(()=>`Negative dimension size caused by overflow when multiplying\n ${s} and ${t} for depthToSpace with input shape\n ${r.shape}`)),re(a*t>=0,(()=>`Negative dimension size caused by overflow when multiplying\n ${a} and ${t} for depthToSpace with input shape\n ${r.shape}`)),re(i%(t*t)==0,(()=>`Dimension size must be evenly divisible by ${t*t} but is ${i} for depthToSpace with input shape ${r.shape}`));const o={x:r},l={blockSize:t,dataFormat:n};return da.runKernel(Ot,o,l)}}),Wu=Ta({depthwiseConv2d_:function(e,t,n,r,s="NHWC",a=[1,1],i){const o=Ia(e,"x","depthwiseConv2d","float32"),l=Ia(t,"filter","depthwiseConv2d","float32");let u=o,c=!1;3===o.rank&&(c=!0,u=uu(o,[1,o.shape[0],o.shape[1],o.shape[2]])),re(4===u.rank,(()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${u.rank}.`)),re(4===l.rank,(()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${l.rank}.`)),re(u.shape[3]===l.shape[2],(()=>`Error in depthwiseConv2d: number of input channels (${u.shape[3]}) must match the inChannels dimension in filter ${l.shape[2]}.`)),lu("depthwiseConv2d",r,i);const h={x:u,filter:l},p={strides:n,pad:r,dataFormat:s,dilations:a,dimRoundingMode:i},d=da.runKernel(Lt,h,p);return c?uu(d,[d.shape[1],d.shape[2],d.shape[3]]):d}}),Gu=Ta({diag_:function(e){const t={x:Ia(e,"x","diag")};return da.runKernel(Bt,t)}}),Hu=Ta({dilation2d_:function(e,t,n,r,s=[1,1],a="NHWC"){const i=Ia(e,"x","dilation2d"),o=Ia(t,"filter","dilation2d");re(3===i.rank||4===i.rank,(()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${i.rank}.`)),re(3===o.rank,(()=>`Error in dilation2d: filter must be rank 3, but got rank ${o.rank}.`)),re("NHWC"===a,(()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${a}`));let l=i,u=!1;3===i.rank&&(l=uu(i,[1,i.shape[0],i.shape[1],i.shape[2]]),u=!0);const c={x:l,filter:o},h={strides:n,pad:r,dilations:s},p=da.runKernel(Vt,c,h);return u?uu(p,[p.shape[1],p.shape[2],p.shape[3]]):p}}),ju=Ta({equal_:function(e,t){let n=Ia(e,"a","equal","string_or_numeric"),r=Ia(t,"b","equal","string_or_numeric");[n,r]=sa(n,r),Zi(n.shape,r.shape);const s={a:n,b:r};return da.runKernel(Xt,s)}}),qu=Ta({where_:function(e,t,n){const r=Ia(t,"a","where"),s=Ia(n,"b","where"),a=Ia(e,"condition","where","bool"),i=Zi(Zi(a.shape,r.shape),s.shape),o={condition:Nu(a,i),t:Nu(r,i),e:Nu(s,i)};return da.runKernel(mr,o)}}),Ku=Ta({divNoNan_:function(e,t){let n=Ia(e,"a","div"),r=Ia(t,"b","div");[n,r]=sa(n,r);const s=cl(n,r),a=fl(s),i=ju(r,a);return qu(i,a,s)}}),Xu=Ta({dot_:function(e,t){const n=Ia(e,"t1","dot"),r=Ia(t,"t2","dot");re(!(1!==n.rank&&2!==n.rank||1!==r.rank&&2!==r.rank),(()=>`Error in dot: inputs must all be rank 1 or 2, but got ranks ${n.rank} and ${r.rank}.`));const s=1===n.rank?n.size:n.shape[1],a=1===r.rank?r.size:r.shape[0];if(re(s===a,(()=>`Error in dot: inner dimensions of inputs must match, but got ${s} and ${a}.`)),1===n.rank&&1===r.rank){const e=uu(n,[1,-1]),t=uu(r,[-1,1]),s=Hi(e,t);return uu(s,[])}if(1===n.rank&&2===r.rank){const e=uu(n,[1,-1]),t=uu(r,[r.shape[0],r.shape[1]]),s=Hi(e,t);return uu(s,[s.size])}if(2===n.rank&&1===r.rank){const e=uu(r,[-1,1]),t=Hi(n,e);return uu(t,[t.size])}{const e=uu(r,[r.shape[0],r.shape[1]]);return Hi(n,e)}}}),Yu=Ta({einsum_:function(e,...t){const n=t.map(((e,t)=>Ia(e,`tensors${t}`,"einsum"))),r={equation:e};return da.runKernel(Ht,n,r)}}),Zu=Ta({elu_:function(e){const t={x:Ia(e,"x","elu","float32")};return da.runKernel(jt,t)}}),Ju=Ta({erf_:function(e){let t=Ia(e,"x","erf");re("int32"===t.dtype||"float32"===t.dtype,(()=>"Input dtype must be `int32` or `float32`.")),"int32"===t.dtype&&(t=Si(t,"float32"));const n={x:t};return da.runKernel(Kt,n)}}),Qu=Ta({exp_:function(e){const t={x:Ia(e,"x","exp")};return da.runKernel(Yt,t)}}),ec=Ta({expandDims_:function(e,t=0){const n=Ia(e,"x","expandDims","string_or_numeric");re(t<=n.rank,(()=>"Axis must be <= rank of the tensor"));const r={input:n},s={dim:t};return da.runKernel(Zt,r,s)}}),tc=Ta({expm1_:function(e){const t={x:Ia(e,"x","expm1")};return da.runKernel(Jt,t)}}),nc=Ta({tile_:function(e,t){const n=Ia(e,"x","tile","string_or_numeric");re(n.rank===t.length,(()=>`Error in transpose: rank of input ${n.rank} must match length of reps ${t}.`));const r={x:n},s={reps:t};return da.runKernel(Ur,r,s)}}),rc=Ta({eye_:function(e,t,n,r="float32"){null==t&&(t=e);const s=Ni([e,t],r),a=e<=t?e:t;for(let e=0;e`Error in localResponseNormalization: x must be rank 3 or 4 but got\n rank ${a.rank}.`)),re(ce(t),(()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`));let i=a,o=!1;3===a.rank&&(o=!0,i=uu(a,[1,a.shape[0],a.shape[1],a.shape[2]]));const l={x:i},u={depthRadius:t,bias:n,alpha:r,beta:s},c=da.runKernel(Tn,l,u);return o?uu(c,[c.shape[1],c.shape[2],c.shape[3]]):c}}),yc=Ta({log_:function(e){const t={x:Ia(e,"x","log","float32")};return da.runKernel(wn,t)}}),bc=Ta({log1p_:function(e){const t={x:Ia(e,"x","log1p")};return da.runKernel(vn,t)}}),xc=Ta({neg_:function(e){const t={x:Ia(e,"x","neg")};return da.runKernel(Un,t)}}),wc=Ta({softplus_:function(e){const t={x:Ia(e,"x","softplus")};return da.runKernel(kr,t)}}),vc=Ta({logSigmoid_:function(e){const t=Ia(e,"x","logSigmoid");return wl((e=>({value:xc(wc(xc(e))),gradFunc:t=>hl(t,du(xc(e)))})))(t)}}),kc=Ta({max_:function(e,t=null,n=!1){const r={x:Ia(e,"x","max")},s={reductionIndices:t,keepDims:n};return da.runKernel(En,r,s)}}),Ic=Ta({sum_:function(e,t=null,n=!1){let r=Ia(e,"x","sum");"bool"===r.dtype&&(r=Si(r,"int32"));const s={x:r},a={axis:t,keepDims:n};return da.runKernel(Nr,s,a)}}),Nc=Ta({logSoftmax_:function(e,t=-1){const n=Ia(e,"logits","logSoftmax");if(-1===t&&(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 wl(((e,n)=>{const r=kc(e,t,!0),s=El(e,r),a=El(Si(s,"float32"),yc(Ic(Qu(s),t,!0)));return n([a]),{value:a,gradFunc:(e,n)=>{const[r]=n,s=Qu(r);return El(e,hl(Ic(e,t,!0),s))}}}))(n)}});function Sc(e,t){for(let n=0;ne[t]))]}function Ec(e,t){return Tc(e,t.map((e=>1)),t)}function $c(e,t,n){re(Sc(t,n),(()=>`${e} supports only inner-most axes for now. Got axes ${t} and rank-${n} input.`))}function Ac(e,t){if(Sc(e,t))return null;const n=[];for(let r=0;rn.push(e))),n}function Rc(e){return e.map(((e,t)=>[t,e])).sort(((e,t)=>e[1]-t[1])).map((e=>e[0]))}function Mc(e,t){const n=[];for(let r=t-e;r`Error in maxPool: input must be rank 4 but got rank ${i.rank}.`)),re(iu(n,1),(()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${n} and dilations '1'`)),lu("maxPool",r,s);const l={x:i},u={filterSize:t,strides:n,pad:r,dimRoundingMode:s},c=da.runKernel(An,l,u);return o?uu(c,[c.shape[1],c.shape[2],c.shape[3]]):c}}),Pc=Ta({maxPool3d_:function(e,t=[1,1,1],n,r,s,a="NDHWC"){const i=Ia(e,"x","maxPool3d");let o=i,l=!1;4===i.rank&&(l=!0,o=uu(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),re(5===o.rank,(()=>`Error in maxPool3d: x must be rank 5 but got rank ${o.rank}.`)),re("NDHWC"===a,(()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${a}`)),lu("maxPool3d",r,s);const u={x:o},c={filterSize:t,strides:n,pad:r,dimRoundingMode:s,dataFormat:a},h=da.runKernel(Mn,u,c);return l?uu(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}}),Bc=Ta({maxPoolWithArgmax_:function(e,t,n,r,s=!1){const a={x:Ia(e,"x","maxPoolWithArgmax")},i={filterSize:t,strides:n,pad:r,includeBatchInIndex:s},o=da.runKernel(Dn,a,i);return{result:o[0],indexes:o[1]}}}),Vc=Ta({mean_:function(e,t=null,n=!1){const r={x:Ia(e,"x","mean")},s={axis:t,keepDims:n};return da.runKernel(_n,r,s)}});function Uc(e,t="float32"){if("complex64"===t){const t=Uc(e,"float32"),n=Uc(e,"float32");return Ca(t,n)}const n=Le(oe(e),t);return da.makeTensor(n,e,t)}function Wc(e,t="float32"){if("complex64"===t){const t=Wc(e,"float32"),n=Uc(e,"float32");return Ca(t,n)}const n=Oe(oe(e),t);return da.makeTensor(n,e,t)}function Gc(e,t,{indexing:n="xy"}={}){if("xy"!==n&&"ij"!==n)throw new TypeError(`${n} is not a valid third argument to meshgrid`);if(void 0===e)return[];let r=Ia(e,"x","meshgrid",e instanceof qs?e.dtype:"float32");if(void 0===t)return[r];let s=Ia(t,"y","meshgrid",t instanceof qs?t.dtype:"float32");const a=oe(r.shape),i=oe(s.shape);return"xy"===n?(r=uu(r,[1,-1]),s=uu(s,[-1,1]),[Hi(Wc([i,1],r.dtype),r),Hi(s,Wc([1,a],s.dtype))]):(r=uu(r,[-1,1]),s=uu(s,[1,-1]),[Hi(r,Wc([1,i],r.dtype)),Hi(Wc([a,1],s.dtype),s)])}const Hc=Ta({min_:function(e,t=null,n=!1){const r={x:Ia(e,"x","min")},s={axis:t,keepDims:n};return da.runKernel(On,r,s)}}),jc=Ta({minimum_:function(e,t){let n=Ia(e,"a","minimum"),r=Ia(t,"b","minimum");[n,r]=sa(n,r),"bool"===n.dtype&&(n=Si(n,"int32"),r=Si(r,"int32")),Zi(n.shape,r.shape);const s={a:n,b:r};return da.runKernel(Ln,s)}}),qc=Ta({mirrorPad_:function(e,t,n){re("reflect"===n||"symmetric"===n,(()=>`Invalid mode. Mode must be either reflect or symmetric. Got ${n}.`));const r=Ia(e,"x","mirrorPad");if(0===r.rank)throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");re(t.length===r.rank,(()=>`Padding doesn't match input. Must be ${r.rank}. Got ${t.length}.`));const s="reflect"===n?1:0;for(let e=0;e"Invalid number of paddings. Must be length of 2 each.")),re(t[e][0]>=0&&t[e][0]<=r.shape[e]-s&&t[e][1]>=0&&t[e][1]<=r.shape[e]-s,(()=>`Padding in dimension ${e} cannot be greater than or equal to ${r.shape[e]-s} or less than 0 for input of shape ${r.shape}`));const a={paddings:t,mode:n},i={x:r};return da.runKernel(zn,i,a)}}),Kc=Ta({mod_:function(e,t){let n=Ia(e,"a","mod"),r=Ia(t,"b","mod");[n,r]=sa(n,r);const s={a:n,b:r};return da.runKernel(Pn,s)}}),Xc=Ta({moments_:function(e,t=null,n=!1){const r=ye(t,(e=Ia(e,"x","moments")).shape),s=Vc(e,r,n);let a=s.shape;n||(a=Ec(s.shape,r));const i=dl(El(Si(e,"float32"),uu(s,a)));return{mean:s,variance:Vc(i,r,n)}}}),Yc=Ta({multiRNNCell_:function(e,t,n,r){const s=Ia(t,"data","multiRNNCell"),a=Na(n,"c","multiRNNCell"),i=Na(r,"h","multiRNNCell");let o=s;const l=[];for(let t=0;t2)throw new Error(`Rank of probabilities must be 1 or 2, but is ${i}`);n=n||Math.random();const o={logits:1===i?uu(s,[1,-1]):s},l={numSamples:t,seed:n,normalized:r},u=da.runKernel(Bn,o,l);return 1===i?uu(u,[u.size]):u}}),Jc=Ta({notEqual_:function(e,t){let n=Ia(e,"a","notEqual","string_or_numeric"),r=Ia(t,"b","notEqual","string_or_numeric");[n,r]=sa(n,r),Zi(n.shape,r.shape);const s={a:n,b:r};return da.runKernel(Wn,s)}}),Qc=Ta({onesLike_:function(e){const t={x:Ia(e,"x","onesLike")};return da.runKernel(qn,t)}}),eh=Ta({outerProduct_:function(e,t){const n=Ia(e,"v1","outerProduct"),r=Ia(t,"v2","outerProduct");re(1===n.rank&&1===r.rank,(()=>`Error in outerProduct: inputs must be rank 1, but got ranks ${n.rank} and ${r.rank}.`));const s=uu(n,[-1,1]),a=uu(r,[1,-1]);return Hi(s,a)}}),th=Ta({pad_:function(e,t,n=0){const r=Ia(e,"x","pad");if(0===r.rank)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");const s={paddings:t,constantValue:n},a={x:r};return da.runKernel(Yn,a,s)}}),nh=Ta({pad1d_:function(e,t,n=0){return re(2===t.length,(()=>"Invalid number of paddings. Must be length of 2.")),th(e,[t],n)}}),rh=Ta({pad2d_:function(e,t,n=0){return re(2===t.length&&2===t[0].length&&2===t[1].length,(()=>"Invalid number of paddings. Must be length of 2 each.")),th(e,t,n)}}),sh=Ta({pad3d_:function(e,t,n=0){return re(3===t.length&&2===t[0].length&&2===t[1].length&&2===t[2].length,(()=>"Invalid number of paddings. Must be length of 2 each.")),th(e,t,n)}}),ah=Ta({pad4d_:function(e,t,n=0){return re(4===t.length&&2===t[0].length&&2===t[1].length&&2===t[2].length&&2===t[3].length,(()=>"Invalid number of paddings. Must be length of 2 each.")),th(e,t,n)}}),ih=Ta({spaceToBatchND_:function(e,t,n){const r=Ia(e,"x","spaceToBatchND");re(r.rank>=1+t.length,(()=>`input rank ${r.rank} should be > than [blockShape] ${t.length}`)),re(n.length===t.length,(()=>`paddings.shape[0] ${n.length} must be equal to [blockShape] ${t.length}`)),re(r.shape.reduce(((e,r,s)=>s>0&&s<=t.length?e&&(r+n[s-1][0]+n[s-1][1])%t[s-1]==0:e),!0),(()=>`input spatial dimensions ${r.shape.slice(1)} with paddings ${n.toString()} must be divisible by blockShapes ${t.toString()}`));const s={x:r},a={blockShape:t,paddings:n};return da.runKernel(Sr,s,a)}}),oh=Ta({pool_:function(e,t,n,r,s,a,i){null==s&&(s=[1,1]),null==a&&(a=1),0===r&&(r="valid");const o=Ia(e,"x","maxPool");let l=o,u=!1;3===o.rank&&(u=!0,l=uu(o,[1,o.shape[0],o.shape[1],o.shape[2]])),re(iu(a,s),(()=>`Error in pool: Either strides or dilations must be 1. Got strides ${a} and dilations '${s}'`));const c=Yl(l.shape,t,a,s,r),h=[c.dilationHeight,c.dilationWidth];let p;p="same"===r?function(e,t){const n=e.map(((e,n)=>e+(e-1)*(t[n]-1))).map((e=>e-1)),r=n.map((e=>Math.floor(e/2))),s=n.map(((e,t)=>e-r[t]));return n.map(((e,t)=>[r[t],s[t]]))}([c.filterHeight,c.filterWidth],h):[[0,0],[0,0]];const d=1===h[0]&&1===h[1],[f,m]=function(e,t,n){const r=n.map((e=>e[0])),s=n.map((e=>e[1])),a=e.concat(r,s),i=t.map(((e,t)=>(e-a[t]%e)%e)),o=s.map(((e,t)=>e+i[t]));return[t.map(((e,t)=>[r[t],o[t]])),t.map(((e,t)=>[0,i[t]]))]}([c.inHeight,c.inWidth],h,p),g=d?r:"valid",y=d?l:ih(l,h,f),b=("avg"===n?()=>cu(y,t,a,g,i):()=>zc(y,t,a,g,i))(),x=d?b:yu(b,h,m);return u?uu(x,[x.shape[1],x.shape[2],x.shape[3]]):x}}),lh=Ta({prelu_:function(e,t){const n={x:Ia(e,"x","prelu"),alpha:Ia(t,"alpha","prelu")};return da.runKernel(Qn,n)}}),uh=Ta({prod_:function(e,t=null,n=!1){let r=Ia(e,"x","prod");"bool"===r.dtype&&(r=Si(r,"int32"));const s={x:r},a={axis:t,keepDims:n};return da.runKernel(er,s,a)}}),ch=Ta({rand_:function(e,t,n){const r=oe(e);let s=null;if(null==n||"float32"===n)s=new Float32Array(r);else if("int32"===n)s=new Int32Array(r);else{if("bool"!==n)throw new Error(`Unknown data type ${n}`);s=new Uint8Array(r)}for(let e=0;e=1||0===a);const i=Math.sqrt(-2*Math.log(a)/a);e=this.mean+this.stdDev*r*i,t=this.mean+this.stdDev*s*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 null==this.dtype||"float32"===this.dtype?e:Math.round(e)}isValidTruncated(e){return e<=this.upper&&e>=this.lower}}class dh{constructor(e,t,n,r){this.alpha=e,this.beta=1/t,this.dtype=n;const s=r||Math.random();this.randu=hh.alea(s.toString()),this.randn=new ph(0,1,n,!1,this.randu()),this.d=e<1?e+2/3:e-1/3,this.c=1/Math.sqrt(9*this.d)}nextValue(){let e,t,n,r,s,a;for(;;){do{r=this.randn.nextValue(),a=1+this.c*r}while(a<=0);if(a*=a*a,e=r*r,t=1-.331*e*e,n=.5*e+this.d*(1-a+Math.log(a)),s=this.randu(),snull==this.dtype||"float32"===this.dtype,this.min=e,this.range=t-e,this.dtype=n,null==r&&(r=Math.random()),"number"==typeof r&&(r=r.toString()),!this.canReturnFloat()&&this.range<=1)throw new Error(`The difference between ${e} - ${t} <= 1 and dtype is not float`);this.random=hh.alea(r)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}}const mh=Ta({randomGamma_:function(e,t,n=1,r="float32",s){if(null==n&&(n=1),null==r&&(r="float32"),"float32"!==r&&"int32"!==r)throw new Error(`Unsupported data type ${r}`);const a=new dh(t,n,r,s),i=Ni(e,r);for(let e=0;e`Error in reverse1D: x must be rank 1 but got rank ${t.rank}.`)),Ih(t,0)}}),Sh=Ta({reverse2d_:function(e,t){const n=Ia(e,"x","reverse");return re(2===n.rank,(()=>`Error in reverse2D: x must be rank 2 but got rank ${n.rank}.`)),Ih(n,t)}}),Th=Ta({reverse3d_:function(e,t){const n=Ia(e,"x","reverse");return re(3===n.rank,(()=>`Error in reverse3D: x must be rank 3 but got rank ${n.rank}.`)),Ih(n,t)}}),Ch=Ta({reverse4d_:function(e,t){const n=Ia(e,"x","reverse");return re(4===n.rank,(()=>`Error in reverse4D: x must be rank 4 but got rank ${n.rank}.`)),Ih(n,t)}}),Eh=Ta({round_:function(e){const t={x:Ia(e,"x","round")};return da.runKernel(pr,t)}}),$h=Ta({rsqrt_:function(e){const t={x:Ia(e,"x","rsqrt","float32")};return da.runKernel(dr,t)}}),Ah=Ta({selu_:function(e){const t={x:Ia(e,"x","selu")};return da.runKernel(gr,t)}}),Rh=Ta({separableConv2d_:function(e,t,n,r,s,a=[1,1],i="NHWC"){const o=Ia(e,"x","separableConv2d"),l=Ia(t,"depthwiseFilter","separableConv2d"),u=Ia(n,"pointwiseFilter","separableConv2d");let c=o,h=!1;if(3===o.rank&&(h=!0,c=uu(o,[1,o.shape[0],o.shape[1],o.shape[2]])),"NCHW"===i)throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");re(4===c.rank,(()=>`Error in separableConv2d: input must be rank 4, but got rank ${c.rank}.`)),re(4===l.rank,(()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${l.rank}.`)),re(4===u.rank,(()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${l.rank}.`)),re(1===u.shape[0],(()=>`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${u.shape[0]}.`)),re(1===u.shape[1],(()=>`Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${u.shape[1]}.`));const p=l.shape[2],d=l.shape[3];re(u.shape[2]===p*d,(()=>`Error in separableConv2d: the third dimension of pointwise filter must be ${p*d}, but got ${u.shape[2]}.`));const f=Wu(c,l,r,s,i,a),m=Ru(f,u,1,"valid",i);return h?uu(m,[m.shape[1],m.shape[2],m.shape[3]]):m}}),Mh=async function(e,t){const n=Ia(e,"x","setdiff1d"),r=Ia(t,"y","setdiff1d");re(n.dtype===r.dtype,(()=>`x and y should have the same dtype, but got x (${n.dtype}) and y (${r.dtype}).`)),re(1===n.rank,(()=>`x should be 1D tensor, but got x (${n.shape}).`)),re(1===r.rank,(()=>`y should be 1D tensor, but got y (${r.shape}).`));const s=await n.data(),a=await r.data(),i=new Set(a);let o=0;for(let e=0;e`slice1d expects a rank-1 tensor, but got a rank-${r.rank} tensor`)),fu(r,[t],[n])}}),Lh=Ta({slice2d_:function(e,t,n){const r=Ia(e,"x","slice2d");return re(2===r.rank,(()=>`slice2d expects a rank-2 tensor, but got a rank-${r.rank} tensor`)),fu(r,t,n)}}),zh=Ta({slice3d_:function(e,t,n){const r=Ia(e,"x","slice3d");return re(3===r.rank,(()=>`slice3d expects a rank-3 tensor, but got a rank-${r.rank} tensor`)),fu(r,t,n)}}),Ph=Ta({slice4d_:function(e,t,n){const r=Ia(e,"x","slice4d");return re(4===r.rank,(()=>`slice4d expects a rank-4 tensor, but got a rank-${r.rank} tensor`)),fu(r,t,n)}}),Bh=Ta({softmax_:function(e,t=-1){const n=Ia(e,"logits","softmax","float32");if(-1===t&&(t=n.rank-1),t!==n.rank-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${n.rank} and dim was ${t}`);const r={logits:n},s={dim:t};return da.runKernel(Cr,r,s)}}),Vh=Ta({fft_:function(e){re("complex64"===e.dtype,(()=>`The dtype for tf.spectral.fft() must be complex64 but got ${e.dtype}.`));const t={input:e};return da.runKernel(Qt,t)}}),Uh=Ta({ifft_:function(e){re("complex64"===e.dtype,(()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${e.dtype}.`));const t={input:e};return da.runKernel(hn,t)}}),Wh=Ta({irfft_:function(e){const t=e.shape[e.shape.length-1],n=e.size/t;let r;if(t<=2){const s=uu(e,[n,t]);r=Uh(s)}else{const s=[n,2*(t-1)],a=uu(xh(e),[n,t]),i=uu(lc(e),[n,t]),o=Ih(fu(a,[0,1],[n,t-2]),1),l=hl(Ih(fu(i,[0,1],[n,t-2]),1),kl(-1)),u=pu([a,o],1),c=pu([i,l],1),h=uu(Ca(u,c),[s[0],s[1]]);r=Uh(h)}if(r=xh(r),3===e.rank&&0!==e.shape[0]){const t=r,n=e.shape[0];r=uu(r,[n,r.shape[0]/n,r.shape[1]]),t.dispose()}return r}}),Gh=Ta({split_:function(e,t,n=0){const r={x:Ia(e,"x","split")},s={numOrSizeSplits:t,axis:n};return da.runKernel(Tr,r,s)}}),Hh=Ta({rfft_:function(e,t){re("float32"===e.dtype,(()=>`The dtype for rfft() must be real value but got ${e.dtype}`));let n=e.shape[e.shape.length-1];const r=e.size/n;let s;if(null!=t&&t0)),a=e.shape.map((e=>e));a[e.shape.length-1]=t,s=fu(e,r,a),n=t}else if(null!=t&&t>n){const r=e.shape.map((e=>e));r[e.shape.length-1]=t-n,s=pu([e,Uc(r)],e.shape.length-1),n=t}else s=e;const a=fl(s),i=uu(Ca(s,a),[r,n]),o=Vh(i),l=Math.floor(n/2)+1,u=xh(o),c=lc(o),h=Gh(u,[l,n-l],u.shape.length-1),p=Gh(c,[l,n-l],c.shape.length-1),d=s.shape.slice();return d[s.shape.length-1]=l,uu(Ca(h[0],p[0]),d)}}),jh=Ta({squaredDifference_:function(e,t){let n=Ia(e,"a","squaredDifference"),r=Ia(t,"b","squaredDifference");[n,r]=sa(n,r),Zi(n.shape,r.shape);const s={a:n,b:r};return da.runKernel(Fr,s,{})}}),qh=Ta({squeeze_:function(e,t){const n=Ia(e,"x","squeeze");return uu(n,be(n.shape,t).newShape)}}),Kh=Ta({stack_:function(e,t=0){const n=Na(e,"tensors","stack","string_or_numeric");re(n.length>=1,(()=>"Pass at least one tensor to tf.stack")),n.length>0&&re(t<=n[0].rank,(()=>"Axis must be <= rank of the tensor"));const r=n,s={axis:t};return da.runKernel(Xn,r,s)}}),Xh=Ta({step_:function(e,t=0){const n={x:Ia(e,"x","step")},r={alpha:t};return da.runKernel(Yr,n,r)}}),Yh=Ta({stridedSlice_:function(e,t,n,r,s=0,a=0,i=0,o=0,l=0){const u={x:Ia(e,"x","stridedSlice","string_or_numeric")},c={begin:t,end:n,strides:r,beginMask:s,endMask:a,ellipsisMask:i,newAxisMask:o,shrinkAxisMask:l};return da.runKernel(_r,u,c)}}),Zh=Ta({tan_:function(e){const t={x:Ia(e,"x","tan","float32")};return da.runKernel(Br,t)}});function Jh(e,t){ae(e);const n=wa(e,t);if(1!==n.length)throw new Error("tensor1d() requires values to be a flat/TypedArray");return Ea(e,null,n,t)}function Qh(e,t,n){if(ae(e),null!=t&&2!==t.length)throw new Error("tensor2d() requires shape to have two numbers");const r=wa(e,n);if(2!==r.length&&1!==r.length)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(1===r.length&&null==t)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return Ea(e,t,r,n)}function ep(e,t,n){if(ae(e),null!=t&&4!==t.length)throw new Error("tensor4d() requires shape to have four numbers");const r=wa(e,n);if(4!==r.length&&1!==r.length)throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");if(1===r.length&&null==t)throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");return Ea(e,t,r,n)}function tp(e,t,n){if(ae(e),null!=t&&5!==t.length)throw new Error("tensor5d() requires shape to have five numbers");const r=wa(e,n);if(5!==r.length&&1!==r.length)throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray");if(1===r.length&&null==t)throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");return Ea(e,t,r,n)}function np(e,t,n){if(ae(e),null!=t&&6!==t.length)throw new Error("tensor6d() requires shape to have six numbers");const r=wa(e,n);if(6!==r.length&&1!==r.length)throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray");if(1===r.length&&null==t)throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");return Ea(e,t=t||r,r,n)}const rp=Ta({topk_:function(e,t=1,n=!0){const r=Ia(e,"x","topk");if(0===r.rank)throw new Error("topk() expects the input to be of rank 1 or higher");const s=r.shape[r.shape.length-1];if(t<0)throw new Error(`'k' passed to topk() must be >= 0 but got ${t}`);if(t>s)throw new Error(`'k' passed to topk() must be <= the last dimension (${s}) but got ${t}`);const a={x:r},i={k:t,sorted:n},[o,l]=da.runKernel(Wr,a,i);return{values:o,indices:l}}}),sp=Ta({truncatedNormal_:function(e,t=0,n=1,r,s){if(null!=r&&"bool"===r)throw new Error("Unsupported data type $ { dtype }");const a=new ph(t,n,r,!0,s),i=Ni(e,r);for(let e=0;e0,(()=>"The input tensor must be at least 1D"));const r={x:n},s={axis:t},[a,i]=da.runKernel(jr,r,s);return{values:a,indices:i}}}),ip=Ta({unsortedSegmentSum_:function(e,t,n){const r=Ia(e,"x","unsortedSegmentSum"),s=Ia(t,"segmentIds","unsortedSegmentSum","int32");re(ce(n),(()=>"numSegments must be of dtype int"));const a={x:r,segmentIds:s},i={numSegments:n};return da.runKernel(Kr,a,i)}}),op=Ta({unstack_:function(e,t=0){const n=Ia(e,"x","unstack","string_or_numeric");re(t>=-n.shape.length&&t`Axis = ${t} is not in [-${n.shape.length}, ${n.shape.length})`));const r={value:n},s={axis:t};return da.runKernel(qr,r,s)}});function lp(e,t=!0,n,r){return da.makeVariable(e,t,n,r)}function up(e,t){const n=[];for(let e=0;e0,(()=>"mask cannot be scalar")),se(o.slice(a,a+i),s.shape,"mask's shape must match the first K dimensions of tensor's shape,");let l=1;for(let e=a;e"Shape mismatch in v and x"));const l=kl(1),u=El(l,o);let c=hl(El(i,a),u);if(s){re(null!=r,(()=>"When using zeroDebias: true, step is required."));const e=Ia(r,"step","movingAverage");c=cl(c,El(l,Cl(o,e)))}return ll(a,c)}}),mp=Ta({scatterND_:function(e,t,n){const r=Ia(e,"indices","scatterND","int32"),s=Ia(t,"updates","scatterND");io(s,r,n);const a={indices:r,updates:s},i={shape:n};return da.runKernel(fr,a,i)}}),gp=Ta({sparseToDense_:function(e,t,n,r=0){const s=Ia(e,"sparseIndices","sparseToDense","int32"),a=Ia(t,"sparseValues","sparseToDense"),i=Ia(r,"defaultValue","sparseToDense",a.dtype);!function(e,t,n,r){if("int32"!==e.dtype)throw new Error(`tf.sparseToDense() expects the indices to be int32 type, but the dtype was ${e.dtype}.`);if(e.rank>2)throw new Error(`sparseIndices should be a scalar, vector, or matrix, but got shape ${e.shape}.`);const s=e.rank>0?e.shape[0]:1,a=e.rank>1?e.shape[1]:1;if(n.length!==a)throw new Error(`outputShape has incorrect number of elements:, ${n.length}, should be: ${a}.`);const i=t.size;if(0!==t.rank&&(1!==t.rank||i!==s))throw new Error(`sparseValues has incorrect shape ${t.shape}, should be [] or [${s}]`);if(t.dtype!==r.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}(s,a,n,i);const o={sparseIndices:s,sparseValues:a,defaultValue:i},l={outputShape:n};return da.runKernel(Mr,o,l)}}),yp=Ta({gatherND_:function(e,t){const n=Ia(t,"indices","gatherND","int32"),r={params:Ia(e,"x","gatherND","string_or_numeric"),indices:n};return da.runKernel(on,r)}}),bp=Ta({dropout_:function(e,t,n,r){const s=Ia(e,"x","dropout");if(re("float32"===s.dtype,(()=>`x has to be a floating point tensor since it's going to be scaled, but got a ${s.dtype} tensor instead.`)),re(t>=0&&t<1,(()=>`rate must be a float in the range [0, 1), but got ${t}.`)),0===t)return e instanceof qs?s.clone():s;const a=function(e,t){if(null==t)return e.shape.slice();if(ue(e.shape,t))return t;if(e.shape.length===t.length){const n=[];for(let r=0;r1,(()=>`inTopK() expects the predictions to be of rank 2 or higher, but got ${r.rank}`)),re(r.rank-1===s.rank,(()=>`predictions rank should be 1 larger than targets rank, but got predictions rank ${r.rank} and targets rank ${s.rank}`)),se(r.shape.slice(0,r.shape.length-1),s.shape,"predictions's shape should be align with the targets' shape, except the last dimension.");const a=r.shape[r.shape.length-1];re(n>0&&n<=a,(()=>`'k' passed to inTopK() must be > 0 && <= the predictions last dimension (${a}), but got ${n}`));const i=await r.data(),o=await s.data(),[l,u]=[i.length/a,a],c=xe("bool",l);for(let e=0;et.value-e.value)),c[e]=0;for(let t=0;t`Error in conv2dDerFilter: input must be rank 4, but got shape ${o.shape}.`)),re(4===l.rank,(()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${l.shape}.`)),re(4===n.length,(()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${n}.`));const u="NHWC"===a?o.shape[3]:o.shape[1],c="NHWC"===a?l.shape[3]:l.shape[1];re(u===n[2],(()=>`Error in conv2dDerFilter: depth of input ${u}) must match input depth in filter (${n[2]}.`)),re(c===n[3],(()=>`Error in conv2dDerFilter: depth of dy (${c}) must match output depth for filter (${n[3]}).`)),lu("conv2dDerFilter",s,i);const h={x:o,dy:l},p={strides:r,pad:s,dataFormat:a,dimRoundingMode:i,filterShape:n};return da.runKernel(Tt,h,p)}});function Ip(e,t,n){if(null==n||"linear"===n)return e;if("relu"===n)return hl(e,Xh(t));throw new Error(`Cannot compute gradient for fused activation ${n}.`)}function Np(e,t){let n=t;const r=Yi(e.shape,t.shape);return r.length>0&&(n=Ic(n,r)),uu(n,e.shape)}function Sp(e,t,n,r){if("linear"===t)return e;if("relu"===t)return vh(e);if("elu"===t)return Zu(e);if("relu6"===t)return kh(e);if("prelu"===t)return lh(e,n);if("leakyrelu"===t)return pc(e,r);if("sigmoid"===t)return du(e);throw new Error(`Unknown fused activation ${t}.`)}const Tp=(e,t)=>!(e>0)||"linear"===t,Cp=Ta({fusedConv2d_:function({x:e,filter:t,strides:n,pad:r,dataFormat:s="NHWC",dilations:a=[1,1],dimRoundingMode:i,bias:o,activation:l="linear",preluActivationWeights:u,leakyreluAlpha:c}){if(l=l||"linear",!1===Tp(da.state.gradientDepth,l)){let h=Ru(e,t,n,r,s,a,i);return null!=o&&(h=ll(h,o)),Sp(h,l,u,c)}const h=Ia(e,"x","conv2d","float32"),p=Ia(t,"filter","conv2d","float32");let d=h,f=!1;3===h.rank&&(f=!0,d=uu(h,[1,h.shape[0],h.shape[1],h.shape[2]])),re(4===d.rank,(()=>`Error in fused conv2d: input must be rank 4, but got rank ${d.rank}.`)),re(4===p.rank,(()=>`Error in fused conv2d: filter must be rank 4, but got rank ${p.rank}.`)),lu("fused conv2d",r,i),re(d.shape[3]===p.shape[2],(()=>`Error in conv2d: depth of input (${d.shape[3]}) must match input depth for filter ${p.shape[2]}.`)),re(iu(n,a),(()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`)),re("NHWC"===s,(()=>`Error in conv2d: got dataFormat of ${s} but only NHWC is currently supported.`));const m=Jl(d.shape,p.shape,n,a,r,i);let g,y;null!=o&&(g=Ia(o,"bias","fused conv2d"),[g]=sa(g,h),Zi(m.outShape,g.shape)),null!=u&&(y=Ia(u,"prelu weights","fused conv2d"));const b=(e,t)=>{const[s,i,o,u]=t,c=Ip(e,o,l);re(au(a),(()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${a}'`));const h=[Fu(i.shape,c,s,n,r),kp(i,c,s.shape,n,r)];if(null!=u){const e=Np(u,c);h.push(e)}return h},x={x:d,filter:p,bias:g,preluActivationWeights:y},w={strides:n,pad:r,dataFormat:s,dilations:a,dimRoundingMode:i,activation:l,leakyreluAlpha:c};return null==o?wl(((e,t,n)=>{let r=da.runKernel(es,x,w);return n([t,e,r]),f&&(r=uu(r,[r.shape[1],r.shape[2],r.shape[3]])),{value:r,gradFunc:b}}))(d,p):wl(((e,t,n,r)=>{let s=da.runKernel(es,x,w);return r([t,e,s,n]),f&&(s=uu(s,[s.shape[1],s.shape[2],s.shape[3]])),{value:s,gradFunc:b}}))(d,p,g)}}),Ep=Ta({depthwiseConv2dNativeBackpropFilter_:function(e,t,n,r,s,a=[1,1],i){let o=e;3===e.rank&&(o=uu(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;3===l.rank&&(l=uu(t,[1,t.shape[0],t.shape[1],t.shape[2]]));const u={x:o,dy:l},c={strides:r,pad:s,dimRoundingMode:i,dilations:a,filterShape:n};return da.runKernel(zt,u,c)}}),$p=Ta({depthwiseConv2dNativeBackpropInput_:function(e,t,n,r,s,a=[1,1],i){let o=t,l=!1;3===t.rank&&(l=!0,o=uu(t,[1,t.shape[0],t.shape[1],t.shape[2]]));const u={dy:o,filter:n},c={strides:r,pad:s,dimRoundingMode:i,dilations:a,inputShape:e},h=da.runKernel(Pt,u,c);return l?uu(h,[h.shape[1],h.shape[2],h.shape[3]]):h}}),Ap=Ta({fusedDepthwiseConv2d_:function({x:e,filter:t,strides:n,pad:r,dataFormat:s="NHWC",dilations:a=[1,1],dimRoundingMode:i,bias:o,activation:l="linear",preluActivationWeights:u,leakyreluAlpha:c}){if(!1===Tp(da.state.gradientDepth,l)){let h=Wu(e,t,n,r,s,a,i);return null!=o&&(h=ll(h,o)),Sp(h,l,u,c)}const h=Ia(e,"x","depthwiseConv2d","float32"),p=Ia(t,"filter","depthwiseConv2d","float32");let d=h,f=!1;3===h.rank&&(f=!0,d=uu(h,[1,h.shape[0],h.shape[1],h.shape[2]])),re(4===d.rank,(()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${d.rank}.`)),re(4===p.rank,(()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${p.rank}.`)),re(d.shape[3]===p.shape[2],(()=>`Error in fused depthwiseConv2d: number of input channels (${d.shape[3]}) must match the inChannels dimension in filter ${p.shape[2]}.`)),null==a&&(a=[1,1]),re(iu(n,a),(()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`)),lu("fused depthwiseConv2d",r,i);const m=Jl(d.shape,p.shape,n,a,r,i,!0);let g,y;null!=o&&(g=Ia(o,"bias","fused conv2d"),[g]=sa(g,h),Zi(m.outShape,g.shape)),null!=u&&(y=Ia(u,"prelu weights","fused depthwiseConv2d"));const b=(e,t)=>{re(au(a),(()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${a}'`));const[s,o,u,c]=t,h=Ip(e,u,l),p=$p(o.shape,h,s,n,r,a,i),d=Ep(o,h,s.shape,n,r,a,i);return null!=c?[p,d,Np(g,h)]:[p,d]},x={x:d,filter:p,bias:g,preluActivationWeights:y},w={strides:n,pad:r,dataFormat:s,dilations:a,dimRoundingMode:i,activation:l,leakyreluAlpha:c};return null==o?wl(((e,t,n)=>{let r=da.runKernel(ts,x,w);return n([t,e,r]),f&&(r=uu(r,[r.shape[1],r.shape[2],r.shape[3]])),{value:r,gradFunc:b}}))(d,p):wl(((e,t,n,r)=>{let s=da.runKernel(ts,x,w);return r([t,e,s,n]),f&&(s=uu(s,[s.shape[1],s.shape[2],s.shape[3]])),{value:s,gradFunc:b}}))(d,p,g)}}),Rp=Ta({fusedMatMul_:function({a:e,b:t,transposeA:n=!1,transposeB:r=!1,bias:s,activation:a="linear",preluActivationWeights:i,leakyreluAlpha:o}){if(!1===Tp(da.state.gradientDepth,a)){let l=Hi(e,t,n,r);return null!=s&&(l=ll(l,s)),Sp(l,a,i,o)}let l=Ia(e,"a","fused matMul"),u=Ia(t,"b","fused matMul");[l,u]=sa(l,u);const c=n?l.shape[l.rank-2]:l.shape[l.rank-1],h=r?u.shape[u.rank-1]:u.shape[u.rank-2],p=n?l.shape[l.rank-1]:l.shape[l.rank-2],d=r?u.shape[u.rank-2]:u.shape[u.rank-1],f=l.shape.slice(0,-2),m=u.shape.slice(0,-2),g=oe(f),y=oe(m);re(c===h,(()=>`Error in fused matMul: inner shapes (${c}) and (${h}) of Tensors with shapes ${l.shape} and ${u.shape} and transposeA=${n} and transposeB=${r} must match.`));const b=Zi(l.shape.slice(0,-2),u.shape.slice(0,-2)).concat([p,d]),x=uu(l,n?[g,c,p]:[g,p,c]),w=uu(u,r?[y,d,h]:[y,h,d]);let v,k;null!=s&&(v=Ia(s,"bias","fused matMul"),[v]=sa(v,l),Zi(b,v.shape)),null!=i&&(k=Ia(i,"prelu weights","fused matMul"));const I=(e,t)=>{const[i,o,l,u]=t,c=Ip(uu(e,l.shape),l,a);let h,p;return n||r?!n&&r?(h=Hi(c,o,!1,!1),p=Hi(c,i,!0,!1)):n&&!r?(h=Hi(o,c,!1,!0),p=Hi(i,c,!1,!1)):(h=Hi(o,c,!0,!0),p=Hi(c,i,!0,!0)):(h=Hi(c,o,!1,!0),p=Hi(i,c,!0,!1)),null!=s?[h,p,Np(u,c)]:[h,p]},N={a:x,b:w,bias:v,preluActivationWeights:k},S={transposeA:n,transposeB:r,activation:a,leakyreluAlpha:o};return null==s?wl(((e,t,n)=>{const r=da.runKernel(Qr,N,S);return n([e,t,r]),{value:uu(r,b),gradFunc:I}}))(x,w):wl(((e,t,n,r)=>{const s=da.runKernel(Qr,N,S);return r([e,t,s,n]),{value:uu(s,b),gradFunc:I}}))(x,w,v)}}),Mp=Ta({hammingWindow_:function(e){return wp(e,.54,.46)}}),Fp=Ta({hannWindow_:function(e){return wp(e,.5,.5)}}),Dp=Ta({frame_:function(e,t,n,r=!1,s=0){let a=0;const i=[];for(;a+t<=e.size;)i.push(fu(e,a,t)),a+=n;if(r)for(;a`Error in cropAndResize: image must be rank 4,but got rank ${i.rank}.`)),re(2===o.rank&&4===o.shape[1],(()=>`Error in cropAndResize: boxes must be have size [${u},4] but had shape ${o.shape}.`)),re(1===l.rank&&l.shape[0]===u,(()=>`Error in cropAndResize: boxInd must be have size [${u}] but had shape ${o.shape}.`)),re(2===r.length,(()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${r.length}.`)),re(r[0]>=1&&r[1]>=1,(()=>`cropSize must be atleast [1,1], but was ${r}`)),re("bilinear"===s||"nearest"===s,(()=>`method must be bilinear or nearest, but was ${s}`));const c={image:i,boxes:o,boxInd:l},h={method:s,extrapolationValue:a,cropSize:r};return da.runKernel(Dt,c,h)}}),Lp=Ta({flipLeftRight_:function(e){const t=Ia(e,"image","flipLeftRight","float32");re(4===t.rank,(()=>`Error in flipLeftRight: image must be rank 4,but got rank ${t.rank}.`));const n={image:t};return da.runKernel(tn,n,{})}}),zp=Ta({grayscaleToRGB_:function(e){const t=Ia(e,"image","grayscaleToRGB"),n=t.rank-1,r=t.shape[n];re(t.rank>=2,(()=>`Error in grayscaleToRGB: images must be at least rank 2, but got rank ${t.rank}.`)),re(1===r,(()=>`Error in grayscaleToRGB: last dimension of a grayscale image should be size 1, but got size ${r}.`));const s=new Array(t.rank);return s.fill(1,0,n),s[n]=3,nc(t,s)}}),Pp=Ta({rotateWithOffset_:function(e,t,n=0,r=.5){const s=Ia(e,"image","rotateWithOffset","float32");re(4===s.rank,(()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${s.rank}.`));const a={image:s},i={radians:t,fillValue:n,center:r};return da.runKernel(Jr,a,i)}});function Bp(e,t,n,r,s,a){null==r&&(r=.5),null==s&&(s=Number.NEGATIVE_INFINITY),null==a&&(a=0);const i=e.shape[0];return n=Math.min(n,i),re(0<=r&&r<=1,(()=>`iouThreshold must be in [0, 1], but was '${r}'`)),re(2===e.rank,(()=>`boxes must be a 2D tensor, but was of rank '${e.rank}'`)),re(4===e.shape[1],(()=>`boxes must have 4 columns, but 2nd dimension was ${e.shape[1]}`)),re(1===t.rank,(()=>"scores must be a 1D tensor")),re(t.shape[0]===i,(()=>`scores has incompatible shape with boxes. Expected ${i}, but was ${t.shape[0]}`)),re(0<=a&&a<=1,(()=>`softNmsSigma must be in [0, 1], but was '${a}'`)),{maxOutputSize:n,iouThreshold:r,scoreThreshold:s,softNmsSigma:a}}const Vp=Ta({nonMaxSuppression_:function(e,t,n,r=.5,s=Number.NEGATIVE_INFINITY){const a=Ia(e,"boxes","nonMaxSuppression","float32"),i=Ia(t,"scores","nonMaxSuppression","float32"),o=Bp(a,i,n,r,s),l={maxOutputSize:n=o.maxOutputSize,iouThreshold:r=o.iouThreshold,scoreThreshold:s=o.scoreThreshold};return da.runKernel(Gn,{boxes:a,scores:i},l)}});function Up(e,t,n){const r=function(e,t,n){return function(e,t,n){let r=0,s=e.length,a=0,i=!1;for(;r>>1);const o=n(t,e[a]);o>0?r=a+1:(s=a,i=!o)}return i?r:-r-1}(e,t,n||Wp)}(e,t,n),s=r<0?-(r+1):r;e.splice(s,0,t)}function Wp(e,t){return e>t?1:es&&u.push({score:t[e],boxIndex:e,suppressBeginIndex:0});u.sort(Yp);const c=a>0?-.5/a:0,h=[],p=[];for(;h.length0;){const t=u.pop(),{score:n,boxIndex:a,suppressBeginIndex:i}=t;if(n=i;--n){const i=Kp(e,a,h[n]);if(i>=r){o=!0;break}if(t.score=t.score*Xp(r,c,i),t.score<=s)break}t.suppressBeginIndex=h.length,o||(t.score===n?(h.push(a),p.push(t.score)):t.score>s&&Up(u,t,Yp))}const d=h.length,f=n-d;o&&f>0&&(h.push(...new Array(f).fill(0)),p.push(...new Array(f).fill(0)));const m={selectedIndices:h};return i&&(m.selectedScores=p),l&&(m.validOutputs=d),m}function Kp(e,t,n){const r=e.subarray(4*t,4*t+4),s=e.subarray(4*n,4*n+4),a=Math.min(r[0],r[2]),i=Math.min(r[1],r[3]),o=Math.max(r[0],r[2]),l=Math.max(r[1],r[3]),u=Math.min(s[0],s[2]),c=Math.min(s[1],s[3]),h=Math.max(s[0],s[2]),p=Math.max(s[1],s[3]),d=(o-a)*(l-i),f=(h-u)*(p-c);if(d<=0||f<=0)return 0;const m=Math.max(a,u),g=Math.max(i,c),y=Math.min(o,h),b=Math.min(l,p),x=Math.max(y-m,0)*Math.max(b-g,0);return x/(d+f-x)}function Xp(e,t,n){const r=Math.exp(t*n*n);return n<=e?r:0}function Yp(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex}const Zp=Ta({nonMaxSuppressionWithScore_:function(e,t,n,r=.5,s=Number.NEGATIVE_INFINITY,a=0){const i=Ia(e,"boxes","nonMaxSuppression"),o=Ia(t,"scores","nonMaxSuppression"),l=Bp(i,o,n,r,s,a),u={boxes:i,scores:o},c={maxOutputSize:n=l.maxOutputSize,iouThreshold:r=l.iouThreshold,scoreThreshold:s=l.scoreThreshold,softNmsSigma:a=l.softNmsSigma},h=da.runKernel(jn,u,c);return{selectedIndices:h[0],selectedScores:h[1]}}}),Jp=Ta({nonMaxSuppressionPadded_:function(e,t,n,r=.5,s=Number.NEGATIVE_INFINITY,a=!1){const i=Ia(e,"boxes","nonMaxSuppression"),o=Ia(t,"scores","nonMaxSuppression"),l=Bp(i,o,n,r,s,null),u={boxes:i,scores:o},c={maxOutputSize:l.maxOutputSize,iouThreshold:l.iouThreshold,scoreThreshold:l.scoreThreshold,padToMaxOutputSize:a},h=da.runKernel(Hn,u,c);return{selectedIndices:h[0],validOutputs:h[1]}}}),Qp=Ta({resizeBilinear_:function(e,t,n=!1,r=!1){const s=Ia(e,"images","resizeBilinear");re(3===s.rank||4===s.rank,(()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${s.rank}.`)),re(2===t.length,(()=>`Error in resizeBilinear: new shape must 2D, but got shape ${t}.`)),re(!1===r||!1===n,(()=>"Error in resizeBilinear: If halfPixelCenters is true, alignCorners must be false."));let a=s,i=!1;3===s.rank&&(i=!0,a=uu(s,[1,s.shape[0],s.shape[1],s.shape[2]]));const[]=t,o={images:a},l={alignCorners:n,halfPixelCenters:r,size:t},u=da.runKernel(lr,o,l);return i?uu(u,[u.shape[1],u.shape[2],u.shape[3]]):u}}),ed=Ta({resizeNearestNeighbor_:function(e,t,n=!1,r=!1){const s=Ia(e,"images","resizeNearestNeighbor");re(3===s.rank||4===s.rank,(()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${s.rank}.`)),re(2===t.length,(()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${t}.`)),re("float32"===s.dtype||"int32"===s.dtype,(()=>"`images` must have `int32` or `float32` as dtype")),re(!1===r||!1===n,(()=>"Error in resizeNearestNeighbor: If halfPixelCenters is true, alignCorners must be false."));let a=s,i=!1;3===s.rank&&(i=!0,a=uu(s,[1,s.shape[0],s.shape[1],s.shape[2]]));const[]=t,o={images:a},l={alignCorners:n,halfPixelCenters:r,size:t},u=da.runKernel(ir,o,l);return i?uu(u,[u.shape[1],u.shape[2],u.shape[3]]):u}}),td=Ta({threshold_:function(e,t="binary",n=!1,r=.5){const s=Ia(e,"image","threshold"),a=s.shape[0]*s.shape[1];let i,o,l,u,c=hl(Jh([r]),255);if(re(3===s.rank,(()=>`Error in threshold: image must be rank 3,but got rank ${s.rank}.`)),re(3===s.shape[2]||1===s.shape[2],(()=>`Error in threshold: image color channel must be equal to 3 or 1but got ${s.shape[2]}.`)),re("int32"===s.dtype||"float32"===s.dtype,(()=>`Error in dtype: image dtype must be int32 or float32,but got dtype ${s.dtype}.`)),re("otsu"===t||"binary"===t,(()=>`Method must be binary or otsu, but was ${t}`)),3===s.shape[2]){[i,o,l]=Gh(s,[1,1,1],-1);const e=hl(i,.2989),t=hl(o,.587),n=hl(l,.114);u=ll(ll(e,t),n)}else u=e;"otsu"===t&&(c=function(e,t){let n,r,s,a,i,o,l=Jh([-1]),u=Jh([0]),c=Jh([0]);for(let h=0;h`Error in transform: image must be rank 4,but got rank ${i.rank}.`)),re(2===o.rank&&(o.shape[0]===i.shape[0]||1===o.shape[0])&&8===o.shape[1],(()=>"Error in transform: Input transform should be batch x 8 or 1 x 8")),re(null==a||2===a.length,(()=>`Error in transform: outputShape must be [height, width] or null, but got ${a}.`));const l={image:i,transforms:o},u={interpolation:n,fillMode:r,fillValue:s,outputShape:a};return da.runKernel(Gr,l,u)}}),rd=Ta({bandPart_:function(e,t,n){re(t%1==0,(()=>`bandPart(): numLower must be an integer, got ${t}.`)),re(n%1==0,(()=>`bandPart(): numUpper must be an integer, got ${n}.`));const r=Ia(e,"a","bandPart");re(r.rank>=2,(()=>`bandPart(): Rank must be at least 2, got ${r.rank}.`));const s=r.shape,[a,i]=r.shape.slice(-2);if(!(t<=a))throw new Error(`bandPart(): numLower (${t}) must not be greater than the number of rows (${a}).`);if(!(n<=i))throw new Error(`bandPart(): numUpper (${n}) must not be greater than the number of columns (${i}).`);t<0&&(t=a),n<0&&(n=i);const o=uu(bh(0,a,1,"int32"),[-1,1]),l=bh(0,i,1,"int32"),u=El(o,l),c=Dc(fc(u,kl(+t,"int32")),oc(u,kl(-n,"int32"))),h=Uc([a,i],r.dtype);return uu(Kh(op(uu(r,[-1,a,i])).map((e=>qu(c,e,h)))),s)}}),sd=Ta({gramSchmidt_:function(e){let t;if(Array.isArray(e)){t=!1,re(null!=e&&e.length>0,(()=>"Gram-Schmidt process: input must not be null, undefined, or empty"));const n=e[0].shape[0];for(let t=1;t`Gram-Schmidt: Non-unique lengths found in the input vectors: (${e[t].shape[0]} vs. ${n})`))}else t=!0,e=Gh(e,e.shape[0],0).map((e=>qh(e,[0])));re(e.length<=e[0].shape[0],(()=>`Gram-Schmidt: Number of vectors (${e.length}) exceeds number of dimensions (${e[0].shape[0]}).`));const n=[],r=e;for(let t=0;t{let e=r[t];if(t>0)for(let r=0;r{re(2===e.shape.length,(()=>`qr2d() requires a 2D Tensor, but got a ${e.shape.length}D Tensor.`));const n=e.shape[0],r=e.shape[1];let s=rc(n),a=Ti(e);const i=Qh([[1]],[1,1]);let o=Ti(i);const l=n>=r?r:n;for(let e=0;e{const t=fu(a,[e,e],[n-e,1]),l=dp(t),u=fu(a,[e,e],[1,1]),c=qu(ic(u,0),Qh([[-1]]),Qh([[1]])),h=El(u,hl(c,l)),p=cl(t,h);o=1===p.shape[0]?Ti(i):pu([i,fu(p,[1,0],[p.shape[0]-1,p.shape[1]])],0);const d=xc(cl(Hi(c,h),l)),f=fu(a,[e,0],[n-e,r]),m=hl(d,o),g=qi(o);if(0===e)a=El(f,Hi(m,Hi(g,f)));else{const t=El(f,Hi(m,Hi(g,f)));a=pu([fu(a,[0,0],[e,r]),t],0)}const y=qi(m),b=fu(s,[0,e],[n,s.shape[1]-e]);if(0===e)s=El(b,Hi(Hi(b,o),y));else{const t=El(b,Hi(Hi(b,o),y));s=pu([fu(s,[0,0],[n,e]),t],1)}return[o,a,s]})),Yo([t,l,u])}return!t&&n>r&&(s=fu(s,[0,0],[n,r]),a=fu(a,[0,0],[r,r])),[s,a]}))}const id=Ta({qr_:function(e,t=!1){if(re(e.rank>=2,(()=>`qr() requires input tensor to have a rank >= 2, but got rank ${e.rank}`)),2===e.rank)return ad(e,t);{const n=e.shape.slice(0,e.shape.length-2).reduce(((e,t)=>e*t)),r=op(uu(e,[n,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),s=[],a=[];return r.forEach((e=>{const[n,r]=ad(e,t);s.push(n),a.push(r)})),[uu(Kh(s,0),e.shape),uu(Kh(a,0),e.shape)]}}});var od;!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"}(od||(od={}));const ld=Ta({computeWeightedLoss_:function(e,t,n=od.SUM_BY_NONZERO_WEIGHTS){const r=Ia(e,"losses","computeWeightedLoss");let s=null;null!=t&&(s=Ia(t,"weights","computeWeightedLoss"));const a=null==s?r:hl(r,s);if(n===od.NONE)return a;if(n===od.SUM)return Ic(a);if(n===od.MEAN){if(null==s)return Vc(a);{const e=r.size/s.size,t=cl(Ic(a),Ic(s));return e>1?cl(t,kl(e)):t}}if(n===od.SUM_BY_NONZERO_WEIGHTS){if(null==s)return cl(Ic(a),kl(r.size));{const e=hl(s,Wc(r.shape)),t=Si(Ic(Jc(e,kl(0))),"float32");return cl(Ic(a),t)}}throw Error(`Unknown reduction: ${n}`)}}),ud=Ta({absoluteDifference_:function(e,t,n,r=od.SUM_BY_NONZERO_WEIGHTS){const s=Ia(e,"labels","absoluteDifference"),a=Ia(t,"predictions","absoluteDifference");let i=null;null!=n&&(i=Ia(n,"weights","absoluteDifference")),se(s.shape,a.shape,"Error in absoluteDifference: ");const o=Al(El(s,a));return ld(o,i,r)}}),cd=Ta({cosineDistance_:function(e,t,n,r,s=od.SUM_BY_NONZERO_WEIGHTS){const a=Ia(e,"labels","cosineDistance"),i=Ia(t,"predictions","cosineDistance");let o=null;null!=r&&(o=Ia(r,"weights","cosineDistance")),se(a.shape,i.shape,"Error in cosineDistance: ");const l=kl(1),u=El(l,Ic(hl(a,i),n,!0));return ld(u,o,s)}}),hd=Ta({hingeLoss_:function(e,t,n,r=od.SUM_BY_NONZERO_WEIGHTS){let s=Ia(e,"labels","hingeLoss");const a=Ia(t,"predictions","hingeLoss");let i=null;null!=n&&(i=Ia(n,"weights","hingeLoss")),se(s.shape,a.shape,"Error in hingeLoss: ");const o=kl(1);s=El(hl(kl(2),s),o);const l=vh(El(o,hl(s,a)));return ld(l,i,r)}}),pd=Ta({huberLoss_:function(e,t,n,r=1,s=od.SUM_BY_NONZERO_WEIGHTS){const a=Ia(e,"labels","huberLoss"),i=Ia(t,"predictions","huberLoss");let o=null;null!=n&&(o=Ia(n,"weights","huberLoss")),se(a.shape,i.shape,"Error in huberLoss: ");const l=kl(r),u=Al(El(i,a)),c=jc(u,l),h=El(u,c),p=ll(hl(kl(.5),dl(c)),hl(l,h));return ld(p,o,s)}}),dd=Ta({logLoss_:function(e,t,n,r=1e-7,s=od.SUM_BY_NONZERO_WEIGHTS){const a=Ia(e,"labels","logLoss"),i=Ia(t,"predictions","logLoss");let o=null;null!=n&&(o=Ia(n,"weights","logLoss")),se(a.shape,i.shape,"Error in logLoss: ");const l=kl(1),u=kl(r),c=xc(hl(a,yc(ll(i,u)))),h=hl(El(l,a),yc(ll(El(l,i),u))),p=El(c,h);return ld(p,o,s)}}),fd=Ta({meanSquaredError_:function(e,t,n,r=od.SUM_BY_NONZERO_WEIGHTS){const s=Ia(e,"labels","meanSquaredError"),a=Ia(t,"predictions","meanSquaredError");let i=null;null!=n&&(i=Ia(n,"weights","meanSquaredError")),se(s.shape,a.shape,"Error in meanSquaredError: ");const o=jh(s,a);return ld(o,i,r)}}),md=Ta({sigmoidCrossEntropy_:function(e,t,n,r=0,s=od.SUM_BY_NONZERO_WEIGHTS){let a=Ia(e,"multiClassLabels","sigmoidCrossEntropy");const i=Ia(t,"logits","sigmoidCrossEntropy");let o=null;if(null!=n&&(o=Ia(n,"weights","sigmoidCrossEntropy")),se(a.shape,i.shape,"Error in sigmoidCrossEntropy: "),r>0){const e=kl(r),t=kl(1),n=kl(.5);a=ll(hl(a,El(t,e)),hl(n,e))}const l=function(e,t){const n=Ia(e,"labels","sigmoidCrossEntropyWithLogits"),r=Ia(t,"logits","sigmoidCrossEntropyWithLogits");se(n.shape,r.shape,"Error in sigmoidCrossEntropyWithLogits: ");const s=vh(r),a=hl(r,n),i=bc(Qu(xc(Al(r))));return ll(El(s,a),i)}(a,i);return ld(l,o,s)}}),gd=Ta({softmaxCrossEntropy_:function(e,t,n,r=0,s=od.SUM_BY_NONZERO_WEIGHTS){let a=Ia(e,"onehotLabels","softmaxCrossEntropy");const i=Ia(t,"logits","softmaxCrossEntropy");let o=null;if(null!=n&&(o=Ia(n,"weights","softmaxCrossEntropy")),se(a.shape,i.shape,"Error in softmaxCrossEntropy: "),r>0){const e=kl(r),t=kl(1),n=kl(a.shape[1]);a=ll(hl(a,El(t,e)),cl(e,n))}const l=function(e,t,n=-1){if(-1===n&&(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 wl(((e,t,r)=>{const s=Fc(t,[n],!0),a=El(Si(t,"float32"),s);r([e,a]);const i=xc(hl(a,e));return{value:Ic(i,[n]),gradFunc:(e,t)=>{const[r,s]=t,a=Ec(e.shape,[n]);return[hl(uu(e,a),El(Si(r,"float32"),Qu(s))),hl(uu(e,a),El(Qu(s),Si(r,"float32")))]}}}))(e,t)}(a,i);return ld(l,o,s)}}),yd=Ta({sparseFillEmptyRows_:function(e,t,n,r){const s=Ia(e,"indices","sparseFillEmptyRows","int32"),a=Ia(t,"values","sparseFillEmptyRows"),i=Ia(n,"denseShape","sparseFillEmptyRows","int32"),o=Ia(r,"defaultValue","sparseFillEmptyRows",a.dtype);if(2!==s.rank)throw new Error(`Indices should be Tensor2D but received shape\n ${s.shape}`);if(1!==a.rank)throw new Error(`Values should be Tensor1D but received shape ${a.shape}`);if(1!==i.rank)throw new Error(`Dense shape should be Tensor1D but received shape ${i.shape}`);if(0!==o.rank)throw new Error(`Default value should be a scalar but received shape ${o.shape}`);const l={indices:s,values:a,denseShape:i,defaultValue:o},u=da.runKernel(Er,l);return{outputIndices:u[0],outputValues:u[1],emptyRowIndicator:u[2],reverseIndexMap:u[3]}}}),bd=Ta({sparseReshape_:function(e,t,n){const r=Ia(e,"inputIndices","sparseReshape","int32"),s=Ia(t,"inputShape","sparseReshape","int32"),a=Ia(n,"newShape","sparseReshape","int32");if(2!==r.rank)throw new Error(`Input indices should be Tensor2D but received shape\n ${r.shape}`);if(1!==s.rank)throw new Error(`Input shape should be Tensor1D but received shape ${s.shape}`);if(1!==a.rank)throw new Error(`New shape should be Tensor1D but received shape ${a.shape}`);const i={inputIndices:r,inputShape:s,newShape:a},o=da.runKernel($r,i);return{outputIndices:o[0],outputShape:o[1]}}}),xd=Ta({sparseSegmentMean_:function(e,t,n){const r=Ia(e,"data","sparseSegmentMean"),s=Ia(t,"indices","sparseSegmentMean","int32"),a=Ia(n,"segmentIds","sparseSegmentMean","int32");if(r.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(1!==s.rank)throw new Error(`Indices should be Tensor1D but received shape\n ${s.shape}`);if(1!==a.rank)throw new Error(`Segment ids should be Tensor1D but received shape\n ${a.shape}`);const i={data:r,indices:s,segmentIds:a};return da.runKernel(Ar,i)}}),wd=Ta({sparseSegmentSum_:function(e,t,n){const r=Ia(e,"data","sparseSegmentSum"),s=Ia(t,"indices","sparseSegmentSum","int32"),a=Ia(n,"segmentIds","sparseSegmentSum","int32");if(r.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(1!==s.rank)throw new Error(`Indices should be Tensor1D but received shape\n ${s.shape}`);if(1!==a.rank)throw new Error(`Segment ids should be Tensor1D but received shape\n ${a.shape}`);const i={data:r,indices:s,segmentIds:a};return da.runKernel(Rr,i)}}),vd=Ta({stringNGrams_:function(e,t,n,r,s,a,i,o){const l=Ia(e,"data","stringNGrams","string");if("string"!==l.dtype)throw new Error("Data must be of datatype string");if(1!==l.shape.length)throw new Error(`Data must be a vector, saw: ${l.shape}`);const u=Ia(t,"dataSplits","stringNGrams");if("int32"!==u.dtype)throw new Error("Data splits must be of datatype int32");const c={separator:n,nGramWidths:r,leftPad:s,rightPad:a,padWidth:i,preserveShortSequences:o},h={data:l,dataSplits:u},p=da.runKernel(Or,h,c);return{nGrams:p[0],nGramsSplits:p[1]}}}),kd=Ta({stringSplit_:function(e,t,n=!0){const r=Ia(e,"input","stringSplit","string"),s=Ia(t,"delimiter","stringSplit","string");if(1!==r.rank)throw new Error(`Input should be Tensor1D but received shape ${r.shape}`);if(0!==s.rank)throw new Error(`Delimiter should be a scalar but received shape ${s.shape}`);const a={skipEmpty:n},i={input:r,delimiter:s},o=da.runKernel(Lr,i,a);return{indices:o[0],values:o[1],shape:o[2]}}}),Id=Ta({stringToHashBucketFast_:function(e,t){const n=Ia(e,"input","stringToHashBucketFast","string"),r={numBuckets:t};if(t<=0)throw new Error("Number of buckets must be at least 1");const s={input:n};return da.runKernel(zr,s,r)}}),Nd={fft:Vh,ifft:Uh,rfft:Hh,irfft:Wh},Sd={hammingWindow:Mp,hannWindow:Fp,frame:Dp,stft:_p},Td={flipLeftRight:Lp,grayscaleToRGB:zp,resizeNearestNeighbor:ed,resizeBilinear:Qp,rotateWithOffset:Pp,cropAndResize:Op,nonMaxSuppression:Vp,nonMaxSuppressionAsync:async function(e,t,n,r=.5,s=Number.NEGATIVE_INFINITY){const a=Ia(e,"boxes","nonMaxSuppressionAsync"),i=Ia(t,"scores","nonMaxSuppressionAsync"),o=Bp(a,i,n,r,s);n=o.maxOutputSize,r=o.iouThreshold,s=o.scoreThreshold;const l=await Promise.all([a.data(),i.data()]),u=l[0],c=l[1],{selectedIndices:h}=Gp(u,c,n,r,s);return a!==e&&a.dispose(),i!==t&&i.dispose(),Jh(h,"int32")},nonMaxSuppressionWithScore:Zp,nonMaxSuppressionWithScoreAsync:async function(e,t,n,r=.5,s=Number.NEGATIVE_INFINITY,a=0){const i=Ia(e,"boxes","nonMaxSuppressionAsync"),o=Ia(t,"scores","nonMaxSuppressionAsync"),l=Bp(i,o,n,r,s,a);n=l.maxOutputSize,r=l.iouThreshold,s=l.scoreThreshold,a=l.softNmsSigma;const u=await Promise.all([i.data(),o.data()]),c=u[0],h=u[1],{selectedIndices:p,selectedScores:d}=jp(c,h,n,r,s,a);return i!==e&&i.dispose(),o!==t&&o.dispose(),{selectedIndices:Jh(p,"int32"),selectedScores:Jh(d)}},nonMaxSuppressionPadded:Jp,nonMaxSuppressionPaddedAsync:async function(e,t,n,r=.5,s=Number.NEGATIVE_INFINITY,a=!1){const i=Ia(e,"boxes","nonMaxSuppressionAsync"),o=Ia(t,"scores","nonMaxSuppressionAsync"),l=Bp(i,o,n,r,s,null),u=l.maxOutputSize,c=l.iouThreshold,h=l.scoreThreshold,[p,d]=await Promise.all([i.data(),o.data()]),{selectedIndices:f,validOutputs:m}=Hp(p,d,u,c,h,a);return i!==e&&i.dispose(),o!==t&&o.dispose(),{selectedIndices:Jh(f,"int32"),validOutputs:kl(m,"int32")}},threshold:td,transform:nd},Cd={bandPart:rd,gramSchmidt:sd,qr:id},Ed={absoluteDifference:ud,computeWeightedLoss:ld,cosineDistance:cd,hingeLoss:hd,huberLoss:pd,logLoss:dd,meanSquaredError:fd,sigmoidCrossEntropy:md,softmaxCrossEntropy:gd},$d={sparseFillEmptyRows:yd,sparseReshape:bd,sparseSegmentMean:xd,sparseSegmentSum:wd},Ad={stringNGrams:vd,stringSplit:kd,stringToHashBucketFast:Id},Rd={sgd:Ol.sgd,momentum:Ol.momentum,adadelta:Ol.adadelta,adagrad:Ol.adagrad,rmsprop:Ol.rmsprop,adamax:Ol.adamax,adam:Ol.adam},Md="undefined"!=typeof requestAnimationFrame?requestAnimationFrame:"undefined"!=typeof setImmediate?setImmediate:e=>e();function Fd(){return new Promise((e=>Md((()=>e()))))}function Dd(e,t){const n=e[0].length;e.forEach(((e,t)=>{re(e.length===n,(()=>`Error in concat${n}D: rank of tensors[${t}] must be the same as the rank of the rest (${n})`))})),re(t>=0&&t`Error in concat${n}D: axis must be between 0 and ${n-1}.`));const r=e[0];e.forEach(((e,s)=>{for(let a=0;a`Error in concat${n}D: Shape of tensors[${s}] (${e}) does not match the shape of the rest (${r}) along the non-concatenated axis ${s}.`))}))}function _d(e,t){const n=e[0].slice();for(let r=1;r=2*t+1||r%2==1?s.push(r):n.push(r);r.push(...n),r.push(0),r.push(...s)}return r}function Vd(e,t,n,r=!0){const s=[];r?s.push(e[0]/n):s.push(e[0]*n);for(let n=1;n/g;function lf(e,t){const n=((e=e.replace(/\s/g,"")).length-e.replace(of,"").length)/"->".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 ("->").');const[r,s]=e.split("->");re(-1===r.indexOf("..."),(()=>'The ellipsis notation ("...") is not supported yet.'));const a=r.split(","),i=a.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.");const o=[];for(let e=0;e-1!==e.indexOf(t))))throw new Error(`Output subscripts contain the label ${t} not present in the input subscripts.`);-1===o.indexOf(t)&&o.push(t)}for(let e=0;e-1!==e)),{permutationIndices:n,expandDims:r}}function cf(e,t,n){const r=new Array(e);for(let e=0;e`Expected dimension ${r[t[e][n]]} at axis ${n} of input shaped ${JSON.stringify(s)}, but got dimension ${s[n]}`))}}function hf(e,t){const n=e,r=[];let s=0;0===e.length&&n.push(-1),s=e.length+1;for(let e=0;ee===t))}function df(e,t){const n=[];for(let r=0;r"Number of splits must evenly divide the axis.")),r=new Array(t).fill(e.shape[n]/t);else{re(t.reduce(((e,t)=>(-1===t&&(e+=1),e)),0)<=1,(()=>"There should be only one negative value in split array."));const s=t.indexOf(-1);if(-1!==s){const r=t.reduce(((e,t)=>t>0?e+t:e));t[s]=e.shape[n]-r}re(e.shape[n]===t.reduce(((e,t)=>e+t)),(()=>"The sum of sizes must match the size of the axis dimension.")),r=t}return r}function mf(e){return`Received SparseTensor with denseShape[0] = 0 but\n indices.shape[0] = ${e}`}function gf(e,t){return`indices(${e}, 0) is invalid: ${t} < 0`}function yf(e,t,n){return`indices(${e}, 0) is invalid: ${t} >= ${n}`}function bf(e,t){return`only one output dimension may be -1, not both ${e} and ${t}`}function xf(e,t){return`size ${e} must be non-negative, not ${t}`}function wf(){return"reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero"}function vf(e,t){return`Input to reshape is a SparseTensor with ${oe(e)}\n dense values, but the requested shape requires a multiple of ${oe(t)}. inputShape=${e} outputShape= ${t}`}function kf(e,t){return`Input to reshape is a tensor with ${oe(e)} dense values, but the requested shape has ${oe(t)}. inputShape=${e} outputShape=${t}`}function If(){return"segment ids must be >= 0"}function Nf(){return"segment ids are not increasing"}function Sf(e,t){return`Segment id ${e} out of range [0, ${t}), possibly because segmentIds input is not sorted.`}function Tf(e,t,n){return`Bad: indices[${e}] == ${t} out of range [0, ${n})`}function Cf(e,t){let n,r=!1;for(e<=Od?(n=e,r=!0):n=Me(e,Math.floor(Math.sqrt(e)));!r;)n>t||n===e?r=!0:n=Me(e,n+1);return n}function Ef(e,t,n){const r=[],s=e.length;for(let a=0;as))throw new Error(`Expect batchDims in the range of [-${s}, ${s}], but got ${r}`);if(r<0&&(r+=s),r>a)throw new Error(`batchDims (${r}) must be less than rank(x) (\n ${a}).`);if(nDs(e)))}catch(e){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${e}`)}}function Rf(e){return e.map((e=>Fs(e)))}const Mf={kernelName:Ye,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>hl(e,Xh(Si(n,"float32"),-1))}}},Ff={kernelName:Ze,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const t=dl(Si(n,"float32")),r=pl(El(kl(1),t));return xc(cl(e,r))}}}},Df={kernelName:Je,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const t=pl(El(dl(Si(n,"float32")),1));return cl(e,t)}}}},_f={kernelName:Qe,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,s=Zi(n.shape,r.shape);return{a:()=>{let t=e;const r=Yi(n.shape,s);return r.length>0&&(t=Ic(t,r)),uu(t,n.shape)},b:()=>{let t=e;const n=Yi(r.shape,s);return n.length>0&&(t=Ic(t,n)),uu(t,r.shape)}}}},Of={kernelName:et,saveAllInputs:!0,gradFunc:(e,t)=>{const n={};return t.forEach(((t,r)=>{n[r]=()=>e.clone()})),n}},Lf={kernelName:rt,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>fl(n)}}},zf={kernelName:st,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>fl(n)}}},Pf={kernelName:at,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>cl(e,pl(El(kl(1),dl(Si(n,"float32")))))}}},Bf={kernelName:it,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const t=pl(ll(kl(1),dl(Si(n,"float32"))));return cl(e,t)}}}},Vf={kernelName:ut,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,s=Zi(n.shape,r.shape);return{a:()=>{const t=ll(dl(n),dl(r));let a=hl(e,cl(r,t));const i=Yi(n.shape,s);return i.length>0&&(a=Ic(a,i)),uu(a,n.shape)},b:()=>{const t=ll(dl(n),dl(r));let a=xc(hl(e,cl(n,t)));const i=Yi(r.shape,s);return i.length>0&&(a=Ic(a,i)),uu(a,r.shape)}}}},Uf={kernelName:ot,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>cl(e,ll(dl(Si(n,"float32")),1))}}},Wf={kernelName:lt,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>cl(e,El(kl(1),dl(Si(n,"float32"))))}}},Gf=Ta({avgPool3dGrad_:function(e,t,n,r,s,a){const i=Ia(e,"dy","avgPool3dGrad"),o=Ia(t,"input","avgPool3dGrad");let l=i,u=o,c=!1;4===o.rank&&(c=!0,l=uu(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]]),u=uu(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),re(5===l.rank,(()=>`Error in avgPool3dGrad: dy must be rank 5 but got rank ${l.rank}.`)),re(5===u.rank,(()=>`Error in avgPool3dGrad: input must be rank 5 but got rank ${u.rank}.`)),lu("avgPool3dGrad",s,a);const h={dy:l,input:u},p={filterSize:n,strides:r,pad:s,dimRoundingMode:a},d=da.runKernel(dt,h,p);return c?uu(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}}),Hf={kernelName:pt,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,{filterSize:s,strides:a,pad:i,dimRoundingMode:o}=n;return{x:()=>Gf(e,r,s,a,i,o)}}},jf=Ta({avgPoolGrad_:function(e,t,n,r,s){const a=Ia(e,"dy","avgPoolGrad"),i=Ia(t,"input","avgPoolGrad");re(i.rank===a.rank,(()=>`Rank of input (${i.rank}) does not match rank of dy (${a.rank})`));let o=i,l=a,u=!1;3===i.rank&&(u=!0,o=uu(i,[1,i.shape[0],i.shape[1],i.shape[2]]),l=uu(a,[1,a.shape[0],a.shape[1],a.shape[2]])),re(4===l.rank,(()=>`Error in avgPoolGrad: dy must be rank 4 but got rank ${l.rank}.`)),re(4===o.rank,(()=>`Error in avgPoolGrad: input must be rank 4 but got rank ${o.rank}.`));const c={dy:l,input:o},h={filterSize:n,strides:r,pad:s},p=da.runKernel(ht,c,h);return u?uu(p,[p.shape[1],p.shape[2],p.shape[3]]):p}}),qf={kernelName:ct,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,{filterSize:s,strides:a,pad:i}=n;return{x:()=>jf(e,r,s,a,i)}}},Kf={kernelName:ft,inputsToSave:["a","b"],gradFunc:(e,t,n)=>{const[r,s]=t,{transposeA:a,transposeB:i}=n;return a||i?!a&&i?{a:()=>Hi(e,s,!1,!1),b:()=>Hi(e,r,!0,!1)}:a&&!i?{a:()=>Hi(s,e,!1,!0),b:()=>Hi(r,e,!1,!1)}:{a:()=>Hi(s,e,!0,!0),b:()=>Hi(e,r,!0,!0)}:{a:()=>Hi(e,s,!1,!0),b:()=>Hi(r,e,!0,!1)}}},Xf={kernelName:mt,gradFunc:(e,t,n)=>{const{blockShape:r,crops:s}=n;return{x:()=>ih(e,r,s)}}},Yf={kernelName:yt,gradFunc:(e,t,n)=>{const r=n,s=r.inputShape,a=r.shape,i=Array.from(a);for(let e=s.length-1;e>=0;e--)if(s[e]===a[e])i[e]=1;else if(1!==s[e])throw new Error(`broadcastTo(): [${s}] cannot be broadcast to [${a}].`);const o=[];for(let e=0;e1&&o.push(e);return{x:()=>Ic(e,o,!0)}}},Zf={kernelName:xt,gradFunc:e=>({x:()=>e.clone()})},Jf={kernelName:wt,gradFunc:e=>({x:()=>fl(e)})},Qf={kernelName:vt,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,{clipValueMin:s,clipValueMax:a}=n;return{x:()=>qu(Dc(oc(r,s),fc(r,a)),e,fl(e))}}},em={kernelName:It,inputsToSave:["x"],gradFunc:Mf.gradFunc},tm={kernelName:Nt,saveAllInputs:!0,gradFunc:(e,t,n)=>{const r=t.map((e=>e.shape)),{axis:s}=n,a=ye(s,t[0].shape)[0],i=r.map((e=>e[a]));return Gh(e,i,a).map((e=>()=>e))}},nm={kernelName:St,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const[r,s]=t,{dilations:a,strides:i,pad:o,dataFormat:l}=n;return re(au(a),(()=>`Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${a}'`)),{x:()=>Fu(r.shape,e,s,i,o,l),filter:()=>kp(r,e,s.shape,i,o,l)}}},rm={kernelName:Ct,inputsToSave:["dy","filter"],gradFunc:(e,t,n)=>{const[r,s]=t,{strides:a,pad:i,dataFormat:o,dimRoundingMode:l}=n;return{dy:()=>Ru(e,s,a,i,o,1,l),filter:()=>kp(e,r,s.shape,a,i,o,l)}}},sm=Ta({conv3DBackpropFilter_:function(e,t,n,r,s){let a=e;4===e.rank&&(a=uu(e,[1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]]));let i=t;4===i.rank&&(i=uu(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]])),re(5===a.rank,(()=>`Error in conv3dDerFilter: input must be rank 5, but got shape ${a.shape}.`)),re(5===i.rank,(()=>`Error in conv3dDerFilter: dy must be rank 5, but got shape ${i.shape}.`)),re(5===n.length,(()=>`Error in conv3dDerFilter: filterShape must be length 5, but got ${n}.`)),re(a.shape[4]===n[3],(()=>`Error in conv3dDerFilter: depth of input ${a.shape[4]}) must match input depth in filter (${n[3]}.`)),re(i.shape[4]===n[4],(()=>`Error in conv3dDerFilter: depth of dy (${i.shape[4]}) must match output depth for filter (${n[4]}).`));const o={x:a,dy:i},l={strides:r,pad:s,filterShape:n};return da.runKernel($t,o,l)}}),am={kernelName:Et,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const{dilations:r,strides:s,pad:a}=n;re(au(r),(()=>`Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${r}'`));const[i,o]=t;return{x:()=>Ou(i.shape,e,o,s,a),filter:()=>sm(i,e,o.shape,s,a)}}},im={kernelName:Rt,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>hl(xc(Dh(Si(n,"float32"))),e)}}},om={kernelName:Mt,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>hl(_h(Si(n,"float32")),e)}}},lm={kernelName:Ft,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,{axis:s,exclusive:a,reverse:i}=n;return{x:()=>{const t=Ac([s],r.rank);let n=Bu(e,s,a,!i);return null!=t&&(n=qi(n,t)),n}}}},um={kernelName:Lt,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const{dilations:r,strides:s,pad:a,dimRoundingMode:i}=n,o=null==r?[1,1]:r;re(au(o),(()=>`Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations '${o}'`));const[l,u]=t;return re(4===l.rank,(()=>`Error in gradient of depthwiseConv2dNative: input must be rank 4, but got rank ${l.rank}.`)),re(4===u.rank,(()=>`Error in gradient of depthwiseConv2dNative: filter must be rank 4, but got rank ${u.rank}.`)),re(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]}.`)),re(iu(s,o),(()=>`Error in gradient of depthwiseConv2d: Either strides or dilations must be 1. Got strides ${s} and dilations '${o}'.`)),lu("depthwiseConv2d",a,i),{x:()=>$p(l.shape,e,u,s,a,o,i),filter:()=>Ep(l,e,u.shape,s,a,o,i)}}},cm={kernelName:Vt,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const[r,s]=t,a={x:r,filter:s,dy:e},i={x:r,filter:s,dy:e};return{x:()=>da.runKernel(Ut,a,n),filter:()=>da.runKernel(Wt,i,n)}}},hm={kernelName:jt,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t,r={dy:e,y:n};return{x:()=>da.runKernel(qt,r)}}},pm={kernelName:Kt,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t,r=hl(Qu(xc(dl(n))),2/Math.sqrt(Math.PI));return{x:()=>hl(e,r)}}},dm={kernelName:Yt,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>hl(e,n)}}},fm={kernelName:Zt,inputsToSave:["input"],gradFunc:(e,t)=>{const[n]=t;return{input:()=>uu(e,n.shape)}}},mm={kernelName:Jt,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>hl(e,Qu(n))}}},gm={kernelName:nn,gradFunc:e=>({x:()=>fl(e)})},ym={kernelName:rn,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,s=Zi(n.shape,r.shape);return{a:()=>{const t=cl(e,Si(r,"float32")),a=Yi(n.shape,s);return a.length>0?uu(Ic(t,a),n.shape):t},b:()=>{let t=hl(e,Si(n,"float32"));const a=Yi(r.shape,s);a.length>0&&(t=uu(Ic(t,a),r.shape));const i=dl(r);return xc(cl(t,Si(i,"float32")))}}}},bm={kernelName:sn,inputsToSave:["x","mean","variance","scale"],gradFunc:(e,t,n)=>{const{varianceEpsilon:r}=n,[s,a,i,o]=t,l=null==o?kl(1):o,u=Yi(a.shape,s.shape),c=[];if(1===a.rank){for(let e=0;e1===a.rank?uu(hl(hl(e,nc(uu(d,[1,1,1,a.shape[0]]),c)),l),s.shape):uu(hl(hl(e,d),l),s.shape),mean:()=>{let e=hl(hl(d,kl(-1)),p);return 1===a.rank&&(e=Ic(e,u)),uu(e,a.shape)},variance:()=>{let e=hl(hl(f,h),p);return 1===a.rank&&(e=Ic(e,u)),uu(e,a.shape)},scale:()=>{const t=hl(h,d);let n=hl(e,t);return 1===a.rank&&(n=Ic(n,u)),uu(n,a.shape)},offset:()=>{let t=e;return 1===a.rank&&(t=Ic(t,u)),uu(t,a.shape)}}}},xm={kernelName:an,inputsToSave:["x","indices"],gradFunc:(e,t,n)=>{const[r,s]=t,{axis:a}=n,i=ye(a,r.shape)[0];return{x:()=>{const t=r.shape,n=s.size,o=t.slice(0,i),l=o.length,u=t.slice(a,t.length).slice(1),c=u.length,h=wm(0,l),p=wm(l+1,l+1+c),d=vm([o,[n],u]),f=uu(e,d),m=uu(s,[n]),g=vm([[l],h,p]),y=qi(f,g);let b=ip(y,m,r.shape[i]);const x=Rc(g);return b=qi(b,x),b},indices:()=>s}}};function wm(e,t){const n=[];for(let r=e;r{const[n,r]=t;return{a:()=>fl(n),b:()=>fl(r)}}},Im={kernelName:cn,gradFunc:e=>({x:()=>Si(e,"float32")})},Nm={kernelName:dn,gradFunc:e=>({x:()=>fl(e)})},Sm={kernelName:fn,gradFunc:e=>({x:()=>fl(e)})},Tm={kernelName:mn,gradFunc:e=>({x:()=>fl(e)})},Cm={kernelName:gn,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,{alpha:s}=n,a=ic(r,0);return{x:()=>qu(a,e,hl(e,s))}}},Em={kernelName:vn,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>cl(e,ll(n,1))}}},$m={kernelName:wn,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>cl(e,Si(n,"float32"))}}},Am={kernelName:Sn,inputsToSave:[],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[r]=t,{axis:s}=n;return{logits:()=>{const t=Qu(r);return El(e,hl(Ic(e,s,!0),t))}}}},Rm=Ta({localResponseNormalizationBackprop_:function(e,t,n,r=5,s=1,a=1,i=.5){const o={x:e,y:t,dy:n},l={depthRadius:r,bias:s,alpha:a,beta:i};return da.runKernel(Cn,o,l)}}),Mm={kernelName:Tn,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[r,s]=t,{depthRadius:a,bias:i,alpha:o,beta:l}=n;return{x:()=>Rm(r,s,e,a,i,o,l)}}};function Fm(e,t,n,r){return t.rankhl(e,Si(ju(n,t),e.dtype))}}const Dm={kernelName:En,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const r=n,{reductionIndices:s}=r,a=t[0],i=Fm(e,t[1],a,ye(s,a.shape));return{x:()=>i.x()}}},_m={kernelName:$n,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t;return{a:()=>hl(e,Si(oc(n,r),"float32")),b:()=>hl(e,Si(dc(n,r),"float32"))}}},Om=Ta({maxPool3dGrad_:function(e,t,n,r,s,a,i){const o=Ia(e,"dy","maxPool3dGrad"),l=Ia(t,"input","maxPool3dGrad"),u=Ia(n,"output","maxPool3dGrad");let c=o,h=l,p=u,d=!1;4===l.rank&&(d=!0,c=uu(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]]),h=uu(l,[1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]]),p=uu(u,[1,u.shape[0],u.shape[1],u.shape[2],u.shape[3]])),re(5===c.rank,(()=>`Error in maxPool3dGrad: dy must be rank 5 but got rank ${c.rank}.`)),re(5===h.rank,(()=>`Error in maxPool3dGrad: input must be rank 5 but got rank ${h.rank}.`)),re(5===p.rank,(()=>`Error in maxPool3dGrad: output must be rank 5 but got rank ${p.rank}.`)),lu("maxPool3dGrad",a,i);const f={dy:c,input:h,output:p},m={filterSize:r,strides:s,pad:a,dimRoundingMode:i},g=da.runKernel(Fn,f,m);return d?uu(g,[g.shape[1],g.shape[2],g.shape[3],g.shape[4]]):g}}),Lm={kernelName:Mn,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[r,s]=t,{filterSize:a,strides:i,pad:o,dimRoundingMode:l}=n;return{x:()=>Om(e,r,s,a,i,o,l)}}},zm=Ta({maxPoolGrad_:function(e,t,n,r,s,a,i){const o=Ia(e,"dy","maxPoolGrad"),l=Ia(t,"input","maxPoolGrad"),u=Ia(n,"output","maxPoolGrad");re(l.rank===o.rank,(()=>`Rank of input (${l.rank}) does not match rank of dy (${o.rank})`)),re(4===o.rank,(()=>`Error in maxPoolGrad: dy must be rank 4 but got rank ${o.rank}.`)),re(4===l.rank,(()=>`Error in maxPoolGrad: input must be rank 4 but got rank ${l.rank}.`)),lu("maxPoolGrad",a,i);const c={dy:o,input:l,output:u},h={filterSize:r,strides:s,pad:a,dimRoundingMode:i};return da.runKernel(Rn,c,h)}}),Pm={kernelName:Yn,inputsToSave:["x"],gradFunc:(e,t,n)=>{const r=t[0],{paddings:s}=n,a=s.map((e=>e[0]));return{x:()=>fu(e,a,r.shape)}}},Bm={kernelName:Sr,gradFunc:(e,t,n)=>{const{blockShape:r,paddings:s}=n;return{x:()=>yu(e,r,s)}}},Vm={kernelName:Tr,gradFunc:(e,t,n)=>{const{axis:r}=n;return{x:()=>pu(e,r)}}},Um=[Mf,Ff,Df,_f,Of,Lf,zf,Pf,Bf,Vf,Uf,Wf,Hf,qf,Kf,Xf,Yf,Zf,Jf,Qf,em,tm,rm,nm,am,im,om,lm,um,cm,{kernelName:Gt,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,s=Zi(n.shape,r.shape);return{a:()=>{const t=cl(e,Si(r,"float32")),a=Yi(n.shape,s);return a.length>0?uu(Ic(t,a),n.shape):t},b:()=>{let t=hl(e,Si(n,"float32"));const a=Yi(r.shape,s);a.length>0&&(t=uu(Ic(t,a),r.shape));const i=dl(r);return xc(cl(t,Si(i,"float32")))}}}},hm,pm,dm,fm,mm,ym,gm,bm,xm,km,Im,Nm,Sm,Tm,Cm,Em,$m,Am,Mm,Dm,Dm,_m,Lm,{kernelName:An,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[r,s]=t,{filterSize:a,strides:i,pad:o}=n;return{x:()=>zm(e,r,s,a,i,o)}}},{kernelName:_n,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,{axis:s}=n,a=ye(s,r.shape),i=oe(Cc(r.shape,a)[1]);return{x:()=>{const t=r.shape.slice();a.forEach((e=>{t[e]=1}));const n=uu(e,t);return cl(hl(n,Wc(r.shape,"float32")),i)}}}},{kernelName:On,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const r=n,{axis:s}=r,[a,i]=t,o=Fm(e,i,a,ye(s,a.shape));return{x:()=>o.x()}}},{kernelName:Ln,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t;return{a:()=>hl(e,Si(fc(n,r),"float32")),b:()=>hl(e,Si(ic(n,r),"float32"))}}},{kernelName:zn,inputsToSave:["x"],gradFunc:(e,t,n)=>{const r=t[0],{paddings:s}=n,a=s.map((e=>e[0]));return{x:()=>fu(e,a,r.shape)}}},{kernelName:Pn,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,s=Zi(n.shape,r.shape);return{a:()=>{const t=Yi(n.shape,s);return t.length>0?uu(Ic(e,t),n.shape):e},b:()=>{const t=hl(e,xc(sc(cl(n,r)))),a=Yi(r.shape,s);return a.length>0?uu(Ic(t,a),r.shape):t}}}},{kernelName:Vn,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,s=Zi(n.shape,r.shape);return{a:()=>{const t=hl(e,Si(r,"float32")),a=Yi(n.shape,s);return a.length>0?uu(Ic(t,a),n.shape):t},b:()=>{const t=hl(e,Si(n,"float32")),a=Yi(r.shape,s);return a.length>0?uu(Ic(t,a),r.shape):t}}}},{kernelName:Un,gradFunc:e=>({x:()=>xc(e)})},{kernelName:Kn,inputsToSave:["indices"],gradFunc:(e,t)=>{const n=t[0];return{indices:()=>Uc(n.shape,"float32")}}},{kernelName:qn,gradFunc:e=>({x:()=>fl(e)})},{kernelName:Xn,saveAllInputs:!0,gradFunc:(e,t,n)=>{const{axis:r}=n;return op(e,r).map((e=>()=>e))}},Pm,Pm,{kernelName:Jn,inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:(e,t)=>{const[n,r,s]=t,a=n,i=r,o=Zi(a.shape,i.shape);return{a:()=>{const t=Si(i,"float32");let n=hl(e,hl(t,Cl(a,El(t,kl(1)))));const r=Yi(a.shape,o);return r.length>0&&(n=Ic(n,r)),uu(n,a.shape)},b:()=>{const t=ic(a,0),n=qu(t,yc(a),fl(a));let r=hl(e,hl(s,n));const l=Yi(i.shape,o);return l.length>0&&(r=Ic(r,l)),uu(r,i.shape)}}}},{kernelName:Qn,inputsToSave:["x","alpha"],gradFunc:(e,t)=>{const[n,r]=t,s=ic(n,0);return{x:()=>qu(s,e,hl(e,r)),alpha:()=>{let t=qu(s,fl(e),hl(e,n));const a=Yi(r.shape,e.shape);return a.length>0&&(t=Ic(t,a)),uu(t,r.shape)}}}},{kernelName:rr,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>cl(e,xc(dl(n)))}}},{kernelName:cr,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t,r=hl(fc(n,6),Xh(n));return{x:()=>hl(e,Si(r,"float32"))}}},{kernelName:sr,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>hl(e,Si(Xh(n),"float32"))}}},{kernelName:ar,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>uu(e,n.shape)}}},{kernelName:lr,inputsToSave:["images"],gradFunc:(e,t,n)=>{const[r]=t,s={dy:e,images:r};return{images:()=>da.runKernel(ur,s,n)}}},{kernelName:ir,inputsToSave:["images"],gradFunc:(e,t,n)=>{const[r]=t,s={dy:e,images:r};return{images:()=>da.runKernel(or,s,n)}}},{kernelName:hr,gradFunc:(e,t,n)=>{const{dims:r}=n,s=ye(r,e.shape);return{x:()=>Ih(e,s)}}},{kernelName:pr,gradFunc:e=>({x:()=>fl(e)})},{kernelName:dr,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>xc(cl(e,hl(Cl(n,1.5),2)))}}},{kernelName:mr,inputsToSave:["condition"],gradFunc:(e,t)=>{const[n]=t;return{condition:()=>Si(fl(n),"float32"),t:()=>hl(e,Si(n,e.dtype)),e:()=>hl(e,Si(_c(n),e.dtype))}}},{kernelName:gr,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const t=ic(n,kl(0)),r=kl(Gd),s=kl(Hd),a=hl(e,s),i=hl(hl(e,r),Qu(Si(n,"float32")));return qu(t,a,i)}}}},{kernelName:vr,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>hl(e,hl(n,El(kl(1),n)))}}},{kernelName:wr,gradFunc:e=>({x:()=>fl(e)})},{kernelName:br,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>hl(zu(Si(n,"float32")),e)}}},{kernelName:xr,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>hl(Pu(Si(n,"float32")),e)}}},{kernelName:yr,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,{begin:s,size:a}=n,i=r.shape,[o,l]=Io(r,s,a),u=[];for(let t=0;tth(e,u)}}},{kernelName:Cr,outputsToSave:[!0],gradFunc:(e,t,n)=>{const[r]=t,{dim:s}=n,a=hl(e,r);return{logits:()=>El(a,hl(Ic(a,[s],!0),r))}}},{kernelName:kr,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>hl(e,du(n))}}},Bm,Bm,Vm,Vm,{kernelName:Ir,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>cl(e,hl(pl(Si(n,"float32")),2))}}},{kernelName:Fr,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,s=kl(2);return{a:()=>hl(e,hl(s,El(n,r))),b:()=>hl(e,hl(s,El(r,n)))}}},{kernelName:Dr,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>hl(e,hl(Si(n,"float32"),2))}}},{kernelName:Yr,gradFunc:e=>({x:()=>fl(e)})},{kernelName:Pr,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,s=Zi(n.shape,r.shape);return{a:()=>{let t=e;const r=Yi(n.shape,s);return r.length>0&&(t=Ic(t,r)),uu(t,n.shape)},b:()=>{let t=e;const n=Yi(r.shape,s);return n.length>0&&(t=Ic(t,n)),uu(xc(t),r.shape)}}}},{kernelName:Nr,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,s=r.shape.slice(),{axis:a}=n;ye(a,r.shape).forEach((e=>{s[e]=1}));const i=uu(e,s),o=hl(i,Wc(r.shape,"float32"));return{x:()=>o}}},{kernelName:Br,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>cl(e,dl(zu(n)))}}},{kernelName:Vr,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>hl(El(kl(1),dl(n)),e)}}},{kernelName:Ur,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,{reps:s}=n;return{x:()=>{let t=fl(r);if(1===r.rank)for(let n=0;n{const r=n,{perm:s}=r,a=Rc(s);return{x:()=>qi(e,a)}}},{kernelName:qr,gradFunc:(e,t,n)=>{const r=n,{axis:s}=r;return{value:()=>Kh(e,s)}}},{kernelName:Kr,inputsToSave:["segmentIds"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>function(e,t){const n=Rl(t,fl(t)),r=ac(e,n);let s=oc(t,kl(0,"int32"));const a=r.rank-s.rank;for(let e=0;e({x:()=>fl(e)})}];for(const e of Um)cs(e);let Wm;function Gm(){return null==Wm&&(Wm=il().epsilon()),Wm}Ks().prototype.abs=function(){return this.throwIfDisposed(),Al(this)},Ks().prototype.acos=function(){return this.throwIfDisposed(),Ll(this)},Ks().prototype.acosh=function(){return this.throwIfDisposed(),zl(this)},Ks().prototype.add=function(e){return this.throwIfDisposed(),ll(this,e)},Ks().prototype.all=function(e,t){return this.throwIfDisposed(),Bl(this,e,t)},Ks().prototype.any=function(e,t){return this.throwIfDisposed(),Vl(this,e,t)},Ks().prototype.argMax=function(e){return this.throwIfDisposed(),Ul(this,e)},Ks().prototype.argMin=function(e){return this.throwIfDisposed(),Wl(this,e)},Ks().prototype.asScalar=function(){return this.throwIfDisposed(),re(1===this.size,(()=>"The array must have only 1 element.")),uu(this,[])},Ks().prototype.asType=function(e){return this.throwIfDisposed(),Si(this,e)},Ks().prototype.as1D=function(){return this.throwIfDisposed(),uu(this,[this.size])},Ks().prototype.as2D=function(e,t){return this.throwIfDisposed(),uu(this,[e,t])},Ks().prototype.as3D=function(e,t,n){return this.throwIfDisposed(),uu(this,[e,t,n])},Ks().prototype.as4D=function(e,t,n,r){return this.throwIfDisposed(),uu(this,[e,t,n,r])},Ks().prototype.as5D=function(e,t,n,r,s){return this.throwIfDisposed(),uu(this,[e,t,n,r,s])},Ks().prototype.asin=function(){return this.throwIfDisposed(),Gl(this)},Ks().prototype.asinh=function(){return this.throwIfDisposed(),Hl(this)},Ks().prototype.atan=function(){return this.throwIfDisposed(),jl(this)},Ks().prototype.atan2=function(e){return this.throwIfDisposed(),ql(this,e)},Ks().prototype.atanh=function(){return this.throwIfDisposed(),Kl(this)},Ks().prototype.avgPool=function(e,t,n,r){return this.throwIfDisposed(),cu(this,e,t,n,r)},Ks().prototype.batchToSpaceND=function(e,t){return this.throwIfDisposed(),yu(this,e,t)},Ks().prototype.batchNorm=function(e,t,n,r,s){return this.throwIfDisposed(),bu(this,e,t,n,r,s)},Ks().prototype.broadcastTo=function(e){return this.throwIfDisposed(),Nu(this,e)},Ks().prototype.cast=function(e){return this.throwIfDisposed(),Si(this,e)},Ks().prototype.ceil=function(){return this.throwIfDisposed(),Su(this)},Ks().prototype.clipByValue=function(e,t){return this.throwIfDisposed(),Tu(this,e,t)},Ks().prototype.concat=function(e,t){return this.throwIfDisposed(),e instanceof qs&&(e=[e]),pu([this,...e],t)},Ks().prototype.conv1d=function(e,t,n,r,s,a){return this.throwIfDisposed(),Mu(this,e,t,n,r,s,a)},Ks().prototype.conv2dTranspose=function(e,t,n,r,s){return this.throwIfDisposed(),Du(this,e,t,n,r,s)},Ks().prototype.conv2d=function(e,t,n,r,s,a){return this.throwIfDisposed(),Ru(this,e,t,n,r,s,a)},Ks().prototype.cos=function(){return this.throwIfDisposed(),zu(this)},Ks().prototype.cosh=function(){return this.throwIfDisposed(),Pu(this)},Ks().prototype.cumsum=function(e,t,n){return this.throwIfDisposed(),Bu(this,e,t,n)},Ks().prototype.depthToSpace=function(e,t){return this.throwIfDisposed(),Uu(this,e,t)},Ks().prototype.depthwiseConv2d=function(e,t,n,r,s,a){return this.throwIfDisposed(),Wu(this,e,t,n,r,s,a)},Ks().prototype.dilation2d=function(e,t,n,r,s){return this.throwIfDisposed(),Hu(this,e,t,n,r,s)},Ks().prototype.divNoNan=function(e){return this.throwIfDisposed(),Ku(this,e)},Ks().prototype.div=function(e){return this.throwIfDisposed(),cl(this,e)},Ks().prototype.dot=function(e){return this.throwIfDisposed(),Xu(this,e)},Ks().prototype.elu=function(){return this.throwIfDisposed(),Zu(this)},Ks().prototype.equal=function(e){return this.throwIfDisposed(),ju(this,e)},Ks().prototype.erf=function(){return this.throwIfDisposed(),Ju(this)},Ks().prototype.exp=function(){return this.throwIfDisposed(),Qu(this)},Ks().prototype.expandDims=function(e){return this.throwIfDisposed(),ec(this,e)},Ks().prototype.expm1=function(){return this.throwIfDisposed(),tc(this)},Ks().prototype.fft=function(){return this.throwIfDisposed(),Vh(this)},Ks().prototype.flatten=function(){return this.throwIfDisposed(),uu(this,[this.size])},Ks().prototype.floor=function(){return this.throwIfDisposed(),sc(this)},Ks().prototype.floorDiv=function(e){return this.throwIfDisposed(),ul(this,e)},Ks().prototype.gather=function(e,t){return this.throwIfDisposed(),ac(this,e,t)},Ks().prototype.greaterEqual=function(e){return this.throwIfDisposed(),oc(this,e)},Ks().prototype.greater=function(e){return this.throwIfDisposed(),ic(this,e)},Ks().prototype.ifft=function(){return this.throwIfDisposed(),Uh(this)},Ks().prototype.irfft=function(){return this.throwIfDisposed(),Wh(this)},Ks().prototype.isFinite=function(){return this.throwIfDisposed(),uc(this)},Ks().prototype.isInf=function(){return this.throwIfDisposed(),cc(this)},Ks().prototype.isNaN=function(){return this.throwIfDisposed(),hc(this)},Ks().prototype.leakyRelu=function(e){return this.throwIfDisposed(),pc(this,e)},Ks().prototype.lessEqual=function(e){return this.throwIfDisposed(),fc(this,e)},Ks().prototype.less=function(e){return this.throwIfDisposed(),dc(this,e)},Ks().prototype.localResponseNormalization=function(e,t,n,r){return this.throwIfDisposed(),gc(this,e,t,n,r)},Ks().prototype.logSigmoid=function(){return this.throwIfDisposed(),vc(this)},Ks().prototype.logSoftmax=function(e){return this.throwIfDisposed(),Nc(this,e)},Ks().prototype.logSumExp=function(e,t){return this.throwIfDisposed(),Fc(this,e,t)},Ks().prototype.log=function(){return this.throwIfDisposed(),yc(this)},Ks().prototype.log1p=function(){return this.throwIfDisposed(),bc(this)},Ks().prototype.logicalAnd=function(e){return this.throwIfDisposed(),Dc(this,e)},Ks().prototype.logicalNot=function(){return this.throwIfDisposed(),_c(this)},Ks().prototype.logicalOr=function(e){return this.throwIfDisposed(),Oc(this,e)},Ks().prototype.logicalXor=function(e){return this.throwIfDisposed(),Lc(this,e)},Ks().prototype.matMul=function(e,t,n){return this.throwIfDisposed(),Hi(this,e,t,n)},Ks().prototype.maxPool=function(e,t,n,r){return this.throwIfDisposed(),zc(this,e,t,n,r)},Ks().prototype.max=function(e,t){return this.throwIfDisposed(),kc(this,e,t)},Ks().prototype.maximum=function(e){return this.throwIfDisposed(),Rl(this,e)},Ks().prototype.mean=function(e,t){return this.throwIfDisposed(),Vc(this,e,t)},Ks().prototype.min=function(e,t){return this.throwIfDisposed(),Hc(this,e,t)},Ks().prototype.minimum=function(e){return this.throwIfDisposed(),jc(this,e)},Ks().prototype.mirrorPad=function(e,t){return this.throwIfDisposed(),qc(this,e,t)},Ks().prototype.mod=function(e){return this.throwIfDisposed(),Kc(this,e)},Ks().prototype.mul=function(e){return this.throwIfDisposed(),hl(this,e)},Ks().prototype.neg=function(){return this.throwIfDisposed(),xc(this)},Ks().prototype.norm=function(e,t,n){return this.throwIfDisposed(),dp(this,e,t,n)},Ks().prototype.notEqual=function(e){return this.throwIfDisposed(),Jc(this,e)},Ks().prototype.oneHot=function(e,t=1,n=0){return this.throwIfDisposed(),ji(this,e,t,n)},Ks().prototype.onesLike=function(){return this.throwIfDisposed(),Qc(this)},Ks().prototype.pad=function(e,t){return this.throwIfDisposed(),th(this,e,t)},Ks().prototype.pool=function(e,t,n,r,s,a){return this.throwIfDisposed(),oh(this,e,t,n,r,s,a)},Ks().prototype.pow=function(e){return this.throwIfDisposed(),Cl(this,e)},Ks().prototype.prelu=function(e){return this.throwIfDisposed(),lh(this,e)},Ks().prototype.prod=function(e,t){return this.throwIfDisposed(),uh(this,e,t)},Ks().prototype.reciprocal=function(){return this.throwIfDisposed(),wh(this)},Ks().prototype.relu=function(){return this.throwIfDisposed(),vh(this)},Ks().prototype.relu6=function(){return this.throwIfDisposed(),kh(this)},Ks().prototype.reshapeAs=function(e){return this.throwIfDisposed(),uu(this,e.shape)},Ks().prototype.reshape=function(e){return this.throwIfDisposed(),uu(this,e)},Ks().prototype.resizeBilinear=function(e,t,n){return this.throwIfDisposed(),Qp(this,e,t,n)},Ks().prototype.resizeNearestNeighbor=function(e,t,n){return this.throwIfDisposed(),ed(this,e,t,n)},Ks().prototype.reverse=function(e){return this.throwIfDisposed(),Ih(this,e)},Ks().prototype.rfft=function(){return this.throwIfDisposed(),Hh(this)},Ks().prototype.round=function(){return this.throwIfDisposed(),Eh(this)},Ks().prototype.rsqrt=function(){return this.throwIfDisposed(),$h(this)},Ks().prototype.selu=function(){return this.throwIfDisposed(),Ah(this)},Ks().prototype.separableConv2d=function(e,t,n,r,s,a){return this.throwIfDisposed(),Rh(this,e,t,n,r,s,a)},Ks().prototype.sigmoid=function(){return this.throwIfDisposed(),du(this)},Ks().prototype.sign=function(){return this.throwIfDisposed(),Fh(this)},Ks().prototype.sin=function(){return this.throwIfDisposed(),Dh(this)},Ks().prototype.sinh=function(){return this.throwIfDisposed(),_h(this)},Ks().prototype.slice=function(e,t){return this.throwIfDisposed(),fu(this,e,t)},Ks().prototype.softmax=function(e){return this.throwIfDisposed(),Bh(this,e)},Ks().prototype.softplus=function(){return this.throwIfDisposed(),wc(this)},Ks().prototype.spaceToBatchND=function(e,t){return this.throwIfDisposed(),ih(this,e,t)},Ks().prototype.split=function(e,t){return this.throwIfDisposed(),Gh(this,e,t)},Ks().prototype.sqrt=function(){return this.throwIfDisposed(),pl(this)},Ks().prototype.square=function(){return this.throwIfDisposed(),dl(this)},Ks().prototype.squaredDifference=function(e){return this.throwIfDisposed(),jh(this,e)},Ks().prototype.squeeze=function(e){return this.throwIfDisposed(),qh(this,e)},Ks().prototype.stack=function(e,t){this.throwIfDisposed();const n=e instanceof qs?[this,e]:[this,...e];return Kh(n,t)},Ks().prototype.step=function(e){return this.throwIfDisposed(),Xh(this,e)},Ks().prototype.stridedSlice=function(e,t,n,r,s,a,i,o){return this.throwIfDisposed(),Yh(this,e,t,n,r,s,a,i,o)},Ks().prototype.sub=function(e){return this.throwIfDisposed(),El(this,e)},Ks().prototype.sum=function(e,t){return this.throwIfDisposed(),Ic(this,e,t)},Ks().prototype.tan=function(){return this.throwIfDisposed(),Zh(this)},Ks().prototype.tanh=function(){return this.throwIfDisposed(),mu(this)},Ks().prototype.tile=function(e){return this.throwIfDisposed(),nc(this,e)},Ks().prototype.toBool=function(){return this.throwIfDisposed(),Si(this,"bool")},Ks().prototype.toFloat=function(){return this.throwIfDisposed(),Si(this,"float32")},Ks().prototype.toInt=function(){return this.throwIfDisposed(),Si(this,"int32")},Ks().prototype.topk=function(e,t){return this.throwIfDisposed(),rp(this,e,t)},Ks().prototype.transpose=function(e){return this.throwIfDisposed(),qi(this,e)},Ks().prototype.unique=function(e){return this.throwIfDisposed(),ap(this,e)},Ks().prototype.unsortedSegmentSum=function(e,t){return this.throwIfDisposed(),ip(this,e,t)},Ks().prototype.unstack=function(e){return this.throwIfDisposed(),op(this,e)},Ks().prototype.where=function(e,t){return this.throwIfDisposed(),qu(e,this,t)},Ks().prototype.zerosLike=function(){return this.throwIfDisposed(),fl(this)};class Hm extends Error{constructor(e){super(e),Object.setPrototypeOf(this,Hm.prototype)}}class jm extends Error{constructor(e){super(e),Object.setPrototypeOf(this,jm.prototype)}}class qm extends Error{constructor(e){super(e),Object.setPrototypeOf(this,qm.prototype)}}class Km extends Error{constructor(e){super(e),Object.setPrototypeOf(this,Km.prototype)}}class Xm extends Error{constructor(e){super(e),Object.setPrototypeOf(this,Xm.prototype)}}function Ym(e,t){if(Array.isArray(e)){let n=[];for(let r=0;rt.toUpperCase()))}Error;let rg={};function sg(e){if(null==e)return null;const t={};return t.className=e.getClassName(),t.config=e.getConfig(),t}function ag(e){if(null!=e&&"object"==typeof e)if(Array.isArray(e))e.forEach((e=>ag(e)));else{const t=Object.keys(e);for(const n of t){const t=e[n];null!=t&&"object"==typeof t&&(Array.isArray(t)||"ndarray"!==t.type||"number"!=typeof t.value?ag(t):e[n]=t.value)}}}function ig(e,t={},n={},r="object",s=!1){if("string"==typeof e){const s=e;let a;if(s in n)a=n[s];else if(s in rg)a=rg[s];else if(a=t[s],null==a)throw new qm(`Unknown ${r}: ${e}. This may be due to one of the following reasons:\n1. The ${r} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.\n2. The custom ${r} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);return a}{const a=e;if(null==a.className||null==a.config)throw new qm(`${r}: Improper config format: ${JSON.stringify(a)}.\n'className' and 'config' must set.`);const i=a.className;let o,l;if(i in n?[o,l]=n[i]:i in rg?[o,l]=rg.className:i in t&&([o,l]=t[i]),null==o)throw new qm(`Unknown ${r}: ${i}. This may be due to one of the following reasons:\n1. The ${r} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.\n2. The custom ${r} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);if(null!=l){const e={};for(const t of Object.keys(rg))e[t]=rg[t];for(const t of Object.keys(n))e[t]=n[t];a.config.customObjects=e;const t=Object.assign({},rg);for(const e of Object.keys(n))rg[e]=n[e];ag(a.config);const r=l(o,a.config,n,s);return rg=Object.assign({},t),r}{const e=Object.assign({},rg);for(const e of Object.keys(n))rg[e]=n[e];const t=new o(a.config);return rg=Object.assign({},e),t}}}function og(e,t){return-1*function(e,t){return et?1:0}(e,t)}function lg(e){if(null==e)return e;const t=[];for(const n of e)-1===t.indexOf(n)&&t.push(n);return t}function ug(e){if(null==e)throw new qm(`Invalid value in obj: ${JSON.stringify(e)}`);for(const t in e)if(e.hasOwnProperty(t))return!1;return!0}function cg(e,t,n){if(null!=n&&e.indexOf(n)<0)throw new qm(`${n} is not a valid ${t}. Valid values are ${e} or null/undefined.`)}function hg(e,t,n=0,r=1/0){return Zm(n>=0),Zm(r>=n),Array.isArray(e)&&e.length>=n&&e.length<=r&&e.every((e=>typeof e===t))}function pg(e,t){Array.isArray(e)?(re(e.length>0,(()=>`${t} is unexpectedly an empty array.`)),e.forEach(((e,n)=>pg(e,`element ${n+1} of ${t}`)))):re(Number.isInteger(e)&&e>0,(()=>`Expected ${t} to be a positive integer, but got ${dg(e)}.`))}function dg(e){return null===e?"null":Array.isArray(e)?"["+e.map((e=>dg(e))).join(",")+"]":"string"==typeof e?`"${e}"`:`${e}`}function fg(e){return"relu"===e?"relu":"linear"===e?"linear":"elu"===e?"elu":null}function mg(e,t){return Xo((()=>pl(Ic(hl(e,e),t,!0))))}class gg extends To{getConfig(){return{}}}class yg extends gg{constructor(e){super(),this.defaultMaxValue=2,this.defaultAxis=0,this.maxValue=null!=e.maxValue?e.maxValue:this.defaultMaxValue,this.axis=null!=e.axis?e.axis:this.defaultAxis}apply(e){return Xo((()=>{const t=mg(e,this.axis),n=Tu(t,0,this.maxValue);return hl(e,cl(n,ll(Gm(),t)))}))}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}}yg.className="MaxNorm",Eo(yg);class bg extends gg{constructor(e){super(),this.defaultAxis=0,this.axis=null!=e.axis?e.axis:this.defaultAxis}apply(e){return Xo((()=>cl(e,ll(Gm(),mg(e,this.axis)))))}getConfig(){return{axis:this.axis}}}bg.className="UnitNorm",Eo(bg);class xg extends gg{apply(e){return vh(e)}}xg.className="NonNeg",Eo(xg);class wg extends gg{constructor(e){super(),this.defaultMinValue=0,this.defaultMaxValue=1,this.defaultRate=1,this.defaultAxis=0,this.minValue=null!=e.minValue?e.minValue:this.defaultMinValue,this.maxValue=null!=e.maxValue?e.maxValue:this.defaultMaxValue,this.rate=null!=e.rate?e.rate:this.defaultRate,this.axis=null!=e.axis?e.axis:this.defaultAxis}apply(e){return Xo((()=>{const t=mg(e,this.axis),n=ll(hl(this.rate,Tu(t,this.minValue,this.maxValue)),hl(1-this.rate,t));return hl(e,cl(n,ll(Gm(),t)))}))}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}}wg.className="MinMaxNorm",Eo(wg);const vg={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function kg(e){return sg(e)}function Ig(e,t={}){return ig(e,Co.getMap().classNameMap,t,"constraint")}function Ng(e){return null==e?null:"string"==typeof e?Ig({className:e in vg?vg[e]:e,config:{}}):e instanceof gg?e:Ig(e)}function Sg(e){return new yg(e)}function Tg(e){return new bg(e)}function Cg(){return new xg}function Eg(e){return new wg(e)}const $g=["channelsFirst","channelsLast"],Ag=["nearest","bilinear"],Rg=["valid","same","causal"],Mg=["max","avg"],Fg=["sum","mul","concat","ave"],Dg=new Map;function _g(e){cg($g,"DataFormat",e)}function Og(e){cg(Rg,"PaddingMode",e)}function Lg(e){cg(Mg,"PoolMode",e)}const zg=[];function Pg(e,t){zg.push(e);try{const e=t();return zg.pop(),e}catch(e){throw zg.pop(),e}}function Bg(e){if(!Wg(e))throw new Error("Not a valid tensor name: '"+e+"'");return(0===zg.length?"":zg.join("/")+"/")+e}function Vg(e){if(!Wg(e))throw new Error("Not a valid tensor name: '"+e+"'");Dg.has(e)||Dg.set(e,0);const t=Dg.get(e);if(Dg.set(e,Dg.get(e)+1),t>0){const n=`${e}_${t}`;return Dg.set(n,1),n}return e}const Ug=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function Wg(e){return!!e.match(Ug)}function Gg(e,t,n){null==t&&(t=0),null==n&&(n=e.length);let r=1;for(let s=t;st&&(t=r)}return t}function qg(e,t){if(t{switch(e.rank){case 1:return Oh(e,t,n);case 2:return Lh(e,[t,0],[n,e.shape[1]]);case 3:return zh(e,[t,0,0],[n,e.shape[1],e.shape[2]]);case 4:return Ph(e,[t,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3]]);case 5:return fu(e,[t,0,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3],e.shape[4]]);case 6:return fu(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 qm(`sliceAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}}))}function Zg(e,t,n){return Xo((()=>{switch(e.rank){case 1:return Oh(e,t,n);case 2:return Lh(e,[0,t],[e.shape[0],n]);case 3:return zh(e,[0,0,t],[e.shape[0],e.shape[1],n]);case 4:return Ph(e,[0,0,0,t],[e.shape[0],e.shape[1],e.shape[2],n]);default:throw new qm(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}}))}function Jg(e,t,n,r){return Xo((()=>{switch(e.rank){case 1:return Oh(e,t,n);case 2:switch(r){case 1:return Yg(e,t,n);case 2:return Zg(e,t,n);default:throw new qm(`The axis is not within the rank of the tensor ${r}`)}case 3:switch(r){case 1:return Yg(e,t,n);case 2:return zh(e,[0,t,0],[e.shape[0],n,e.shape[2]]);case 3:return Zg(e,t,n);default:throw new qm(`The axis is not within the rank of the tensor ${r}`)}case 4:switch(r){case 1:return Yg(e,t,n);case 2:return Ph(e,[0,t,0,0],[e.shape[0],n,e.shape[2],e.shape[3]]);case 3:return Ph(e,[0,0,t,0],[e.shape[0],e.shape[1],n,e.shape[3]]);case 4:return Zg(e,t,n);default:throw new qm(`The axis is not within the rank of the tensor ${r}`)}default:throw new qm(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}}))}function Qg(e,t=-1){let n;return t<0&&(n=e[0].rank,t=0!==n?n:0),t===e[0].rank&&(t=-1),pu(e,t)}function ey(e,t){switch(e.rank){case 1:return Cu([e,t]);case 2:return Eu([e,t],0);case 3:return $u([e,t],0);case 4:return Au([e,t],0);default:throw new qm(`concatAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}}function ty(e,t){if(Array.isArray(t)||(t=[t]),e.rank!==t.length)throw new qm(`The length of input n (${t.length}) does not match the number of dimensions in input x (${e.rank})`);return nc(e,t)}function ny(e,t=0,n=1,r,s){return gh(e,t,n,r,s)}function ry(e,t,n,r){if(e.rank<2||t.rank<2)throw new Km(`dot requires both inputs to be rank >= 2 but got x shape = ${e.shape} and y shape = ${t.shape}`);if(t.rank>=3&&e.shape.slice(-1)[0]!==t.shape.slice(-2)[0])throw new Km(`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(2===e.rank&&2===t.rank)return Rp({a:e,b:t,transposeA:!1,transposeB:!1,bias:r?iy(e.rank,r,"channelsLast"):null,activation:n});{const s=e.shape.slice(),a=s.pop();e=uu(e,[-1,a]);const i=t.shape.slice(),o=i.pop(),l=i.pop(),u=[...i,o],c=Array.from({length:t.rank},((e,n)=>0===n?t.rank-2:n<=t.rank-2?n-1:n));t=uu(qi(t,c),[l,-1]);const h=[...s,...u];return uu(Rp({a:e,b:t,transposeA:!1,transposeB:!1,bias:r?iy(e.rank,r,"channelsLast"):null,activation:n}),h)}}function sy(e,t,n){return Xo((()=>(t=Array.isArray(t)?Jh(t,"int32"):Si(t,"int32"),ac(e,t,n))))}function ay(e){return hl(e,e)}function iy(e,t,n){const r=t.shape;if(1!==t.rank&&t.rank!==e)throw new qm(`Unexpected bias dimensions: ${t.rank}; expected it to be 1 or ${e}`);if(5===e){if("channelsFirst"===n)return 1===r.length?uu(t,[1,r[0],1,1,1]):uu(t,[1,r[3],r[0],r[1],r[2]]);if("channelsLast"===n)return 1===r.length?uu(t,[1,1,1,1,r[0]]):uu(t,[1].concat(r))}else if(4===e){if("channelsFirst"===n)return 1===r.length?uu(t,[1,r[0],1,1]):uu(t,[1,r[2],r[0],r[1]]);if("channelsLast"===n)return 1===r.length?uu(t,[1,1,1,r[0]]):uu(t,[1].concat(r))}else if(3===e){if("channelsFirst"===n)return 1===r.length?uu(t,[1,r[0],1]):uu(t,[1,r[1],r[0]]);if("channelsLast"===n)return 1===r.length?uu(t,[1,1,r[0]]):uu(t,[1].concat(r))}else if(e<3)return t;throw new qm(`Unsupported input rank by biasAdd: ${t.rank}`)}function oy(e,t,n){return Xo((()=>(null==n&&(n="channelsLast"),_g(n),ll(e,iy(e.rank,t,n)))))}function ly(e,t,n,r){return Xo((()=>bp(e,t,n,r)))}function uy(e,t,n=!1){return n?e():t()}const cy=["fanIn","fanOut","fanAvg"],hy=["normal","uniform","truncatedNormal"];class py extends To{fromConfigUsesCustomObjects(){return!1}getConfig(){return{}}}class dy extends py{apply(e,t){return Uc(e,t)}}dy.className="Zeros",Eo(dy);class fy extends py{apply(e,t){return Wc(e,t)}}fy.className="Ones",Eo(fy);class my extends py{constructor(e){if(super(),"object"!=typeof e)throw new qm(`Expected argument of type ConstantConfig but got ${e}`);if(void 0===e.value)throw new qm(`config must have value set but got ${e}`);this.value=e.value}apply(e,t){return Xo((()=>hl(kl(this.value),Wc(e,t))))}getConfig(){return{value:this.value}}}my.className="Constant",Eo(my);class gy extends py{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 yh(e,this.minval,this.maxval,t)}getConfig(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}}}gy.className="RandomUniform",Eo(gy);class yy extends py{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("float32"!==(t=t||"float32")&&"int32"!==t)throw new Km(`randomNormal does not support dType ${t}.`);return ny(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}}yy.className="RandomNormal",Eo(yy);class by extends py{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("float32"!==(t=t||"float32")&&"int32"!==t)throw new Km(`truncatedNormal does not support dType ${t}.`);return sp(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}}by.className="TruncatedNormal",Eo(by);class xy extends py{constructor(e){super(),this.gain=null!=e.gain?e.gain:1}apply(e,t){return Xo((()=>{if(2!==e.length||e[0]!==e[1])throw new qm("Identity matrix initializer can only be used for 2D square matrices.");return hl(this.gain,rc(e[0]))}))}getConfig(){return{gain:this.gain}}}xy.className="Identity",Eo(xy);class wy extends py{constructor(e){if(super(),e.scale<0)throw new qm(`scale must be a positive float. Got: ${e.scale}`);var t;this.scale=null==e.scale?1:e.scale,this.mode=null==e.mode?"fanIn":e.mode,t=this.mode,cg(cy,"FanMode",t),this.distribution=null==e.distribution?"normal":e.distribution,function(e){cg(hy,"Distribution",e)}(this.distribution),this.seed=e.seed}apply(e,t){const n=function(e,t="channelsLast"){let n,r;if(_g(t),2===e.length)n=e[0],r=e[1];else if(-1!==[3,4,5].indexOf(e.length)){if("channelsFirst"===t){const t=Gg(e,2);n=e[1]*t,r=e[0]*t}else if("channelsLast"===t){const t=Gg(e,0,e.length-2);n=e[e.length-2]*t,r=e[e.length-1]*t}}else{const t=Gg(e);n=Math.sqrt(t),r=Math.sqrt(t)}return[n,r]}(e),r=n[0],s=n[1];let a=this.scale;if("fanIn"===this.mode?a/=Math.max(1,r):"fanOut"===this.mode?a/=Math.max(1,s):a/=Math.max(1,(r+s)/2),"normal"===this.distribution){const n=Math.sqrt(a);if("float32"!==(t=t||"float32")&&"int32"!==t)throw new Km(`${this.getClassName()} does not support dType ${t}.`);return sp(e,0,n,t,this.seed)}{const n=Math.sqrt(3*a);return yh(e,-n,n,t)}}getConfig(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}}}wy.className="VarianceScaling",Eo(wy);class vy extends wy{constructor(e){super({scale:1,mode:"fanAvg",distribution:"uniform",seed:null==e?null:e.seed})}getClassName(){return wy.className}}vy.className="GlorotUniform",Eo(vy);class ky extends wy{constructor(e){super({scale:1,mode:"fanAvg",distribution:"normal",seed:null==e?null:e.seed})}getClassName(){return wy.className}}ky.className="GlorotNormal",Eo(ky);class Iy extends wy{constructor(e){super({scale:2,mode:"fanIn",distribution:"normal",seed:null==e?null:e.seed})}getClassName(){return wy.className}}Iy.className="HeNormal",Eo(Iy);class Ny extends wy{constructor(e){super({scale:2,mode:"fanIn",distribution:"uniform",seed:null==e?null:e.seed})}getClassName(){return wy.className}}Ny.className="HeUniform",Eo(Ny);class Sy extends wy{constructor(e){super({scale:1,mode:"fanIn",distribution:"normal",seed:null==e?null:e.seed})}getClassName(){return wy.className}}Sy.className="LeCunNormal",Eo(Sy);class Ty extends wy{constructor(e){super({scale:1,mode:"fanIn",distribution:"uniform",seed:null==e?null:e.seed})}getClassName(){return wy.className}}Ty.className="LeCunNormal",Eo(Ty);class Cy extends py{constructor(e){if(super(),this.DEFAULT_GAIN=1,this.gain=null==e.gain?this.DEFAULT_GAIN:e.gain,this.seed=e.seed,null!=this.seed)throw new Km("Random seed is not implemented for Orthogonal Initializer yet.")}apply(e,t){return Xo((()=>{if(e.length<2)throw new Km("Shape must be at least 2D.");e[0]*e[1]>2e3&&console.warn(`Orthogonal initializer is being called on a matrix with more than 2000 (${e[0]*e[1]}) elements: Slowness may result.`);const t=ny(e[0]>e[1]?[e[1],e[0]]:e,0,1,"float32");let n=Cd.gramSchmidt(t);return e[0]>e[1]&&(n=qi(n)),hl(this.gain,n)}))}getConfig(){return{gain:this.gain,seed:this.seed}}}Cy.className="Orthogonal",Eo(Cy);const Ey={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 $y(e,t={}){return ig(e,Co.getMap().classNameMap,t,"initializer")}function Ay(e){return sg(e)}function Ry(e){if("string"==typeof e){const t=e in Ey?Ey[e]:e;if("GlorotNormal"===t)return new ky;if("GlorotUniform"===t)return new vy;if("HeNormal"===t)return new Iy;if("HeUniform"===t)return new Ny;if("LeCunNormal"===t)return new Sy;if("LeCunUniform"===t)return new Ty;{const e={};return e.className=t,e.config={},$y(e)}}return e instanceof py?e:$y(e)}function My(){return new dy}function Fy(){return new fy}function Dy(e){return new my(e)}function _y(e){return new gy(e)}function Oy(e){return new yy(e)}function Ly(e){return new by(e)}function zy(e){return new xy(e)}function Py(e){return new wy(e)}function By(e){return new vy(e)}function Vy(e){return new ky(e)}function Uy(e){return new Iy(e)}function Wy(e){return new Ny(e)}function Gy(e){return new Sy(e)}function Hy(e){return new Ty(e)}function jy(e){return new Cy(e)}let qy=0;function Ky(){return qy++}const Xy={};function Yy(e=""){return e in Xy||(Xy[e]=0),Xy[e]+=1,e+Xy[e].toString()}function Zy(e){return Array.isArray(e)&&Array.isArray(e[0])}function Jy(e){return 0===e.length?[]:Array.isArray(e[0])?e:[e]}function Qy(e){let t;if(Array.isArray(e)){if(1!==e.length)throw new qm(`Expected Tensor length to be 1; got ${e.length}`);t=e[0]}else t=e;return t}function eb(e){if(Array.isArray(e)&&Array.isArray(e[0])){if(1===e.length)return(e=e)[0];throw new qm(`Expected exactly 1 Shape; got ${e.length}`)}return e}function tb(e){let t=0;for(const n of e)0===n.shape.length?t+=1:t+=n.shape.reduce(((e,t)=>e*t));return t}class nb{constructor(e,t="float32",n="Variable",r=!0,s=null){this.dtype=null==t?"float32":t,this.shape=e.shape,this.id=Ky(),n=null==n?"Variable":n,this.originalName=Bg(n),this.name=Vg(this.originalName),this.trainable_=r,this.constraint=s,this.val=lp(e,this.trainable_,this.name,this.dtype)}read(){return this.assertNotDisposed(),this.val}write(e){return this.assertNotDisposed(),function(e,t){if(e.shape.toString()!==t.shape.toString())throw new Error("Shape mismatch: "+JSON.stringify(e.shape)+" vs. "+JSON.stringify(t.shape))}(this.val,e),this.val.id!==e.id&&(this.val.assign(e),null!=this.constraint&&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 rb(e){return e.map((e=>e.read()))}function sb(e){e.forEach((e=>{e[0].write(e[1])}))}class ab{constructor(e){this.dtype=e.dtype,this.shape=e.shape,null!=e.shape?this.ndim=e.shape.length:this.ndim=e.ndim,this.maxNDim=e.maxNDim,this.minNDim=e.minNDim,this.axes=e.axes||{}}}class ib{constructor(e,t,n,r,s,a,i){this.dtype=e,this.shape=t,this.sourceLayer=n,this.inputs=r,this.callArgs=s,this.outputTensorIndex=i,this.id=Ky(),null!=a&&(this.originalName=Bg(a),this.name=Vg(this.originalName)),this.rank=t.length}}let ob=0;class lb{constructor(e,t){this.callArgs=t,this.id=ob++,this.outboundLayer=e.outboundLayer,this.inboundLayers=e.inboundLayers,this.nodeIndices=e.nodeIndices,this.tensorIndices=e.tensorIndices,this.inputTensors=e.inputTensors,this.outputTensors=e.outputTensors,this.inputMasks=e.inputMasks,this.outputMasks=e.outputMasks,this.inputShapes=e.inputShapes,this.outputShapes=e.outputShapes;for(const t of e.inboundLayers)null!=t&&t.outboundNodes.push(this);e.outboundLayer.inboundNodes.push(this)}getConfig(){const e=[];for(const t of this.inboundLayers)null!=t?e.push(t.name):e.push(null);return{outboundLayer:this.outboundLayer?this.outboundLayer.name:null,inboundLayers:e,nodeIndices:this.nodeIndices,tensorIndices:this.tensorIndices}}}let ub=0;class cb extends To{constructor(e={}){super(),this._callHook=null,this._addedWeightNames=[],this._stateful=!1,this.id=ub++,this.activityRegularizer=null,this.inputSpec=null,this.supportsMasking=!1,this._trainableWeights=[],this._nonTrainableWeights=[],this._losses=[],this._updates=[],this._built=!1,this.inboundNodes=[],this.outboundNodes=[];let t=e.name;if(!t){const e=this.getClassName();t=tg(e)+"_"+Yy(e)}if(this.name=t,this.trainable_=null==e.trainable||e.trainable,null!=e.inputShape||null!=e.batchInputShape){let t;if(null!=e.batchInputShape)t=e.batchInputShape;else if(null!=e.inputShape){let n=null;null!=e.batchSize&&(n=e.batchSize),t=[n].concat(e.inputShape)}this.batchInputShape=t;let n=e.dtype;null==n&&(n=e.inputDType),null==n&&(n="float32"),this.dtype=n}null!=e.weights?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(0===this.inboundNodes.length)throw new jm(`The layer has never been called and thus has no defined ${t}.`);if(this.inboundNodes.length<=e)throw new qm(`Asked to get ${t} at node ${e}, but the layer has only ${this.inboundNodes.length} inbound nodes.`);return this.inboundNodes[e]}getInputAt(e){return Qm(this.getNodeAtIndex(e,"input").inputTensors)}getOutputAt(e){return Qm(this.getNodeAtIndex(e,"output").outputTensors)}get input(){if(this.inboundNodes.length>1)throw new Hm(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer input" is ill-defined. Use \`getInputAt(nodeIndex)\` instead.`);if(0===this.inboundNodes.length)throw new Hm(`Layer ${this.name} is not connected, no input to return.`);return Qm(this.getNodeAtIndex(0,"input").inputTensors)}get output(){if(0===this.inboundNodes.length)throw new Hm(`Layer ${this.name} has no inbound nodes.`);if(this.inboundNodes.length>1)throw new Hm(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use \`getOutputAt(nodeIndex)\` instead.`);return Qm(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=eg(e),null==this.inputSpec||0===this.inputSpec.length)return;const t=eg(this.inputSpec);if(e.length!==t.length)throw new qm(`Layer ${this.name} expects ${t.length} inputs, but it received ${e.length} input tensors. Input received: ${e}`);for(let n=0;ns.maxNDim)throw new qm(`Input ${n} is incompatible with layer ${this.name}: expected max_ndim=${s.maxNDim}, found ndim=${a}`);if(null!=s.minNDim&&a=0?e[r]:e[e.length+r];if(null!=a&&-1===[a,null].indexOf(i))throw new qm(`Input ${n} is incompatible with layer ${this.name}: expected axis ${r} of input shape to have value ${a} but got shape ${e}.`)}}if(null!=s.shape)for(let e=0;e{if(!this.built){this.assertInputCompatibility(e);const t=[];for(const n of eg(e))t.push(n.shape);this.build(Qm(t)),this.built=!0,this.initialWeights&&this.setWeights(this.initialWeights),null===this._refCount&&s&&(this._refCount=1)}if(this.assertInputCompatibility(e),s){let r=this.call(e,t);const s=eg(r),a=[];for(let e of s)-1!==n.indexOf(e)&&(e=e.clone()),a.push(e);if(r=Qm(a),null!=this.activityRegularizer)throw new Km("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return r}{const n=function(e){e=eg(e);const t=[];for(const n of e)t.push(n.shape);return Qm(t)}(e),r=this.computeOutputShape(n);let s;const a="float32";if(this.warnOnIncompatibleInputShape(Array.isArray(e)?n[0]:n),s=null!=r&&r.length>0&&Array.isArray(r[0])?r.map(((n,r)=>new ib(a,n,this,eg(e),t,this.name,r))):new ib(a,r,this,eg(e),t,this.name),this.addInboundNode(e,s,null,null,n,r,t),this._refCount++,null!=this.activityRegularizer)throw new Km("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return s}}))}warnOnIncompatibleInputShape(e){if(null!=this.batchInputShape)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,r)=>{null!=n&&null!=e[r]&&e[r]!==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(null==this.inboundNodes||0===this.inboundNodes.length)throw new Hm(`The layer ${this.name} has never been called and thus has no defined output shape.`);const e=[];for(const t of this.inboundNodes){const n=JSON.stringify(t.outputShapes);-1===e.indexOf(n)&&e.push(n)}if(1===e.length){const e=this.inboundNodes[0].outputShapes;return Array.isArray(e)&&Array.isArray(e[0])&&1===e.length?e[0]:e}throw new Hm(`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 jm(`You tried to call countParams() on ${this.name}, but the layer is not built yet. Build it first by calling build(batchInputShape).`);return tb(this.weights)}build(e){this.built=!0}getWeights(e=!1){return rb(e?this.trainableWeights:this.weights)}setWeights(e){Xo((()=>{const t=this.weights;if(t.length!==e.length)throw new qm(`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(0===t.length)return;const n=[],r=rb(t);for(let s=0;ss.apply(u.read()))),null==a&&(a=!0),a?this._trainableWeights.push(u):this._nonTrainableWeights.push(u),u}setFastWeightInitDuringBuild(e){this.fastWeightInitDuringBuild=e}addLoss(e){null==e||Array.isArray(e)&&0===e.length||(e=eg(e),void 0!==this._losses&&null!==this._losses&&this.losses.push(...e))}computeOutputShape(e){return e}computeMask(e,t){if(!this.supportsMasking){if(null!=t){if(!Array.isArray(t))throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`);t.forEach((e=>{if(null!=e)throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`)}))}return null}return t}addInboundNode(e,t,n,r,s,a,i=null){const o=eg(e);t=eg(t),n=eg(n),r=eg(r),s=Jy(s),a=Jy(a);const l=[],u=[],c=[];for(const e of o)l.push(e.sourceLayer),u.push(e.nodeIndex),c.push(e.tensorIndex);new lb({outboundLayer:this,inboundLayers:l,nodeIndices:u,tensorIndices:c,inputTensors:o,outputTensors:t,inputMasks:n,outputMasks:r,inputShapes:s,outputShapes:a},i);for(let e=0;ee.dispose())),this.weights.length}assertNotDisposed(){if(0===this._refCount)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(null===this._refCount)throw new Error(`Cannot dispose Layer ${this.name} because it has not been used yet.`);this.assertNotDisposed();let e=0;return 0==--this._refCount&&(e=this.disposeWeights()),{refCountAfterDispose:this._refCount,numDisposedVariables:e}}}function hb(e,t,n){if((null==t||null!=n&&n>0)&&(t=e.sourceLayer,n=e.nodeIndex),0===t.inboundNodes.length)return[e];{const e=t.inboundNodes[n];if(0===e.inboundLayers.length)return e.inputTensors;{const t=[];for(let n=0;n0){const s=await Promise.all(t);for(let t=0;tll(this.totals[e],hl(r,n))));this.totals[e]=s,null!=t&&t.dispose()}}}async onEpochEnd(e,t){if(null!=t)for(const e of this.params.metrics)null!=this.totals[e]&&("number"==typeof this.totals[e]?t[e]=this.totals[e]/this.seen:Xo((()=>{const n=hl(cl(1,this.seen),this.totals[e]);t[e]=n,this.totals[e].dispose(),Zo(t[e])})))}}class wb extends yb{async onTrainBegin(e){this.epoch=[],this.history={}}async onEpochEnd(e,t){null==t&&(t={}),this.epoch.push(e);for(const e in t)null==this.history[e]&&(this.history[e]=[]),this.history[e].push(t[e])}async syncData(){const e=[],t=[],n=[];for(const r in this.history){const s=this.history[r];for(let a=0;a{const i=null!=n?n():Rs();return i-snew vb(e,t)))}class Ib{constructor(){}static registerCallbackConstructor(e,t){re(e>=0&&Number.isInteger(e),(()=>`Verbosity level is expected to be an integer >= 0, but got ${e}`)),Ib.checkForDuplicate(t),null==Ib.constructors[e]&&(Ib.constructors[e]=[]),Ib.constructors[e].push(t)}static checkForDuplicate(e){for(const t in Ib.constructors)Ib.constructors[+t].forEach((t=>{if(t===e)throw new qm("Duplicate callback constructor.")}))}static clear(){Ib.constructors={}}static createCallbacks(e){const t=[];for(const n in Ib.constructors){const r=+n;e>=r&&t.push(...Ib.constructors[r])}return t.map((e=>new e))}}function Nb(e,t,n,r,s,a,i,o,l){const u=new wb,c=[new xb,...Ib.createCallbacks(t)];null!=e&&c.push(...e),c.push(u);const h=new bb(c);return h.setParams({epochs:n,initialEpoch:r,samples:s,steps:a,batchSize:i,verbose:t,doValidation:o,metrics:l}),{callbackList:h,history:u}}function Sb(e,t={},n=!1){return ig(e,Co.getMap().classNameMap,t,"layer",n)}function Tb(e,t){return Xo((()=>{"float32"!==e.dtype&&(e=Si(e,"float32"));const n=Ic(ay(e),t,!0),r=Sl(n.shape,Gm()),s=pl(Rl(n,r));return cl(e,s)}))}function Cb(e,t){return Xo((()=>Vc(ay(El(t,e)),-1)))}function Eb(e,t){return Xo((()=>Vc(Al(El(t,e)),-1)))}function $b(e,t){return Xo((()=>{const n=El(e,t),r=Tu(Al(e),Gm(),Number.MAX_VALUE),s=Al(cl(n,r));return hl(100,Vc(s,-1))}))}function Ab(e,t,n=!1){return Xo((()=>{if(n)t=Bh(t);else{const e=Ic(t,t.shape.length-1,!0);t=cl(t,e)}return t=Tu(t,Gm(),1-Gm()),xc(Ic(hl(Si(e,"float32"),yc(t)),t.shape.length-1))}))}function Rb(e,t,n=!1){return Xo((()=>{const r=Si(sc(function(e){const t=[Gg(e.shape)];return uu(e,t)}(e)),"int32"),s=(t=Tu(t,Gm(),1-Gm())).shape;return Ab(uu(ji(r,s[s.length-1]),s),t,n)}))}function Mb(e,t){return Xo((()=>{let n;return n=Tu(t,Gm(),1-Gm()),n=yc(cl(n,El(1,n))),Vc(function(e,t){if(!ue(e.shape,t.shape))throw new qm(`logits and labels must have the same shape, but got shapes ${JSON.stringify(e.shape)} and ${JSON.stringify(t.shape)}`);return Xo((()=>{const n=vh(t),r=xc(Al(t));return ll(El(n,hl(t,e)),bc(Qu(r)))}))}(e,n),-1)}))}function Fb(e,t){return Xo((()=>{const n=Tb(e,-1),r=Tb(t,-1),s=hl(n,r);return xc(Ic(s,-1))}))}Ib.constructors={};const Db={meanSquaredError:Cb,meanAbsoluteError:Eb,meanAbsolutePercentageError:$b,meanSquaredLogarithmicError:function(e,t){return Xo((()=>{const n=Tu(t,Gm(),Number.MAX_VALUE),r=yc(ll(1,n)),s=Tu(e,Gm(),Number.MAX_VALUE),a=yc(ll(1,s));return Vc(ay(El(r,a)),-1)}))},squaredHinge:function(e,t){return Xo((()=>{const n=Rl(0,El(1,hl(e,t)));return Vc(ay(n),-1)}))},hinge:function(e,t){return Xo((()=>{const n=Rl(0,El(1,hl(e,t)));return Vc(n,-1)}))},categoricalHinge:function(e,t){return Xo((()=>{const n=Ic(hl(e,t),-1),r=kc(hl(El(1,e),t),-1);return Rl(0,ll(1,El(r,n)))}))},logcosh:function(e,t){return Xo((()=>{const n=Math.log(2),r=El(t,e),s=El(ll(r,wc(hl(-2,r))),n);return Vc(s,-1)}))},categoricalCrossentropy:Ab,sparseCategoricalCrossentropy:Rb,binaryCrossentropy:Mb,kullbackLeiblerDivergence:function(e,t){return Xo((()=>{const n=Tu(e,Gm(),1),r=Tu(t,Gm(),1);return Ic(hl(e,yc(cl(n,r))),-1)}))},poisson:function(e,t){return Xo((()=>{const n=yc(ll(Gm(),t));return Vc(El(t,hl(e,n)),-1)}))},cosineProximity:Fb};function _b(e){if("string"==typeof e){if(e in Db)return Db[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 qm(t)}return e}function Ob(e,t){return Xo((()=>{const n=hl(.5,Qc(t)),r=Kg(ic(t,n),e.dtype);return Vc(ju(e,r),-1)}))}function Lb(e,t){return Xo((()=>Kg(ju(Ul(e,-1),Ul(t,-1)),"float32")))}function zb(e,t){return Xo((()=>Si(Ic(Dc(ju(e,1),ju(t,1))),"float32")))}function Pb(e,t){return Xo((()=>{const n=zb(e,t),r=function(e,t){return Xo((()=>Si(Ic(Dc(ju(e,0),ju(t,1))),"float32")))}(e,t),s=ll(n,r);return Si(qu(ic(s,0),cl(n,s),0),"float32")}))}function Bb(e,t){return Mb(e,t)}function Vb(e,t){return e.rank===t.rank&&(e=qh(e,[e.rank-1])),(t=Ul(t,-1)).dtype!==e.dtype&&(t=Si(t,e.dtype)),Si(ju(e,t),"float32")}const Ub=Ab,Wb=Rb,Gb={binaryAccuracy:Ob,categoricalAccuracy:Lb,precision:Pb,categoricalCrossentropy:Ub,sparseCategoricalCrossentropy:Wb,mse:Cb,MSE:Cb,mae:Eb,MAE:Eb,mape:$b,MAPE:$b,cosine:Fb};function Hb(e){if("string"==typeof e&&e in Gb)return Gb[e];if("string"!=typeof e&&null!=e)return e;throw new qm(`Unknown metric ${e}`)}function jb(e){if(Zm(null!==e,`Unknown LossOrMetricFn ${e}`),"string"==typeof e)return e;{let t;for(const n of Object.keys(Db))if(Db[n]===e){t=n;break}if(void 0!==t)return t;for(const n of Object.keys(Gb))if(Gb[n]===e){t=n;break}return void 0!==t?t:e.name}}function qb(e,t,n=!1){if(null==e||"object"!=typeof e||Object.getPrototypeOf(e)!==Object.prototype||!Kb(e))throw new Error("User-defined metadata is expected to be a JSON object, but is not.");if(n){const n=JSON.stringify(e);n.length>1048576&&console.warn(`User-defined metadata of model "${t}" is too large in size (length=${n.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 Kb(e){if(null===e)return!0;if("object"==typeof e){if(Object.getPrototypeOf(e)===Object.prototype){const t=Object.keys(e);for(const n of t){if("string"!=typeof n)return!1;if(!Kb(e[n]))return!1}return!0}if(Array.isArray(e)){for(const t of e)if(!Kb(t))return!1;return!0}return!1}{const t=typeof e;return"string"===t||"number"===t||"boolean"===t}}function Xb(e,t,n=console.log){let r="";for(let n=0;n0&&(r=r.slice(0,r.length-1)+" "),r+=e[n],r=r.slice(0,t[n]),r+=" ".repeat(t[n]-r.length);n(r)}function Yb(e,t,n){let r;try{r=JSON.stringify(e.outputShape)}catch(e){r="multiple"}Xb([`${e.name} (${e.getClassName()})`,r,e.countParams().toString()],t,n)}function Zb(e,t,n,r){let s;try{s=JSON.stringify(e.outputShape)}catch(e){s="multiple"}const a=[];for(const t of e.inboundNodes)if(!(null!=n&&n.length>0&&-1===n.indexOf(t)))for(let e=0;ee.name)),l=[],u=t.names();for(const e of o)-1!==u.indexOf(e)?l.push(t.getValue(e)):l.push(null);null!=r&&(r.maxNumTensors=-1/0,r.minNumTensors=1/0);const c=o.join(",")+"|"+t.names().join(",");let h,p;if(null==rx[c]){const e=function(e,t){re(null!=e&&e.length>0,(()=>"Expected at least one fetch, got none"));let n=[],r={};if(1===e.length){const s=ox(e[0],t);n=s.sorted,r=s.recipientMap}else{const s=new Set;for(const a of e){const{sorted:e,recipientMap:i}=ox(a,t);for(const t of e)s.has(t.name)||(n.push(t),s.add(t.name));for(const e in i)null==r[e]&&(r[e]=new Set),i[e].forEach((t=>r[e].add(t)))}}return{sorted:n,recipientCounts:ix(r)}}(i,t);h=e.sorted,p=e.recipientCounts,rx[c]=h,sx[c]=p}h=rx[c],p={},s||Object.assign(p,sx[c]);const d=new nx(t);for(let e=0;er.maxNumTensors&&(r.maxNumTensors=e),e0;){const e=a[a.length-1];if(n.has(e.name)){a.pop();continue}const t=i[i.length-1]===a.length-1;if(0===e.inputs.length||t)a.pop(),r.push(e),n.add(e.name),t&&i.pop();else{i.push(a.length-1);for(const t of e.inputs)null==s[t.name]&&(s[t.name]=new Set),s[t.name].add(e.name),n.has(t.name)||a.push(t)}}return{sorted:r,recipientMap:s}}function lx(e){let t;if(1===e.sourceLayer.inboundNodes.length)t=e.sourceLayer.output;else{let n=null;for(let t=0;te.name))}`);lg(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((e=>e.name))}`),this.inputLayers=[],this.inputLayersNodeIndices=[],this.inputLayersTensorIndices=[],this.outputLayers=[],this.outputLayersNodeIndices=[],this.outputLayersTensorIndices=[],this.layers=[],this.internalContainerRefs=[];for(const e of this.outputs){const t=e.sourceLayer,n=e.nodeIndex,r=e.tensorIndex;this.outputLayers.push(t),this.outputLayersNodeIndices.push(n),this.outputLayersTensorIndices.push(r)}for(const e of this.inputs){const t=e.sourceLayer,n=e.nodeIndex,r=e.tensorIndex;Zm(0===n,"input layer has >1 nodes"),Zm(0===r,"input layer has >1 tensors"),this.inputLayers.push(t),this.inputLayersNodeIndices.push(n),this.inputLayersTensorIndices.push(r)}this.inputNames=[],this.outputNames=[],this.feedInputShapes=[],this.feedInputNames=[],this.feedOutputNames=[];for(let t=0;te.shape)),this.internalOutputShapes=this.outputs.map((e=>e.shape));const t={},n={},r={},s={},a={},i=[],o=(e,t,n,r,s,l)=>{null!=r&&null!=s&&null!=l||(r=e.sourceLayer,s=e.nodeIndex,l=e.tensorIndex);const u=r.inboundNodes[s];if(-1!==n.indexOf(u))throw new jm(`The tensor ${e.name} at layer "${r.name}" is part of a cycle.`);if(-1!==t.indexOf(u))return;this.containerNodes.add(ux.nodeKey(r,s)),r.id in a||(a[r.id]=Object.keys(a).length),-1===n.indexOf(u)&&n.push(u);const c=u.inboundLayers.length;for(let e=0;e=0;)n.splice(n.indexOf(u),1);i.push(u)},l=[],u=[];for(const e of this.outputs)o(e,l,u);const c=i.slice().reverse();for(const e of c){n[e.id]=e,e.id in t||(t[e.id]=0);let a=t[e.id];const i=null==r[e.outboundLayer.id]?0:r[e.outboundLayer.id];a=Math.max(a,i),r[e.outboundLayer.id]=a,s[e.outboundLayer.id]=e.outboundLayer,t[e.id]=a;for(let r=0;rparseInt(e,10))).sort(og);this.layers=[];for(const e of d){const t=p[e];t.sort(((e,t)=>{const n=a[e.id],r=a[t.id];return nr?1:0}));for(const e of t)e instanceof ux&&this.internalContainerRefs.push(e),this.layers.push(e)}this.layersByDepth=p,d=Object.keys(h).map((e=>parseInt(e,10))).sort(og);const f=this.inputs.slice(),m=[];for(const e of d)for(const t of h[e]){const e=t.outboundLayer;if(null!=e){for(const n of t.inputTensors)if(-1===f.indexOf(n))throw new jm(`Graph disconnected: cannot obtain value for tensor ${n} at layer "${e.name}". The following previous layers were accessed without issue: ${m}`);for(const e of t.outputTensors)f.push(e);m.push(e.name)}}this.nodesByDepth=h;const g=this.layers.map((e=>e.name));for(const e of g){const t=g.filter((t=>t===e)).length;if(1!==t)throw new jm(`The name "${e}" is used ${t} times in the model. All layer names should be unique. Layer names: `+JSON.stringify(g))}this.outboundNodes=[],this.inboundNodes=[],new lb({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:this.inputs.map((e=>null)),outputMasks:this.outputs.map((e=>null)),inputShapes:this.inputs.map((e=>e.shape)),outputShapes:this.outputs.map((e=>e.shape))}),this.built=!0,this._refCount=1}assertNotDisposed(){if(0===this._refCount)throw new Error(`Container '${this.name}' is already disposed.`)}dispose(){this.assertNotDisposed();const e={refCountAfterDispose:null,numDisposedVariables:0};if(0==--this._refCount){for(const t of this.layers)e.numDisposedVariables+=t.dispose().numDisposedVariables;for(const t of this.internalContainerRefs)e.numDisposedVariables+=t.dispose().numDisposedVariables}return e.refCountAfterDispose=this._refCount,e}get trainable(){return this.trainable_}set trainable(e){this.layers.forEach((t=>{t._trainableWeights.forEach((t=>t.trainable=e))})),this.trainable_=e}get trainableWeights(){if(this._trainableWeights.length>0)throw new qm("Container instance unexpectedly contains _trainableWeights.The trainable weights of a Container are a union of the trainable weights of its consituent Layers. Its own _trainableWeights must remain an empty Array.");if(!this.trainable)return[];let e=[];for(const t of this.layers)e=e.concat(t.trainableWeights);return e}get nonTrainableWeights(){const e=[];for(const t of this.layers)e.push(...t.nonTrainableWeights);if(!this.trainable){const t=[];for(const e of this.layers)t.push(...e.trainableWeights);return t.concat(e)}return e}get weights(){return this.trainableWeights.concat(this.nonTrainableWeights)}loadWeights(e,t=!0){const n={};let r=0;for(const e of this.layers)for(const t of e.weights){if(null!=n[t.originalName])throw new qm(`Duplicate weight name: ${t.originalName}`);n[t.originalName]=t,r++}const s=[];for(const r in e){let a=r;if(null==n[r]){const e=r.split("/");a=e.slice(0,-2).concat([e[e.length-1]]).join("/")}if(null!=n[a])s.push([n[a],e[r]]);else if(t)throw new qm(`Provided weight data has no target variable: ${r}`);delete n[a]}if(t){const e=[];for(const t in n)e.push(t);if(e.length>0)throw new qm(`${e.length} of ${r} weights are not set: ${e}`)}sb(s)}updatedConfig(){const e=this.getConfig(),t={};return t.className=this.getClassName(),t.config=e,t.kerasVersion=`tfjs-layers ${tx}`,t.backend="TensorFlow.js",t}toJSON(e,t=!0){const n=ex(this.updatedConfig());return t?JSON.stringify(n):n}call(e,t){return Xo((()=>{e=eg(e);const n=new nx;for(let t=0;t{let n;return e=eg(e),n=null==t?Ym(null,e.length):eg(t),this.runInternalGraph(e,n)[1]}))}computeOutputShape(e){const t=Jy(e);if(t.length!==this.inputLayers.length)throw new qm(`Invalid inputShape argument ${e}: model has ${this.inputLayers.length} tensor inputs.`);const n={};for(let e=0;eparseInt(e,10))).sort(og);if(r.length>1)for(const e of r){const t=this.nodesByDepth[e];for(const e of t){const t=e.outboundLayer;if(-1!==this.inputLayers.map((e=>e.id)).indexOf(t.id))continue;const r=[];for(let t=0;tparseInt(e,10))).sort(og);for(const e of r){const t=this.nodesByDepth[e];for(const e of t){const t=e.outboundLayer,r=e.inputTensors,s=e.outputTensors,a=new Array;for(const e of r)e.id in n&&a.push(n[e.id]);if(a.length===r.length){let r,i,o,l,u={};if(null!=e.callArgs&&(u=e.callArgs),1===a.length){const[e,n]=a[0];null==u.mask&&(u.mask=n),o=eg(t.call(e,u)),l=eg(t.computeMask(e,n)),r=[e],i=[n]}else r=a.map((e=>e[0])),i=a.map((e=>e[1])),null==u.mask&&(u.mask=i),o=eg(t.call(r,u)),l=eg(t.computeMask(r,i));if(t.activityRegularizer)throw new Km("LayersModel invocation with concrete Tensor value(s) in the presence of activity regularizer(s) is not supported yet.");for(let e=0;e{const e=[];for(const t of this.layers)for(let n=0;n0){const e=[];for(let n=0;n0&&e.apply(Qm(n),r)}function l(e){const n=e.name,a=Sb(e,null!=t.customObjects?t.customObjects:{});a.setFastWeightInitDuringBuild(r),s[n]=a,e.inboundNodes.forEach((e=>{if(!(e instanceof Array))throw new qm(`Corrupted configuration, expected array for nodeData: ${e}`);i(a,e)}))}const u=t.name,c=t.layers;for(const e of c)l(e);for(;!ug(a);)for(const e of c){const t=s[e.name];if(t.name in a){const e=a[t.name];delete a[t.name];for(const n of e)o(t,n)}}const h=[],p=[],d=t.inputLayers;for(const e of d){const t=e[0],n=e[1],r=e[2];Zm(t in s);const a=s[t].inboundNodes[n].outputTensors;h.push(a[r])}const f=t.outputLayers;for(const e of f){const t=e[0],n=e[1],r=e[2];Zm(t in s);const a=s[t].inboundNodes[n].outputTensors;p.push(a[r])}return new e({inputs:h,outputs:p,name:u})}get stateful(){if(this._stateful)throw new qm("Container instance unexpectedly has _stateful = true. The statefulness of a Container is determined by the Layers it contains. Its _stateful property must remain the default false.");for(const e of this.layers)if(e.stateful)return!0;return!1}resetStates(){Xo((()=>{this.layers.forEach((e=>{e.stateful&&e.resetStates()}))}))}}function cx(e,t){return function(e,t,n){const r=t.length;if(null==e||Array.isArray(e)&&0===e.length)return t.map((e=>null));if(1===r)return Array.isArray(e)&&1===e.length?e:"object"==typeof e&&t[0]in e?[e[t[0]]]:[e];if(Array.isArray(e)){if(e.length!==r)throw new Error(`Provided ${n} is an array of ${e.length} element(s), but the model has ${r} outputs. Make sure a set of weights is provided for each model output.`);return e}if("object"==typeof e&&Object.keys(e).length>0&&"object"==typeof e[Object.keys(e)[0]]){const n=[];return t.forEach((t=>{t in e?n.push(e[t]):n.push(null)})),n}throw new Error(`The model has multiple (${r}) outputs, so ${n} must be either an array with ${r} elements or an object with ${t} keys. Provided ${n} not understood: ${JSON.stringify(e)}`)}(e,t,"classWeight")}async function hx(e,t,n,r){if(null!=t||null!=r)throw new Error("Support sampleWeight is not implemented yet");if(null!=n){const t=Xo((()=>{if(1===e.shape.length)return Ti(e);if(2===e.shape.length){if(e.shape[1]>1)return Ul(e,1);if(1===e.shape[1])return uu(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.`)}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.`)})),r=Array.from(await t.data());Yo(t);const s=[];return r.forEach((e=>{if(null==n[e])throw new Error(`classWeight must contain all classes in the training data. The class ${e} exists in the data but not in classWeight`);s.push(n[e])})),Jh(s,"float32")}return null}function px(e,t){return hl(e,t)}function dx(e,t){let n,r;const s=t;n=s.xs,r=s.ys,re(null!=n&&null!=r,(()=>`A Dataset iterator for fitDataset() is expected to generate objects of the form \`{xs: xVal, ys: yVal}\`, where the two values may be \`tf.Tensor\`, an array of Tensors, or a map of string to Tensor. The provided Dataset instead generates ${t}`));const a=fx("input",e.inputNames,n),i=fx("output",e.outputNames,r),o=a[0].shape[0];re(a.length===e.inputs.length,(()=>`LayersModel has ${e.inputs.length} inputs, but the dataset provides ${a.length} inputs. (Expected input keys: ${JSON.stringify(e.inputNames)})`)),re(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 t=0;t`Batch size mismatch: input ${e.inputNames[t]} has ${a[t].shape[0]}; expected ${o} based on input ${e.inputNames[0]}.`));for(let t=0;t`Batch size mismatch: output ${e.outputNames[t]} has ${i[t].shape[0]}; expected ${o} based on input ${e.inputNames[0]}.`));return{xs:a,ys:i}}function fx(e,t,n){if(n instanceof qs)return[n];if(Array.isArray(n))return re(n.length===t.length,(()=>`Received an array of ${n.length} Tensors, but expected ${t.length} to match the ${e} keys ${t}.`)),n;{const r=[];for(const s of t){if(null==n[s])throw new qm(`The feature data generated by the dataset lacks the required ${e} key '${s}'.`);r.push(n[s])}return r}}function mx(e){return"function"==typeof e.iterator}function gx(e){re(e>0&&Number.isInteger(e),(()=>`batchSize is required to be a positive integer, but got ${e}`))}function yx(e,t,n){return null==e?[null]:Array.isArray(e)?e.map((e=>Yg(e,t,n-t))):Yg(e,t,n-t)}function bx(e,t){return Xo((()=>null==e?null:Array.isArray(e)?e.map((e=>bx(e,t))):sy(e,"int32"===t.dtype?t:Si(t,"int32"))))}function xx(e,t){const n=[];let r=0,s=null;for(;r=e&&(s=e),n.push([r,s]),r=s;return n}function wx(e){const t=[];e instanceof qs&&(e=[e]);for(let n=0;nn.push(e.id)));else if(null!=t)for(const e in t){const r=t[e];n.push(r.id)}const r=[];if(e instanceof qs)-1===n.indexOf(e.id)&&r.push(e);else if(Array.isArray(e))e.forEach((e=>{-1===n.indexOf(e.id)&&r.push(e)}));else if(null!=e)for(const t in e){const s=e[t];-1===n.indexOf(s.id)&&r.push(s)}r.forEach((e=>{e.isDisposed||e.dispose()}))}function kx(e){return Array.isArray(e)}function Ix(e){return!function(e){return e instanceof qs}(e)&&!kx(e)}function Nx(e,t,n,r=!0,s=""){if(null==t||0===t.length){if(null!=e){let t=!1;if(kx(e)&&e.length>0)t=!0;else if(Ix(e)){for(const n in e)if(e.hasOwnProperty(n)){t=!0;break}}else t=!0;if(t)throw new qm(`Error when checking model ${s} expected no data, but got ${e}`)}return[]}if(null==e)return t.map((e=>null));let a;if(Ix(e)){e=e,a=[];for(const n of t){if(null==e[n])throw new qm(`No data provided for "${n}". Need data for each key in: ${t}`);a.push(e[n])}}else if(kx(e)){if((e=e).length!==t.length)throw new qm(`Error when checking model ${s}: 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}`);a=e}else{if(e=e,t.length>1)throw new qm(`The model ${s} expects ${t.length} Tensor(s), but only received one Tensor. Found: Tensor with shape ${e.shape}`);a=[e]}if(a=wx(a),null!=n)for(let e=0;e=0&&a!==o)throw new qm(`${s} expected a batch of elements where each example has shape [${n[e].slice(1,n[e].length)}] (i.e.,tensor shape [*,${n[e].slice(1,n[e].length)}]) but the ${s} received an input with ${i.shape[0]} examples, each with shape [${i.shape.slice(1,i.shape.length)}] (tensor shape [${i.shape}])`)}}return a}function Sx(e,t,n,r=!0,s=""){let a;if(Array.isArray(e)){if(e.length!==t.length)throw new qm(`Error when checking model ${s}: the Array of Tensors that you are passing to your model is not the size the the model expected. Expected to see ${t.length} Tensor(s), but instead got ${e.length} Tensors(s).`);a=e}else{if(t.length>1)throw new qm(`The model expects ${t.length} ${s} Tensors, but only received one Tensor. Found: array with shape ${JSON.stringify(e.shape)}.`);a=[e]}if(null!=n)for(let e=0;e1||1===e.length&&e[0].inboundLayers.length>1){t=!1;break}r.push(...e)}if(t)for(const n of e.layers){let e=!1;for(const s of n.inboundNodes)if(-1!==r.indexOf(s)){if(e){t=!1;break}e=!0}if(!t)break}return t}(e),a=["Layer (type)","Output shape","Param #"];let i;if(s?(t=t||65,n=n||[.45,.85,1]):(t=t||98,n=n||[.33,.55,.67,1]),n[n.length-1]<=1&&(n=n.map((e=>Math.floor(t*e)))),!s){a.push("Receives inputs"),i=[];for(const t in e.nodesByDepth)i.push(...e.nodesByDepth[t])}r("_".repeat(t)),Xb(a,n,r),r("=".repeat(t));const o=e.layers;for(let e=0;eRd.adagrad(.01),Adadelta:()=>Rd.adadelta(1,.95,Gm()),Adam:()=>Rd.adam(.001,.9,.999,Gm()),Adamax:()=>Rd.adamax(.002,.9,.999,Gm(),0),RMSProp:()=>Rd.rmsprop(.001,.9,0,Gm()),SGD:()=>Rd.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 qm(`Unknown Optimizer ${e}`)}(e.optimizer),this.isOptimizerOwned=!0;else{if(!(e.optimizer instanceof Il))throw new qm("User-defined optimizer must be an instance of tf.Optimizer.");this.optimizer_=e.optimizer,this.isOptimizerOwned=!1}let t=[];if(Array.isArray(e.loss)||"string"==typeof e.loss||"function"==typeof e.loss)if(Array.isArray(e.loss)){if(e.loss.length!==this.outputs.length)throw new qm(`When passing an Array as loss, it should have one entry per model output. The model has ${this.outputs.length} output(s), but you passed loss=${e.loss}.`);const n=e.loss;t=n.map((e=>_b(e)))}else{const n=_b(e.loss);this.outputs.forEach((e=>{t.push(n)}))}else{e.loss=e.loss;for(const t in e.loss)if(-1===this.outputNames.indexOf(t))throw new qm(`Unknown entry in loss dictionary: "${t}". Only expected the following keys: ${this.outputNames}`);for(const n of this.outputNames)null==e.loss[n]&&console.warn(`Output "${n}" is missing from loss dictionary. We assume this was done on purpose, and we will not be expecting data to be passed to ${n} during training`),t.push(_b(e.loss[n]))}this.lossFunctions=t,this.feedOutputNames=[],this.feedOutputShapes=[],this.feedLossFns=[];for(let e=0;e{for(let e=0;e1&&(this.metricsTensors.push([t,e]),this.metricsNames.push(this.outputNames[e]+"_loss"))}}));const r=function(e,t){if(null==e||Array.isArray(e)&&0===e.length)return t.map((e=>[]));let n;if("string"==typeof e||"function"==typeof e)n=[e];else{if(!Array.isArray(e)&&"object"!=typeof e)throw new TypeError(`Type of metrics argument not understood. Expected an string,function, Array, or Object, found: ${e}`);n=e}if(Array.isArray(n))return t.map((e=>n));{const e=[];for(const r of t){let t=n.hasOwnProperty(r)?n[r]:[];Array.isArray(t)||(t=[t]),e.push(t)}return e}}(e.metrics,this.outputNames),s=(e,t,n)=>{this.outputNames.length>1&&(t=this.outputNames[e]+"_"+t),this.metricsNames.push(t),this.metricsTensors.push([n,e])};Pg("metric",(()=>{for(let e=0;e{let n,r,a;for(const i of t){if("string"==typeof i&&-1!==["accuracy","acc","crossentropy","ce"].indexOf(i)){const t=this.internalOutputShapes[e];let s;1===t[t.length-1]||this.lossFunctions[e]===Mb?-1!==["accuracy","acc"].indexOf(i)?r=Ob:-1!==["crossentropy","ce"].indexOf(i)&&(r=Bb):this.lossFunctions[e]===Rb?-1!==["accuracy","acc"].indexOf(i)?r=Vb:-1!==["crossentropy","ce"].indexOf(i)&&(r=Wb):-1!==["accuracy","acc"].indexOf(i)?r=Lb:-1!==["crossentropy","ce"].indexOf(i)&&(r=Ub),-1!==["accuracy","acc"].indexOf(i)?s="acc":-1!==["crossentropy","ce"].indexOf(i)&&(s="ce"),a=r,n=""+s}else{const e=Hb(i);a=e,n=""+jb(i)}let t;Pg(n,(()=>{t=a})),s(e,n,t)}})(r[e])})),this.collectedTrainableWeights=this.trainableWeights}checkTrainableWeightsConsistency(){null!=this.collectedTrainableWeights&&this.trainableWeights.length!==this.collectedTrainableWeights.length&&console.warn("Discrepancy between trainableweights and collected trainable weights. Did you set `model.trainable` without calling `model.compile()` afterwards?")}evaluate(e,t,n={}){const r=null==n.batchSize?32:n.batchSize;gx(r);const s=this.standardizeUserDataXY(e,t,!0,r);try{const a=s[0].concat(s[1]);this.makeTestFunction();const i=this.testFunction;return Qm(this.testLoop(i,a,r,n.verbose,n.steps))}finally{vx(s[0],e),vx(s[1],t)}}async evaluateDataset(e,t){return this.makeTestFunction(),async function(e,t,n){const r=null!=(n=n||{}).batches,s=e.testFunction;let a=[];if(n.verbose>0)throw new Km("Verbose mode is not implemented yet.");re(!r||n.batches>0&&Number.isInteger(n.batches),(()=>`Test loop expects \`batches\` to be a positive integer, but received ${JSON.stringify(n.batches)}`));const i="function"==typeof t.next?t:await t.iterator();let o=0,l=0;for(;!r||l{if(t.value){const{xs:n,ys:r}=dx(e,t.value),i=n.concat(r),u=Xo((()=>s(i)));if(Yo(i),0===l)for(let e=0;ell(a[e],hl(c,t)))),l>0&&Yo(n)}Yo(u),o+=c,++l}return a})),t.done){r&&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 e=0;ee.name));for(let r=0;r0){const n=[];throw t.forEach(((t,r)=>{null==t&&n.push(e[r])})),new qm(`Cannot find SymbolicTensors for output name(s): ${JSON.stringify(n)}`)}return t}predictLoop(e,t=32,n=!1){return Xo((()=>{const r=this.checkNumSamples(e);if(n)throw new Km("Verbose predictLoop() is not implemented yet.");const s=xx(r,t),a=this.outputs.map((e=>[]));for(let t=0;t{const n=s[t][0],r=s[t][1],a=yx(e,n,r),i=[];if(Array.isArray(a))for(let e=0;ea[t].push(e)));return Qm(a.map((e=>pu(e,0))))}))}predict(e,t={}){const n=wx(e);Sx(n,this.inputNames,this.feedInputShapes,!1);try{const r=null==t.batchSize?32:t.batchSize;return gx(r),this.predictLoop(n,r)}finally{vx(n,e)}}predictOnBatch(e){Sx(e,this.inputNames,this.feedInputShapes,!0);const t=(Array.isArray(e)?e[0]:e).shape[0];return this.predictLoop(e,t)}standardizeUserDataXY(e,t,n=!0,r){if(null==this.optimizer_)throw new jm("You must compile a model before training/testing. Use LayersModel.compile(modelCompileArgs).");const s=[];for(let e=0;ee.shape[0])));r.sort();const s=lg(t.map((e=>e.shape[0])));if(s.sort(),r.length>1)throw new qm(`All input Tensors (x) should have the same number of samples. Got array shapes: ${JSON.stringify(e.map((e=>e.shape)))}`);if(s.length>1)throw new qm(`All target Tensors (y) should have the same number of samples. Got array shapes: ${JSON.stringify(t.map((e=>e.shape)))}`);if(r.length>0&&s.length>0&&!ue(r,s))throw new qm(`Input Tensors should have the same number of samples as target Tensors. Found ${r[0]} input sample(s) and ${s[0]} target sample(s).`)}(e=Nx(e,this.feedInputNames,this.feedInputShapes,!1,"input"),t=Nx(t,this.feedOutputNames,s,!1,"target")),function(e,t,n){const r=[Cb,Mb,Ab];for(let s=0;s0&&e[0].shape[0]%r!=0)throw new qm(`In a stateful network, you should only pass inputs with a number of samples that is divisible by the batch size ${r}. Found: ${e[0].shape[0]} sample(s).`);return[e,t]}async standardizeUserData(e,t,n,r,s=!0,a){const[i,o]=this.standardizeUserDataXY(e,t,s,a);if(null!=n)throw new Error("sample weight is not supported yet.");let l=null;if(null!=r){const e=cx(r,this.outputNames);l=[];for(let t=0;t{const a=this.checkNumSamples(t,n,s,"steps"),i=[];if(r>0)throw new Km("Verbose mode is not implemented yet.");if(null!=s)throw new Km("steps mode in testLoop() is not implemented yet");{const r=xx(a,n),s=Jh(qg(0,a));for(let n=0;n1&&(s+=`_${Jm(e.slice(0,n),r)}`),t.push(s)}return t}makeTrainFunction(){return e=>{const t=[],n=e.slice(0,this.inputs.length),r=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),s=e.slice(this.inputs.length+this.outputs.length,this.inputs.length+2*this.outputs.length),a=[],i=this.collectedTrainableWeights.map((e=>e.read()));return[this.optimizer_.minimize((()=>{const e=[];for(let t=0;t1&&e{l=ll(l,e)})),l}),!0,i)].concat(a)}}makeTestFunction(){this.testFunction=e=>Xo((()=>{const t=[];let n;const r=e.slice(0,this.inputs.length),s=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),a=[];for(let e=0;e0){if(y=!0,2!==r.validationData.length)throw 3===r.validationData.length?new Km("validationData including sample weights is not supported yet."):new qm(`When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; ${r.validationData} is invalid.`);l=r.validationData[0],u=r.validationData[1];const t=!0,n=await e.standardizeUserData(l,u,null,null,t,d);c=n[0],h=n[1],g=c.concat(h)}else if(null!=r.validationSplit&&r.validationSplit>0&&r.validationSplit<1){y=!0;const e=Math.floor(s[0].shape[0]*(1-r.validationSplit)),t=s[0].shape[0];c=yx(s,e,t),i=s,s=yx(s,0,e),h=yx(a,e,t),o=a,a=yx(a,0,e),g=c.concat(h)}else null!=r.validationSteps&&(y=!0);const b=s.concat(a).concat(p);e.checkTrainableWeightsConsistency();const x=e.makeTrainFunction(),w=e.getDedupedMetricsNames();let v,k;y?(e.makeTestFunction(),v=e.testFunction,k=w.slice().concat(w.map((e=>"val_"+e)))):(v=null,g=[],k=w.slice());const I=kb(r.callbacks,r.yieldEvery);return await async function(e,t,n,r,s,a,i,o,l,u,c,h,p,d,f){null==s&&(s=32),null==a&&(a=1),null==c&&(c=!0),null==p&&(p=0);let m=!1;null!=l&&null!=u&&(m=!0);const g=e.checkNumSamples(n,s,d,"steps_per_epoch");let y;null!=g&&(y=qg(0,g)),null==i&&(i=1);const{callbackList:b,history:x}=Nb(o,i,a,p,g,d,s,m,h);b.setModel(e),e.history=x,await b.onTrainBegin(),e.stopTraining_=!1;for(let i=p;i{const p=o[c][0],d=o[c][1],f=Yg(i,p,d-p);h.batch=c,h.size=d-p;const g=bx(n,f),y=t(g);for(let e=0;e"You must compile a model before training/testing. Use LayersModel.compile(modelCompileConfig).")),re(null!=n,(()=>"For fitDataset(), the 2nd argument (config) is required, but it is not provided in this call.")),re(null!=n.epochs&&n.epochs>0&&Number.isInteger(n.epochs),(()=>`For fitDataset(), config.epochs is expected to be a positive integer, but got ${n.epochs}`)),re(!r||n.batchesPerEpoch>0&&Number.isInteger(n.batchesPerEpoch),(()=>`For fitDataset(), config.batchesPerEpoch is expected to be a positive integer if specified, but got ${n.batchesPerEpoch}`)),re(null==n.validationSplit,(()=>"`validationSplit` is not supported by `fitDataset()`. Use validationData instead.")),e.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");e.isTraining=!0;try{const s=null!=n.validationData;let a,i;if(s)if(mx(n.validationData))re(null==n.validationBatches||n.validationBatches>0&&Number.isInteger(n.validationBatches),(()=>`For fitDataset() with dataset-based validation, config.validationBatches is expected not to be provided, or to be a positive integer, but got ${n.validationBatches}`));else{const e=function(e){if(3===e.length)throw new Km("Validation with sample weights is not implemented yet.");return{xs:e[0],ys:e[1]}}(n.validationData);a=e.xs,i=e.ys}const o=e.makeTrainFunction(),l=e.getDedupedMetricsNames();let u;u=s?l.slice().concat(l.map((e=>"val_"+e))):l.slice();const c=kb(n.callbacks,n.yieldEvery),h=null==n.verbose?1:n.verbose,{callbackList:p,history:d}=Nb(c,h,n.epochs,null,null,function(e,t){let n=null;return null!=t.batchesPerEpoch?n=t.batchesPerEpoch:Number.isFinite(e.size)&&(n=e.size),n}(t,n),null,s,u);p.setModel(e),e.history=d,await p.onTrainBegin(),e.stopTraining_=!1;let f=null==n.initialEpoch?0:n.initialEpoch,m=await t.iterator();for(;f=n.batchesPerEpoch:t.done){if(s){let t;t=mx(n.validationData)?eg(await e.evaluateDataset(n.validationData,{batches:n.validationBatches})):eg(e.evaluate(a,i,{batchSize:null==n.validationBatchSize?32:n.validationBatchSize,verbose:0}));for(let n=0;ntg(e)))}else{const t=Object.keys(this.loss);e={};const n=this.loss;for(const r of t){if("string"!=typeof n[r])throw new Error("Serialization of non-string loss is not supported.");e[r]=tg(n[r])}}return e}getMetricIdentifiers(){if("string"==typeof this.metrics||"function"==typeof this.metrics)return[tg(jb(this.metrics))];if(Array.isArray(this.metrics))return this.metrics.map((e=>tg(jb(e))));{const e={};for(const t in this.metrics)e[t]=tg(jb(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(null!=e.weighted_metrics)throw new Error("Loading weight_metrics is not supported yet.");if(null!=e.loss_weights)throw new Error("Loading loss_weights is not supported yet.");if(null!=e.sample_weight_mode)throw new Error("Loading sample_weight_mode is not supported yet.");const t=Sb(Qb(e.optimizer_config));let n,r;if("string"==typeof e.loss)n=ng(e.loss);else if(Array.isArray(e.loss))n=e.loss.map((e=>ng(e)));else if(null!=e.loss){n={};for(const t in e.loss)n[t]=ng(e.loss[t])}if(Array.isArray(e.metrics))r=e.metrics.map((e=>ng(e)));else if(null!=e.metrics){r={};for(const t in e.metrics)r[t]=ng(e.metrics[t])}this.compile({loss:n,metrics:r,optimizer:t})}async save(e,t){if("string"==typeof e){const t=Ha(e);if(0===t.length)throw new qm(`Cannot find any save handlers for URL '${e}'`);if(t.length>1)throw new qm(`Found more than one (${t.length}) save handlers for URL '${e}'`);e=t[0]}if(null==e.save)throw new qm("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");const n=await Ra(this.getNamedWeights(t)),r={modelTopology:this.toJSON(null,!1),format:"layers-model",generatedBy:`TensorFlow.js tfjs-layers v${tx}`,convertedBy:null};if(null!=t&&t.includeOptimizer&&null!=this.optimizer){r.trainingConfig=this.getTrainingConfig();const e="optimizer",{data:t,specs:s}=await Ra(await this.optimizer.getWeights(),e);n.specs.push(...s),n.data=Oa([n.data,t])}if(null!=this.userDefinedMetadata){const e=!0;qb(this.userDefinedMetadata,this.name,e),r.userDefinedMetadata=this.userDefinedMetadata}return r.weightData=n.data,r.weightSpecs=n.specs,e.save(r)}setUserDefinedMetadata(e){qb(e,this.name),this.userDefinedMetadata=e}getUserDefinedMetadata(){return this.userDefinedMetadata}}Tx.className="Model",Eo(Tx);class Cx extends Tx{}async function Ex(e,t){"modelTopology"in e||(e={modelTopology:e});let n=(e=e).modelTopology;null!=n.model_config&&(n=n.model_config);const r=Sb(Qb(n),t);if(null!=e.weightsManifest){const t=await Di(e.weightsManifest,e.pathPrefix,r.weights.map((e=>e.originalName))),n={};for(const e of r.weights)n[e.originalName]=t[e.originalName];r.loadWeights(n),Yo(t)}return r}Cx.className="Functional",Eo(Cx);class $x extends Tx{constructor(e){if(super({inputs:[],outputs:[]}),e=e||{},this.trainable=!0,this.built=!1,this.name=null!=e.name?e.name:Yy("sequential_"),null!=e.layers)for(const t of e.layers)this.add(t)}checkShape(e){if(e.inboundNodes[0].outputTensors[0].shape.some((e=>e<0)))throw new qm(`Negative dimension size caused by adding layer ${e.name} with input shape [${e.inboundNodes[0].inputTensors[0].shape}]`)}add(e){const t=e instanceof $x||e instanceof Tx;let n;if(t){if(n=e,1!==n.outputs.length)throw new qm("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");if(1!==n.inputs.length)throw new qm("All layers in a Sequential model should have a single input tensor. For multi-input layers, use the functional API.")}if(0===this.outputs.length){if(0===e.inboundNodes.length){if(null==e.batchInputShape)throw new qm("The first layer in a Sequential model must get an `inputShape` or `batchInputShape` argument.");const t=db({batchShape:e.batchInputShape,dtype:e.dtype,name:e.name+"_input"});e.apply(t)}if(t)this.outputs=n.outputs,this.inputs=n.inputs;else{if(1!==e.inboundNodes.length)throw new qm(`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(1!==e.inboundNodes[0].outputTensors.length)throw new qm("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=hb(this.outputs[0])}this.inboundNodes=[],new lb({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:Ym(null,this.inputs.length),outputMasks:[null],inputShapes:this.inputs.map((e=>e.shape)),outputShapes:this.outputs[0].shape})}else{const t=e.apply(this.outputs[0]);if(Array.isArray(t))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=[t],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}this.layers.push(e),this.built=!1}pop(){if(0===this.layers.length)throw new TypeError("There are no layers in the model.");if(this.layers.pop(),0===this.layers.length)this.outputs=[],this.inboundNodes=[],this.outboundNodes=[];else{const e=this.layers.length-1;this.layers[e].outboundNodes=[],this.outputs=[this.layers[e].output],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}}call(e,t){return null==this.model&&this.build(),this.model.call(e,t)}build(e){if(eb(e),0===this.inputs.length||0===this.outputs.length)throw new TypeError("Sequential model cannot be built: model is empty. Add some layers first.");this.model=new Tx({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){null==this.model&&this.build(),this.model.setWeights(e)}evaluate(e,t,n={}){if(!this.built)throw new jm("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 jm("The model needs to be compiled before being used.");return this.model.evaluateDataset(e,t)}predict(e,t={}){return null==this.model&&this.build(),this.model.predict(e,t)}predictOnBatch(e){return null==this.model&&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 null==this.model?void 0:this.model.optimizer}set optimizer(e){this.model.optimizer=e}async fit(e,t,n={}){if(!this.built)throw new jm("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 jm("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={},r=!1){let s,a={};if(t instanceof Array){if(null==t[0].className||"Merge"===t[0].className)throw new qm("Legacy serialization format not supported yet.");s=t}else re(null!=t.layers,(()=>"When the config data for a Sequential model is not an Array, it must be an Object that contains the 'layers' field.")),s=t.layers,delete t.layers,a=t;const i=new e(a);if(!(i instanceof $x))throw new Km(`Sequential.fromConfig called on non-Sequential input: ${i}`);for(const e of s){const t=Sb(e,void 0,r);r&&t.setFastWeightInitDuringBuild(!0),i.add(t)}return i}set stopTraining(e){if(null==this.model)throw new qm("Cannot set the stopTraining property of a sequential model before it is compiled.");this.model.stopTraining=e}get stopTraining(){if(null==this.model)throw new qm("Cannot get the stopTraining property of a sequential model before it is compiled.");return this.model.stopTraining}getConfig(){const e=[];for(const t of this.layers){const n={};n.className=t.getClassName(),n.config=t.getConfig(),e.push(n)}return{name:this.name,layers:e}}}function Ax(e){return new Tx(e)}function Rx(e){return new $x(e)}function Mx(e,t){return null==t&&(t={}),async function(e,t){if(null==t&&(t={}),"string"==typeof e){const n=ja(e,t);if(0===n.length)n.push(Bi(e,t));else if(n.length>1)throw new qm(`Found more than one (${n.length}) load handlers for URL '${e}'`);e=n[0]}return async function(e,t,n){if(null==n&&(n={}),null==e.load)throw new qm("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");const r=await e.load();let s=r.modelTopology;null!=s.model_config&&(s=s.model_config);const a=null==n.strict||n.strict,i=null!=r.weightData&&null!=r.weightSpecs&&a,o=Sb(Qb(s),void 0,i),l=r.trainingConfig;if(null!=l&&o.loadTrainingConfig(l),null!=r.userDefinedMetadata&&o.setUserDefinedMetadata(r.userDefinedMetadata),null!=r.weightData){if(null==r.weightSpecs)throw new qm("LayersModel artifacts contains weight data, but not weight specs. Therefore loading of weights cannot proceed.");const{modelWeights:e,optimizerWeights:t}=function(e,t){const n=Ma(e,t),r={},s=[];return t.forEach((e=>{"optimizer"===e.group?s.push({name:e.name,tensor:n[e.name]}):r[e.name]=n[e.name]})),{modelWeights:r,optimizerWeights:s}}(r.weightData,r.weightSpecs);o.loadWeights(e,a),null!=o.optimizer&&t.length>0&&await o.optimizer.setWeights(t),Yo(e),Yo(t.map((e=>e.tensor)))}return o}(e,0,t)}(e,t)}function Fx(e){return db(e)}function Dx(e,t){Ib.registerCallbackConstructor(e,t)}$x.className="Sequential",Eo($x);class _x extends To{getConfig(){return{}}}class Ox extends _x{apply(e,t=1){return function(e,t=1){if(1!==t)throw new Km(`Support for alpha values other than 1 (${t}) is not implemented yet.`);return Zu(e)}(e,t)}}Ox.className="elu",Eo(Ox);class Lx extends _x{apply(e){return Ah(e)}}Lx.className="selu",Eo(Lx);class zx extends _x{apply(e){return vh(e)}}zx.className="relu",Eo(zx);class Px extends _x{apply(e){return Xo((()=>jc(6,vh(e))))}}Px.className="relu6",Eo(Px);class Bx extends _x{apply(e){return e}}Bx.className="linear",Eo(Bx);class Vx extends _x{apply(e){return du(e)}}Vx.className="sigmoid",Eo(Vx);class Ux extends _x{apply(e){return function(e){return Xo((()=>{const t=ll(.5,hl(.2,e));return Tu(t,0,1)}))}(e)}}Ux.className="hardSigmoid",Eo(Ux);class Wx extends _x{apply(e){return wc(e)}}Wx.className="softplus",Eo(Wx);class Gx extends _x{apply(e){return function(e){return Xo((()=>cl(e,ll(Al(e),1))))}(e)}}Gx.className="softsign",Eo(Gx);class Hx extends _x{apply(e){return mu(e)}}Hx.className="tanh",Eo(Hx);class jx extends _x{apply(e,t=-1){return Bh(e,t)}}jx.className="softmax",Eo(jx);class qx extends _x{apply(e,t=-1){return Nc(e,t)}}qx.className="logSoftmax",Eo(qx);class Kx extends _x{apply(e,t=1){return Xo((()=>hl(du(hl(e,t)),e)))}}Kx.className="swish",Eo(Kx);class Xx extends _x{apply(e){return Xo((()=>hl(e,mu(wc(e)))))}}function Yx(e){return e.getClassName()}function Zx(e,t={}){return ig(e,Co.getMap().classNameMap,t,"activation")}function Jx(e){if(null==e){return Zx({className:"linear",config:{}})}if("string"==typeof e){const t={};return t.className=e,t.config={},Zx(t)}return e instanceof _x?e:Zx(e)}function Qx(e){if(null!=e&&"object"!=typeof e)throw new Error(`Argument to L1L2 regularizer's constructor is expected to be an object, but received: ${e}`)}Xx.className="mish",Eo(Xx);class ew extends To{}class tw extends ew{constructor(e){super(),Qx(e),this.l1=null==e||null==e.l1?.01:e.l1,this.l2=null==e||null==e.l2?.01:e.l2,this.hasL1=0!==this.l1,this.hasL2=0!==this.l2}apply(e){return Xo((()=>{let t=Uc([1]);return this.hasL1&&(t=ll(t,Ic(hl(this.l1,Al(e))))),this.hasL2&&(t=ll(t,Ic(hl(this.l2,ay(e))))),uu(t,[])}))}getConfig(){return{l1:this.l1,l2:this.l2}}static fromConfig(e,t){return new e({l1:t.l1,l2:t.l2})}}tw.className="L1L2",Eo(tw);const nw={l1l2:"L1L2"};function rw(e){return sg(e)}function sw(e,t={}){return ig(e,Co.getMap().classNameMap,t,"regularizer")}function aw(e){return null==e?null:"string"==typeof e?sw({className:e in nw?nw[e]:e,config:{}}):e instanceof ew?e:sw(e)}class iw extends cb{constructor(e){super(null==e?{}:e),this.supportsMasking=!0,null!=e&&(this.maxValue=e.maxValue)}call(e,t){e=Qy(e);let n=vh(e);return null!=this.maxValue&&(n=Tu(n,0,this.maxValue)),n}computeOutputShape(e){return e}getConfig(){const e={maxValue:this.maxValue},t=super.getConfig();return Object.assign(e,t),e}}iw.className="ReLU",Eo(iw);class ow extends cb{constructor(e){super(null==e?{}:e),this.DEFAULT_ALPHA=.3,null==e&&(e={}),this.alpha=null==e.alpha?this.DEFAULT_ALPHA:e.alpha}call(e,t){const n=Qy(e);return pc(n,this.alpha)}computeOutputShape(e){return e}getConfig(){const e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}}ow.className="LeakyReLU",Eo(ow);class lw extends cb{constructor(e){if(super(null==e?{}:e),this.DEFAULT_ALPHA_INITIALIZER="zeros",null==e&&(e={}),this.supportsMasking=!0,this.alphaInitializer=Ry(e.alphaInitializer||this.DEFAULT_ALPHA_INITIALIZER),this.alphaRegularizer=aw(e.alphaRegularizer),this.alphaConstraint=Ng(e.alphaConstraint),null==e.sharedAxes)this.sharedAxes=null;else if(Array.isArray(e.sharedAxes))this.sharedAxes=e.sharedAxes;else{if("number"!=typeof e.sharedAxes)throw new qm(`Expected sharedAxes to be a number or an array of numbers, but got ${e.sharedAxes}`);this.sharedAxes=[e.sharedAxes]}}build(e){const t=(e=eb(e)).slice(1);if(null!=this.sharedAxes)for(const e of this.sharedAxes)t[e-1]=1;this.alpha=this.addWeight("alpha",t,"float32",this.alphaInitializer,this.alphaRegularizer,!0,this.alphaConstraint);const n={};if(null!=this.sharedAxes)for(let t=1;t(_g(t),"channelsFirst"===t?qi(e,[0,2,3,1]):e)))}function gw(e,t){return Xo((()=>(_g(t),"channelsFirst"===t?qi(e,[0,2,3,4,1]):e)))}function yw(e,t,n,r=[1,1],s="valid",a,i,o=null){return Xo((()=>{if(null==a&&(a="channelsLast"),_g(a),3!==e.rank&&4!==e.rank)throw new qm(`conv2dWithBiasActivation expects input to be of rank 3 or 4, but received ${e.rank}.`);if(3!==t.rank&&4!==t.rank)throw new qm(`conv2dWithBiasActivation expects kernel to be of rank 3 or 4, but received ${e.rank}.`);let l=mw(e,a);if("causal"===s)throw new Km("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");return l=Cp({x:l,filter:t,strides:r,pad:"same"===s?"same":"valid",dilations:i,dataFormat:"NHWC",bias:n,activation:o}),"channelsFirst"===a&&(l=qi(l,[0,3,1,2])),l}))}hw.className="Softmax",Eo(hw);class bw extends cb{constructor(e,t){if(super(t),this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",bw.verifyArgs(t),this.rank=e,pg(this.rank,"rank"),1!==this.rank&&2!==this.rank&&3!==this.rank)throw new Km(`Convolution layer for rank other than 1, 2, or 3 (${this.rank}) is not implemented yet.`);if(this.kernelSize=pw(t.kernelSize,e,"kernelSize"),this.strides=pw(null==t.strides?1:t.strides,e,"strides"),this.padding=null==t.padding?"valid":t.padding,Og(this.padding),this.dataFormat=null==t.dataFormat?"channelsLast":t.dataFormat,_g(this.dataFormat),this.activation=Jx(t.activation),this.useBias=null==t.useBias||t.useBias,this.biasInitializer=Ry(t.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.biasConstraint=Ng(t.biasConstraint),this.biasRegularizer=aw(t.biasRegularizer),this.activityRegularizer=aw(t.activityRegularizer),this.dilationRate=pw(null==t.dilationRate?1:t.dilationRate,e,"dilationRate"),1===this.rank&&Array.isArray(this.dilationRate)&&1!==this.dilationRate.length)throw new qm(`dilationRate must be a number or an array of a single number for 1D convolution, but received ${JSON.stringify(this.dilationRate)}`);if(2===this.rank){if("number"==typeof this.dilationRate)this.dilationRate=[this.dilationRate,this.dilationRate];else if(2!==this.dilationRate.length)throw new qm(`dilationRate must be a number or array of two numbers for 2D convolution, but received ${JSON.stringify(this.dilationRate)}`)}else if(3===this.rank)if("number"==typeof this.dilationRate)this.dilationRate=[this.dilationRate,this.dilationRate,this.dilationRate];else if(3!==this.dilationRate.length)throw new qm(`dilationRate must be a number or array of three numbers for 3D convolution, but received ${JSON.stringify(this.dilationRate)}`)}static verifyArgs(e){if(Zm("kernelSize"in e,"required key 'kernelSize' not in config"),"number"!=typeof e.kernelSize&&!hg(e.kernelSize,"number",1,3))throw new qm(`BaseConv expects config.kernelSize to be number or number[] with length 1, 2, or 3, but received ${JSON.stringify(e.kernelSize)}.`)}getConfig(){const e={kernelSize:this.kernelSize,strides:this.strides,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,activation:Yx(this.activation),useBias:this.useBias,biasInitializer:Ay(this.biasInitializer),biasRegularizer:rw(this.biasRegularizer),activityRegularizer:rw(this.activityRegularizer),biasConstraint:kg(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}}class xw extends bw{constructor(e,t){super(e,t),this.kernel=null,xw.verifyArgs(t),this.filters=t.filters,pg(this.filters,"filters"),this.kernelInitializer=Ry(t.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.kernelConstraint=Ng(t.kernelConstraint),this.kernelRegularizer=aw(t.kernelRegularizer)}build(e){e=eb(e);const t="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[t])throw new qm(`The channel dimension of the input should be defined. Found ${e[t]}`);const n=e[t],r=this.kernelSize.concat([n,this.filters]);this.kernel=this.addWeight("kernel",r,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 Xo((()=>{let t;e=Qy(e);const n=null==this.bias?null:this.bias.read(),r=fg(this.activation.getClassName());if(null!=r&&2===this.rank)t=yw(e,this.kernel.read(),n,this.strides,this.padding,this.dataFormat,this.dilationRate,r);else{if(1===this.rank)t=function(e,t,n,r=1,s="valid",a,i=1){return Xo((()=>{if(null==a&&(a="channelsLast"),_g(a),3!==e.shape.length)throw new qm(`The input of a conv1dWithBias operation should be 3, but is ${e.shape.length} instead.`);if(3!==t.shape.length)throw new qm(`The kernel for a conv1dWithBias operation should be 3, but is ${t.shape.length} instead`);if(null!=n&&1!==n.shape.length)throw new qm(`The bias for a conv1dWithBias operation should be 1, but is ${t.shape.length} instead`);if("channelsFirst"===a&&(e=qi(e,[0,2,1])),"causal"===s)throw new Km("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");let o=Mu(e,t,r,"same"===s?"same":"valid","NWC",i);return null!=n&&(o=oy(o,n)),o}))}(e,this.kernel.read(),n,this.strides[0],this.padding,this.dataFormat,this.dilationRate[0]);else if(2===this.rank)t=yw(e,this.kernel.read(),n,this.strides,this.padding,this.dataFormat,this.dilationRate);else{if(3!==this.rank)throw new Km("convolutions greater than 3D are not implemented yet.");t=function(e,t,n,r=[1,1,1],s="valid",a,i){return Xo((()=>{if(null==a&&(a="channelsLast"),_g(a),4!==e.rank&&5!==e.rank)throw new qm(`conv3dWithBias expects input to be of rank 4 or 5, but received ${e.rank}.`);if(4!==t.rank&&5!==t.rank)throw new qm(`conv3dWithBias expects kernel to be of rank 4 or 5, but received ${e.rank}.`);let o=gw(e,a);if("causal"===s)throw new Km("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");return o=_u(o,t,r,"same"===s?"same":"valid","NDHWC",i),null!=n&&(o=oy(o,n)),"channelsFirst"===a&&(o=qi(o,[0,4,1,2,3])),o}))}(e,this.kernel.read(),n,this.strides,this.padding,this.dataFormat,this.dilationRate)}null!=this.activation&&(t=this.activation.apply(t))}return t}))}computeOutputShape(e){e=eb(e);const t=[],n="channelsLast"===this.dataFormat?e.slice(1,e.length-1):e.slice(2);for(let e=0;e 0 but got ${JSON.stringify(e.filters)}`)}}class ww extends xw{constructor(e){super(2,e),ww.verifyArgs(e)}getConfig(){const e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if("number"!=typeof e.kernelSize&&!hg(e.kernelSize,"number",1,2))throw new qm(`Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received ${JSON.stringify(e.kernelSize)}.`)}}ww.className="Conv2D",Eo(ww);class vw extends xw{constructor(e){super(3,e),vw.verifyArgs(e)}getConfig(){const e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if("number"!=typeof e.kernelSize&&(!Array.isArray(e.kernelSize)||1!==e.kernelSize.length&&3!==e.kernelSize.length))throw new qm(`Conv3D expects config.kernelSize to be number or [number, number, number], but received ${JSON.stringify(e.kernelSize)}.`)}}vw.className="Conv3D",Eo(vw);class kw extends ww{constructor(e){if(super(e),this.inputSpec=[new ab({ndim:4})],"same"!==this.padding&&"valid"!==this.padding)throw new qm(`Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(4!==(e=eb(e)).length)throw new qm("Input should have rank 4; Received input shape: "+JSON.stringify(e));const t="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[t])throw new qm("The channel dimension of the inputs should be defined. Found `None`.");const n=e[t],r=this.kernelSize.concat([this.filters,n]);this.kernel=this.addWeight("kernel",r,"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 ab({ndim:4,axes:{[t]:n}})],this.built=!0}call(e,t){return Xo((()=>{let t=Qy(e);if(4!==t.shape.length)throw new qm(`Conv2DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${t.shape.length}`);const n=t.shape,r=n[0];let s,a;"channelsFirst"===this.dataFormat?(s=2,a=3):(s=1,a=2);const i=n[s],o=n[a],l=this.kernelSize[0],u=this.kernelSize[1],c=this.strides[0],h=this.strides[1],p=[r,fw(i,c,l,this.padding),fw(o,h,u,this.padding),this.filters];"channelsLast"!==this.dataFormat&&(t=qi(t,[0,2,3,1]));let d=Du(t,this.kernel.read(),p,this.strides,this.padding);return"channelsLast"!==this.dataFormat&&(d=qi(d,[0,3,1,2])),null!=this.bias&&(d=oy(d,this.bias.read(),this.dataFormat)),null!=this.activation&&(d=this.activation.apply(d)),d}))}computeOutputShape(e){const t=(e=eb(e)).slice();let n,r,s;"channelsFirst"===this.dataFormat?(n=1,r=2,s=3):(n=3,r=1,s=2);const a=this.kernelSize[0],i=this.kernelSize[1],o=this.strides[0],l=this.strides[1];return t[n]=this.filters,t[r]=fw(t[r],o,a,this.padding),t[s]=fw(t[s],l,i,this.padding),t}getConfig(){const e=super.getConfig();return delete e.dilationRate,e}}kw.className="Conv2DTranspose",Eo(kw);class Iw extends vw{constructor(e){if(super(e),this.inputSpec=[new ab({ndim:5})],"same"!==this.padding&&"valid"!==this.padding)throw new qm(`Conv3DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(5!==(e=eb(e)).length)throw new qm("Input should have rank 5; Received input shape: "+JSON.stringify(e));const t="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[t])throw new qm("The channel dimension of the inputs should be defined. Found `None`.");const n=e[t],r=this.kernelSize.concat([this.filters,n]);this.kernel=this.addWeight("kernel",r,"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 ab({ndim:5,axes:{[t]:n}})],this.built=!0}call(e,t){return Xo((()=>{let t=Qy(e);if(5!==t.shape.length)throw new qm(`Conv3DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${t.shape.length}`);const n=t.shape,r=n[0];let s,a,i;"channelsFirst"===this.dataFormat?(i=2,s=3,a=4):(i=1,s=2,a=3);const o=n[i],l=n[s],u=n[a],c=this.kernelSize[0],h=this.kernelSize[1],p=this.kernelSize[2],d=this.strides[0],f=this.strides[1],m=this.strides[2],g=[r,fw(o,d,c,this.padding),fw(l,f,h,this.padding),fw(u,m,p,this.padding),this.filters];"channelsLast"!==this.dataFormat&&(t=qi(t,[0,2,3,4,1]));let y=Lu(t,this.kernel.read(),g,this.strides,this.padding);return"channelsLast"!==this.dataFormat&&(y=qi(y,[0,4,1,2,3])),null!==this.bias&&(y=oy(y,this.bias.read(),this.dataFormat)),null!==this.activation&&(y=this.activation.apply(y)),y}))}computeOutputShape(e){const t=(e=eb(e)).slice();let n,r,s,a;"channelsFirst"===this.dataFormat?(n=1,r=2,s=3,a=4):(n=4,r=1,s=2,a=3);const i=this.kernelSize[0],o=this.kernelSize[1],l=this.kernelSize[2],u=this.strides[0],c=this.strides[1],h=this.strides[2];return t[n]=this.filters,t[r]=fw(t[r],u,i,this.padding),t[s]=fw(t[s],c,o,this.padding),t[a]=fw(t[a],h,l,this.padding),t}getConfig(){const e=super.getConfig();return delete e.dilationRate,e}}Iw.className="Conv3DTranspose",Eo(Iw);class Nw extends xw{constructor(e,t){if(super(e,t),this.DEFAULT_DEPTHWISE_INITIALIZER="glorotUniform",this.DEFAULT_POINTWISE_INITIALIZER="glorotUniform",this.depthwiseKernel=null,this.pointwiseKernel=null,null==t.filters)throw new qm("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(null!=t.kernelInitializer||null!=t.kernelRegularizer||null!=t.kernelConstraint)throw new qm("Fields kernelInitializer, kernelRegularizer and kernelConstraint are invalid for SeparableConv2D. Use depthwiseInitializer, depthwiseRegularizer, depthwiseConstraint, pointwiseInitializer, pointwiseRegularizer and pointwiseConstraint instead.");if(null!=t.padding&&"same"!==t.padding&&"valid"!==t.padding)throw new qm(`SeparableConv${this.rank}D supports only padding modes: 'same' and 'valid', but received ${JSON.stringify(t.padding)}`);this.depthMultiplier=null==t.depthMultiplier?1:t.depthMultiplier,this.depthwiseInitializer=Ry(t.depthwiseInitializer||this.DEFAULT_DEPTHWISE_INITIALIZER),this.depthwiseRegularizer=aw(t.depthwiseRegularizer),this.depthwiseConstraint=Ng(t.depthwiseConstraint),this.pointwiseInitializer=Ry(t.depthwiseInitializer||this.DEFAULT_POINTWISE_INITIALIZER),this.pointwiseRegularizer=aw(t.pointwiseRegularizer),this.pointwiseConstraint=Ng(t.pointwiseConstraint)}build(e){if((e=eb(e)).length{let t;if(e=Qy(e),1===this.rank)throw new Km("1D separable convolution is not implemented yet.");return 2===this.rank&&("channelsFirst"===this.dataFormat&&(e=qi(e,[0,2,3,1])),t=Rh(e,this.depthwiseKernel.read(),this.pointwiseKernel.read(),this.strides,this.padding,this.dilationRate,"NHWC")),this.useBias&&(t=oy(t,this.bias.read(),this.dataFormat)),null!=this.activation&&(t=this.activation.apply(t)),"channelsFirst"===this.dataFormat&&(t=qi(t,[0,3,1,2])),t}))}getConfig(){const e=super.getConfig();return delete e.rank,delete e.kernelInitializer,delete e.kernelRegularizer,delete e.kernelConstraint,e.depthwiseInitializer=Ay(this.depthwiseInitializer),e.pointwiseInitializer=Ay(this.pointwiseInitializer),e.depthwiseRegularizer=rw(this.depthwiseRegularizer),e.pointwiseRegularizer=rw(this.pointwiseRegularizer),e.depthwiseConstraint=kg(this.depthwiseConstraint),e.pointwiseConstraint=kg(this.pointwiseConstraint),e}}Nw.className="SeparableConv";class Sw extends Nw{constructor(e){super(2,e)}}Sw.className="SeparableConv2D",Eo(Sw);class Tw extends xw{constructor(e){super(1,e),Tw.verifyArgs(e),this.inputSpec=[{ndim:3}]}getConfig(){const e=super.getConfig();return delete e.rank,delete e.dataFormat,e}static verifyArgs(e){if("number"!=typeof e.kernelSize&&!hg(e.kernelSize,"number",1,1))throw new qm(`Conv1D expects config.kernelSize to be number or number[] with length 1, but received ${JSON.stringify(e.kernelSize)}.`)}}Tw.className="Conv1D",Eo(Tw);class Cw extends cb{constructor(e){super(e),"number"==typeof e.cropping?this.cropping=[[e.cropping,e.cropping],[e.cropping,e.cropping]]:"number"==typeof e.cropping[0]?this.cropping=[[e.cropping[0],e.cropping[0]],[e.cropping[1],e.cropping[1]]]:this.cropping=e.cropping,this.dataFormat=void 0===e.dataFormat?"channelsLast":e.dataFormat,this.inputSpec=[{ndim:4}]}computeOutputShape(e){return"channelsFirst"===this.dataFormat?[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 Xo((()=>{if(e=Qy(e),"channelsLast"===this.dataFormat){const t=Jg(e,this.cropping[0][0],e.shape[1]-this.cropping[0][0]-this.cropping[0][1],2);return Jg(t,this.cropping[1][0],e.shape[2]-this.cropping[1][1]-this.cropping[1][0],3)}{const t=Jg(e,this.cropping[0][0],e.shape[2]-this.cropping[0][0]-this.cropping[0][1],3);return Jg(t,this.cropping[1][0],e.shape[3]-this.cropping[1][1]-this.cropping[1][0],4)}}))}getConfig(){const e={cropping:this.cropping,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}Cw.className="Cropping2D",Eo(Cw);class Ew extends cb{constructor(e){var t;super(e),this.DEFAULT_SIZE=[2,2],this.inputSpec=[{ndim:4}],this.size=null==e.size?this.DEFAULT_SIZE:e.size,this.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,_g(this.dataFormat),this.interpolation=null==e.interpolation?"nearest":e.interpolation,t=this.interpolation,cg(Ag,"InterpolationFormat",t)}computeOutputShape(e){if("channelsFirst"===this.dataFormat){const t=null==e[2]?null:this.size[0]*e[2],n=null==e[3]?null:this.size[1]*e[3];return[e[0],e[1],t,n]}{const t=null==e[1]?null:this.size[0]*e[1],n=null==e[2]?null:this.size[1]*e[2];return[e[0],t,n,e[3]]}}call(e,t){return Xo((()=>{let t=Qy(e);const n=t.shape;if("channelsFirst"===this.dataFormat){t=qi(t,[0,2,3,1]);const e=this.size[0]*n[2],r=this.size[1]*n[3],s="nearest"===this.interpolation?Td.resizeNearestNeighbor(t,[e,r]):Td.resizeBilinear(t,[e,r]);return qi(s,[0,3,1,2])}{const e=this.size[0]*n[1],r=this.size[1]*n[2];return"nearest"===this.interpolation?Td.resizeNearestNeighbor(t,[e,r]):Td.resizeBilinear(t,[e,r])}}))}getConfig(){const e={size:this.size,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}Ew.className="UpSampling2D",Eo(Ew);class $w extends bw{constructor(e){super(2,e),this.depthwiseKernel=null,this.depthMultiplier=null==e.depthMultiplier?1:e.depthMultiplier,this.depthwiseInitializer=Ry(e.depthwiseInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.depthwiseConstraint=Ng(e.depthwiseConstraint),this.depthwiseRegularizer=aw(e.depthwiseRegularizer)}build(e){if((e=eb(e)).length<4)throw new qm(`Inputs to DepthwiseConv2D should have rank 4. Received input shape: ${JSON.stringify(e)}.`);const t="channelsFirst"===this.dataFormat?1:3;if(null==e[t]||e[t]<0)throw new qm(`The channel dimension of the inputs to DepthwiseConv2D should be defined, but is not (${e[t]}).`);const n=e[t],r=[this.kernelSize[0],this.kernelSize[1],n,this.depthMultiplier];this.depthwiseKernel=this.addWeight("depthwise_kernel",r,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 Xo((()=>{let t=function(e,t,n=[1,1],r="valid",s,a){return Xo((()=>{null==s&&(s="channelsLast"),_g(s);let i=mw(e,s);if(4!==e.rank)throw new qm(`Input for depthwiseConv2d is required to be 4-D, but is instead ${e.rank}-D`);if(4!==t.rank)throw new qm(`depthwiseKernel is required to be 4-D, but is instead ${t.rank}-D`);return i=Wu(i,t,n,"same"===r?"same":"valid","NHWC",a),"channelsFirst"===s&&(i=qi(i,[0,3,1,2])),i}))}(e=Qy(e),this.depthwiseKernel.read(),this.strides,this.padding,this.dataFormat,null);return this.useBias&&(t=oy(t,this.bias.read(),this.dataFormat)),null!=this.activation&&(t=this.activation.apply(t)),t}))}computeOutputShape(e){e=eb(e);const t="channelsFirst"===this.dataFormat?e[2]:e[1],n="channelsFirst"===this.dataFormat?e[3]:e[2],r="channelsFirst"===this.dataFormat?e[1]*this.depthMultiplier:e[3]*this.depthMultiplier,s=dw(t,this.kernelSize[0],this.padding,this.strides[0]),a=dw(n,this.kernelSize[1],this.padding,this.strides[1]);return"channelsFirst"===this.dataFormat?[e[0],r,s,a]:[e[0],s,a,r]}getConfig(){const e=super.getConfig();return e.depthMultiplier=this.depthMultiplier,e.depthwiseInitializer=Ay(this.depthwiseInitializer),e.depthwiseRegularizer=rw(this.depthwiseRegularizer),e.depthwiseConstraint=kg(this.depthwiseRegularizer),e}}function Aw(e,t,n,r){if(Array.isArray(e)){if(null!=t||null!=n)throw new qm("When inputs is an array, neither initialState or constants should be provided");null!=r&&(n=e.slice(e.length-r,e.length),e=e.slice(0,e.length-r)),e.length>1&&(t=e.slice(1,e.length)),e=e[0]}function s(e){return null==e||Array.isArray(e)?e:[e]}return{inputs:e,initialState:t=s(t),constants:n=s(n)}}function Rw(e,t,n,r=!1,s,a,i=!1,o=!1){return Xo((()=>{const l=t.shape.length;if(l<3)throw new qm(`Input should be at least 3D, but is ${l}D.`);const u=[1,0].concat(qg(2,l));if(t=qi(t,u),null!=a)throw new Km("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."),null!=s&&((s=Si(Si(s,"bool"),"float32")).rank===l-1&&(s=ec(s,-1)),s=qi(s,u)),r&&(t=Ih(t,0),null!=s&&(s=Ih(s,0)));const c=[];let h,p=n;const d=t.shape[0],f=op(t);let m,g;null!=s&&(m=op(s));for(let t=0;te(n,p)));if(null==s)h=r[0],p=r[1];else{const e=Xo((()=>{const e=m[t],n=El(Qc(e),e);return{output:ll(hl(r[0],e),hl(p[0],n)),newStates:p.map(((t,s)=>ll(hl(r[1][s],e),hl(t,n))))}}));h=e.output,p=e.newStates}o&&c.push(h)}return o&&(g=Kh(c,1)),[h,g,p]}))}$w.className="DepthwiseConv2D",Eo($w);class Mw extends cb{constructor(e){let t;if(super(e),null==e.cell)throw new qm("cell property is missing for the constructor of RNN.");if(t=Array.isArray(e.cell)?new Bw({cells:e.cell}):e.cell,null==t.stateSize)throw new qm("The RNN cell should have an attribute `stateSize` (tuple of integers, one integer per RNN state).");this.cell=t,this.returnSequences=null!=e.returnSequences&&e.returnSequences,this.returnState=null!=e.returnState&&e.returnState,this.goBackwards=null!=e.goBackwards&&e.goBackwards,this._stateful=null!=e.stateful&&e.stateful,this.unroll=null!=e.unroll&&e.unroll,this.supportsMasking=!0,this.inputSpec=[new ab({ndim:3})],this.stateSpec=null,this.states_=null,this.numConstants=null,this.keptStates=[]}getStates(){return null==this.states_?qg(0,Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1).map((e=>null)):this.states_}setStates(e){this.states_=e}computeOutputShape(e){Zy(e)&&(e=e[0]),e=e;let t=this.cell.stateSize;Array.isArray(t)||(t=[t]);const n=t[0];let r;if(r=this.returnSequences?[e[0],e[1],n]:[e[0],n],this.returnState){const n=[];for(const r of t)n.push([e[0],r]);return[r].concat(n)}return r}computeMask(e,t){return Xo((()=>{Array.isArray(t)&&(t=t[0]);const e=this.returnSequences?t:null;if(this.returnState){const t=this.states.map((e=>null));return[e].concat(t)}return e}))}get states(){if(null==this.states_){const e=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1,t=[];for(let n=0;ne.shape[e.shape.length-1])),s))throw new qm(`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=s.map((e=>new ab({shape:[null,e]})));this.stateful&&this.resetStates()}resetStates(e,t=!1){Xo((()=>{if(!this.stateful)throw new Hm("Cannot call resetStates() on an RNN Layer that is not stateful.");const n=this.inputSpec[0].shape[0];if(null==n)throw new qm("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(null==this.states_)Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map((e=>Uc([n,e]))):this.states_=[Uc([n,this.cell.stateSize])];else if(null==e)Yo(this.states_),null!=this.keptStates&&(Yo(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map((e=>Uc([n,e]))):this.states_[0]=Uc([n,this.cell.stateSize]);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new qm(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${e.length} state value(s). Input received: ${e}`);!0===t?this.keptStates.push(this.states_.slice()):Yo(this.states_);for(let t=0;tZo(e.clone())))}))}apply(e,t){let n=null==t?null:t.initialState,r=null==t?null:t.constants;null==t&&(t={});const s=Aw(e,n,r,this.numConstants);e=s.inputs,n=s.initialState,r=s.constants;let a=[],i=[];if(null!=n){t.initialState=n,a=a.concat(n),this.stateSpec=[];for(const e of n)this.stateSpec.push(new ab({shape:e.shape}));i=i.concat(this.stateSpec)}if(null!=r&&(t.constants=r,a=a.concat(r),this.numConstants=r.length),a[0]instanceof ib){const n=[e].concat(a),r=this.inputSpec.concat(i),s=this.inputSpec;this.inputSpec=r;const o=super.apply(n,t);return this.inputSpec=s,o}return super.apply(e,t)}call(e,t){return Xo((()=>{const n=null==t?null:t.mask,r=null==t?null:t.training;let s=null==t?null:t.initialState;e=Qy(e),null==s&&(s=this.stateful?this.states_:this.getInitialState(e));const a=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;if(s.length!==a)throw new qm(`RNN Layer has ${a} state(s) but was passed ${s.length} initial state(s).`);this.unroll&&console.warn("Ignoring unroll = true for RNN layer, due to imperative backend.");const i={training:r},o=Rw(((e,t)=>{const n=this.cell.call([e].concat(t),i);return[n[0],n.slice(1)]}),e,s,this.goBackwards,n,null,this.unroll,this.returnSequences),l=o[0],u=o[1],c=o[2];this.stateful&&this.resetStates(c,r);const h=this.returnSequences?u:l;return this.returnState?[h].concat(c):h}))}getInitialState(e){return Xo((()=>{let t=Uc(e.shape);return t=Ic(t,[1,2]),t=Xg(t),Array.isArray(this.cell.stateSize)?this.cell.stateSize.map((e=>e>1?ty(t,[1,e]):t)):this.cell.stateSize>1?[ty(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),null!=this.cell&&this.cell.setFastWeightInitDuringBuild(e)}getConfig(){const e=super.getConfig(),t={returnSequences:this.returnSequences,returnState:this.returnState,goBackwards:this.goBackwards,stateful:this.stateful,unroll:this.unroll};null!=this.numConstants&&(t.numConstants=this.numConstants);const n=this.cell.getConfig();return this.getClassName()===Mw.className&&(t.cell={className:this.cell.getClassName(),config:n}),Object.assign({},n,e,t)}static fromConfig(e,t,n={}){const r=Sb(t.cell,n);return new e(Object.assign(t,{cell:r}))}}Mw.className="RNN",Eo(Mw);class Fw extends cb{}class Dw extends Fw{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,pg(this.units,"units"),this.activation=Jx(null==e.activation?this.DEFAULT_ACTIVATION:e.activation),this.useBias=null==e.useBias||e.useBias,this.kernelInitializer=Ry(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Ry(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Ry(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=aw(e.kernelRegularizer),this.recurrentRegularizer=aw(e.recurrentRegularizer),this.biasRegularizer=aw(e.biasRegularizer),this.kernelConstraint=Ng(e.kernelConstraint),this.recurrentConstraint=Ng(e.recurrentConstraint),this.biasConstraint=Ng(e.biasConstraint),this.dropout=Hg([1,jg([0,null==e.dropout?0:e.dropout])]),this.recurrentDropout=Hg([1,jg([0,null==e.recurrentDropout?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=eb(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 Xo((()=>{if(2!==(e=e).length)throw new qm(`SimpleRNNCell expects 2 input Tensors, got ${e.length}.`);let n=e[1];e=e[0];const r=null!=t.training&&t.training;let s;0Qc(e),rate:this.dropout,training:r,dropoutFunc:this.dropoutFunc})),0Qc(n),rate:this.recurrentDropout,training:r,dropoutFunc:this.dropoutFunc}));const a=this.dropoutMask,i=this.recurrentDropoutMask;s=ry(null!=a?hl(e,a):e,this.kernel.read()),null!=this.bias&&(s=oy(s,this.bias.read())),null!=i&&(n=hl(n,i));let o=ll(s,ry(n,this.recurrentKernel.read()));return null!=this.activation&&(o=this.activation.apply(o)),[o,o]}))}getConfig(){const e=super.getConfig(),t={units:this.units,activation:Yx(this.activation),useBias:this.useBias,kernelInitializer:Ay(this.kernelInitializer),recurrentInitializer:Ay(this.recurrentInitializer),biasInitializer:Ay(this.biasInitializer),kernelRegularizer:rw(this.kernelRegularizer),recurrentRegularizer:rw(this.recurrentRegularizer),biasRegularizer:rw(this.biasRegularizer),activityRegularizer:rw(this.activityRegularizer),kernelConstraint:kg(this.kernelConstraint),recurrentConstraint:kg(this.recurrentConstraint),biasConstraint:kg(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout};return Object.assign({},e,t)}}Dw.className="SimpleRNNCell",Eo(Dw);class _w extends Mw{constructor(e){e.cell=new Dw(e),super(e)}call(e,t){return Xo((()=>{null!=this.cell.dropoutMask&&(Yo(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(Yo(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const n=null==t?null:t.mask,r=null==t?null:t.training,s=null==t?null:t.initialState;return super.call(e,{mask:n,training:r,initialState:s})}))}static fromConfig(e,t){return new e(t)}}_w.className="SimpleRNN",Eo(_w);class Ow extends Fw{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 qm("GRUCell does not support reset_after parameter set to true.");this.units=e.units,pg(this.units,"units"),this.activation=Jx(void 0===e.activation?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=Jx(void 0===e.recurrentActivation?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=null==e.useBias||e.useBias,this.kernelInitializer=Ry(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Ry(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Ry(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=aw(e.kernelRegularizer),this.recurrentRegularizer=aw(e.recurrentRegularizer),this.biasRegularizer=aw(e.biasRegularizer),this.kernelConstraint=Ng(e.kernelConstraint),this.recurrentConstraint=Ng(e.recurrentConstraint),this.biasConstraint=Ng(e.biasConstraint),this.dropout=Hg([1,jg([0,null==e.dropout?0:e.dropout])]),this.recurrentDropout=Hg([1,jg([0,null==e.recurrentDropout?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.implementation=e.implementation,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){const t=(e=eb(e))[e.length-1];this.kernel=this.addWeight("kernel",[t,3*this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,3*this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[3*this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return Xo((()=>{if(2!==(e=e).length)throw new qm(`GRUCell expects 2 input Tensors (inputs, h, c), got ${e.length}.`);const n=null!=t.training&&t.training;let r=e[1];e=e[0],0Qc(e),rate:this.dropout,training:n,count:3,dropoutFunc:this.dropoutFunc})),0Qc(r),rate:this.recurrentDropout,training:n,count:3,dropoutFunc:this.dropoutFunc}));const s=this.dropoutMask,a=this.recurrentDropoutMask;let i,o,l;0{null!=this.cell.dropoutMask&&(Yo(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(Yo(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const n=null==t?null:t.mask,r=null==t?null:t.training,s=null==t?null:t.initialState;return super.call(e,{mask:n,training:r,initialState:s})}))}static fromConfig(e,t){return 0===t.implmentation&&(t.implementation=1),new e(t)}}Lw.className="GRU",Eo(Lw);class zw extends Fw{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,pg(this.units,"units"),this.activation=Jx(void 0===e.activation?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=Jx(void 0===e.recurrentActivation?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=null==e.useBias||e.useBias,this.kernelInitializer=Ry(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Ry(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Ry(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.unitForgetBias=e.unitForgetBias,this.kernelRegularizer=aw(e.kernelRegularizer),this.recurrentRegularizer=aw(e.recurrentRegularizer),this.biasRegularizer=aw(e.biasRegularizer),this.kernelConstraint=Ng(e.kernelConstraint),this.recurrentConstraint=Ng(e.recurrentConstraint),this.biasConstraint=Ng(e.biasConstraint),this.dropout=Hg([1,jg([0,null==e.dropout?0:e.dropout])]),this.recurrentDropout=Hg([1,jg([0,null==e.recurrentDropout?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;const n=(e=eb(e))[e.length-1];let r;if(this.kernel=this.addWeight("kernel",[n,4*this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,4*this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias){if(this.unitForgetBias){const e=this.biasInitializer,n=this.units;r=new((t=class extends py{apply(t,r){const s=e.apply([n]),a=(new fy).apply([n]),i=e.apply([2*n]);return ey(ey(s,a),i)}}).className="CustomInit",t)}else r=this.biasInitializer;this.bias=this.addWeight("bias",[4*this.units],null,r,this.biasRegularizer,!0,this.biasConstraint)}else this.bias=null;this.built=!0}call(e,t){return Xo((()=>{const n=null!=t.training&&t.training;if(3!==(e=e).length)throw new qm(`LSTMCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);let r=e[1];const s=e[2];e=e[0],0Qc(e),rate:this.dropout,training:n,count:4,dropoutFunc:this.dropoutFunc})),0Qc(r),rate:this.recurrentDropout,training:n,count:4,dropoutFunc:this.dropoutFunc}));const a=this.dropoutMask,i=this.recurrentDropoutMask;let o,l,u,c;0{null!=this.cell.dropoutMask&&(Yo(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(Yo(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const n=null==t?null:t.mask,r=null==t?null:t.training,s=null==t?null:t.initialState;return super.call(e,{mask:n,training:r,initialState:s})}))}static fromConfig(e,t){return 0===t.implmentation&&(t.implementation=1),new e(t)}}Pw.className="LSTM",Eo(Pw);class Bw extends Fw{constructor(e){super(e),this.cells=e.cells}get stateSize(){const e=[];for(const t of this.cells.slice().reverse())Array.isArray(t.stateSize)?e.push(...t.stateSize):e.push(t.stateSize);return e}call(e,t){return Xo((()=>{let n=(e=e).slice(1);const r=[];for(const e of this.cells.slice().reverse())Array.isArray(e.stateSize)?r.push(n.splice(0,e.stateSize.length)):r.push(n.splice(0,1));r.reverse();const s=[];let a;for(let i=0;i{Pg(`RNNCell_${r}`,(()=>{n.build(e),t=Array.isArray(n.stateSize)?n.stateSize[0]:n.stateSize,e=[e[0],t]}))})),this.built=!0}getConfig(){const e=super.getConfig(),t={cells:this.cells.map((e=>({className:e.getClassName(),config:e.getConfig()})))};return Object.assign({},e,t)}static fromConfig(e,t,n={}){const r=[];for(const e of t.cells)r.push(Sb(e,n));return new e({cells:r})}get trainableWeights(){if(!this.trainable)return[];const e=[];for(const t of this.cells)e.push(...t.trainableWeights);return e}get nonTrainableWeights(){const e=[];for(const t of this.cells)e.push(...t.nonTrainableWeights);if(!this.trainable){const t=[];for(const e of this.cells)t.push(...e.trainableWeights);return t.concat(e)}return e}getWeights(){const e=[];for(const t of this.cells)e.push(...t.weights);return rb(e)}setWeights(e){const t=[];for(const n of this.cells){const r=n.weights.length,s=e.splice(r);for(let e=0;enull!=a?a(t(),n):ly(t(),n),o=()=>uy(i,t,r);return!s||s<=1?Zo(o().clone()):Array(s).fill(void 0).map(o).map((e=>Zo(e.clone())))}Bw.className="StackedRNNCells",Eo(Bw);class Uw extends Mw{constructor(e){if(e.unroll)throw new Km("Unrolling is not possible with convolutional RNNs.");if(Array.isArray(e.cell))throw new Km("It is not possible at the moment to stack convolutional cells.");super(e),this.inputSpec=[new ab({ndim:5})]}call(e,t){return Xo((()=>{if(null!=this.cell.dropoutMask&&(Yo(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(Yo(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null),t&&t.constants)throw new qm("ConvRNN2D cell does not support constants");const n=null==t?null:t.mask,r=null==t?null:t.training,s=null==t?null:t.initialState;return super.call(e,{mask:n,training:r,initialState:s})}))}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 Xo((()=>{const{stateSize:t}=this.cell,n=e.shape,r=this.computeSingleOutputShape(n),s=Uc([r[0],...r.slice(2)]);return Array.isArray(t)?Array(t.length).fill(s):[s]}))}resetStates(e,t=!1){Xo((()=>{if(!this.stateful)throw new Hm("Cannot call resetStates() on an RNN Layer that is not stateful.");const n=this.inputSpec[0].shape,r=this.computeSingleOutputShape(n),s=[r[0],...r.slice(2)];if(null==n[0])throw new qm("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(null==this.getStates())Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map((()=>Uc(s))):this.states_=[Uc(s)];else if(null==e)Yo(this.states_),null!=this.keptStates&&(Yo(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map((()=>Uc(s))):this.states_[0]=Uc(s);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new qm(`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()):Yo(this.states_);for(let t=0;tZo(e.clone())))}))}computeSingleOutputShape(e){const{dataFormat:t,filters:n,kernelSize:r,padding:s,strides:a,dilationRate:i}=this.cell,o="channelsFirst"===t,l=e[o?3:2],u=e[o?4:3],c=dw(l,r[0],s,a[0],i[0]),h=dw(u,r[1],s,a[1],i[1]);return[...e.slice(0,2),...o?[n,c,h]:[c,h,n]]}}Uw.className="ConvRNN2D";class Ww extends zw{constructor(e){const{filters:t,kernelSize:n,strides:r,padding:s,dataFormat:a,dilationRate:i}=e;super(Object.assign({},e,{units:t})),this.filters=t,pg(this.filters,"filters"),this.kernelSize=pw(n,2,"kernelSize"),this.kernelSize.forEach((e=>pg(e,"kernelSize"))),this.strides=pw(r||1,2,"strides"),this.strides.forEach((e=>pg(e,"strides"))),this.padding=s||"valid",Og(this.padding),this.dataFormat=a||"channelsLast",_g(this.dataFormat),this.dilationRate=pw(i||1,2,"dilationRate"),this.dilationRate.forEach((e=>pg(e,"dilationRate")))}build(e){var t;e=eb(e);const n="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[n])throw new qm(`The channel dimension of the input should be defined. Found ${e[n]}`);const r=e[n],s=this.kernelSize.concat([r,4*this.filters]);this.kernel=this.addWeight("kernel",s,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint);const a=this.kernelSize.concat([this.filters,4*this.filters]);if(this.recurrentKernel=this.addWeight("recurrent_kernel",a,null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias){let e;if(this.unitForgetBias){const n=this.biasInitializer,r=this.filters;e=new((t=class extends py{apply(e,t){return Qg([n.apply([r]),Wc([r]),n.apply([2*r])])}}).className="CustomInit",t)}else e=this.biasInitializer;this.bias=this.addWeight("bias",[4*this.filters],null,e,this.biasRegularizer,!0,this.biasConstraint)}this.built=!0}call(e,t){return Xo((()=>{if(3!==e.length)throw new qm(`ConvLSTM2DCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);const n=t.training||!1,r=e[0],s=e[1],a=e[2];0Qc(r),rate:this.dropout,training:n,count:4,dropoutFunc:this.dropoutFunc}));const i=this.dropoutMask,o=(e,t,n)=>t&&t[n]?hl(t[n],e):e;let l=o(r,i,0),u=o(r,i,1),c=o(r,i,2),h=o(r,i,3);0Qc(s),rate:this.recurrentDropout,training:n,count:4,dropoutFunc:this.dropoutFunc}));const p=this.recurrentDropoutMask;let d=o(s,p,0),f=o(s,p,1),m=o(s,p,2),g=o(s,p,3);const[y,b,x,w]=Gh(this.kernel.read(),4,3),[v,k,I,N]=this.useBias?Gh(this.bias.read(),4):[null,null,null,null];l=this.inputConv(l,y,v,this.padding),u=this.inputConv(u,b,k,this.padding),c=this.inputConv(c,x,I,this.padding),h=this.inputConv(h,w,N,this.padding);const[S,T,C,E]=Gh(this.recurrentKernel.read(),4,3);d=this.recurrentConv(d,S),f=this.recurrentConv(f,T),m=this.recurrentConv(m,C),g=this.recurrentConv(g,E);const $=this.recurrentActivation.apply(ll(l,d)),A=this.recurrentActivation.apply(ll(u,f)),R=ll(hl(A,a),hl($,this.activation.apply(ll(c,m)))),M=hl(this.recurrentActivation.apply(ll(h,g)),this.activation.apply(R));return[M,M,R]}))}getConfig(){const e=super.getConfig(),{units:t}=e,n=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(r=Object.getOwnPropertySymbols(e);s{this.invokeCallHook(e,t);const n=Qy(e);if(0ly(n,this.rate,r,this.seed)),(()=>n),e)}return e}))}getConfig(){const e={rate:this.rate,noiseShape:this.noiseShape,seed:this.seed},t=super.getConfig();return Object.assign(e,t),e}dispose(){return super.dispose()}}Hw.className="Dropout",Eo(Hw);class jw extends Hw{constructor(e){super(e),this.inputSpec=[{ndim:3}]}getNoiseShape(e){const t=e.shape;return[t[0],1,t[2]]}}jw.className="SpatialDropout1D",Eo(jw);class qw extends cb{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",null==e.batchInputShape&&null==e.inputShape&&null!=e.inputDim){let t=null;null!=e.batchSize&&(t=e.batchSize),this.batchInputShape=[t,e.inputDim]}this.units=e.units,pg(this.units,"units"),this.activation=Jx(e.activation),null!=e.useBias&&(this.useBias=e.useBias),this.kernelInitializer=Ry(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.biasInitializer=Ry(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelConstraint=Ng(e.kernelConstraint),this.biasConstraint=Ng(e.biasConstraint),this.kernelRegularizer=aw(e.kernelRegularizer),this.biasRegularizer=aw(e.biasRegularizer),this.activityRegularizer=aw(e.activityRegularizer),this.supportsMasking=!0,this.inputSpec=[{minNDim:2}]}build(e){const t=(e=eb(e))[e.length-1];null==this.kernel&&(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){const t=(e=eb(e)).slice();return t[t.length-1]=this.units,t}call(e,t){return Xo((()=>{this.invokeCallHook(e,t);const n=Qy(e),r=fg(this.activation.getClassName());let s;return null!=r?s=ry(n,this.kernel.read(),r,this.bias?this.bias.read():null):(s=ry(n,this.kernel.read()),null!=this.bias&&(s=oy(s,this.bias.read())),null!=this.activation&&(s=this.activation.apply(s))),s}))}getConfig(){const e={units:this.units,activation:Yx(this.activation),useBias:this.useBias,kernelInitializer:Ay(this.kernelInitializer),biasInitializer:Ay(this.biasInitializer),kernelRegularizer:rw(this.kernelRegularizer),biasRegularizer:rw(this.biasRegularizer),activityRegularizer:rw(this.activityRegularizer),kernelConstraint:kg(this.kernelConstraint),biasConstraint:kg(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}}qw.className="Dense",Eo(qw);class Kw extends cb{constructor(e){super(e=e||{}),this.inputSpec=[{minNDim:3}],this.dataFormat=e.dataFormat}computeOutputShape(e){e=eb(e);for(const t of e.slice(1))if(null==t)throw new qm(`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],Gg(e,1)]}call(e,t){return Xo((()=>{this.invokeCallHook(e,t);let n=Qy(e);if("channelsFirst"===this.dataFormat&&n.rank>1){const e=[0];for(let t=2;t{this.invokeCallHook(e,t);const n=Qy(e);return this.activation.apply(n)}))}getConfig(){const e={activation:Yx(this.activation)},t=super.getConfig();return Object.assign(e,t),e}}Xw.className="Activation",Eo(Xw);class Yw extends cb{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 Xo((()=>{return e=Qy(e),t=e,n=this.n,Xo((()=>{if(2!==t.shape.length)throw new qm(`repeat() expects a rank-2 tensor, but received a rank-${t.shape.length} tensor.`);return ty(Xg(t,1),[1,n,1])}));var t,n}))}getConfig(){const e={n:this.n},t=super.getConfig();return Object.assign(e,t),e}}Yw.className="RepeatVector",Eo(Yw);class Zw extends cb{constructor(e){super(e),this.targetShape=e.targetShape;for(let e=0;e{this.invokeCallHook(e,t);const n=Qy(e),r=n.shape,s=r.slice(0,1).concat(this.fixUnknownDimension(r.slice(1),this.targetShape));return uu(n,s)}))}getConfig(){const e={targetShape:this.targetShape},t=super.getConfig();return Object.assign(e,t),e}}Zw.className="Reshape",Eo(Zw);class Jw extends cb{constructor(e){if(super(e),null==e.dims)throw new Error("Required configuration field `dims` is missing during Permute constructor call.");if(!Array.isArray(e.dims))throw new Error(`Permute constructor requires \`dims\` to be an Array, but received ${e.dims} instead.`);const t=qg(1,e.dims.length+1);if(!ue(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 ab({ndim:this.dims.length+1})]}computeOutputShape(e){const t=(e=eb(e)).slice();return this.dims.forEach(((n,r)=>{t[r+1]=e[n]})),t}call(e,t){return qi(Qy(e),this.dimsIncludingBatch)}getConfig(){const e={dims:this.dims},t=super.getConfig();return Object.assign(e,t),e}}Jw.className="Permute",Eo(Jw);class Qw extends cb{constructor(e){super(null==e?{}:e),this.supportsMasking=!0,this.maskValue=null!=e?null==e.maskValue?0:e.maskValue:0}computeOutputShape(e){return e}getConfig(){const e=super.getConfig(),t={maskValue:this.maskValue};return Object.assign(t,e),t}computeMask(e,t){const n=Qy(e);return Vl(Jc(n,this.maskValue),-1)}call(e,t){return Xo((()=>{this.invokeCallHook(e,t);const n=Qy(e),r=Vl(Jc(n,this.maskValue),-1,!0);return hl(n,Si(r,n.dtype))}))}}Qw.className="Masking",Eo(Qw);class ev extends cb{constructor(e){if(super(e),this.embeddings=null,this.DEFAULT_EMBEDDINGS_INITIALIZER="randomUniform",null==e.batchInputShape&&null==e.inputShape){let t=null;null!=e.batchSize&&(t=e.batchSize),null==e.inputLength?this.batchInputShape=[t,null]:this.batchInputShape=[t].concat(eg(e.inputLength))}this.inputDim=e.inputDim,pg(this.inputDim,"inputDim"),this.outputDim=e.outputDim,pg(this.outputDim,"outputDim"),this.embeddingsInitializer=Ry(e.embeddingsInitializer||this.DEFAULT_EMBEDDINGS_INITIALIZER),this.embeddingsRegularizer=aw(e.embeddingsRegularizer),this.activityRegularizer=aw(e.activityRegularizer),this.embeddingsConstraint=Ng(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 Xo((()=>this.maskZero?(e=Qy(e),Jc(e,fl(e))):null))}computeOutputShape(e){if(e=eb(e),null==this.inputLength)return[...e,this.outputDim];const t=eg(this.inputLength);if(t.length!==e.length-1)throw new qm(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);{let n=0;for(let r=0;r{this.invokeCallHook(e,t);let n=Qy(e);"int32"!==n.dtype&&(n=Kg(n,"int32"));const r=sy(this.embeddings.read(),uu(n,[n.size]));return uu(r,eb(this.computeOutputShape(n.shape)))}))}getConfig(){const e={inputDim:this.inputDim,outputDim:this.outputDim,embeddingsInitializer:Ay(this.embeddingsInitializer),embeddingsRegularizer:rw(this.embeddingsRegularizer),activityRegularizer:rw(this.activityRegularizer),embeddingsConstraint:kg(this.embeddingsConstraint),maskZero:this.maskZero,inputLength:this.inputLength},t=super.getConfig();return Object.assign(e,t),e}}ev.className="Embedding",Eo(ev);class tv extends cb{constructor(e){super(e||{}),this.supportsMasking=!0}mergeFunction(e){throw new Km}computeElementwiseOpOutputShape(e,t){if(null==e||null==t)return null;if(e.length1)throw new qm(`Can not merge tensors with different batch sizes. Got tensors with shapes: ${JSON.stringify(e)}.`);let n=null==e[0]?null:e[0].slice(1);for(let t=1;te.length));-1===e.indexOf(null)&&1===lg(r).length?this.reshapeRequired=!1:this.reshapeRequired=!0}call(e,t){return Xo((()=>{if(e=e,this.reshapeRequired){const t=[],n=e.map((e=>e.rank));if(-1===n.indexOf(null)){const r=jg(n);for(let n of e){const e=n.rank;for(let t=0;t1){const s=qg(1,e).concat([0]);t.push(qi(r,s)),n=!0}else t.push(r)}let r=this.mergeFunction(t);const s=r.rank;if(n)if(null==s){const e=r.shape,t=e[e.length-1],n=[t].concat(e.slice(0,e.length-1));r=uu(qi(uu(r,[-1,t]),[1,0]),n)}else if(s>1){const e=[s-1].concat(qg(0,s-1));r=qi(r,e)}return r}}return this.mergeFunction(e)}))}computeOutputShape(e){let t;t=null==(e=e)[0]?null:e[0].slice(1);for(let n=1;n{if(null==t)return null;if(!Array.isArray(t))throw new qm("`mask` should be an Array");if(!Array.isArray(e))throw new qm("`inputs` should be an Array");if(t.length!==e.length)throw new qm(`The Array 'inputs' and 'mask' are expected to have the same length, but have different lengths (${e.length} vs ${t.length})`);if(t.every((e=>null==e)))return null;let n=(t=t.map((e=>null==e?e:ec(e,0))))[0];for(let e=1;e{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 qm("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(e))}mergeFunction(e){return Xo((()=>Qg(e,this.axis)))}computeOutputShape(e){if(!Array.isArray(e)||!Array.isArray(e[0]))throw new qm("A `Concatenate` layer should be called on a list of inputs.");const t=e,n=t[0].slice(),r=this.axis<0?n.length+this.axis:this.axis;for(const e of t.slice(1)){if(null==n[r]||null==e[r]){n[r]=null;break}n[r]+=e[r]}return n}computeMask(e,t){if(null==t)return null;if(!Array.isArray(t))throw new qm("`mask` should be an array for Concatenate");if(!Array.isArray(e))throw new qm("`inputs` should be an array for Concatenate");if(t.length!==e.length)throw new qm(`Mismatch in the length of mask (${t.length}) and the legnth of inputs (${e.length})`);return Xo((()=>{let n=!0;if(t.forEach((e=>{null==e||(n=!1)})),n)return null;const r=[];for(let n=0;n"A `Dot` layer should be called on a list of exactly 2 inputs."));const t=e[0],n=e[1];if(t.length>3||n.length>3)throw new Km("Dot layer does not support tensors of 4D or higher rank yet.");const r=this.interpretAxes(t,n);if(t[r[0]]!==n[r[1]])throw new qm(`Dimension incompatibility: ${t[r[0]]} !== ${n[r[1]]}`)}mergeFunction(e){if(2!==e.length)throw new qm(`A \`Dot\` layer must be called on exactly 2 inputs, but received ${e.length} input(s).`);let t,n=e[0],r=e[1];return t=Array.isArray(this.axes)?this.axes.map(((t,n)=>lv(t,e[n].shape.length))):[lv(this.axes,n.shape.length),lv(this.axes,r.shape.length)],this.normalize&&(n=Tb(n,t[0]),r=Tb(r,t[1])),function(e,t,n){if(e.shape.length>3||t.shape.length>3)throw new Km("batchDot is not implemented for tensors of 4D or higher rank yet");if(re(e.shape.length>=2,(()=>`batchDot requires the rank of x to be >= 2, but got ${e.shape.length}`)),re(e.shape.length>=2,(()=>`batchDot requires the rank of y to be >= 2, but got ${t.shape.length}`)),"number"==typeof n&&(n=[n,n]),"complex64"===e.dtype||"complex64"===t.dtype)throw new Km("batchDot is not implemented for complex64-type Tensors yet.");const r=e.shape.length,s=t.shape.length;null==n&&(n=[r-1,s-2]);const a=n;return Xo((()=>{let n,i;if(r>s){n=r-s;const e=[];for(let t=0;tr){n=s-r;const t=[];for(let e=0;e0){let e;e=r>s?r+s-3:r-1;const t=[];for(let r=e;r"A `Dot` layer should be called on a list of exactly 2 inputs."));const t=e[0].slice(),n=e[1].slice();if(t.length>3||n.length>3)throw new Km("Dot layer does not support tensors of 4D or higher rank yet.");const r=this.interpretAxes(t,n);t.splice(r[0],1),n.splice(r[1],1),n.splice(0,1);const s=t.concat(n);return 1===s.length&&s.push(1),s}computeMask(e,t){return null}getConfig(){const e={axes:this.axes,normalize:this.normalize},t=super.getConfig();return Object.assign(e,t),e}}uv.className="Dot",Eo(uv);class cv extends cb{constructor(e){super(e),this.supportsMasking=!0,this.stddev=e.stddev}computeOutputShape(e){return e}getConfig(){const e=super.getConfig(),t={stddev:this.stddev};return Object.assign(t,e),t}call(e,t){return Xo((()=>{this.invokeCallHook(e,t);const n=Qy(e);return uy((()=>ll(ny(n.shape,0,this.stddev),n)),(()=>n),t.training||!1)}))}}cv.className="GaussianNoise",Eo(cv);class hv extends cb{constructor(e){super(e),this.supportsMasking=!0,this.rate=e.rate}computeOutputShape(e){return e}getConfig(){const e=super.getConfig(),t={rate:this.rate};return Object.assign(t,e),t}call(e,t){return Xo((()=>{this.invokeCallHook(e,t);const n=Qy(e);return this.rate>0&&this.rate<1?uy((()=>{const e=Math.sqrt(this.rate/(1-this.rate));return hl(n,ny(n.shape,1,e))}),(()=>n),t.training||!1):n}))}}hv.className="GaussianDropout",Eo(hv);class pv extends cb{constructor(e){super(e),this.supportsMasking=!0,this.rate=e.rate,this.noiseShape=e.noiseShape}_getNoiseShape(e){return this.noiseShape||Qy(e).shape}computeOutputShape(e){return e}getConfig(){const e=super.getConfig(),t={rate:this.rate};return Object.assign(t,e),t}call(e,t){return Xo((()=>{if(this.rate<1&&this.rate>0){const n=this._getNoiseShape(e);return uy((()=>{const t=Qy(e),r=-1.7580993408473766;let s=oc(yh(n),this.rate);s=Kg(s,"float32");const a=((1-this.rate)*(1+this.rate*r**2))**-.5,i=-a*r*this.rate,o=ll(hl(t,s),hl(ll(s,-1),r));return ll(hl(o,a),i)}),(()=>Qy(e)),t.training||!1)}return e}))}}function dv(e,t,n,r,s,a=.001){let i;if(2===e.rank)i=xu(e,t,n,r,s,a);else if(3===e.rank)i=wu(e,t,n,r,s,a);else{if(4!==e.rank)throw new Km(`batchNormalization is not implemented for array of rank ${e.rank} yet`);i=vu(e,t,n,r,s,a)}return i}pv.className="AlphaDropout",Eo(pv);class fv extends cb{constructor(e){null==e&&(e={}),super(e),this.supportsMasking=!0,this.axis=null==e.axis?-1:e.axis,this.momentum=null==e.momentum?.99:e.momentum,this.epsilon=null==e.epsilon?.001:e.epsilon,this.center=null==e.center||e.center,this.scale=null==e.scale||e.scale,this.betaInitializer=Ry(e.betaInitializer||"zeros"),this.gammaInitializer=Ry(e.gammaInitializer||"ones"),this.movingMeanInitializer=Ry(e.movingMeanInitializer||"zeros"),this.movingVarianceInitializer=Ry(e.movingVarianceInitializer||"ones"),this.betaConstraint=Ng(e.betaConstraint),this.gammaConstraint=Ng(e.gammaConstraint),this.betaRegularizer=aw(e.betaRegularizer),this.gammaRegularizer=aw(e.gammaRegularizer)}build(e){e=eb(e);const t=this.axis>=0?this.axis:this.axis+e.length,n=e[t];if(null==n)throw new qm(`Axis ${t} of input tensor should have a defined dimension but the layer received an input with shape ${JSON.stringify(e)}.`);this.inputSpec=[new ab({ndim:e.length,axes:{[t]:n}})];const r=[n];this.scale&&(this.gamma=this.addWeight("gamma",r,null,this.gammaInitializer,this.gammaRegularizer,!0,this.gammaConstraint)),this.center&&(this.beta=this.addWeight("beta",r,null,this.betaInitializer,this.betaRegularizer,!0,this.betaConstraint)),this.movingMean=this.addWeight("moving_mean",r,null,this.movingMeanInitializer,null,!1),this.movingVariance=this.addWeight("moving_variance",r,null,this.movingVarianceInitializer,null,!1),this.built=!0}call(e,t){return Xo((()=>{const n=null!=t.training&&t.training,r=Qy(e),s=r.shape,a=s.length,i=qg(0,a),o=this.axis>=0?this.axis:this.axis+a;i.splice(o,1);const l=Ym(1,a);l[o]=s[o];const u=i.slice();u.sort();const c=!ue(u,qg(0,a).slice(0,a-1));if(!n)return(()=>{if(c){const e=uu(this.movingMean.read(),l),t=uu(this.movingVariance.read(),l),n=this.center?uu(this.beta.read(),l):null,s=this.scale?uu(this.gamma.read(),l):null;return dv(r,e,t,n,s,this.epsilon)}return dv(r,this.movingMean.read(),this.movingVariance.read(),null==this.beta?null:this.beta.read(),null==this.gamma?null:this.gamma.read(),this.epsilon)})();const[h,p,d]=function(e,t,n,r,s=.001){return ue(r.slice().sort(),qg(0,e.rank-1))?function(e,t,n,r,s=.001){return Xo((()=>{const a=Xc(e,r),i=a.mean,o=a.variance;return[dv(e,i,o,n,t,s),i,o]}))}(e,t,n,r,s):function(e,t,n,r,s=.001){return Xo((()=>{const a=Xc(e,r),i=a.mean,o=a.variance,l=[];for(const t of qg(0,e.rank))-1!==r.indexOf(t)?l.push(1):l.push(e.shape[t]);const u=uu(i,l),c=uu(o,l),h=null==t?null:uu(t,l),p=null==n?null:uu(n,l);return[dv(e,u,c,p,h,s),i,o]}))}(e,t,n,r,s)}(r,this.gamma.read(),this.beta.read(),i,this.epsilon),f=(e,t,n)=>{Xo((()=>{const r=1-n,s=e.read(),a=hl(El(s,t),r);e.write(El(s,a))}))};return(()=>{f(this.movingMean,p,this.momentum),f(this.movingVariance,d,this.momentum)})(),h}))}getConfig(){const e={axis:this.axis,momentum:this.momentum,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:Ay(this.betaInitializer),gammaInitializer:Ay(this.gammaInitializer),movingMeanInitializer:Ay(this.movingMeanInitializer),movingVarianceInitializer:Ay(this.movingVarianceInitializer),betaRegularizer:rw(this.betaRegularizer),gammaRegularizer:rw(this.gammaRegularizer),betaConstraint:kg(this.betaConstraint),gammaConstraint:kg(this.gammaConstraint)},t=super.getConfig();return Object.assign(e,t),e}}fv.className="BatchNormalization",Eo(fv);class mv extends cb{constructor(e){if(null==e&&(e={}),super(e),this.axis=null==e.axis?-1:e.axis,"number"==typeof this.axis){if(!Number.isInteger(this.axis))throw new Error(`Expected axis to be an integer, but received ${this.axis}`)}else{if(!Array.isArray(this.axis))throw new Error(`Expected axis to be an integer or an array of integers, but received ${JSON.stringify(this.axis)}`);for(const e of this.axis)if(!Number.isInteger(e))throw new Error(`Expected axis to be an array of integers, but received ${JSON.stringify(this.axis)}`)}this.epsilon=null==e.epsilon?.001:e.epsilon,this.center=null==e.center||e.center,this.scale=null==e.scale||e.scale,this.betaInitializer=Ry(e.betaInitializer||"zeros"),this.gammaInitializer=Ry(e.gammaInitializer||"ones"),this.betaRegularizer=aw(e.betaRegularizer),this.gammaRegularizer=aw(e.gammaRegularizer),this.supportsMasking=!0}build(e){const t=(e=eb(e)).length;"number"==typeof this.axis&&(this.axis=[this.axis]);for(let e=0;e=t)throw new Error(`Invalid axis: ${e}`);if(this.axis.length!==lg(this.axis).length)throw new Error(`Found duplicate axes in: ${this.axis}`);const n=this.axis.map((t=>e[t]));this.scale?this.gamma=this.addWeight("gamma",n,"float32",this.gammaInitializer,this.gammaRegularizer,!0):this.gamma=null,this.center?this.beta=this.addWeight("beta",n,"float32",this.betaInitializer,this.betaRegularizer,!0):this.beta=null,this.built=!0}call(e,t){const n=Qy(e),r=n.shape,s=r.length;return Xo((()=>{let{mean:e,variance:t}=Xc(n,this.axis,!0);const a=Ym(1,s);for(const e of this.axis)a[e]=r[e];const i=e=>null!=e&&e.shape.length!==s?uu(e,a):e;let o=i(this.gamma.read()),l=i(this.beta.read());const u=[],c=[];for(let e=0;e=0?e[2]+this.padding[0][0]+this.padding[0][1]:null,n=null!=e[3]&&e[3]>=0?e[3]+this.padding[1][0]+this.padding[1][1]:null,[e[0],e[1],t,n]):(t=null!=e[1]&&e[1]>=0?e[1]+this.padding[0][0]+this.padding[0][1]:null,n=null!=e[2]&&e[2]>=0?e[2]+this.padding[1][0]+this.padding[1][1]:null,[e[0],t,n,e[3]])}call(e,t){return Xo((()=>{return t=Qy(e),n=this.padding,r=this.dataFormat,Xo((()=>{if(4!==t.rank)throw new qm(`temporalPadding expects input tensor to be 4-D, but received a ${t.rank}-D tensor.`);if(null==n&&(n=[[1,1],[1,1]]),2!==n.length||2!==n[0].length||2!==n[1].length)throw new qm("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");if(null==r&&(r="channelsLast"),"channelsLast"!==r&&"channelsFirst"!==r)throw new qm(`Unknown data format: ${r}. Supported data formats are 'channelsLast' and 'channelsFirst.`);let e;return e="channelsFirst"===r?[[0,0],[0,0],n[0],n[1]]:[[0,0],n[0],n[1],[0,0]],th(t,e)}));var t,n,r}))}getConfig(){const e={padding:this.padding,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}function yv(e,t,n,r,s,a){return Xo((()=>{let i;_g(s),Lg(a),Og(r),null==n&&(n=[1,1]),null==r&&(r="valid"),null==s&&(s="channelsLast"),null==a&&(a="max"),e=mw(e,s);const o="same"===r?"same":"valid";return i="max"===a?zc(e,t,n,o):cu(e,t,n,o),"channelsFirst"===s&&(i=qi(i,[0,3,1,2])),i}))}function bv(e,t,n,r,s,a){return Xo((()=>{let i;_g(s),Lg(a),Og(r),null==n&&(n=[1,1,1]),null==r&&(r="valid"),null==s&&(s="channelsLast"),null==a&&(a="max"),e=gw(e,s);const o="same"===r?"same":"valid";return i="max"===a?Pc(e,t,n,o):hu(e,t,n,o),"channelsFirst"===s&&(i=qi(i,[0,4,1,2,3])),i}))}gv.className="ZeroPadding2D",Eo(gv);class xv extends cb{constructor(e){if(null==e.poolSize&&(e.poolSize=2),super(e),"number"==typeof e.poolSize)this.poolSize=[e.poolSize];else{if(!Array.isArray(e.poolSize)||1!==e.poolSize.length||"number"!=typeof e.poolSize[0])throw new qm(`poolSize for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.poolSize)}`);this.poolSize=e.poolSize}if(pg(this.poolSize,"poolSize"),null==e.strides)this.strides=this.poolSize;else if("number"==typeof e.strides)this.strides=[e.strides];else{if(!Array.isArray(e.strides)||1!==e.strides.length||"number"!=typeof e.strides[0])throw new qm(`strides for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.strides)}`);this.strides=e.strides}pg(this.strides,"strides"),this.padding=null==e.padding?"valid":e.padding,Og(this.padding),this.inputSpec=[new ab({ndim:3})]}computeOutputShape(e){const t=dw((e=eb(e))[1],this.poolSize[0],this.padding,this.strides[0]);return[e[0],t,e[2]]}call(e,t){return Xo((()=>{this.invokeCallHook(e,t),e=Xg(Qy(e),2);const n=this.poolingFunction(Qy(e),[this.poolSize[0],1],[this.strides[0],1],this.padding,"channelsLast");return qh(n,[2])}))}getConfig(){const e={poolSize:this.poolSize,padding:this.padding,strides:this.strides},t=super.getConfig();return Object.assign(e,t),e}}class wv extends xv{constructor(e){super(e)}poolingFunction(e,t,n,r,s){return _g(s),Og(r),yv(e,t,n,r,s,"max")}}wv.className="MaxPooling1D",Eo(wv);class vv extends xv{constructor(e){super(e)}poolingFunction(e,t,n,r,s){return _g(s),Og(r),yv(e,t,n,r,s,"avg")}}vv.className="AveragePooling1D",Eo(vv);class kv extends cb{constructor(e){if(null==e.poolSize&&(e.poolSize=[2,2]),super(e),this.poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize],null==e.strides)this.strides=this.poolSize;else if(Array.isArray(e.strides)){if(2!==e.strides.length)throw new qm(`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];pg(this.poolSize,"poolSize"),pg(this.strides,"strides"),this.padding=null==e.padding?"valid":e.padding,this.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,_g(this.dataFormat),Og(this.padding),this.inputSpec=[new ab({ndim:4})]}computeOutputShape(e){e=eb(e);let t="channelsFirst"===this.dataFormat?e[2]:e[1],n="channelsFirst"===this.dataFormat?e[3]:e[2];return t=dw(t,this.poolSize[0],this.padding,this.strides[0]),n=dw(n,this.poolSize[1],this.padding,this.strides[1]),"channelsFirst"===this.dataFormat?[e[0],e[1],t,n]:[e[0],t,n,e[3]]}call(e,t){return Xo((()=>(this.invokeCallHook(e,t),this.poolingFunction(Qy(e),this.poolSize,this.strides,this.padding,this.dataFormat))))}getConfig(){const e={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}class Iv extends kv{constructor(e){super(e)}poolingFunction(e,t,n,r,s){return _g(s),Og(r),yv(e,t,n,r,s,"max")}}Iv.className="MaxPooling2D",Eo(Iv);class Nv extends kv{constructor(e){super(e)}poolingFunction(e,t,n,r,s){return _g(s),Og(r),yv(e,t,n,r,s,"avg")}}Nv.className="AveragePooling2D",Eo(Nv);class Sv extends cb{constructor(e){if(null==e.poolSize&&(e.poolSize=[2,2,2]),super(e),this.poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize,e.poolSize],null==e.strides)this.strides=this.poolSize;else if(Array.isArray(e.strides)){if(3!==e.strides.length)throw new qm(`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];pg(this.poolSize,"poolSize"),pg(this.strides,"strides"),this.padding=null==e.padding?"valid":e.padding,this.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,_g(this.dataFormat),Og(this.padding),this.inputSpec=[new ab({ndim:5})]}computeOutputShape(e){e=eb(e);let t="channelsFirst"===this.dataFormat?e[2]:e[1],n="channelsFirst"===this.dataFormat?e[3]:e[2],r="channelsFirst"===this.dataFormat?e[4]:e[3];return t=dw(t,this.poolSize[0],this.padding,this.strides[0]),n=dw(n,this.poolSize[1],this.padding,this.strides[1]),r=dw(r,this.poolSize[2],this.padding,this.strides[2]),"channelsFirst"===this.dataFormat?[e[0],e[1],t,n,r]:[e[0],t,n,r,e[4]]}call(e,t){return Xo((()=>(this.invokeCallHook(e,t),this.poolingFunction(Qy(e),this.poolSize,this.strides,this.padding,this.dataFormat))))}getConfig(){const e={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}class Tv extends Sv{constructor(e){super(e)}poolingFunction(e,t,n,r,s){return _g(s),Og(r),bv(e,t,n,r,s,"max")}}Tv.className="MaxPooling3D",Eo(Tv);class Cv extends Sv{constructor(e){super(e)}poolingFunction(e,t,n,r,s){return _g(s),Og(r),bv(e,t,n,r,s,"avg")}}Cv.className="AveragePooling3D",Eo(Cv);class Ev extends cb{constructor(e){super(e),this.inputSpec=[new ab({ndim:3})]}computeOutputShape(e){return[e[0],e[2]]}call(e,t){throw new Km}}class $v extends Ev{constructor(e){super(e||{})}call(e,t){return Xo((()=>{const t=Qy(e);return Vc(t,1)}))}}$v.className="GlobalAveragePooling1D",Eo($v);class Av extends Ev{constructor(e){super(e||{})}call(e,t){return Xo((()=>{const t=Qy(e);return kc(t,1)}))}}Av.className="GlobalMaxPooling1D",Eo(Av);class Rv extends cb{constructor(e){super(e),this.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,_g(this.dataFormat),this.inputSpec=[new ab({ndim:4})]}computeOutputShape(e){return e=e,"channelsLast"===this.dataFormat?[e[0],e[3]]:[e[0],e[1]]}call(e,t){throw new Km}getConfig(){const e={dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}class Mv extends Rv{call(e,t){return Xo((()=>{const t=Qy(e);return"channelsLast"===this.dataFormat?Vc(t,[1,2]):Vc(t,[2,3])}))}}Mv.className="GlobalAveragePooling2D",Eo(Mv);class Fv extends Rv{call(e,t){return Xo((()=>{const t=Qy(e);return"channelsLast"===this.dataFormat?kc(t,[1,2]):kc(t,[2,3])}))}}Fv.className="GlobalMaxPooling2D",Eo(Fv);class Dv extends cb{constructor(e){super(e),this.layer=e.layer}build(e){this.built=!0}get trainable(){return null!=this.layer&&this.layer.trainable}set trainable(e){null!=this.layer&&(this.layer.trainable=e)}get trainableWeights(){return this.layer.trainableWeights}get nonTrainableWeights(){return this.layer.nonTrainableWeights}get updates(){return this.layer._updates}get losses(){return this.layer.losses}getWeights(){return this.layer.getWeights()}setWeights(e){this.layer.setWeights(e)}getConfig(){const e={layer:{className:this.layer.getClassName(),config:this.layer.getConfig()}},t=super.getConfig();return Object.assign(e,t),e}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),null!=this.layer&&this.layer.setFastWeightInitDuringBuild(e)}static fromConfig(e,t,n={}){const r=Sb(t.layer,n);delete t.layer;const s={layer:r};return Object.assign(s,t),new e(s)}}class _v extends Dv{constructor(e){super(e),this.supportsMasking=!0}build(e){if((e=eb(e)).length<3)throw new qm(`TimeDistributed layer expects an input shape >= 3D, but received input shape ${JSON.stringify(e)}`);this.inputSpec=[{shape:e}];const t=[e[0]].concat(e.slice(2));this.layer.built||(this.layer.build(t),this.layer.built=!0),super.build(e)}computeOutputShape(e){const t=[(e=eb(e))[0]].concat(e.slice(2)),n=this.layer.computeOutputShape(t),r=e[1];return[n[0],r].concat(n.slice(1))}call(e,t){return Xo((()=>Rw(((e,n)=>[Qy(this.layer.call(e,t)),[]]),e=Qy(e),[],!1,null,null,!1,!0)[1]))}}_v.className="TimeDistributed",Eo(_v);class Ov extends Dv{constructor(e){super(e);const t=e.layer.getConfig(),n={};n.className=e.layer.getClassName(),n.config=t,this.forwardLayer=Sb(n),t.goBackwards=!0!==t.goBackwards;const r={};var s;if(r.className=e.layer.getClassName(),r.config=t,this.backwardLayer=Sb(r),this.forwardLayer.name="forward_"+this.forwardLayer.name,this.backwardLayer.name="backward_"+this.backwardLayer.name,this.mergeMode=void 0===e.mergeMode?"concat":e.mergeMode,s=this.mergeMode,cg(Fg,"BidirectionalMergeMode",s),e.weights)throw new Km("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,null!=this.forwardLayer&&(this.forwardLayer.trainable=e),null!=this.backwardLayer&&(this.backwardLayer.trainable=e)}getWeights(){return this.forwardLayer.getWeights().concat(this.backwardLayer.getWeights())}setWeights(e){const t=e.length,n=Math.floor(t/2);this.forwardLayer.setWeights(e.slice(0,n)),this.backwardLayer.setWeights(e.slice(n))}computeOutputShape(e){let t,n,r,s=this.forwardLayer.computeOutputShape(e);return Array.isArray(s)&&Array.isArray(s[0])||(s=[s]),s=s,this.returnState?(r=s.slice(1),t=s[0]):t=s[0],t=t,"concat"===this.mergeMode?(t[t.length-1]*=2,n=[t]):n=null==this.mergeMode?[t,t.slice()]:[t],this.returnState?null==this.mergeMode?n.concat(r).concat(r.slice()):[t].concat(r).concat(r.slice()):Qm(n)}apply(e,t){let n=null==t?null:t.initialState,r=null==t?null:t.constants;null==t&&(t={});const s=Aw(e,n,r,this.numConstants);if(e=s.inputs,n=s.initialState,r=s.constants,Array.isArray(e)&&(n=e.slice(1),e=e[0]),(null==n||0===n.length)&&null==r)return super.apply(e,t);const a=[],i=[];if(null!=n){const e=n.length;if(e%2>0)throw new qm("When passing `initialState` to a Bidrectional RNN, the state should be an Array containing the states of the underlying RNNs.");t.initialState=n,a.push(...n);const r=n.map((e=>new ab({shape:e.shape})));this.forwardLayer.stateSpec=r.slice(0,e/2),this.backwardLayer.stateSpec=r.slice(e/2),i.push(...r)}if(null!=r)throw new Km("Support for constants in Bidirectional layers is not implemented yet.");const o=a[0]instanceof ib;for(const e of a)if(e instanceof ib!==o)throw new qm("The initial state of a Bidirectional layer cannot be specified as a mix of symbolic and non-symbolic tensors");if(o){const n=[e].concat(a),r=this.inputSpec.concat(i),s=this.inputSpec;this.inputSpec=r;const o=super.apply(n,t);return this.inputSpec=s,o}return super.apply(e,t)}call(e,t){return Xo((()=>{const n=t.initialState;let r,s,a,i;if(null==n)r=this.forwardLayer.call(e,t),s=this.backwardLayer.call(e,t);else{const a=n.slice(0,n.length/2),i=n.slice(n.length/2);r=this.forwardLayer.call(e,Object.assign(t,{initialState:a})),s=this.backwardLayer.call(e,Object.assign(t,{initialState:i}))}return this.returnState&&(Array.isArray(r)&&(a=r.slice(1).concat(s.slice(1))),r=r[0],s=s[0]),this.returnSequences&&(s=Ih(s,1)),"concat"===this.mergeMode?i=Qg([r,s]):"sum"===this.mergeMode?i=ll(r,s):"ave"===this.mergeMode?i=hl(.5,ll(r,s)):"mul"===this.mergeMode?i=hl(r,s):null==this.mergeMode&&(i=[r,s]),this.returnState?null==this.mergeMode?i.concat(a):[i].concat(a):i}))}resetStates(e){this.forwardLayer.resetStates(),this.backwardLayer.resetStates()}build(e){Pg(this.forwardLayer.name,(()=>{this.forwardLayer.build(e)})),Pg(this.backwardLayer.name,(()=>{this.backwardLayer.build(e)})),this.built=!0}computeMask(e,t){let n;if(Array.isArray(t)&&(t=t[0]),n=this.returnSequences?null==this.mergeMode?[t,t]:t:null==this.mergeMode?[null,null]:null,this.returnState){const e=this.forwardLayer.states.map((e=>null));return Array.isArray(n)?n.concat(e).concat(e):[n].concat(e).concat(e)}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),null!=this.forwardLayer&&this.forwardLayer.setFastWeightInitDuringBuild(e),null!=this.backwardLayer&&this.backwardLayer.setFastWeightInitDuringBuild(e)}getConfig(){const e={mergeMode:this.mergeMode},t=super.getConfig();return Object.assign(e,t),e}static fromConfig(e,t){const n=Sb(t.layer);if(delete t.layer,null!=t.numConstants)throw new Km("Deserialization of a Bidirectional layer with numConstants present is not supported yet.");const r=t;return r.layer=n,new e(r)}}function Lv(e){return new pb(e)}function zv(e){return new uw(e)}function Pv(e){return new iw(e)}function Bv(e){return new ow(e)}function Vv(e){return new lw(e)}function Uv(e){return new hw(e)}function Wv(e){return new cw(e)}function Gv(e){return new Tw(e)}function Hv(e){return new ww(e)}function jv(e){return new kw(e)}function qv(e){return new vw(e)}function Kv(e){return new Iw(e)}function Xv(e){return new Sw(e)}function Yv(e){return new Cw(e)}function Zv(e){return new Ew(e)}function Jv(e){return new $w(e)}function Qv(e){return new Xw(e)}function ek(e){return new qw(e)}function tk(e){return new Hw(e)}function nk(e){return new jw(e)}function rk(e){return new Kw(e)}function sk(e){return new Yw(e)}function ak(e){return new Zw(e)}function ik(e){return new Jw(e)}function ok(e){return new ev(e)}function lk(e){return new nv(e)}function uk(e){return new sv(e)}function ck(e){return new ov(e)}function hk(e){return new av(e)}function pk(e){return new iv(e)}function dk(e){return new rv(e)}function fk(e){return new uv(e)}function mk(e){return new fv(e)}function gk(e){return new mv(e)}function yk(e){return new gv(e)}function bk(e){return new vv(e)}function xk(e){return bk(e)}function wk(e){return bk(e)}function vk(e){return new Nv(e)}function kk(e){return vk(e)}function Ik(e){return vk(e)}function Nk(e){return new Cv(e)}function Sk(e){return Nk(e)}function Tk(e){return Nk(e)}function Ck(e){return new $v(e)}function Ek(e){return new Mv(e)}function $k(e){return new Av(e)}function Ak(e){return new Fv(e)}function Rk(e){return new wv(e)}function Mk(e){return new Iv(e)}function Fk(e){return new Tv(e)}function Dk(e){return new Lw(e)}function _k(e){return new Ow(e)}function Ok(e){return new Pw(e)}function Lk(e){return new zw(e)}function zk(e){return new _w(e)}function Pk(e){return new Dw(e)}function Bk(e){return new Gw(e)}function Vk(e){return new Ww(e)}function Uk(e){return new Mw(e)}function Wk(e){return new Bw(e)}function Gk(e){return new Ov(e)}function Hk(e){return new _v(e)}Ov.className="Bidirectional",Eo(Ov);const jk=$k,qk=Ak,Kk=Rk,Xk=Mk;function Yk(e){return new cv(e)}function Zk(e){return new hv(e)}function Jk(e){return new pv(e)}function Qk(e){return new Qw(e)}function eI(e,t){return Ob(e,t)}function tI(e,t){return Bb(e,t)}function nI(e,t){return Vb(e,t)}function rI(e,t){return Lb(e,t)}function sI(e,t){return Ub(e,t)}function aI(e,t){return Pb(e,t)}function iI(e,t){return function(e,t){return Xo((()=>{const n=zb(e,t),r=function(e,t){return Xo((()=>Si(Ic(Dc(ju(e,1),ju(t,0))),"float32")))}(e,t),s=ll(n,r);return Si(qu(ic(s,0),cl(n,s),0),"float32")}))}(e,t)}function oI(e,t){return Fb(e,t)}function lI(e,t){return Eb(e,t)}function uI(e,t){return $b(e,t)}function cI(e,t){return $b(e,t)}function hI(e,t){return $b(e,t)}function pI(e,t){return Cb(e,t)}function dI(e,t){return Cb(e,t)}function fI(e,t){return Cb(e,t)}function mI(e){return new tw(e)}function gI(e){return Qx(t=e),new tw({l1:null!=t?t.l1:null,l2:0});var t}function yI(e){return Qx(t=e),new tw({l2:null!=t?t.l2:null,l1:0});var t}class bI extends yb{constructor(){super(...arguments),this.model=null}setModel(e){if(!(e instanceof Tx))throw new Error("model must be a LayersModel, not some other Container");this.model=e}}function xI(e,t){return et}class vI extends bI{constructor(e){if(super(),null==e&&(e={}),e.restoreBestWeights)throw new Km("restoreBestWeights = True is not implemented in EarlyStopping yet.");this.monitor=e.monitor||"val_loss",this.minDelta=Math.abs(e.minDelta||0),this.patience=e.patience||0,this.verbose=e.verbose||0,this.mode=e.mode||"auto",this.baseline=e.baseline,-1===["auto","min","max"].indexOf(this.mode)&&(console.warn(`EarlyStopping mode '${this.mode}' is invalid. Falling back to mode 'auto'.`),this.mode="auto"),"min"===this.mode?this.monitorFunc=xI:"max"===this.mode||-1!==this.monitor.indexOf("acc")?this.monitorFunc=wI:this.monitorFunc=xI,this.monitorFunc===xI&&(this.minDelta*=-1)}async onTrainBegin(e){this.wait=0,this.stoppedEpoch=0,null!=this.baseline?this.best=this.baseline:this.best=this.monitorFunc===xI?1/0:-1/0}async onEpochEnd(e,t){await fb(t);const n=this.getMonitorValue(t);null!=n&&(this.monitorFunc(n-this.minDelta,this.best)?(this.best=n,this.wait=0):(this.wait++,this.wait>=this.patience&&(this.stoppedEpoch=e,this.model.stopTraining=!0)))}async onTrainEnd(e){this.stoppedEpoch>0&&this.verbose&&console.log(`Epoch ${this.stoppedEpoch}: early stopping.`)}getMonitorValue(e){null==e&&(e={});const t=e[this.monitor];return null==t&&console.warn(`Metric for EarlyStopping ${this.monitor} is not available. Available metrics are: ${Object.keys(e)}`),t}}const kI={earlyStopping:function(e){return new vI(e)}};var II,NI;He().registerFlag("KEEP_INTERMEDIATE_TENSORS",(()=>!1),(e=>{e&&console.warn("Keep intermediate tensors is ON. This will print the values of all intermediate tensors during model inference. Not all models support this mode. For details, check e2e/benchmarks/ model_config.js. This significantly impacts performance.")})),function(e){e[e.DT_INVALID=0]="DT_INVALID",e[e.DT_FLOAT=1]="DT_FLOAT",e[e.DT_DOUBLE=2]="DT_DOUBLE",e[e.DT_INT32=3]="DT_INT32",e[e.DT_UINT8=4]="DT_UINT8",e[e.DT_INT16=5]="DT_INT16",e[e.DT_INT8=6]="DT_INT8",e[e.DT_STRING=7]="DT_STRING",e[e.DT_COMPLEX64=8]="DT_COMPLEX64",e[e.DT_INT64=9]="DT_INT64",e[e.DT_BOOL=10]="DT_BOOL",e[e.DT_QINT8=11]="DT_QINT8",e[e.DT_QUINT8=12]="DT_QUINT8",e[e.DT_QINT32=13]="DT_QINT32",e[e.DT_BFLOAT16=14]="DT_BFLOAT16",e[e.DT_QINT16=15]="DT_QINT16",e[e.DT_QUINT16=16]="DT_QUINT16",e[e.DT_UINT16=17]="DT_UINT16",e[e.DT_COMPLEX128=18]="DT_COMPLEX128",e[e.DT_HALF=19]="DT_HALF",e[e.DT_RESOURCE=20]="DT_RESOURCE",e[e.DT_VARIANT=21]="DT_VARIANT",e[e.DT_UINT32=22]="DT_UINT32",e[e.DT_UINT64=23]="DT_UINT64",e[e.DT_FLOAT_REF=101]="DT_FLOAT_REF",e[e.DT_DOUBLE_REF=102]="DT_DOUBLE_REF",e[e.DT_INT32_REF=103]="DT_INT32_REF",e[e.DT_UINT8_REF=104]="DT_UINT8_REF",e[e.DT_INT16_REF=105]="DT_INT16_REF",e[e.DT_INT8_REF=106]="DT_INT8_REF",e[e.DT_STRING_REF=107]="DT_STRING_REF",e[e.DT_COMPLEX64_REF=108]="DT_COMPLEX64_REF",e[e.DT_INT64_REF=109]="DT_INT64_REF",e[e.DT_BOOL_REF=110]="DT_BOOL_REF",e[e.DT_QINT8_REF=111]="DT_QINT8_REF",e[e.DT_QUINT8_REF=112]="DT_QUINT8_REF",e[e.DT_QINT32_REF=113]="DT_QINT32_REF",e[e.DT_BFLOAT16_REF=114]="DT_BFLOAT16_REF",e[e.DT_QINT16_REF=115]="DT_QINT16_REF",e[e.DT_QUINT16_REF=116]="DT_QUINT16_REF",e[e.DT_UINT16_REF=117]="DT_UINT16_REF",e[e.DT_COMPLEX128_REF=118]="DT_COMPLEX128_REF",e[e.DT_HALF_REF=119]="DT_HALF_REF",e[e.DT_RESOURCE_REF=120]="DT_RESOURCE_REF",e[e.DT_VARIANT_REF=121]="DT_VARIANT_REF",e[e.DT_UINT32_REF=122]="DT_UINT32_REF",e[e.DT_UINT64_REF=123]="DT_UINT64_REF"}(II||(II={})),function(e){let t;!function(e){e[e.LEGACY=0]="LEGACY",e[e.V1=1]="V1",e[e.V2=2]="V2"}(t=e.CheckpointFormatVersion||(e.CheckpointFormatVersion={}))}(NI||(NI={}));const SI={};function TI(e,t){const n={tfOpName:e,category:"custom",inputs:[],attrs:[],customExecutor:t};SI[e]=n}function CI(e){return SI[e]}function EI(e){delete SI[e]}function $I(e,t,n,r,s){const a=t.inputParams[e];if(a&&void 0!==a.inputIndexStart){const e=a.inputIndexStart,i=0===a.inputIndexEnd?void 0:void 0===a.inputIndexEnd?e+1:a.inputIndexEnd;if("tensor"===a.type)return AI(t.inputNames[a.inputIndexStart],n,r,s);if("tensors"===a.type)return t.inputNames.slice(e,i).map((e=>AI(e,n,r,s)));const o=AI(t.inputNames.slice(e)[0],n,r,s),l=o.dataSync();return"number"===a.type?l[0]:_e(o.shape,l)}const i=t.attrParams[e];return i&&i.value}function AI(e,t,n,r){const[s,a]=FI(e);if(null!=r){const e=r.getHashTableHandleByName(s);if(null!=e)return e}const i=n.currentContextIds.find((e=>!!t[MI(s,e)]));return void 0!==i?t[MI(s,i)][a]:void 0}function RI(e,t){const[n,r,s]=FI(e);return[MI(n,t&&t.currentContextId),r,s]}function MI(e,t){return t?`${e}-${t}`:e}function FI(e){const t=e.split(":");if(1===t.length)return[e,0,void 0];const n=t[0],r=3===t.length?t[1]:void 0;return[n,Number(t[t.length-1]),r]}function DI(e,t,n){let r=$I("pad",e,t,n);if("explicit"===r){r=$I("explicitPaddings",e,t,n);const s=[[0,0],[0,0],[0,0],[0,0]];for(let e=0;e<4;e++)s[e][0]=r[2*e],s[e][1]=r[2*e+1];return s}return r}function _I(e){return e.kept?e:Ti(e)}const OI=[{tfOpName:"Add",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AddV2",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AddN",category:"arithmetic",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}]},{tfOpName:"BiasAdd",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"Sub",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"RealDiv",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Div",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"DivNoNan",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"FloorDiv",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Mul",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Maximum",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Minimum",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Pow",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SquaredDifference",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Mod",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"FloorMod",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}],LI=[{tfOpName:"Abs",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Acos",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Asin",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atan2",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Ceil",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ClipByValue",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"clipValueMin",type:"number"},{start:2,name:"clipValueMax",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Complex",category:"basic_math",inputs:[{start:0,name:"real",type:"tensor"},{start:1,name:"imag",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ComplexAbs",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cos",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cosh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Elu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Exp",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Floor",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Log",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Imag",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"Tout",name:"outputType",type:"dtype",notSupported:!0}]},{tfOpName:"Neg",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Real",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"Tout",name:"outputType",type:"dtype",notSupported:!0}]},{tfOpName:"Prelu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"alpha",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Relu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Relu6",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Selu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sigmoid",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sin",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sinh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sqrt",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Rsqrt",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Square",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Tan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Tanh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sign",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Round",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Expm1",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Log1p",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Reciprocal",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Softplus",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Asinh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Acosh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atanh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Erf",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Prod",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axes",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool",notSupported:!0},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LeakyRelu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"alpha",name:"alpha",type:"number",defaultValue:.2},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"IsNan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}],zI=[{tfOpName:"EmptyTensorList",category:"control",inputs:[{start:0,name:"elementShape",type:"shape"},{start:1,name:"maxNumElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"LoopCond",category:"control",inputs:[{start:0,name:"pred",type:"tensor"}]},{tfOpName:"Switch",category:"control",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"pred",type:"tensor"}]},{tfOpName:"Merge",category:"control",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}]},{tfOpName:"Enter",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"frame_name",name:"frameName",type:"string"},{tfName:"is_constant",name:"isConstant",type:"bool"}]},{tfOpName:"Exit",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"NextIteration",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayV3",category:"control",inputs:[{start:0,name:"size",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"dynamic_size",name:"dynamicSize",type:"bool"},{tfName:"clear_after_read",name:"clearAfterRead",type:"bool"},{tfName:"identical_element_shapes",name:"identicalElementShapes",type:"bool"},{tfName:"tensor_array_name",name:"name",type:"string"}]},{tfOpName:"TensorArrayWriteV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"tensor",type:"tensor"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayReadV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayGatherV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape",name:"elementShape",type:"shape"}]},{tfOpName:"TensorArrayScatterV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"tensor",type:"tensor"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"TensorArrayConcatV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape_except0",name:"elementShapeExcept0",type:"shape",notSupported:!0}]},{tfOpName:"TensorArraySplitV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"tensor",type:"tensor"},{start:2,name:"lengths",type:"number[]"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"TensorArraySizeV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"flowIn",type:"number"}]},{tfOpName:"TensorArrayCloseV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"}]},{tfOpName:"StatelessIf",category:"control",inputs:[{start:0,name:"cond",type:"tensor"},{start:1,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"then_branch",name:"thenBranch",type:"func"},{tfName:"else_branch",name:"elseBranch",type:"func"}]},{tfOpName:"If",category:"control",inputs:[{start:0,name:"cond",type:"tensor"},{start:1,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"then_branch",name:"thenBranch",type:"func"},{tfName:"else_branch",name:"elseBranch",type:"func"}]},{tfOpName:"StatelessWhile",category:"control",inputs:[{start:0,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"cond",name:"cond",type:"func"},{tfName:"body",name:"body",type:"func"}]},{tfOpName:"While",category:"control",inputs:[{start:0,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"cond",name:"cond",type:"func"},{tfName:"body",name:"body",type:"func"}]},{tfOpName:"TensorListScatter",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListScatterV2",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"},{start:3,name:"numElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListGather",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListGetItem",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListSetItem",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"tensor",type:"tensor"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListReserve",category:"control",inputs:[{start:0,name:"elementShape",type:"shape"},{start:1,name:"numElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListFromTensor",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListStack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"},{tfName:"num_elements",name:"numElements",type:"dtype"}]},{tfOpName:"TensorListSplit",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"elementShape",type:"shape"},{start:2,name:"lengths",type:"number[]"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListConcat",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"}],attrs:[{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListPopBack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListPushBack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"tensor",type:"tensor"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]}],PI=[{tfOpName:"AvgPool",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPool",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[],notSupported:!0},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPoolWithArgmax",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"include_batch_in_index",name:"includeBatchInIndex",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AvgPool3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPool3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Conv1D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"stride",name:"stride",type:"number"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NWC"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"dilation",name:"dilation",type:"number",defaultValue:1}]},{tfOpName:"Conv2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"useCudnnOnGpu",name:"useCudnnOnGpu",type:"bool"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"_FusedConv2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"use_cudnn_on_gpu",name:"useCudnnOnGpu",type:"bool",defaultValue:!0},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]",defaultValue:[1,1,1,1]},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:1e-4},{tfName:"leakyrelu_alpha",name:"leakyreluAlpha",type:"number"}]},{tfOpName:"Conv2DBackpropInput",category:"convolution",inputs:[{start:2,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:0,name:"outputShape",type:"number[]"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]",notSupported:!0}]},{tfOpName:"DepthwiseConv2d",category:"convolution",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"DepthwiseConv2dNative",category:"convolution",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"FusedDepthwiseConv2dNative",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]",defaultValue:[1,1,1,1]},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]}]},{tfOpName:"Conv3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"Dilation2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"rates",name:"dilations",type:"number[]"},{tfName:"padding",name:"pad",type:"string"}]}],BI=[{tfOpName:"Fill",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"},{start:1,name:"value",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"LinSpace",category:"creation",inputs:[{start:0,name:"start",type:"number"},{start:1,name:"stop",type:"number"},{start:2,name:"num",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"OneHot",category:"creation",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"depth",type:"number"},{start:2,name:"onValue",type:"number",defaultValue:1},{start:3,name:"offValue",type:"number",defaultValue:0}],attrs:[{tfName:"axis",name:"axis",type:"number",notSupported:!0},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Ones",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"OnesLike",category:"creation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"RandomUniform",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"minval",name:"minval",type:"number",defaultValue:0},{tfName:"maxval",name:"maxval",type:"number",defaultValue:1},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"seed",name:"seed",type:"number",defaultValue:0},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"Range",category:"creation",inputs:[{start:0,name:"start",type:"number"},{start:1,name:"stop",type:"number"},{start:2,name:"step",type:"number",defaultValue:0}],attrs:[{tfName:"Tidx",name:"dtype",type:"dtype"}]},{tfOpName:"TruncatedNormal",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"means",name:"mean",type:"number",defaultValue:0},{tfName:"stddev",name:"stdDev",type:"number",defaultValue:1},{tfName:"seed",name:"seed",type:"number"},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"Zeros",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"ZerosLike",category:"creation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"Multinomial",category:"creation",inputs:[{start:0,name:"logits",type:"tensor"},{start:1,name:"numSamples",type:"number"}],attrs:[{tfName:"seed",name:"seed",type:"number"},{tfName:"seed2",name:"seed2",type:"number"},{tfName:"T",name:"dtype",type:"dtype"},{tfName:"output_dtype",name:"output_dtype",type:"dtype"}]}],VI=[{tfOpName:"NonMaxSuppressionV2",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"}]},{tfOpName:"NonMaxSuppressionV3",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"}]},{tfOpName:"NonMaxSuppressionV4",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"T_threshold",name:"threshold",type:"dtype",notSupported:!0},{tfName:"pad_to_max_output_size",name:"padToMaxOutputSize",type:"bool"}]},{tfOpName:"NonMaxSuppressionV5",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"},{start:5,name:"softNmsSigma",type:"number"}]},{tfOpName:"Where",category:"dynamic",inputs:[{start:0,name:"condition",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ListDiff",category:"dynamic",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}],UI=[{tfOpName:"TopKV2",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"k",type:"number"}],attrs:[{tfName:"sorted",name:"sorted",type:"bool"}]},{tfOpName:"Unique",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"UniqueV2",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]}],WI=[{tfOpName:"PlaceholderWithDefault",category:"graph",inputs:[{start:0,name:"default",type:"tensor"}],attrs:[{tfName:"shape",name:"shape",type:"shape"},{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"Placeholder",category:"graph",attrs:[{tfName:"shape",name:"shape",type:"shape"},{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"Const",category:"graph"},{tfOpName:"Identity",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"IdentityN",category:"graph",inputs:[{start:0,end:0,name:"x",type:"tensors"}]},{tfOpName:"Snapshot",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Rank",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Size",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Shape",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"ShapeN",category:"graph",inputs:[{start:0,end:0,name:"x",type:"tensors"}]},{tfOpName:"Print",category:"graph",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"data",type:"tensors"}],attrs:[{tfName:"message",name:"message",type:"string"},{tfName:"first_n",name:"firstN",type:"number",notSupported:!0},{tfName:"summarize",name:"summarize",type:"number",defaultValue:3}]},{tfOpName:"NoOp",category:"graph",inputs:[]},{tfOpName:"StopGradient",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"FakeQuantWithMinMaxVars",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"min",name:"min",type:"number"},{tfName:"max",name:"max",type:"number"}]}],GI=[{tfOpName:"HashTable",category:"hash_table",inputs:[],attrs:[{tfName:"shared_name",name:"sharedName",type:"string"},{tfName:"use_node_name_sharing",name:"useNodeNameSharing",type:"bool"},{tfName:"key_dtype",name:"keyDType",type:"dtype"},{tfName:"value_dtype",name:"valueDType",type:"dtype"}]},{tfOpName:"HashTableV2",category:"hash_table",inputs:[],attrs:[{tfName:"shared_name",name:"sharedName",type:"string"},{tfName:"use_node_name_sharing",name:"useNodeNameSharing",type:"bool"},{tfName:"key_dtype",name:"keyDType",type:"dtype"},{tfName:"value_dtype",name:"valueDType",type:"dtype"}]},{tfOpName:"LookupTableImport",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableImportV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableFind",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableFindV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableSize",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"}]},{tfOpName:"LookupTableSizeV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"}]}],HI=[{tfOpName:"ResizeBilinear",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"size",type:"number[]"}],attrs:[{tfName:"align_corners",name:"alignCorners",type:"bool"},{tfName:"half_pixel_centers",name:"halfPixelCenters",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ResizeNearestNeighbor",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"size",type:"number[]"}],attrs:[{tfName:"align_corners",name:"alignCorners",type:"bool"},{tfName:"half_pixel_centers",name:"halfPixelCenters",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"CropAndResize",category:"image",inputs:[{start:0,name:"image",type:"tensor"},{start:1,name:"boxes",type:"tensor"},{start:2,name:"boxInd",type:"tensor"},{start:3,name:"cropSize",type:"number[]"}],attrs:[{tfName:"method",name:"method",type:"string"},{tfName:"extrapolation_value",name:"extrapolationValue",type:"number"}]}],jI=[{tfOpName:"Equal",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"NotEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Greater",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"GreaterEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Less",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LessEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalAnd",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalNot",category:"logical",inputs:[{start:0,name:"a",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalOr",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Select",category:"logical",inputs:[{start:0,name:"condition",type:"tensor"},{start:1,name:"a",type:"tensor"},{start:2,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SelectV2",category:"logical",inputs:[{start:0,name:"condition",type:"tensor"},{start:1,name:"a",type:"tensor"},{start:2,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}],qI=[{tfOpName:"_FusedMatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:1e-4},{tfName:"transpose_a",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"transpose_b",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"transpose_a",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"transpose_b",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BatchMatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"adj_x",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"adj_y",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BatchMatMulV2",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"adj_x",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"adj_y",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Transpose",category:"matrices",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"perm",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Einsum",category:"matrices",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}],attrs:[{tfName:"equation",name:"equation",type:"string"},{tfName:"N",name:"n",type:"number",defaultValue:2},{tfName:"T",name:"dtype",type:"dtype"}]}],KI=[{tfOpName:"FusedBatchNorm",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"FusedBatchNormV2",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"FusedBatchNormV3",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"LRN",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"depth_radius",name:"radius",type:"number",defaultValue:5},{tfName:"bias",name:"bias",type:"number",defaultValue:1},{tfName:"alpha",name:"alpha",type:"number",defaultValue:1},{tfName:"beta",name:"beta",type:"number",defaultValue:.5}]},{tfOpName:"Softmax",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"LogSoftmax",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"SparseToDense",category:"normalization",inputs:[{start:0,name:"sparseIndices",type:"tensor"},{start:1,name:"outputShape",type:"number[]"},{start:2,name:"sparseValues",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",defaultValue:!0,notSupported:!0}]}],XI=[{tfOpName:"Bincount",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"size",type:"number"},{start:2,name:"weights",type:"tensor"}]},{tfOpName:"DenseBincount",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"size",type:"number"},{start:2,name:"weights",type:"tensor"}],attrs:[{tfName:"binary_output",name:"binaryOutput",type:"bool"}]},{tfOpName:"Max",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Mean",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Min",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Sum",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"All",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Any",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"ArgMax",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"ArgMin",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"Prod",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Cumsum",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}],attrs:[{tfName:"exclusive",name:"exclusive",type:"bool"},{tfName:"reverse",name:"reverse",type:"bool"}]}],YI=[{tfOpName:"ConcatV2",category:"slice_join",inputs:[{start:0,end:-1,name:"tensors",type:"tensors"},{start:-1,name:"axis",type:"number"}],attrs:[{tfName:"N",name:"n",type:"number",defaultValue:2}]},{tfOpName:"Concat",category:"slice_join",inputs:[{start:1,end:0,name:"tensors",type:"tensors"},{start:0,name:"axis",type:"number"}],attrs:[{tfName:"N",name:"n",type:"number",defaultValue:2}]},{tfOpName:"GatherV2",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"axis",type:"number",defaultValue:0}],attrs:[{tfName:"batch_dims",name:"batchDims",type:"number",defaultValue:0}]},{tfOpName:"Gather",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",notSupported:!0}]},{tfOpName:"Reverse",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"dims",type:"bool[]"}]},{tfOpName:"ReverseV2",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}]},{tfOpName:"Slice",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"begin",type:"number[]"},{start:2,name:"size",type:"number[]"}]},{tfOpName:"StridedSlice",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"begin",type:"number[]"},{start:2,name:"end",type:"number[]"},{start:3,name:"strides",type:"number[]"}],attrs:[{tfName:"begin_mask",name:"beginMask",type:"number",defaultValue:0},{tfName:"end_mask",name:"endMask",type:"number",defaultValue:0},{tfName:"new_axis_mask",name:"newAxisMask",type:"number",defaultValue:0},{tfName:"ellipsis_mask",name:"ellipsisMask",type:"number",defaultValue:0},{tfName:"shrink_axis_mask",name:"shrinkAxisMask",type:"number",defaultValue:0}]},{tfOpName:"Pack",category:"slice_join",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0}]},{tfOpName:"Unpack",category:"slice_join",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0},{tfName:"num",name:"num",type:"number",defaultValue:0,notSupported:!0}]},{tfOpName:"Tile",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"reps",type:"number[]"}]},{tfOpName:"Split",category:"slice_join",inputs:[{start:0,name:"axis",type:"number",defaultValue:0},{start:1,name:"x",type:"tensor"}],attrs:[{tfName:"num_split",name:"numOrSizeSplits",type:"number",defaultValue:1}]},{tfOpName:"SplitV",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"numOrSizeSplits",type:"number[]"},{start:2,name:"axis",type:"number",defaultValue:0}]},{tfOpName:"ScatterNd",category:"slice_join",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"values",type:"tensor"},{start:2,name:"shape",type:"number[]"}]},{tfOpName:"GatherNd",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"}]},{tfOpName:"SparseToDense",category:"slice_join",inputs:[{start:0,name:"sparseIndices",type:"tensor"},{start:1,name:"outputShape",type:"number[]"},{start:2,name:"sparseValues",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",defaultValue:!1,notSupported:!0}]}],ZI=[{tfOpName:"SparseFillEmptyRows",category:"sparse",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"values",type:"tensor"},{start:2,name:"denseShape",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}]},{tfOpName:"SparseReshape",category:"sparse",inputs:[{start:0,name:"inputIndices",type:"tensor"},{start:1,name:"inputShape",type:"tensor"},{start:2,name:"newShape",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SparseSegmentMean",category:"sparse",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"segmentIds",type:"tensor"}]},{tfOpName:"SparseSegmentSum",category:"sparse",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"segmentIds",type:"tensor"}]}],JI=[{tfOpName:"FFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"IFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"RFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"fft_length",type:"number",notSupported:!0}]},{tfOpName:"IRFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"fft_length",type:"number",notSupported:!0}]}],QI=[{tfOpName:"StringNGrams",category:"string",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"dataSplits",type:"tensor"}],attrs:[{tfName:"separator",name:"separator",type:"string"},{tfName:"ngram_widths",name:"nGramWidths",type:"number[]"},{tfName:"left_pad",name:"leftPad",type:"string"},{tfName:"right_pad",name:"rightPad",type:"string"},{tfName:"pad_width",name:"padWidth",type:"number"},{tfName:"preserve_short_sequences",name:"preserveShortSequences",type:"bool"}],outputs:["ngrams","ngrams_splits"]},{tfOpName:"StringSplit",category:"string",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"delimiter",type:"tensor"}],attrs:[{tfName:"skip_empty",name:"skipEmpty",type:"bool"}],outputs:["indices","values","shape"]},{tfOpName:"StringToHashBucketFast",category:"string",inputs:[{start:0,name:"input",type:"tensor"}],attrs:[{tfName:"num_buckets",name:"numBuckets",type:"number"}]}],eN=[{tfOpName:"Cast",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"SrcT",name:"sdtype",type:"dtype",notSupported:!0},{tfName:"DstT",name:"dtype",type:"dtype"}]},{tfOpName:"ExpandDims",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"MirrorPad",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"}],attrs:[{tfName:"mode",name:"mode",type:"string"}]},{tfOpName:"Pad",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"}],attrs:[{tfName:"constant_value",name:"constantValue",type:"number",defaultValue:0}]},{tfOpName:"PadV2",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"},{start:2,name:"constantValue",type:"number",defaultValue:0}]},{tfOpName:"Reshape",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"shape",type:"number[]"}]},{tfOpName:"Squeeze",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"axis",tfDeprecatedName:"squeeze_dims",name:"axis",type:"number[]"}]},{tfOpName:"SpaceToBatchND",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"blockShape",type:"number[]"},{start:2,name:"paddings",type:"number[]"}]},{tfOpName:"BatchToSpaceND",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"blockShape",type:"number[]"},{start:2,name:"crops",type:"number[]"}]},{tfOpName:"DepthToSpace",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"block_size",name:"blockSize",type:"number"},{tfName:"data_format",name:"dataFormat",type:"string"}]},{tfOpName:"BroadcastTo",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"shape",type:"number[]"}],attrs:[]},{tfOpName:"BroadcastArgs",category:"transformation",inputs:[{start:0,name:"s0",type:"tensor"},{start:1,name:"s1",type:"tensor"}],attrs:[]}];class tN{static get Instance(){return this._instance||(this._instance=new this)}constructor(){const e=[].concat(...[S,T,C,E,$,A,R,M,F,D,_,O,L,z,P,B,V,U,W].map((e=>e.json)));this.opMappers=e.reduce(((e,t)=>(e[t.tfOpName]=t,e)),{})}transformGraph(e,t={}){const n=e.node,r=[],s=[],a=[],i=n.reduce(((e,t)=>(e[t.name]=this.mapNode(t),t.op.startsWith("Placeholder")?r.push(e[t.name]):"Const"===t.op?s.push(e[t.name]):null!=t.input&&0!==t.input.length||a.push(e[t.name]),e)),{});let o=[];const l=[];let u={},c={};null!=t&&(u=this.mapSignatureEntries(t.inputs),c=this.mapSignatureEntries(t.outputs));const h=Object.keys(i);h.forEach((e=>{const t=i[e];t.inputNames.forEach(((e,n)=>{const[r,,s]=RI(e),a=i[r];if(null!=a.outputs){const e=a.outputs.indexOf(s);if(-1!==e){const s=`${r}:${e}`;t.inputNames[n]=s}}t.inputs.push(a),a.children.push(t)}))})),0===Object.keys(c).length?h.forEach((e=>{const t=i[e];0===t.children.length&&l.push(t)})):Object.keys(c).forEach((e=>{const[t]=RI(e),n=i[t];null!=n&&(n.signatureKey=c[e],l.push(n))})),Object.keys(u).length>0?Object.keys(u).forEach((e=>{const[t]=RI(e),n=i[t];n&&(n.signatureKey=u[e],o.push(n))})):o=r;let p={};null!=e.library&&null!=e.library.function&&(p=e.library.function.reduce(((e,t)=>(e[t.signature.name]=this.mapFunction(t),e)),{}));const d={nodes:i,inputs:o,outputs:l,weights:s,placeholders:r,signature:t,functions:p};return a.length>0&&(d.initNodes=a),d}mapSignatureEntries(e){return Object.keys(e||{}).reduce(((t,n)=>(t[e[n].name]=n,t)),{})}mapNode(e){const t=CI(e.op)||this.opMappers[e.op]||{};null==e.attr&&(e.attr={});const n={name:e.name,op:e.op,category:t.category,inputNames:(e.input||[]).map((e=>e.startsWith("^")?e.substr(1):e)),inputs:[],children:[],inputParams:{},attrParams:{},rawAttrs:e.attr,outputs:t.outputs};return null!=t.inputs&&(n.inputParams=t.inputs.reduce(((e,t)=>(e[t.name]={type:t.type,inputIndexStart:t.start,inputIndexEnd:t.end},e)),{})),null!=t.attrs&&(n.attrParams=t.attrs.reduce(((t,n)=>{const r=n.type;let s;switch(n.type){case"string":s=rN(e.attr,n.tfName,n.defaultValue),void 0===s&&n.tfDeprecatedName&&(s=rN(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"string[]":s=dN(e.attr,n.tfName,n.defaultValue),void 0===s&&n.tfDeprecatedName&&(s=dN(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"number":s=aN(e.attr,n.tfName,n.defaultValue||0),void 0===s&&n.tfDeprecatedName&&(s=aN(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"number[]":s=pN(e.attr,n.tfName,n.defaultValue),void 0===s&&n.tfDeprecatedName&&(s=pN(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"bool":s=sN(e.attr,n.tfName,n.defaultValue),void 0===s&&n.tfDeprecatedName&&(s=sN(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"bool[]":s=mN(e.attr,n.tfName,n.defaultValue),void 0===s&&n.tfDeprecatedName&&(s=mN(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"shape":s=hN(e.attr,n.tfName,n.defaultValue),void 0===s&&n.tfDeprecatedName&&(s=hN(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"shape[]":s=fN(e.attr,n.tfName,n.defaultValue),void 0===s&&n.tfDeprecatedName&&(s=fN(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"dtype":s=lN(e.attr,n.tfName,n.defaultValue),void 0===s&&n.tfDeprecatedName&&(s=lN(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"dtype[]":s=uN(e.attr,n.tfName,n.defaultValue),void 0===s&&n.tfDeprecatedName&&(s=uN(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"func":s=oN(e.attr,n.tfName,n.defaultValue),void 0===s&&n.tfDeprecatedName&&(s=oN(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"tensor":case"tensors":break;default:throw new Error(`Unsupported param type: ${n.type} for op: ${e.op}`)}return t[n.name]={value:s,type:r},t}),{})),n}mapFunction(e){const t=e.nodeDef,n=[];let r={};null!=t&&(r=t.reduce(((e,t)=>(e[t.name]=this.mapNode(t),"Const"===t.op&&n.push(e[t.name]),e)),{}));const s=[],a=[];e.signature.inputArg.forEach((e=>{const[t]=RI(e.name),n={name:t,op:"Placeholder",inputs:[],inputNames:[],category:"graph",inputParams:{},attrParams:{dtype:{value:iN(e.type),type:"dtype"}},children:[]};n.signatureKey=e.name,s.push(n),r[t]=n})),Object.keys(r).forEach((e=>{const t=r[e];t.inputNames.forEach(((e,n)=>{const[s,,a]=RI(e),i=r[s];if(null!=i.outputs){const e=i.outputs.indexOf(a);if(-1!==e){const r=`${s}:${e}`;t.inputNames[n]=r}}t.inputs.push(i),i.children.push(t)}))}));const i=e.ret;e.signature.outputArg.forEach((e=>{const[t,n]=RI(i[e.name]),s=r[t];null!=s&&(s.defaultOutput=n,a.push(s))}));const o=this.mapArgsToSignature(e);return{nodes:r,inputs:s,outputs:a,weights:n,placeholders:[],signature:o}}mapArgsToSignature(e){return{methodName:e.signature.name,inputs:e.signature.inputArg.reduce(((e,t)=>(e[t.name]=this.mapArgToTensorInfo(t),e)),{}),outputs:e.signature.outputArg.reduce(((t,n)=>(t[n.name]=this.mapArgToTensorInfo(n,e.ret),t)),{})}}mapArgToTensorInfo(e,t){let n=e.name;return null!=t&&(n=t[n]),{name:n,dtype:e.type}}}function nN(e,t){const n=Array.isArray(e)?String.fromCharCode.apply(null,e):function(e){const t=He().global;if(void 0!==t.atob)return t.atob(e);if("undefined"!=typeof Buffer)return new Buffer(e,"base64").toString();throw new Error("Unable to decode base64 in this environment. Missing built-in atob() or Buffer()")}(e);return t?n:n.toLowerCase()}function rN(e,t,n,r=!1){const s=e[t];return null!=s?nN(s.s,r):n}function sN(e,t,n){const r=e[t];return r?r.b:n}function aN(e,t,n){const r=e[t]||{},s=null!=r.i?r.i:null!=r.f?r.f:n;return"number"==typeof s?s:parseInt(s,10)}function iN(e){switch("string"==typeof e&&(e=II[e]),e){case II.DT_FLOAT:case II.DT_HALF:return"float32";case II.DT_INT32:case II.DT_INT64:case II.DT_INT8:case II.DT_UINT8:return"int32";case II.DT_BOOL:return"bool";case II.DT_DOUBLE:return"float32";case II.DT_STRING:return"string";default:return null}}function oN(e,t,n){const r=e[t];return r&&r.func?r.func.name:n}function lN(e,t,n){const r=e[t];return r&&r.type?iN(r.type):n}function uN(e,t,n){const r=e[t];return r&&r.list&&r.list.type?r.list.type.map((e=>iN(e))):n}function cN(e){if(!e.unknownRank)return null!=e.dim?e.dim.map((e=>"number"==typeof e.size?e.size:parseInt(e.size,10))):[]}function hN(e,t,n){const r=e[t];return r&&r.shape?cN(r.shape):n}function pN(e,t,n){const r=e[t];return r?((r.list.f&&r.list.f.length?r.list.f:r.list.i)||[]).map((e=>"number"==typeof e?e:parseInt(e,10))):n}function dN(e,t,n,r=!1){const s=e[t];return s&&s.list&&s.list.s?s.list.s.map((e=>nN(e,r))):n}function fN(e,t,n){const r=e[t];return r&&r.list&&r.list.shape?r.list.shape.map((e=>cN(e))):n}function mN(e,t,n){const r=e[t];return r&&r.list&&r.list.b?r.list.b:n}class gN{constructor(e,t,n){this.node=e,this.tensorMap=t,this.context=n,this.inputs=[],this.attrs={},this.inputs=e.inputNames.map((e=>this.getInput(e))),null!=e.rawAttrs&&(this.attrs=Object.keys(e.rawAttrs).reduce(((e,t)=>(e[t]=this.getAttr(t),e)),{}))}getInput(e){return AI(e,this.tensorMap,this.context)}getAttr(e,t){const n=this.node.rawAttrs[e];if(null!=n.tensor)return AI(e,this.tensorMap,this.context);if(null!=n.i||null!=n.f)return aN(this.node.rawAttrs,e,t);if(null!=n.s)return rN(this.node.rawAttrs,e,t);if(null!=n.b)return sN(this.node.rawAttrs,e,t);if(null!=n.shape)return hN(this.node.rawAttrs,e,t);if(null!=n.type)return lN(this.node.rawAttrs,e,t);if(null!=n.list){if(null!=n.list.i||null!=n.list.f)return pN(this.node.rawAttrs,e,t);if(null!=n.list.s)return dN(this.node.rawAttrs,e,t);if(null!=n.list.shape)return fN(this.node.rawAttrs,e,t);if(null!=n.list.b)return mN(this.node.rawAttrs,e,t);if(null!=n.list.type)return uN(this.node.rawAttrs,e,t)}return t}}function yN(e,t,n=""){if("number"!=typeof e&&"number"!=typeof t){re(e.length===t.length,(()=>n+` Shapes ${e} and ${t} must match`));for(let r=0;rn+` Shapes ${e} and ${t} must match`))}}}function bN(e){return"number"!=typeof e&&!e.some((e=>e<0))}function xN(e,t,n){let r=wN(e,n);const s=!bN(r);if(s&&0===t.length)throw new Error(`Tried to calculate elements of an empty list with non-fully-defined elementShape: ${r}`);if(s&&t.forEach((e=>{r=wN(e.shape,r)})),!bN(r))throw new Error(`Non-fully-defined elementShape: ${r}`);return r}function wN(e,t){if("number"==typeof e)return t;if("number"==typeof t)return e;if(e.length!==t.length)throw new Error(`Incompatible ranks during merge: ${e} vs. ${t}`);const n=[];for(let r=0;r=0&&a>=0&&s!==a)throw new Error(`Incompatible shape during merge: ${e} vs. ${t}`);n[r]=s>=0?s:a}return n}class vN{constructor(e,t,n,r,s,a,i){this.name=e,this.dtype=t,this.maxSize=n,this.elementShape=r,this.identicalElementShapes=s,this.dynamicSize=a,this.clearAfterRead=i,this.tensors=[],this.closed_=!1,this.idTensor=kl(0),Zo(this.idTensor)}get id(){return this.idTensor.id}get closed(){return this.closed_}clearAndClose(e){this.tensors.forEach((t=>{null!=e&&e.has(t.tensor.id)||t.tensor.dispose()})),this.tensors=[],this.closed_=!0,this.idTensor.dispose()}size(){return this.tensors.length}read(e){if(this.closed_)throw new Error(`TensorArray ${this.name} has already been closed.`);if(e<0||e>=this.size())throw new Error(`Tried to read from index ${e}, but array size is: ${this.size()}`);const t=this.tensors[e];if(t.cleared)throw new Error(`TensorArray ${this.name}: Could not read index ${e} twice because it was cleared after a previous read (perhaps try setting clear_after_read = false?).`);return this.clearAfterRead&&(t.cleared=!0),t.read=!0,t.tensor}readMany(e){return e.map((e=>this.read(e)))}write(e,t){if(this.closed_)throw new Error(`TensorArray ${this.name} has already been closed.`);if(e<0||!this.dynamicSize&&e>=this.maxSize)throw new Error(`Tried to write to index ${e}, but array is not resizeable and size is: ${this.maxSize}`);const n=this.tensors[e]||{};if(t.dtype!==this.dtype)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e},\n because the value dtype is ${t.dtype}, but TensorArray dtype is ${this.dtype}.`);if(0!==this.size()||null!=this.elementShape&&0!==this.elementShape.length||(this.elementShape=t.shape),yN(this.elementShape,t.shape,`TensorArray ${this.name}: Could not write to TensorArray index ${e}.`),n.read)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been read.`);if(n.written)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been written.`);n.tensor=t,Zo(t),n.written=!0,this.tensors[e]=n}writeMany(e,t){if(e.length!==t.length)throw new Error(`TensorArray ${this.name}: could not write multiple tensors,because the index size: ${e.length} is not the same as tensors size: ${t.length}.`);e.forEach(((e,n)=>this.write(e,t[n])))}gather(e,t){if(t&&t!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but gather requested dtype ${t}`);if(e)e=e.slice(0,this.size());else{e=[];for(let t=0;t=this.maxSize)throw new Error(`Max index must be < array size (${n} vs. ${this.maxSize})`);this.writeMany(e,op(t,0))}split(e,t){if(t.dtype!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${t.dtype}`);let n=0;const r=e.map((e=>(n+=e,n)));if(n!==t.shape[0])throw new Error(`Expected sum of lengths to be equal to\n tensor.shape[0], but sum of lengths is\n ${n}, and tensor's shape is: ${t.shape}`);if(!this.dynamicSize&&e.length!==this.maxSize)throw new Error(`TensorArray's size is not equal to the size of lengths (${this.maxSize} vs. ${e.length}), and the TensorArray is not marked as dynamically resizeable`);const s=0===n?0:t.size/n,a=[];Xo((()=>{t=uu(t,[1,n,s]);for(let n=0;n{if(n!==e.dtype)throw new Error(`Invalid data types; op elements ${n}, but list elements ${e.dtype}`);yN(t,e.shape,"TensorList shape mismatch: "),Zo(e)})),this.idTensor=kl(0),this.maxNumElements=r,Zo(this.idTensor)}get id(){return this.idTensor.id}copy(){return new kN([...this.tensors],this.elementShape,this.elementDtype)}clearAndClose(e){this.tensors.forEach((t=>{null!=e&&e.has(t.id)||t.dispose()})),this.tensors.length=0,this.idTensor.dispose()}size(){return this.tensors.length}stack(e,t,n=-1){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);if(-1!==n&&this.tensors.length!==n)throw new Error(`Operation expected a list with ${n} elements but got a list with ${this.tensors.length} elements.`);yN(e,this.elementShape,"TensorList shape mismatch: ");const r=xN(this.elementShape,this.tensors,e);return Xo((()=>{const e=this.tensors.map((e=>uu(e,r)));return Kh(e,0)}))}popBack(e,t){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);if(0===this.size())throw new Error("Trying to pop from an empty list.");const n=xN(this.elementShape,this.tensors,e),r=this.tensors.pop();return yN(r.shape,e,"TensorList shape mismatch: "),uu(r,n)}pushBack(e){if(e.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${this.elementDtype}`);if(yN(e.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");Zo(e),this.tensors.push(e)}resize(e){if(e<0)throw new Error(`TensorListResize expects size to be non-negative. Got: ${e}`);if(-1!==this.maxNumElements&&e>this.maxNumElements)throw new Error(`TensorListResize input size ${e} is greater maxNumElement ${this.maxNumElements}.`);this.tensors.length=e}getItem(e,t,n){if(n!==this.elementDtype)throw new Error(`Invalid data types; op elements ${n}, but list elements ${this.elementDtype}`);if(e<0||e>this.tensors.length)throw new Error(`Trying to access element ${e} in a list with ${this.tensors.length} elements.`);if(null==this.tensors[e])throw new Error(`element at index ${e} is null.`);yN(this.tensors[e].shape,t,"TensorList shape mismatch: ");const r=xN(this.elementShape,this.tensors,t);return uu(this.tensors[e],r)}setItem(e,t){if(t.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t.dtype}, but list elements ${this.elementDtype}`);if(e<0||-1!==this.maxNumElements&&e>=this.maxNumElements)throw new Error(`Trying to set element ${e} in a list with max ${this.maxNumElements} elements.`);yN(this.elementShape,t.shape,"TensorList shape mismatch: "),Zo(t),this.tensors[e]=t}gather(e,t,n){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);yN(this.elementShape,n,"TensorList shape mismatch: "),e=e.slice(0,this.size());const r=xN(this.elementShape,this.tensors,n);return 0===e.length?$a([],[0].concat(r)):Xo((()=>{const t=e.map((e=>uu(this.tensors[e],r)));return Kh(t,0)}))}concat(e,t){if(e&&e!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${e}`);yN(this.elementShape,t,"TensorList shape mismatch: ");const n=xN(this.elementShape,this.tensors,t);return 0===this.size()?$a([],[0].concat(n)):Xo((()=>{const e=this.tensors.map((e=>uu(e,n)));return pu(e,0)}))}}function IN(e,t,n){const[r,s]=$I("fusedOps",e,t,n),a="biasadd"===r,i=!a,o="prelu"===s,l="fusedbatchnorm"===r,u=$I("numArgs",e,t,n);if(a){if(o&&2!==u)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!o&&a&&1!==u)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd must have one extra argument: bias.")}if(l)throw new Error("FusedConv2d and DepthwiseConv2d with FusedBatchNorm is not supported");const c=$I("strides",e,t,n),h=DI(e,t,n),p=$I("dataFormat",e,t,n).toUpperCase(),d=$I("dilations",e,t,n);let[f,m]=$I("args",e,t,n);return i&&(m=f,f=void 0),{stride:c,pad:h,dataFormat:p,dilations:d,biasArg:f,preluArg:m,activationFunc:s,leakyreluAlpha:$I("leakyreluAlpha",e,t,n)}}function NN(e,t,n){return{boxes:$I("boxes",e,t,n),scores:$I("scores",e,t,n),maxOutputSize:$I("maxOutputSize",e,t,n),iouThreshold:$I("iouThreshold",e,t,n),scoreThreshold:$I("scoreThreshold",e,t,n),softNmsSigma:$I("softNmsSigma",e,t,n)}}class SN{constructor(e,t){this.keyDType=e,this.valueDType=t,this.handle=kl(0),this.tensorMap=new Map,Zo(this.handle)}get id(){return this.handle.id}clearAndClose(){this.tensorMap.forEach((e=>e.dispose())),this.tensorMap.clear(),this.handle.dispose()}size(){return this.tensorMap.size}tensorSize(){return kl(this.size(),"int32")}async import(e,t){this.checkKeyAndValueTensor(e,t);const n=await e.data();return this.tensorMap.forEach((e=>e.dispose())),this.tensorMap.clear(),Xo((()=>{const e=op(t),r=n.length,s=e.length;re(r===s,(()=>`The number of elements doesn't match, keys has ${r} elements, the values has ${s} elements.`));for(let t=0;t{const e=[];for(let r=0;r{switch(e.category){case"arithmetic":return Xo((()=>((e,t,n)=>{switch(e.op){case"BiasAdd":case"AddV2":case"Add":return[ll($I("a",e,t,n),$I("b",e,t,n))];case"AddN":return[Pl($I("tensors",e,t,n))];case"FloorMod":case"Mod":return[Kc($I("a",e,t,n),$I("b",e,t,n))];case"Mul":return[hl($I("a",e,t,n),$I("b",e,t,n))];case"RealDiv":case"Div":return[cl($I("a",e,t,n),$I("b",e,t,n))];case"DivNoNan":return[Ku($I("a",e,t,n),$I("b",e,t,n))];case"FloorDiv":return[ul($I("a",e,t,n),$I("b",e,t,n))];case"Sub":return[El($I("a",e,t,n),$I("b",e,t,n))];case"Minimum":return[jc($I("a",e,t,n),$I("b",e,t,n))];case"Maximum":return[Rl($I("a",e,t,n),$I("b",e,t,n))];case"Pow":return[Cl($I("a",e,t,n),$I("b",e,t,n))];case"SquaredDifference":return[jh($I("a",e,t,n),$I("b",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"basic_math":return Xo((()=>((e,t,n)=>{switch(e.op){case"Abs":case"ComplexAbs":return[Al($I("x",e,t,n))];case"Acos":return[Ll($I("x",e,t,n))];case"Acosh":return[zl($I("x",e,t,n))];case"Asin":return[Gl($I("x",e,t,n))];case"Asinh":return[Hl($I("x",e,t,n))];case"Atan":return[jl($I("x",e,t,n))];case"Atan2":return[ql($I("x",e,t,n),$I("y",e,t,n))];case"Atanh":return[Kl($I("x",e,t,n))];case"Ceil":return[Su($I("x",e,t,n))];case"Complex":return[Ca($I("real",e,t,n),$I("imag",e,t,n))];case"Cos":return[zu($I("x",e,t,n))];case"Cosh":return[Pu($I("x",e,t,n))];case"Elu":return[Zu($I("x",e,t,n))];case"Erf":return[Ju($I("x",e,t,n))];case"Exp":return[Qu($I("x",e,t,n))];case"Expm1":return[tc($I("x",e,t,n))];case"Floor":return[sc($I("x",e,t,n))];case"Log":return[yc($I("x",e,t,n))];case"Log1p":return[bc($I("x",e,t,n))];case"Imag":return[lc($I("x",e,t,n))];case"Neg":return[xc($I("x",e,t,n))];case"Reciprocal":return[wh($I("x",e,t,n))];case"Real":return[xh($I("x",e,t,n))];case"Relu":return[vh($I("x",e,t,n))];case"Round":return[Eh($I("x",e,t,n))];case"Selu":return[Ah($I("x",e,t,n))];case"Sigmoid":return[du($I("x",e,t,n))];case"Sin":return[Dh($I("x",e,t,n))];case"Sign":return[Fh($I("x",e,t,n))];case"Sinh":return[_h($I("x",e,t,n))];case"Softplus":return[wc($I("x",e,t,n))];case"Sqrt":return[pl($I("x",e,t,n))];case"Square":return[dl($I("x",e,t,n))];case"Tanh":return[mu($I("x",e,t,n))];case"Tan":return[Zh($I("x",e,t,n))];case"ClipByValue":return[Tu($I("x",e,t,n),$I("clipValueMin",e,t,n),$I("clipValueMax",e,t,n))];case"Relu6":return[kh($I("x",e,t,n))];case"Rsqrt":return[$h(AI(e.inputNames[0],t,n))];case"Prod":return[uh($I("x",e,t,n),$I("axes",e,t,n))];case"LeakyRelu":return[pc($I("x",e,t,n),$I("alpha",e,t,n))];case"Prelu":return[lh($I("x",e,t,n),$I("alpha",e,t,n))];case"IsNan":return[hc(AI(e.inputNames[0],t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"control":return(async(e,t,n)=>{switch(e.op){case"If":case"StatelessIf":{const r=$I("thenBranch",e,t,n),s=$I("elseBranch",e,t,n),a=$I("cond",e,t,n),i=$I("args",e,t,n);return(await a.data())[0]?n.functionMap[r].executeFunctionAsync(i,n.tensorArrayMap,n.tensorListMap):n.functionMap[s].executeFunctionAsync(i,n.tensorArrayMap,n.tensorListMap)}case"While":case"StatelessWhile":{const r=$I("body",e,t,n),s=$I("cond",e,t,n),a=$I("args",e,t,n),i=await n.functionMap[s].executeFunctionAsync(a,n.tensorArrayMap,n.tensorListMap),o=a.map((e=>e.id));let l=await i[0].data();i.forEach((e=>{e.kept||-1!==o.indexOf(e.id)||e.dispose()}));let u=a;for(;l[0];){const e=u;u=await n.functionMap[r].executeFunctionAsync(u,n.tensorArrayMap,n.tensorListMap);const t=u.map((e=>e.id));e.forEach((e=>{e.kept||-1!==o.indexOf(e.id)||-1!==t.indexOf(e.id)||e.dispose()}));const a=await n.functionMap[s].executeFunctionAsync(u,n.tensorArrayMap,n.tensorListMap);l=await a[0].data(),a.forEach((e=>{e.kept||-1!==o.indexOf(e.id)||-1!==t.indexOf(e.id)||e.dispose()}))}return u}case"LoopCond":return[_I($I("pred",e,t,n))];case"Switch":{const r=$I("pred",e,t,n);let s=$I("data",e,t,n);return s.kept||(s=_I(s)),(await r.data())[0]?[void 0,s]:[s,void 0]}case"Merge":{const r=e.inputNames.find((e=>void 0!==AI(e,t,n)));return r?[_I(AI(r,t,n))]:void 0}case"Enter":{const r=$I("frameName",e,t,n),s=$I("tensor",e,t,n);return n.enterFrame(r),[_I(s)]}case"Exit":{const r=$I("tensor",e,t,n);return n.exitFrame(),[_I(r)]}case"NextIteration":{const r=$I("tensor",e,t,n);return n.nextIteration(),[_I(r)]}case"TensorArrayV3":{const r=$I("size",e,t,n),s=$I("dtype",e,t,n),a=$I("elementShape",e,t,n),i=$I("dynamicSize",e,t,n),o=$I("clearAfterRead",e,t,n),l=$I("identicalElementShapes",e,t,n),u=$I("name",e,t,n),c=new vN(u,s,r,a,l,i,o);return n.addTensorArray(c),[c.idTensor,kl(1)]}case"TensorArrayWriteV3":{const r=$I("tensorArrayId",e,t,n),s=$I("index",e,t,n),a=$I("tensor",e,t,n),i=n.getTensorArray(r.id);return i.write(s,a),[i.idTensor]}case"TensorArrayReadV3":{const r=$I("tensorArrayId",e,t,n),s=$I("index",e,t,n);return[n.getTensorArray(r.id).read(s)]}case"TensorArrayGatherV3":{const r=$I("tensorArrayId",e,t,n),s=$I("indices",e,t,n),a=$I("dtype",e,t,n);return[n.getTensorArray(r.id).gather(s,a)]}case"TensorArrayScatterV3":{const r=$I("tensorArrayId",e,t,n),s=$I("indices",e,t,n),a=$I("tensor",e,t,n),i=n.getTensorArray(r.id);return i.scatter(s,a),[i.idTensor]}case"TensorArrayConcatV3":{const r=$I("tensorArrayId",e,t,n),s=n.getTensorArray(r.id),a=$I("dtype",e,t,n);return[s.concat(a)]}case"TensorArraySplitV3":{const r=$I("tensorArrayId",e,t,n),s=$I("tensor",e,t,n),a=$I("lengths",e,t,n),i=n.getTensorArray(r.id);return i.split(a,s),[i.idTensor]}case"TensorArraySizeV3":{const r=$I("tensorArrayId",e,t,n);return[kl(n.getTensorArray(r.id).size(),"int32")]}case"TensorArrayCloseV3":{const r=$I("tensorArrayId",e,t,n),s=n.getTensorArray(r.id);return s.clearAndClose(),[s.idTensor]}case"TensorListSetItem":{const r=$I("tensorListId",e,t,n),s=$I("index",e,t,n),a=$I("tensor",e,t,n),i=n.getTensorList(r.id);return i.setItem(s,a),[i.idTensor]}case"TensorListGetItem":{const r=$I("tensorListId",e,t,n),s=$I("index",e,t,n),a=$I("elementShape",e,t,n),i=$I("elementDType",e,t,n);return[n.getTensorList(r.id).getItem(s,a,i)]}case"TensorListScatterV2":case"TensorListScatter":{const r=$I("indices",e,t,n),s=function(e,t,n,r){if(t.length!==e.shape[0])throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${t.length} vs. ${e.shape[0]}`);const s=Math.max(...t);if(null!=r&&-1!==r&&s>=r)throw new Error(`Max index must be < array size (${s} vs. ${r})`);const a=new kN([],n,e.dtype,r),i=op(e,0);return t.forEach(((e,t)=>{a.setItem(e,i[t])})),a}($I("tensor",e,t,n),r,$I("elementShape",e,t,n),$I("numElements",e,t,n));return n.addTensorList(s),[s.idTensor]}case"TensorListReserve":case"EmptyTensorList":{const r=$I("elementShape",e,t,n),s=$I("elementDType",e,t,n);let a;a="TensorListReserve"===e.op?"numElements":"maxNumElements";const i=function(e,t,n){return new kN([],e,t,n)}(r,s,$I(a,e,t,n));return n.addTensorList(i),[i.idTensor]}case"TensorListGather":{const r=$I("tensorListId",e,t,n),s=$I("indices",e,t,n),a=$I("elementShape",e,t,n),i=$I("elementDType",e,t,n);return[n.getTensorList(r.id).gather(s,i,a)]}case"TensorListStack":{const r=$I("tensorListId",e,t,n),s=$I("elementShape",e,t,n),a=$I("elementDType",e,t,n),i=$I("numElements",e,t,n);return[n.getTensorList(r.id).stack(s,a,i)]}case"TensorListFromTensor":{const r=function(e,t,n){const r=e.dtype;if(e.shape.length<1)throw new Error(`Tensor must be at least a vector, but saw shape: ${e.shape}`);if(e.dtype!==n)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${n}`);yN(e.shape.slice(1),t,"TensorList shape mismatch: ");const s=op(e);return new kN(s,t,r)}($I("tensor",e,t,n),$I("elementShape",e,t,n),$I("elementDType",e,t,n));return n.addTensorList(r),[r.idTensor]}case"TensorListConcat":{const r=$I("tensorListId",e,t,n),s=n.getTensorList(r.id),a=$I("dtype",e,t,n),i=$I("elementShape",e,t,n);return[s.concat(a,i)]}case"TensorListPushBack":{const r=$I("tensorListId",e,t,n),s=$I("tensor",e,t,n),a=n.getTensorList(r.id);return a.pushBack(s),[a.idTensor]}case"TensorListPopBack":{const r=$I("tensorListId",e,t,n),s=$I("elementShape",e,t,n),a=$I("elementDType",e,t,n);return[n.getTensorList(r.id).popBack(s,a)]}case"TensorListSplit":{const r=$I("tensor",e,t,n),s=$I("elementShape",e,t,n),a=function(e,t,n){let r=0;const s=t.map((e=>(r+=e,r)));if(r!==e.shape[0])throw new Error(`Expected sum of lengths to be equal to\n tensor.shape[0], but sum of lengths is\n ${r}, and tensor's shape is: ${e.shape}`);const a=wN(e.shape.slice(1),n),i=0===r?0:e.size/r,o=Xo((()=>{const n=[];e=uu(e,[1,r,i]);for(let r=0;r((e,t,n)=>{switch(e.op){case"Conv1D":{const r=$I("stride",e,t,n),s=$I("pad",e,t,n),a=$I("dataFormat",e,t,n).toUpperCase(),i=$I("dilation",e,t,n);return[Mu($I("x",e,t,n),$I("filter",e,t,n),r,s,a,i)]}case"Conv2D":{const r=$I("strides",e,t,n),s=DI(e,t,n),a=$I("dataFormat",e,t,n).toUpperCase(),i=$I("dilations",e,t,n);return[Ru($I("x",e,t,n),$I("filter",e,t,n),[r[1],r[2]],s,a,[i[1],i[2]])]}case"_FusedConv2D":{const{stride:r,pad:s,dataFormat:a,dilations:i,biasArg:o,preluArg:l,activationFunc:u,leakyreluAlpha:c}=IN(e,t,n);return[Cp({x:$I("x",e,t,n),filter:$I("filter",e,t,n),strides:[r[1],r[2]],pad:s,dataFormat:a,dilations:[i[1],i[2]],bias:o,activation:u,preluActivationWeights:l,leakyreluAlpha:c})]}case"FusedDepthwiseConv2dNative":{const{stride:r,pad:s,dataFormat:a,dilations:i,biasArg:o,preluArg:l,activationFunc:u,leakyreluAlpha:c}=IN(e,t,n);return[Ap({x:$I("x",e,t,n),filter:$I("filter",e,t,n),strides:[r[1],r[2]],pad:s,dataFormat:a,dilations:[i[1],i[2]],bias:o,activation:u,preluActivationWeights:l,leakyreluAlpha:c})]}case"Conv2DBackpropInput":case"Conv2dTranspose":{const r=$I("outputShape",e,t,n),s=$I("strides",e,t,n),a=DI(e,t,n);return[Du($I("x",e,t,n),$I("filter",e,t,n),r,[s[1],s[2]],a)]}case"DepthwiseConv2dNative":case"DepthwiseConv2d":{const r=$I("strides",e,t,n),s=DI(e,t,n),a=$I("dilations",e,t,n),i=$I("dataFormat",e,t,n).toUpperCase();return[Wu($I("input",e,t,n),$I("filter",e,t,n),[r[1],r[2]],s,i,[a[1],a[2]])]}case"Conv3D":{const r=$I("strides",e,t,n),s=$I("pad",e,t,n),a=$I("dataFormat",e,t,n).toUpperCase(),i=$I("dilations",e,t,n);return[_u($I("x",e,t,n),$I("filter",e,t,n),[r[1],r[2],r[3]],s,a,[i[1],i[2],i[3]])]}case"AvgPool":{const r=$I("strides",e,t,n),s=$I("pad",e,t,n),a=$I("kernelSize",e,t,n);return[cu($I("x",e,t,n),[a[1],a[2]],[r[1],r[2]],s)]}case"MaxPool":{const r=$I("strides",e,t,n),s=$I("pad",e,t,n),a=$I("kernelSize",e,t,n);return[zc($I("x",e,t,n),[a[1],a[2]],[r[1],r[2]],s)]}case"MaxPoolWithArgmax":{const r=$I("strides",e,t,n),s=$I("pad",e,t,n),a=$I("kernelSize",e,t,n),i=$I("includeBatchInIndex",e,t,n),{result:o,indexes:l}=Bc($I("x",e,t,n),[a[1],a[2]],[r[1],r[2]],s,i);return[o,l]}case"AvgPool3D":{const r=$I("strides",e,t,n),s=$I("pad",e,t,n),a=$I("kernelSize",e,t,n);return[hu($I("x",e,t,n),[a[1],a[2],a[3]],[r[1],r[2],r[3]],s)]}case"MaxPool3D":{const r=$I("strides",e,t,n),s=$I("pad",e,t,n),a=$I("kernelSize",e,t,n);return[Pc($I("x",e,t,n),[a[1],a[2],a[3]],[r[1],r[2],r[3]],s)]}case"Dilation2D":{const r=$I("strides",e,t,n),s=$I("pad",e,t,n),a=$I("dilations",e,t,n),i=r[1],o=r[2],l=a[1],u=a[2];return[Hu($I("x",e,t,n),$I("filter",e,t,n),[i,o],s,[l,u],"NHWC")]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"creation":return Xo((()=>((e,t,n)=>{switch(e.op){case"Fill":{const r=$I("shape",e,t,n),s=$I("dtype",e,t,n);return[Sl(r,$I("value",e,t,n),s)]}case"LinSpace":return[mc($I("start",e,t,n),$I("stop",e,t,n),$I("num",e,t,n))];case"Multinomial":{const r=$I("logits",e,t,n),s=$I("numSamples",e,t,n),a=$I("seed",e,t,n);return[Zc(r,s,a)]}case"OneHot":{const r=$I("indices",e,t,n),s=$I("depth",e,t,n),a=$I("onValue",e,t,n),i=$I("offValue",e,t,n);return[ji(r,s,a,i)]}case"Ones":return[Wc($I("shape",e,t,n),$I("dtype",e,t,n))];case"OnesLike":return[Qc($I("x",e,t,n))];case"RandomUniform":return[yh($I("shape",e,t,n),$I("minval",e,t,n),$I("maxval",e,t,n),$I("dtype",e,t,n))];case"Range":return[bh($I("start",e,t,n),$I("stop",e,t,n),$I("step",e,t,n),$I("dtype",e,t,n))];case"TruncatedNormal":{const r=$I("shape",e,t,n),s=$I("mean",e,t,n),a=$I("stdDev",e,t,n),i=$I("seed",e,t,n);return[sp(r,s,a,$I("dtype",e,t,n),i)]}case"Zeros":return[Uc($I("shape",e,t,n),$I("dtype",e,t,n))];case"ZerosLike":return[fl($I("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"dynamic":return(async(e,t,n)=>{switch(e.op){case"NonMaxSuppressionV5":{const{boxes:r,scores:s,maxOutputSize:a,iouThreshold:i,scoreThreshold:o,softNmsSigma:l}=NN(e,t,n),u=await Td.nonMaxSuppressionWithScoreAsync(r,s,a,i,o,l);return[u.selectedIndices,u.selectedScores]}case"NonMaxSuppressionV4":{const{boxes:r,scores:s,maxOutputSize:a,iouThreshold:i,scoreThreshold:o}=NN(e,t,n),l=$I("padToMaxOutputSize",e,t,n),u=await Td.nonMaxSuppressionPaddedAsync(r,s,a,i,o,l);return[u.selectedIndices,u.validOutputs]}case"NonMaxSuppressionV3":case"NonMaxSuppressionV2":{const{boxes:r,scores:s,maxOutputSize:a,iouThreshold:i,scoreThreshold:o}=NN(e,t,n);return[await Td.nonMaxSuppressionAsync(r,s,a,i,o)]}case"Where":{const r=Si($I("condition",e,t,n),"bool"),s=[await cp(r)];return r.dispose(),s}case"ListDiff":return Mh($I("x",e,t,n),$I("y",e,t,n));default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n);case"evaluation":return Xo((()=>((e,t,n)=>{switch(e.op){case"TopKV2":{const r=$I("x",e,t,n),s=$I("k",e,t,n),a=$I("sorted",e,t,n),i=rp(r,s,a);return[i.values,i.indices]}case"Unique":{const r=$I("x",e,t,n),s=ap(r);return[s.values,s.indices]}case"UniqueV2":{const r=$I("x",e,t,n),s=$I("axis",e,t,n),a=ap(r,s);return[a.values,a.indices]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"image":return Xo((()=>((e,t,n)=>{switch(e.op){case"ResizeBilinear":{const r=$I("images",e,t,n),s=$I("size",e,t,n),a=$I("alignCorners",e,t,n),i=$I("halfPixelCenters",e,t,n);return[Td.resizeBilinear(r,[s[0],s[1]],a,i)]}case"ResizeNearestNeighbor":{const r=$I("images",e,t,n),s=$I("size",e,t,n),a=$I("alignCorners",e,t,n),i=$I("halfPixelCenters",e,t,n);return[Td.resizeNearestNeighbor(r,[s[0],s[1]],a,i)]}case"CropAndResize":{const r=$I("image",e,t,n),s=$I("boxes",e,t,n),a=$I("boxInd",e,t,n),i=$I("cropSize",e,t,n),o=$I("method",e,t,n),l=$I("extrapolationValue",e,t,n);return[Td.cropAndResize(r,s,a,i,o,l)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"graph":return Xo((()=>((e,t,n)=>{switch(e.op){case"Const":return t[e.name];case"PlaceholderWithDefault":const r=$I("default",e,t,n);return[AI(e.name,t,n)||r];case"Placeholder":return[AI(e.name,t,n)];case"Identity":case"StopGradient":case"FakeQuantWithMinMaxVars":return[_I($I("x",e,t,n))];case"IdentityN":return $I("x",e,t,n).map((e=>_I(e)));case"Snapshot":return[_I($I("x",e,t,n))];case"Shape":return[Jh($I("x",e,t,n).shape,"int32")];case"ShapeN":return $I("x",e,t,n).map((e=>Jh(e.shape)));case"Size":return[kl($I("x",e,t,n).size,"int32")];case"Rank":return[kl($I("x",e,t,n).rank,"int32")];case"NoOp":return[kl(1)];case"Print":const s=$I("x",e,t,n),a=$I("data",e,t,n),i=$I("message",e,t,n),o=$I("summarize",e,t,n);console.warn("The graph has a tf.print() operation,usually used for debugging, which slows down performance."),console.log(i);for(let e=0;e((e,t,n)=>{switch(e.op){case"Equal":return[ju($I("a",e,t,n),$I("b",e,t,n))];case"NotEqual":return[Jc($I("a",e,t,n),$I("b",e,t,n))];case"Greater":return[ic($I("a",e,t,n),$I("b",e,t,n))];case"GreaterEqual":return[oc($I("a",e,t,n),$I("b",e,t,n))];case"Less":return[dc($I("a",e,t,n),$I("b",e,t,n))];case"LessEqual":return[fc($I("a",e,t,n),$I("b",e,t,n))];case"LogicalAnd":return[Dc($I("a",e,t,n),$I("b",e,t,n))];case"LogicalNot":return[_c($I("a",e,t,n))];case"LogicalOr":return[Oc($I("a",e,t,n),$I("b",e,t,n))];case"Select":case"SelectV2":return[qu($I("condition",e,t,n),$I("a",e,t,n),$I("b",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"matrices":return Xo((()=>((e,t,n)=>{switch(e.op){case"BatchMatMul":case"BatchMatMulV2":case"MatMul":return[Hi($I("a",e,t,n),$I("b",e,t,n),$I("transposeA",e,t,n),$I("transposeB",e,t,n))];case"Einsum":return[Yu($I("equation",e,t,n),...$I("tensors",e,t,n))];case"Transpose":return[qi($I("x",e,t,n),$I("perm",e,t,n))];case"_FusedMatMul":const[r,s]=$I("fusedOps",e,t,n),a="biasadd"===r,i="prelu"===s,o=$I("numArgs",e,t,n),l=$I("leakyreluAlpha",e,t,n);if(a){if(i&&2!==o)throw new Error("Fused MatMul with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!i&&1!==o)throw new Error("Fused MatMul with BiasAdd must have one extra argument: bias.")}const[u,c]=$I("args",e,t,n);return[Rp({a:$I("a",e,t,n),b:$I("b",e,t,n),transposeA:$I("transposeA",e,t,n),transposeB:$I("transposeB",e,t,n),bias:u,activation:s,preluActivationWeights:c,leakyreluAlpha:l})];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"normalization":return Xo((()=>((e,t,n)=>{switch(e.op){case"FusedBatchNorm":case"FusedBatchNormV2":case"FusedBatchNormV3":return[bu($I("x",e,t,n),$I("mean",e,t,n),$I("variance",e,t,n),$I("offset",e,t,n),$I("scale",e,t,n),$I("epsilon",e,t,n))];case"LRN":return[gc($I("x",e,t,n),$I("radius",e,t,n),$I("bias",e,t,n),$I("alpha",e,t,n),$I("beta",e,t,n))];case"Softmax":return[Bh($I("x",e,t,n))];case"LogSoftmax":return[Nc($I("x",e,t,n))];case"SparseToDense":return[gp($I("sparseIndices",e,t,n),$I("outputShape",e,t,n),$I("sparseValues",e,t,n),$I("defaultValue",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"reduction":return Xo((()=>((e,t,n)=>{switch(e.op){case"Max":{const r=$I("axis",e,t,n),s=$I("keepDims",e,t,n);return[kc($I("x",e,t,n),r,s)]}case"Mean":{const r=$I("axis",e,t,n),s=$I("keepDims",e,t,n);return[Vc($I("x",e,t,n),r,s)]}case"Min":{const r=$I("axis",e,t,n),s=$I("keepDims",e,t,n);return[Hc($I("x",e,t,n),r,s)]}case"Sum":{const r=$I("axis",e,t,n),s=$I("keepDims",e,t,n);return[Ic($I("x",e,t,n),r,s)]}case"All":{const r=$I("axis",e,t,n),s=$I("keepDims",e,t,n);return[Bl($I("x",e,t,n),r,s)]}case"Any":{const r=$I("axis",e,t,n),s=$I("keepDims",e,t,n);return[Vl($I("x",e,t,n),r,s)]}case"ArgMax":{const r=$I("axis",e,t,n);return[Ul($I("x",e,t,n),r)]}case"ArgMin":{const r=$I("axis",e,t,n);return[Wl($I("x",e,t,n),r)]}case"Prod":{const r=$I("axis",e,t,n),s=$I("keepDims",e,t,n);return[uh($I("x",e,t,n),r,s)]}case"Cumsum":{const r=$I("axis",e,t,n),s=$I("exclusive",e,t,n),a=$I("reverse",e,t,n);return[Bu($I("x",e,t,n),r,s,a)]}case"Bincount":const r=$I("x",e,t,n),s=$I("weights",e,t,n),a=$I("size",e,t,n);return[ku(r,s,a)];case"DenseBincount":{const r=$I("x",e,t,n),s=$I("weights",e,t,n),a=$I("size",e,t,n),i=$I("binaryOutput",e,t,n);return[Vu(r,s,a,i)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"slice_join":return Xo((()=>((e,t,n)=>{switch(e.op){case"ConcatV2":case"Concat":{const r=$I("n",e,t,n),s=$I("axis",e,t,n);let a=$I("tensors",e,t,n);return a=a.slice(0,r),[pu(a,s)]}case"Gather":{const r=$I("x",e,t,n),s=$I("indices",e,t,n);return[ac(r,Si(s,"int32"),0)]}case"GatherV2":{const r=$I("axis",e,t,n),s=$I("batchDims",e,t,n),a=$I("x",e,t,n),i=$I("indices",e,t,n);return[ac(a,Si(i,"int32"),r,s)]}case"Reverse":{const r=$I("dims",e,t,n),s=[];for(let e=0;e{const r=$I("axis",e,t,n),s=$I("tensors",e,t,n),a=s[0].shape,i=qh(s[0]).shape,o=s.map((e=>{const t=ue(e.shape,a);if(!t&&!ue(qh(e).shape,i))throw new Error("the input tensors shape does not match");return t?e:uu(e,a)}));return[Kh(o,r)]}));case"Unpack":{const r=$I("axis",e,t,n),s=$I("tensor",e,t,n);return op(s,r)}case"Tile":{const r=$I("reps",e,t,n);return[nc($I("x",e,t,n),r)]}case"Split":case"SplitV":{const r=$I("axis",e,t,n),s=$I("numOrSizeSplits",e,t,n),a=$I("x",e,t,n);return Gh(a,s,r)}case"ScatterNd":{const r=$I("indices",e,t,n),s=$I("values",e,t,n),a=$I("shape",e,t,n);return[mp(r,s,a)]}case"GatherNd":{const r=$I("x",e,t,n),s=$I("indices",e,t,n);return[yp(r,s)]}case"SparseToDense":{const r=$I("sparseIndices",e,t,n),s=$I("outputShape",e,t,n),a=$I("sparseValues",e,t,n),i=$I("defaultValue",e,t,n);return[gp(r,a,s,a.dtype===i.dtype?i:Si(i,a.dtype))]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"sparse":return Xo((()=>((e,t,n)=>{switch(e.op){case"SparseFillEmptyRows":{const{outputIndices:r,outputValues:s,emptyRowIndicator:a,reverseIndexMap:i}=$d.sparseFillEmptyRows($I("indices",e,t,n),$I("values",e,t,n),$I("denseShape",e,t,n),$I("defaultValue",e,t,n));return[r,s,a,i]}case"SparseReshape":{const{outputIndices:r,outputShape:s}=$d.sparseReshape($I("inputIndices",e,t,n),$I("inputShape",e,t,n),$I("newShape",e,t,n));return[r,s]}case"SparseSegmentMean":return[$d.sparseSegmentMean($I("data",e,t,n),$I("indices",e,t,n),$I("segmentIds",e,t,n))];case"SparseSegmentSum":return[$d.sparseSegmentSum($I("data",e,t,n),$I("indices",e,t,n),$I("segmentIds",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"spectral":return Xo((()=>((e,t,n)=>{switch(e.op){case"FFT":return[Vh($I("x",e,t,n))];case"IFFT":return[Uh($I("x",e,t,n))];case"RFFT":return[Hh($I("x",e,t,n))];case"IRFFT":return[Wh($I("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"string":return Xo((()=>((e,t,n)=>{switch(e.op){case"StringNGrams":{const{nGrams:r,nGramsSplits:s}=Ad.stringNGrams($I("data",e,t,n),$I("dataSplits",e,t,n),$I("separator",e,t,n),$I("nGramWidths",e,t,n),$I("leftPad",e,t,n),$I("rightPad",e,t,n),$I("padWidth",e,t,n),$I("preserveShortSequences",e,t,n));return[r,s]}case"StringSplit":{const{indices:r,values:s,shape:a}=Ad.stringSplit($I("input",e,t,n),$I("delimiter",e,t,n),$I("skipEmpty",e,t,n));return[r,s,a]}case"StringToHashBucketFast":return[Ad.stringToHashBucketFast($I("input",e,t,n),$I("numBuckets",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"transformation":return Xo((()=>((e,t,n)=>{switch(e.op){case"Cast":return[Si($I("x",e,t,n),$I("dtype",e,t,n))];case"ExpandDims":{const r=$I("axis",e,t,n);return[ec($I("x",e,t,n),r)]}case"Squeeze":{const r=$I("axis",e,t,n);return[qh($I("x",e,t,n),r)]}case"Reshape":return[uu($I("x",e,t,n),$I("shape",e,t,n))];case"MirrorPad":return[qc($I("x",e,t,n),$I("padding",e,t,n),$I("mode",e,t,n))];case"PadV2":case"Pad":return[th($I("x",e,t,n),$I("padding",e,t,n),$I("constantValue",e,t,n))];case"SpaceToBatchND":{const r=$I("blockShape",e,t,n),s=$I("paddings",e,t,n);return[ih($I("x",e,t,n),r,s)]}case"BatchToSpaceND":{const r=$I("blockShape",e,t,n),s=$I("crops",e,t,n);return[yu($I("x",e,t,n),r,s)]}case"DepthToSpace":{const r=$I("blockSize",e,t,n),s=$I("dataFormat",e,t,n).toUpperCase();return[Uu($I("x",e,t,n),r,s)]}case"BroadcastTo":return[Nu($I("x",e,t,n),$I("shape",e,t,n))];case"BroadcastArgs":return[Iu($I("s0",e,t,n),$I("s1",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"hash_table":return(async(e,t,n,r)=>{switch(e.op){case"HashTable":case"HashTableV2":{const s=$I("keyDType",e,t,n),a=$I("valueDType",e,t,n),i=new SN(s,a);return r.addHashTable(e.name,i),[i.handle]}case"LookupTableImport":case"LookupTableImportV2":{const s=$I("tableHandle",e,t,n,r),a=$I("keys",e,t,n),i=$I("values",e,t,n),o=r.getHashTableById(s.id);return[await o.import(a,i)]}case"LookupTableFind":case"LookupTableFindV2":{const s=$I("tableHandle",e,t,n,r),a=$I("keys",e,t,n),i=$I("defaultValue",e,t,n),o=r.getHashTableById(s.id);return[await o.find(a,i)]}case"LookupTableSize":case"LookupTableSizeV2":{const s=$I("tableHandle",e,t,n,r);return[r.getHashTableById(s.id).tensorSize()]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n,r);case"custom":const s=CI(e.op);if(s&&s.customExecutor)return s.customExecutor(new gN(e,t,n));throw TypeError(`Custom op ${e.op} is not registered.`);default:throw TypeError(`Unknown op '${e.op}'. File an issue at https://github.com/tensorflow/tfjs/issues so we can add it, or register a custom execution with tf.registerOp()`)}})(e,t,n);return Ue(s)?s.then((e=>[].concat(e))):[].concat(s)}class CN{constructor(e={},t={},n={},r={}){this.weightMap=e,this.tensorArrayMap=t,this.tensorListMap=n,this.functionMap=r,this.rootContext={id:0,frameName:"",iterationId:0},this.contexts=[this.rootContext],this.lastId=0,this.generateCurrentContextIds()}newFrame(e,t){return{id:e,frameName:t,iterationId:0}}set currentContext(e){this.contexts!==e&&(this.contexts=e,this.generateCurrentContextIds())}get currentContext(){return this.contexts}get currentContextId(){return this._currentContextIds[0]}get currentContextIds(){return this._currentContextIds}generateCurrentContextIds(){const e=[];for(let t=0;t0===e.id&&0===e.iterationId?"":`${e.frameName}-${e.iterationId}`)).join("/"):""}enterFrame(e){this.contexts&&(this.lastId++,this.contexts=this.contexts.slice(),this.contexts.push(this.newFrame(this.lastId,e)),this._currentContextIds.unshift(this.contextIdforContexts(this.contexts)))}exitFrame(){if(!(this.contexts&&this.contexts.length>1))throw new Error("Cannot exit frame, the context is empty");this.contexts=this.contexts.slice(),this.contexts.splice(-1),this.currentContextIds.shift()}nextIteration(){if(!(this.contexts&&this.contexts.length>0))throw new Error("Cannot increase frame iteration, the context is empty");{this.contexts=this.contexts.slice(),this.lastId++;const e=Object.assign({},this.contexts[this.contexts.length-1]);e.iterationId+=1,e.id=this.lastId,this.contexts.splice(-1,1,e),this._currentContextIds.splice(0,1,this.contextIdforContexts(this.contexts))}}getWeight(e){return this.weightMap[e]}addTensorArray(e){this.tensorArrayMap[e.id]=e}getTensorArray(e){return this.tensorArrayMap[e]}addTensorList(e){this.tensorListMap[e.id]=e}getTensorList(e){return this.tensorListMap[e]}dispose(e){for(const t in this.tensorArrayMap)this.tensorArrayMap[t].clearAndClose(e);for(const t in this.tensorListMap)this.tensorListMap[t].clearAndClose(e)}}function EN(e,t,n,r){const s=new Set,a=[];let i=null,o=null;const l=new Set,u=Object.keys(e).map((e=>FI(e)[0]));let c=[];null!=r&&(c=r.map((e=>FI(e.name)[0])));const h=[...t];for(;h.length>0;){const e=h.pop();(MN(e)||FN(e)||DN(e))&&null==i&&(i=e,o=i.children.map((e=>e.name)).filter((e=>s.has(e)))),s.add(e.name),null==n[e.name]&&-1===u.indexOf(e.name)&&-1===c.indexOf(e.name)&&(0!==e.inputs.length?e.inputs.forEach((e=>{l.has(e.name)||(l.add(e.name),h.push(e))})):a.push(e.name))}return{inputs:e,outputs:t,usedNodes:s,missingInputs:a,dynamicNode:i,syncInputs:o}}const $N=["Switch","Merge","Enter","Exit","NextIteration","StatelessIf","StatelessWhile","if","While"],AN=["NonMaxSuppressionV2","NonMaxSuppressionV3","NonMaxSuppressionV5","Where"],RN=["HashTable","HashTableV2","LookupTableImport","LookupTableImportV2","LookupTableFind","LookupTableFindV2","LookupTableSize","LookupTableSizeV2"];function MN(e){return $N.indexOf(e.op)>=0}function FN(e){return AN.indexOf(e.op)>=0}function DN(e){return RN.indexOf(e.op)>=0}class _N{constructor(e,t){this.graph=e,this.parent=t,this.compiledMap=new Map,this._weightMap={},this.SEPERATOR=",",this._functions={},this._functionExecutorMap={},this.intermediateTensors={},this.keepTensorForDebug=!1,this._outputs=e.outputs,this._inputs=e.inputs,this._initNodes=e.initNodes,this._signature=e.signature,this._functions=e.functions,null!=e.functions&&Object.keys(e.functions).forEach((t=>{this._functionExecutorMap[t]=new _N(e.functions[t],this)}))}get weightIds(){return this.parent?this.parent.weightIds:this._weightIds}get functionExecutorMap(){return this.parent?this.parent.functionExecutorMap:this._functionExecutorMap}get weightMap(){return this.parent?this.parent.weightMap:this._weightMap}set weightMap(e){const t=Object.keys(e).map((t=>e[t].map((e=>e.id))));this._weightIds=[].concat(...t),this._weightMap=e}set resourceManager(e){this._resourceManager=e}get inputs(){return this._inputs.map((e=>({name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0})))}get outputs(){return this._outputs.map((e=>({name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0})))}get inputNodes(){return this._inputs.map((e=>e.signatureKey||e.name))}get outputNodes(){return this._outputs.map((e=>{const t=e.signatureKey||e.name;return e.defaultOutput?`${t}:${e.defaultOutput}`:t}))}get functions(){return Object.keys(this._functions).reduce(((e,t)=>(e[t]=this._functions[t].signature,e)),{})}getCompilationKey(e,t){const n=e.map((e=>e.name)).sort(),r=t.map((e=>e.name)).sort();return n.join(this.SEPERATOR)+"--"+r.join(this.SEPERATOR)}compile(e,t){const n=EN(e,t,this.weightMap,this._initNodes),{missingInputs:r,dynamicNode:s,syncInputs:a}=n;if(null!=s)throw new Error(`This execution contains the node '${s.name}', which has the dynamic op '${s.op}'. Please use model.executeAsync() instead. Alternatively, to avoid the dynamic ops, specify the inputs [${a}]`);if(r.length>0){const n=t.map((e=>e.name)),s=Object.keys(e);throw new Error(`Cannot compute the outputs [${n}] from the provided inputs [${s}]. Missing the following inputs: [${r}]`)}return function(e,t,n){const{usedNodes:r,inputs:s}=n,a=[],i=Object.keys(s).map((e=>FI(e)[0])).map((t=>e.nodes[t])),o=e.initNodes;i.forEach((e=>{r.has(e.name)&&a.push(e)})),e.weights.forEach((e=>{r.has(e.name)&&a.push(e)})),null!=o&&o.forEach((e=>{r.has(e.name)&&a.push(e)}));const l=new Set,u=[];for(;a.length>0;){const e=a.pop();l.add(e.name),t[e.name]||u.push(e),e.children.forEach((e=>{!l.has(e.name)&&r.has(e.name)&&e.inputs.every((e=>l.has(e.name)))&&a.push(e)}))}return u}(this.graph,this.weightMap,n)}execute(e,t){e=this.mapInputs(e);const n=Object.keys(e).sort();this.checkInputs(e),this.checkInputShapeAndType(e),t=this.mapOutputs(t),this.checkOutputs(t);const r=n.map((e=>this.graph.nodes[FI(e)[0]])),s=t.map((e=>FI(e)[0]));let a=s.map((e=>this.graph.nodes[e]));this.resetIntermediateTensors(),0===a.length&&(a=this._outputs);const i=this.getCompilationKey(r,a);let o=this.compiledMap.get(i);null==o&&(o=this.compile(e,a),this.compiledMap.set(i,o));const l={},u={};return Xo((()=>{const n=new CN(this.weightMap,l,u,this.functionExecutorMap),r=Object.assign({},this.weightMap);Object.keys(e).forEach((t=>{const[n,s]=FI(t),a=[];a[s]=e[t],r[n]=a}));const a=this.getFrozenTensorIds(r),i={};for(let e=0;eAI(e,r,n)))}))}getFrozenTensorIds(e){const t=[].concat.apply([],Object.keys(e).map((t=>e[t])).map((e=>e.map((e=>e.id)))));return new Set(t)}checkTensorForDisposal(e,t,n,r,s,a,i){"control"!==t.category&&-1===a.indexOf(e)&&(n[e].forEach((e=>{null!=e&&(i[e.id]=(i[e.id]||0)+t.children.length)})),t.inputs.forEach((e=>{if("control"!==e.category){const a=function(e,t,n){return t[MI(e,n.currentContextId)]}(e.name,n,r);null!=a&&a.forEach((e=>{if(e&&!e.kept&&!s.has(e.id)){const n=i[e.id];if(1===n){if(this.keepTensorForDebug){const[n,s]=RI(t.name,r);this.intermediateTensors[n]||(this.intermediateTensors[n]=[]),this.intermediateTensors[n][s]=e}else e.dispose();delete i[e.id]}else null!=n&&i[e.id]--}}))}})))}async executeAsync(e,t){return this._executeAsync(e,t)}disposeIntermediateTensors(){this.intermediateTensors&&(Object.keys(this.intermediateTensors).forEach((e=>this.intermediateTensors[e].forEach((e=>e.dispose())))),this.disposeTensorsMap())}disposeTensorsMap(){this.tensorsMap&&Object.keys(this.tensorsMap).forEach((e=>{this.tensorsMap[e].forEach((e=>{!e||e.kept||e.isDisposed||this.keepIds.has(e.id)||e.dispose()}))}))}getIntermediateTensors(){return this.tensorsMap}resetIntermediateTensors(){for(const e in this.intermediateTensors)this.intermediateTensors[e].forEach((e=>e.dispose())),delete this.intermediateTensors[e]}async _executeAsync(e,t,n=!1,r={},s={}){n||(e=this.mapInputs(e),this.checkInputs(e),this.checkInputShapeAndType(e),t=this.mapOutputs(t),this.checkOutputs(t));try{this.keepTensorForDebug=He().getBool("KEEP_INTERMEDIATE_TENSORS")}catch(e){console.warn(e.message)}this.resetIntermediateTensors();const a=new CN(this.weightMap,r,s,this.functionExecutorMap);this.tensorsMap=await this.executeWithControlFlow(e,a,t,n);const i=t.map((e=>AI(e,this.tensorsMap,a))),o=i.map((e=>e.id)),l=Object.keys(e).map((t=>e[t].id));return this.keepIds=new Set([...o,...l,...this.weightIds]),this.keepTensorForDebug||this.disposeTensorsMap(),null==this.parent&&a.dispose(this.keepIds),i}async executeFunctionAsync(e,t,n){const r=e.reduce(((e,t,n)=>(e[this.inputs[n].name]=t,e)),{});return this._executeAsync(r,this.outputNodes,!0,t,n)}async executeWithControlFlow(e,t,n,r){const s=Object.keys(e),a=s.map((e=>this.graph.nodes[FI(e)[0]])),i=n.map((e=>FI(e)[0]));let o=i.map((e=>this.graph.nodes[e]));0===o.length&&(o=this._outputs);const{usedNodes:l,missingInputs:u,dynamicNode:c,syncInputs:h}=EN(e,o,this.weightMap,this._initNodes),p=[...a,...this.graph.weights,...this._initNodes||[]].map((e=>({node:e,contexts:t.currentContext}))),d=Object.assign({},this.weightMap);Object.keys(e).forEach((t=>{const[n,r]=FI(t),s=[];s[r]=e[t],d[n]=s}));const f={},m=this.getFrozenTensorIds(d),g={};for(;p.length>0;){const e=this.processStack(a,p,t,d,g,m,i,f,l);await Promise.all(e)}null!=c||r||console.warn("This model execution did not contain any nodes with control flow or dynamic output shapes. You can use model.execute() instead.");const y=o.filter((e=>!MN(e)&&!AI(e.name,d,t))).map((e=>e.name));if(y.length>0){let e="";throw null!=c&&(e=`Alternatively, to avoid the dynamic ops, use model.execute() and specify the inputs [${h}]`),new Error(`Cannot compute the outputs [${y}] from the provided inputs [${s}]. Consider providing the following inputs: [${u}]. ${e}`)}return d}processStack(e,t,n,r,s,a,i,o,l){const u=[];for(;t.length>0;){const e=t.pop();n.currentContext=e.contexts;let c="";if("Enter"===e.node.op&&$I("isConstant",e.node,r,n)&&([c]=RI(e.node.name,n)),null==r[e.node.name]){const h=TN(e.node,r,n,this._resourceManager);c||([c]=RI(e.node.name,n));const p=n.currentContext;Ue(h)?u.push(h.then((u=>(r[c]=u,n.currentContext=p,this.checkTensorForDisposal(c,e.node,r,n,a,i,o),this.processChildNodes(e.node,t,n,r,s,l),u)))):(r[c]=h,this.checkTensorForDisposal(c,e.node,r,n,a,i,o),this.processChildNodes(e.node,t,n,r,s,l))}else this.processChildNodes(e.node,t,n,r,s,l)}return u}processChildNodes(e,t,n,r,s,a){e.children.forEach((e=>{const[i]=RI(e.name,n);!s[i]&&a.has(e.name)&&("Merge"===e.op?e.inputNames.some((e=>!!AI(e,r,n)))&&(s[i]=!0,t.push({contexts:n.currentContext,node:e})):e.inputNames.every((e=>!!AI(e,r,n)))&&(s[i]=!0,t.push({contexts:n.currentContext,node:e})))}))}dispose(){Object.keys(this.weightMap).forEach((e=>this.weightMap[e].forEach((e=>e.dispose()))))}checkInputShapeAndType(e){Object.keys(e).forEach((t=>{const n=e[t],[r]=FI(t),s=this.graph.nodes[r];if(s.attrParams.shape&&s.attrParams.shape.value){const e=s.attrParams.shape.value;re(e.length===n.shape.length&&n.shape.every(((t,n)=>-1===e[n]||e[n]===t)),(()=>`The shape of dict['${s.name}'] provided in model.execute(dict) must be [${e}], but was [${n.shape}]`))}s.attrParams.dtype&&s.attrParams.dtype.value&&re(n.dtype===s.attrParams.dtype.value,(()=>`The dtype of dict['${s.name}'] provided in model.execute(dict) must be ${s.attrParams.dtype.value}, but was ${n.dtype}`))}))}mapInputs(e){const t={};for(const n in e)null!=this._signature&&null!=this._signature.inputs&&null!=this._signature.inputs[n]?t[this._signature.inputs[n].name]=e[n]:t[n]=e[n];return t}checkInputs(e){const t=Object.keys(e).filter((e=>{const[t]=FI(e);return null==this.graph.nodes[t]}));if(t.length>0)throw new Error(`The dict provided in model.execute(dict) has keys: [${t}] that are not part of graph`)}mapOutputs(e){return e.map((e=>null!=this._signature&&null!=this._signature.outputs&&null!=this._signature.outputs[e]?this._signature.outputs[e].name:e),{})}checkOutputs(e){e.forEach((e=>{const[t]=FI(e);if(!this.graph.nodes[t])throw new Error(`The output '${e}' is not found in the graph`)}))}}class ON{constructor(e={},t={}){this.hashTableNameToHandle=e,this.hashTableMap=t}addHashTable(e,t){this.hashTableNameToHandle[e]=t.handle,this.hashTableMap[t.id]=t}getHashTableHandleByName(e){return this.hashTableNameToHandle[e]}getHashTableById(e){return this.hashTableMap[e]}dispose(){for(const e in this.hashTableMap)this.hashTableMap[e].clearAndClose(),delete this.hashTableMap[e];for(const e in this.hashTableNameToHandle)this.hashTableNameToHandle[e].dispose(),delete this.hashTableNameToHandle[e]}}class LN{constructor(e,t={}){this.modelUrl=e,this.loadOptions=t,this.version="n/a",null==t&&(this.loadOptions={}),this.resourceManager=new ON}get modelVersion(){return this.version}get inputNodes(){return this.executor.inputNodes}get outputNodes(){return this.executor.outputNodes}get inputs(){return this.executor.inputs}get outputs(){return this.executor.outputs}get weights(){return this.executor.weightMap}get metadata(){return this.artifacts.userDefinedMetadata}get modelSignature(){return this.signature}findIOHandler(){const e=this.modelUrl;if(null!=e.load)this.handler=e;else if(null!=this.loadOptions.requestInit)this.handler=Bi(e,this.loadOptions);else{const t=ja(e,this.loadOptions);if(0===t.length)t.push(Bi(e,this.loadOptions));else if(t.length>1)throw new Error(`Found more than one (${t.length}) load handlers for URL '${[e]}'`);this.handler=t[0]}}async load(){if(this.findIOHandler(),null==this.handler.load)throw new Error("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");const e=await this.handler.load();return this.loadSync(e)}loadSync(e){this.artifacts=e;const t=this.artifacts.modelTopology;let n;n=null!=this.artifacts.userDefinedMetadata&&null!=this.artifacts.userDefinedMetadata.signature?this.artifacts.userDefinedMetadata.signature:this.artifacts.signature,this.signature=n,this.version=`${t.versions.producer}.${t.versions.minConsumer}`;const r=Ma(this.artifacts.weightData,this.artifacts.weightSpecs);if(this.executor=new _N(tN.Instance.transformGraph(t,this.signature)),this.executor.weightMap=this.convertTensorMapToTensorsMap(r),this.executor.resourceManager=this.resourceManager,null!=e.modelInitializer&&null!=e.modelInitializer.node){const t=tN.Instance.transformGraph(e.modelInitializer);this.initializer=new _N(t),this.initializer.weightMap=this.executor.weightMap,this.initializer.resourceManager=this.resourceManager,this.initializer.executeAsync({},[])}return!0}async save(e,t){if("string"==typeof e){const t=Ha(e);if(0===t.length)throw new Error(`Cannot find any save handlers for URL '${e}'`);if(t.length>1)throw new Error(`Found more than one (${t.length}) save handlers for URL '${e}'`);e=t[0]}if(null==e.save)throw new Error("GraphModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");return e.save(this.artifacts)}predict(e,t){return this.execute(e,this.outputNodes)}normalizeInputs(e){if(!(e instanceof qs||Array.isArray(e)))return e;if((e=Array.isArray(e)?e:[e]).length!==this.inputNodes.length)throw new Error(`Input tensor count mismatch,the graph model has ${this.inputNodes.length} placeholders, while there are ${e.length} input tensors.`);return this.inputNodes.reduce(((t,n,r)=>(t[n]=e[r],t)),{})}normalizeOutputs(e){return e=e||this.outputNodes,Array.isArray(e)?e:[e]}execute(e,t){e=this.normalizeInputs(e),t=this.normalizeOutputs(t);const n=this.executor.execute(e,t);return n.length>1?n:n[0]}async executeAsync(e,t){e=this.normalizeInputs(e),t=this.normalizeOutputs(t);const n=await this.executor.executeAsync(e,t);return n.length>1?n:n[0]}getIntermediateTensors(){return this.executor.getIntermediateTensors()}disposeIntermediateTensors(){this.executor.disposeIntermediateTensors()}convertTensorMapToTensorsMap(e){return Object.keys(e).reduce(((t,n)=>(t[n]=[e[n]],t)),{})}dispose(){this.executor.dispose(),this.initializer&&this.initializer.dispose(),this.resourceManager.dispose()}}async function zN(e,t={}){if(null==e)throw new Error("modelUrl in loadGraphModel() cannot be null. Please provide a url or an IOHandler that loads the model");null==t&&(t={}),t.fromTFHub&&null==e.load&&(e.endsWith("/")||(e+="/"),e=`${e}model.json?tfjs-format=file`);const n=new LN(e,t);return await n.load(),n}const PN="3.13.0";function BN(e,t,n=new Map,r=new Set){if(null==e)return null;if("function"==typeof Blob&&e instanceof Blob)return e.slice();if(r.has(e))throw new Error("Circular references are not supported.");if(n.has(e))return n.get(e);const s=t(e);if(s.recurse&&null!==s.value)throw new Error("A deep map function may not return both a value and recurse=true.");if(s.recurse){if(HN(e)){const s=Array.isArray(e)?[]:{};r.add(e);for(const a in e){const i=BN(e[a],t,n,r);s[a]=i}return r.delete(e),e.__proto__&&(s.__proto__=e.__proto__),s}throw new Error(`Can't recurse into non-iterable type: ${e}`)}return n.set(e,s.value),s.value}function VN(e,t=WN){return UN(e,t)}function UN(e,t,n=new Set){const r=e[0];if(n.has(r))throw new Error("Circular references are not supported.");const s=t(e);if(s.recurse&&null!==s.value)throw new Error("A deep zip function may not return both a value and recurse=true.");if(s.recurse){if(HN(r)){const s=Array.isArray(r)?[]:{};n.add(r);for(const a in r){const r=UN(e.map((e=>e[a])),t,n);s[a]=r}return n.delete(r),s}throw new Error(`Can't recurse into non-iterable type: ${r}`)}return s.value}function WN(e){return null===e?null:HN(e[0])?{value:null,recurse:!0}:{value:e,recurse:!1}}async function GN(e,t){const n=new Map;BN(e,t,n);for(const e of Array.from(n.keys())){const t=n.get(e);if(Ue(t)){const r=await t;n.set(e,r)}}return BN(e,t,n)}function HN(e){let t=!1;if(He().get("IS_BROWSER"))t=e instanceof TextDecoder;else{const{StringDecoder:r}=n(4589);t=e instanceof r}return null!=e&&!ArrayBuffer.isView(e)&&(Array.isArray(e)||"object"==typeof e&&!(e instanceof qs)&&!(e instanceof Promise)&&!t)}function jN(e){return e instanceof qs?{value:e.clone(),recurse:!1}:HN(e)?{value:null,recurse:!0}:{value:e,recurse:!1}}class qN{constructor(e){if(this.capacity=e,this.begin=0,this.end=0,null==e)throw new RangeError("Can't create a ring buffer of unknown capacity.");if(e<1)throw new RangeError("Can't create ring buffer of capacity < 1.");this.data=new Array(e),this.doubledCapacity=2*e}wrap(e){for(;e<0;)e+=this.doubledCapacity;return e%this.doubledCapacity}get(e){if(e<0)throw new RangeError("Can't get item at a negative index.");return this.data[e%this.capacity]}set(e,t){if(e<0)throw new RangeError("Can't set item at a negative index.");this.data[e%this.capacity]=t}length(){let e=this.end-this.begin;return e<0&&(e=this.doubledCapacity+e),e}isFull(){return this.length()===this.capacity}isEmpty(){return 0===this.length()}push(e){if(this.isFull())throw new RangeError("Ring buffer is full.");this.set(this.end,e),this.end=this.wrap(this.end+1)}pushAll(e){for(const t of e)this.push(t)}pop(){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");this.end=this.wrap(this.end-1);const e=this.get(this.end);return this.set(this.end,void 0),e}unshift(e){if(this.isFull())throw new RangeError("Ring buffer is full.");this.begin=this.wrap(this.begin-1),this.set(this.begin,e)}shift(){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");const e=this.get(this.begin);return this.set(this.begin,void 0),this.begin=this.wrap(this.begin+1),e}shuffleExcise(e){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");const t=this.wrap(this.begin+e),n=this.get(t);return this.set(t,this.pop()),n}}class KN extends qN{constructor(){super(KN.INITIAL_CAPACITY)}isFull(){return!1}push(e){super.isFull()&&this.expand(),super.push(e)}unshift(e){super.isFull()&&this.expand(),super.unshift(e)}expand(){const e=2*this.capacity,t=new Array(e),n=this.length();for(let e=0;e!0===e))}rowMajorBatch(e,t=!0){return new rS(this,e,t)}columnMajorBatch(e,t=!0,n=WN){return this.rowMajorBatch(e,t).map((e=>VN(e,n)))}concatenate(e,t){return new cS(XN([this,e]),t)}take(e){return e<0||null==e?this:new nS(this,e)}skip(e){return e<0||null==e?this:new tS(this,e)}prefetch(e){return new dS(this,e)}shuffle(e,t){return new fS(this,e,t)}serial(){return new eS(this)}}class JN extends ZN{constructor(e){super(),this.items=e,this.trav=0}summary(){return`Array of ${this.items.length} items`}async next(){if(this.trav>=this.items.length)return{value:null,done:!0};const e=this.items[this.trav];return this.trav++,{value:(t=e,function(e,t){return BN(e,t)}(t,jN)),done:!1};var t}}class QN extends ZN{constructor(e){super(),this.nextFn=e}summary(){return"Function call"}async next(){try{return this.nextFn()}catch(e){throw e.message=`Error thrown while iterating through a dataset: ${e.message}`,e}}}class eS extends ZN{constructor(e){super(),this.upstream=e,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> Serial`}async next(){return this.lastRead=this.lastRead.then((()=>this.serialNext())),this.lastRead}async serialNext(){return this.upstream.next()}}class tS extends ZN{constructor(e,t){super(),this.upstream=e,this.maxCount=t,this.count=0,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> Skip`}async next(){return this.lastRead=this.lastRead.then((()=>this.serialNext())),this.lastRead}async serialNext(){for(;this.count++ Take`}async next(){return this.count++>=this.maxCount?{value:null,done:!0}:this.upstream.next()}}class rS extends ZN{constructor(e,t,n=!0){super(),this.upstream=e,this.batchSize=t,this.enableSmallLastBatch=n,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> RowMajorBatch`}async next(){return this.lastRead=this.lastRead.then((()=>this.serialNext())),this.lastRead}async serialNext(){const e=[];for(;e.length0?{value:e,done:!1}:{value:null,done:!0};e.push(t.value)}return{value:e,done:!1}}}class sS extends ZN{constructor(e,t){super(),this.upstream=e,this.predicate=t,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> Filter`}async next(){return this.lastRead=this.lastRead.then((()=>this.serialNext())),this.lastRead}async serialNext(){for(;;){const e=await this.upstream.next();if(e.done||this.predicate(e.value))return e;Yo(e.value)}}}class aS extends ZN{constructor(e,t){super(),this.upstream=e,this.transform=t}summary(){return`${this.upstream.summary()} -> Map`}async next(){const e=await this.upstream.next();if(e.done)return{value:null,done:!0};const t=oa(e.value),n=this.transform(e.value),r=oa(n);for(const e of t)ia(e,r)||e.dispose();return{value:n,done:!1}}}class iS extends ZN{constructor(e,t){super(),this.upstream=e,this.handler=t,this.count=0,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> handleErrors`}async next(){return this.lastRead=this.lastRead.then((()=>this.serialNext())),this.lastRead}async serialNext(){for(;;)try{return await this.upstream.next()}catch(e){if(!this.handler(e))return{value:null,done:!0}}}}class oS extends ZN{constructor(e,t){super(),this.upstream=e,this.transform=t}summary(){return`${this.upstream.summary()} -> AsyncMap`}async next(){const e=await this.upstream.next();if(e.done)return{value:null,done:!0};const t=oa(e.value),n=await this.transform(e.value),r=oa(n);for(const e of t)ia(e,r)||e.dispose();return{value:n,done:!1}}}class lS extends ZN{constructor(){super(),this.outputQueue=new KN,this.lastRead=Promise.resolve({value:null,done:!1})}async next(){return this.lastRead=this.lastRead.then((()=>this.serialNext())),this.lastRead}async serialNext(){for(;0===this.outputQueue.length();)if(!await this.pump())return{value:null,done:!0};return{value:this.outputQueue.shift(),done:!1}}}class uS extends lS{constructor(e,t){super(),this.upstream=e,this.transform=t}summary(){return`${this.upstream.summary()} -> Flatmap`}async pump(){const e=await this.upstream.next();if(e.done)return!1;const t=oa(e.value),n=this.transform(e.value),r=oa(n);this.outputQueue.pushAll(n);for(const e of t)ia(e,r)||e.dispose();return!0}}class cS extends ZN{constructor(e,t){super(),this.baseErrorHandler=t,this.lastRead=null,this.iterator=null,this.moreIterators=e}summary(){return"TODO: fill in upstream of chained summaries -> Chained"}async next(){return this.lastRead=this.readFromChain(this.lastRead),this.lastRead}async readFromChain(e){if(await e,null==this.iterator){const e=await this.moreIterators.next();if(e.done)return{value:null,done:!0};this.iterator=e.value,null!=this.baseErrorHandler&&(this.iterator=this.iterator.handleErrors(this.baseErrorHandler))}const t=await this.iterator.next();return t.done?(this.iterator=null,this.readFromChain(e)):t}}var hS;!function(e){e[e.FAIL=0]="FAIL",e[e.SHORTEST=1]="SHORTEST",e[e.LONGEST=2]="LONGEST"}(hS||(hS={}));class pS extends ZN{constructor(e,t=hS.FAIL){super(),this.iterators=e,this.mismatchMode=t,this.count=0,this.currentPromise=null}summary(){return"{TODO: fill in upstream of zip summaries} -> Zip"}async nextState(e){await e;let t=0,n=0;const r=await GN(this.iterators,(function(e){return e instanceof ZN?{value:e.next().then((e=>(t++,e.done&&n++,e.value))),recurse:!1}:{value:null,recurse:!0}}));if(t===n)return{value:null,done:!0};if(n>0)switch(this.mismatchMode){case hS.FAIL:throw new Error(`Zipped streams should have the same length. Mismatched at element ${this.count}.`);case hS.SHORTEST:return{value:null,done:!0};case hS.LONGEST:}return this.count++,{value:r,done:!1}}async next(){return this.currentPromise=this.nextState(this.currentPromise),this.currentPromise}}class dS extends ZN{constructor(e,t){super(),this.upstream=e,this.bufferSize=t,this.buffer=new qN(t)}summary(){return`${this.upstream.summary()} -> Prefetch`}refill(){for(;!this.buffer.isFull();){const e=this.upstream.next();this.buffer.push(e)}}next(){return this.refill(),this.buffer.shift()}}class fS extends dS{constructor(e,t,n){super(e,t),this.upstream=e,this.windowSize=t,this.upstreamExhausted=!1,this.random=hh.alea(n||Rs().toString()),this.lastRead=Promise.resolve({value:null,done:!1})}async next(){return this.lastRead=this.lastRead.then((()=>this.serialNext())),this.lastRead}randomInt(e){return Math.floor(this.random()*e)}chooseIndex(){return this.randomInt(this.buffer.length())}async serialNext(){for(this.upstreamExhausted||this.refill();!this.buffer.isEmpty();){const e=this.chooseIndex(),t=await this.buffer.shuffleExcise(e);if(!t.done)return this.refill(),t;this.upstreamExhausted=!0}return{value:null,done:!0}}}class mS{constructor(){this.size=null}batch(e,t=!0){const n=this;let r;return re(e>0,(()=>`batchSize needs to be positive, but it is\n ${e}`)),r=this.size===1/0||null==this.size?this.size:t?Math.ceil(this.size/e):Math.floor(this.size/e),gS((async()=>(await n.iterator()).columnMajorBatch(e,t,xS)),r)}concatenate(e){const t=this;let n;return n=this.size===1/0||e.size===1/0?1/0:null!=this.size&&null!=e.size?this.size+e.size:null,gS((async()=>(await t.iterator()).concatenate(await e.iterator())),n)}filter(e){const t=this;let n;return n=this.size===1/0?1/0:null,gS((async()=>(await t.iterator()).filter((t=>Xo((()=>e(t)))))),n)}async forEachAsync(e){return(await this.iterator()).forEachAsync(e)}map(e){const t=this;return gS((async()=>(await t.iterator()).map((t=>Xo((()=>e(t)))))),this.size)}mapAsync(e){const t=this;return gS((async()=>(await t.iterator()).mapAsync(e)),this.size)}prefetch(e){if(null==e)throw new RangeError("`Dataset.prefetch()` requires bufferSize to be specified.");const t=this;return gS((async()=>(await t.iterator()).prefetch(e)),this.size)}repeat(e){const t=this;let n;return n=null!=this.size&&e>0?this.size*e:0===e?0:null!=this.size&&(void 0===e||e<0)?1/0:null,gS((async()=>{return n=YN((async()=>({value:await t.iterator(),done:!1}))).take(e),new cS(n,r);var n,r}),n)}skip(e){const t=this;let n;return n=null!=this.size&&e>=0&&this.size>=e?this.size-e:null!=this.size&&(this.size(await t.iterator()).skip(e)),n)}shuffle(e,t,n=!0){if(null==e||e<0)throw null==this.size?new RangeError("`Dataset.shuffle()` requires bufferSize to be specified."):new RangeError(`\`Dataset.shuffle()\` requires bufferSize to be specified. If your data fits in main memory (for regular JS objects), and/or GPU memory (for \`tf.Tensor\`s), consider setting bufferSize to the dataset size (${this.size} elements)`);const r=this,s=hh.alea(t||Rs().toString());return gS((async()=>{let t=s.int32();return n&&(t+=s.int32()),(await r.iterator()).shuffle(e,t.toString())}),this.size)}take(e){const t=this;let n;return n=null!=this.size&&this.size>e?e:null!=this.size&&this.size<=e?this.size:null,gS((async()=>(await t.iterator()).take(e)),n)}async toArray(){if(this.size===1/0)throw new Error("Can not convert infinite data stream to array.");return(await this.iterator()).toArray()}async toArrayForTest(){if(this.size===1/0)throw new Error("Can not convert infinite data stream to array.");return(await this.iterator()).toArrayForTest()}}function gS(e,t=null){return new class extends mS{constructor(){super(...arguments),this.size=t}async iterator(){return e()}}}function yS(e){return gS((async()=>XN(e)),e.length)}function bS(e){if(!HN(e))throw new Error("The argument to zip() must be an object or array.");let t;if(Array.isArray(e))for(let n=0;nfunction(e,t=hS.FAIL){return new pS(e,t)}(await GN(e,(e=>{if(e instanceof mS)return{value:e.iterator(),recurse:!1};if(HN(e))return{value:null,recurse:!0};throw new Error("Leaves of the structure passed to zip() must be Datasets, not primitives.")})),hS.SHORTEST)),t)}function xS(e){if(null===e)return null;return null==(t=e[0])||null===(n=t)||"object"!=typeof n&&"function"!=typeof n||Array.isArray(t)||"object"==typeof t&&t instanceof qs||Ne(t)?{value:function(e){if(0===e.length)throw new Error("Can't make a batch of zero elements.");return e[0]instanceof qs?Kh(e):$a(e)}(e),recurse:!1}:{value:null,recurse:!0};var t,n}mS.MAX_BUFFER_SIZE=1e4;class wS extends mS{constructor(e){super(),this.input=e}async iterator(){return(await this.input.iterator()).decodeUTF8().split("\n").map((e=>(e.endsWith("\r")&&(e=e.slice(0,-1)),e)))}}const vS='"',kS=Symbol("out"),IS=Symbol("field"),NS=Symbol("quote"),SS=Symbol("quoteafterquote"),TS=Symbol("quoteinquote");class CS extends mS{constructor(e,t){super(),this.input=e,this.hasHeader=!0,this.fullColumnNames=null,this.columnNamesValidated=!1,this.columnConfigs=null,this.configuredColumnsOnly=!1,this.delimiter=",",this.delimWhitespace=!1,this.base=new wS(e),t||(t={}),this.hasHeader=!1!==t.hasHeader,this.fullColumnNames=t.columnNames,this.columnConfigs=t.columnConfigs,this.configuredColumnsOnly=t.configuredColumnsOnly,t.delimWhitespace?(re(null==t.delimiter,(()=>"Delimiter should not be provided when delimWhitespace is true.")),this.delimWhitespace=!0,this.delimiter=" "):this.delimiter=t.delimiter?t.delimiter:","}async columnNames(){return this.columnNamesValidated||await this.setColumnNames(),this.configuredColumnsOnly?Object.keys(this.columnConfigs):this.fullColumnNames}async setColumnNames(){const e=await this.maybeReadHeaderLine();if(!this.fullColumnNames&&!e)throw new Error("Column names must be provided if there is no header line.");this.fullColumnNames&&e&&re(e.length===this.fullColumnNames.length,(()=>"The length of provided columnNames ("+this.fullColumnNames.length.toString()+") does not match the length of the header line read from file ("+e.length.toString()+").")),this.fullColumnNames||(this.fullColumnNames=e);const t=this.fullColumnNames.reduce(((e,t)=>(e[t]=e[t]+1||1,e)),{}),n=Object.keys(t).filter((e=>t[e]>1));if(re(0===n.length,(()=>"Duplicate column names found: "+n.toString())),this.columnConfigs)for(const e of Object.keys(this.columnConfigs))if(-1===this.fullColumnNames.indexOf(e))throw new Error('The key "'+e+'" provided in columnConfigs does not match any of the column names ('+this.fullColumnNames.toString()+").");this.columnNamesValidated=!0}async maybeReadHeaderLine(){if(this.hasHeader){const e=await this.base.iterator(),t=await e.next();if(t.done)throw new Error("No data was found for CSV parsing.");const n=t.value;return this.parseRow(n,!1)}return null}async iterator(){this.columnNamesValidated||await this.setColumnNames();let e=await this.base.iterator();return this.hasHeader&&(e=e.skip(1)),e.map((e=>this.makeDataElement(e)))}makeDataElement(e){const t=this.parseRow(e),n={},r={};for(let s=0;s14||!Number.isInteger(t))throw new Error(`Invalid fftSize: it must be a power of 2 between 2 to 4 and 2 to 14, but got ${this.fftSize}`);if(this.numFrames=e.numFramesPerSpectrogram||43,this.sampleRateHz=e.sampleRateHz,this.columnTruncateLength=e.columnTruncateLength||this.fftSize,this.audioTrackConstraints=e.audioTrackConstraints,this.smoothingTimeConstant=e.smoothingTimeConstant||0,this.includeSpectrogram=!1!==e.includeSpectrogram,this.includeWaveform=!0===e.includeWaveform,!this.includeSpectrogram&&!this.includeWaveform)throw new Error("Both includeSpectrogram and includeWaveform are false. At least one type of data should be returned.")}summary(){return"microphone"}static async create(e={}){if(He().get("IS_NODE"))throw new Error("microphone API is only supported in browser environment.");const t=new ES(e);return await t.start(),t}async start(){try{this.stream=await navigator.mediaDevices.getUserMedia({audio:null==this.audioTrackConstraints||this.audioTrackConstraints,video:!1})}catch(e){throw new Error(`Error thrown while initializing video stream: ${e.message}`)}if(!this.stream)throw new Error("Could not obtain audio from microphone.");const e=window.AudioContext||window.webkitAudioContext;if(this.audioContext=new e,this.sampleRateHz){if(this.audioContext.sampleRate!==this.sampleRateHz)throw new Error(`Mismatch in sampling rate: Expected: ${this.sampleRateHz}; Actual: ${this.audioContext.sampleRate}`)}else this.sampleRateHz=this.audioContext.sampleRate;const t=this.audioContext.createMediaStreamSource(this.stream);this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=2*this.fftSize,this.analyser.smoothingTimeConstant=this.smoothingTimeConstant,t.connect(this.analyser),this.freqData=new Float32Array(this.fftSize),this.timeData=new Float32Array(this.fftSize)}async next(){if(this.isClosed)return{value:null,done:!0};let e,t;const n=await this.getAudioData();if(this.includeSpectrogram){const t=this.flattenQueue(n.freqDataQueue);e=this.getTensorFromAudioDataArray(t,[this.numFrames,this.columnTruncateLength,1])}if(this.includeWaveform){const e=this.flattenQueue(n.timeDataQueue);t=this.getTensorFromAudioDataArray(e,[this.numFrames*this.fftSize,1])}return{value:{spectrogram:e,waveform:t},done:!1}}async capture(){return(await this.next()).value}async getAudioData(){const e=[],t=[];let n=0;return new Promise((r=>{const s=setInterval((()=>{this.includeSpectrogram&&(this.analyser.getFloatFrequencyData(this.freqData),this.freqData[0]===-1/0&&r({freqDataQueue:e,timeDataQueue:t}),e.push(this.freqData.slice(0,this.columnTruncateLength))),this.includeWaveform&&(this.analyser.getFloatTimeDomainData(this.timeData),t.push(this.timeData.slice())),++n===this.numFrames&&(clearInterval(s),r({freqDataQueue:e,timeDataQueue:t}))}),this.fftSize/this.sampleRateHz*1e3)}))}stop(){this.isClosed||(this.isClosed=!0,this.analyser.disconnect(),this.audioContext.close(),null!=this.stream&&this.stream.getTracks().length>0&&this.stream.getTracks()[0].stop())}toArray(){throw new Error("Can not convert infinite audio stream to array.")}getSampleRate(){return this.sampleRateHz}flattenQueue(e){const t=e[0].length,n=new Float32Array(e.length*t);return e.forEach(((e,r)=>n.set(e,r*t))),n}getTensorFromAudioDataArray(e,t){const n=new Float32Array(oe(t));return n.set(e,n.length-e.length),$a(n,t)}}class $S extends ZN{constructor(e,t){if(super(),this.webcamVideoElement=e,this.webcamConfig=t,this.isClosed=!0,this.resize=!1,this.needToResize())if(this.resize=!0,this.cropSize=[this.webcamConfig.resizeHeight,this.webcamConfig.resizeWidth],this.cropBoxInd=Jh([0],"int32"),this.webcamConfig.centerCrop){const e=1*this.webcamConfig.resizeWidth/this.webcamVideoElement.width,t=1*this.webcamConfig.resizeHeight/this.webcamVideoElement.height,n=(1-e)/2,r=(1-t)/2,s=n+e,a=t+r;this.cropBox=Qh([r,n,a,s],[1,4])}else this.cropBox=Qh([0,0,1,1],[1,4])}summary(){return"webcam"}static async create(e,t={}){if(He().get("IS_NODE"))throw new Error("tf.data.webcam is only supported in browser environment.");if(!e){if(e=document.createElement("video"),!t.resizeWidth||!t.resizeHeight)throw new Error("Please provide webcam video element, or resizeWidth and resizeHeight to create a hidden video element.");e.width=t.resizeWidth,e.height=t.resizeHeight}const n=new $S(e,t);return await n.start(),n}async start(){this.webcamConfig.facingMode&&re("user"===this.webcamConfig.facingMode||"environment"===this.webcamConfig.facingMode,(()=>`Invalid webcam facing mode: ${this.webcamConfig.facingMode}. Please provide 'user' or 'environment'`));try{this.stream=await navigator.mediaDevices.getUserMedia({video:{deviceId:this.webcamConfig.deviceId,facingMode:this.webcamConfig.facingMode?this.webcamConfig.facingMode:"user",width:this.webcamVideoElement.width,height:this.webcamVideoElement.height}})}catch(e){throw e.message=`Error thrown while initializing video stream: ${e.message}`,e}if(!this.stream)throw new Error("Could not obtain video from webcam.");try{this.webcamVideoElement.srcObject=this.stream}catch(e){console.log(e),this.webcamVideoElement.src=window.URL.createObjectURL(this.stream)}return this.webcamVideoElement.play(),this.isClosed=!1,new Promise((e=>{this.webcamVideoElement.onloadedmetadata=()=>{e()}}))}async next(){if(this.isClosed)return{value:null,done:!0};let e;try{e=ro(this.webcamVideoElement)}catch(e){throw new Error(`Error thrown converting video to pixels: ${JSON.stringify(e)}`)}if(!this.resize)return{value:e,done:!1};try{return{value:this.cropAndResizeFrame(e),done:!1}}catch(e){throw new Error(`Error thrown cropping the video: ${e.message}`)}finally{e.dispose()}}needToResize(){return!(!this.webcamConfig.resizeWidth||!this.webcamConfig.resizeHeight||this.webcamVideoElement.width===this.webcamConfig.resizeWidth&&this.webcamVideoElement.height===this.webcamConfig.resizeHeight)}cropAndResizeFrame(e){return Xo((()=>{const t=ec(Si(e,"float32"),0);let n;n=Td.cropAndResize(t,this.cropBox,this.cropBoxInd,this.cropSize,"bilinear");const r=n.shape;return uu(n,r.slice(1))}))}async capture(){return(await this.next()).value}stop(){this.stream.getTracks().forEach((e=>e.stop()));try{this.webcamVideoElement.srcObject=null}catch(e){console.log(e),this.webcamVideoElement.src=null}this.isClosed=!0}toArray(){throw new Error("Can not convert infinite video stream to array.")}}class AS{}class RS extends ZN{split(e){return new MS(this,e)}}class MS extends RS{constructor(e,t){super(),this.upstream=e,this.impl=new FS(e,t)}summary(){return this.impl.summary()}async next(){return this.impl.next()}}class FS extends lS{constructor(e,t){super(),this.upstream=e,this.separator=t,this.carryover=""}summary(){return`${this.upstream.summary()} -> Split('${this.separator}')`}async pump(){const e=await this.upstream.next();if(e.done)return""!==this.carryover&&(this.outputQueue.push(this.carryover),this.carryover="",!0);const t=e.value.split(this.separator);t[0]=this.carryover+t[0];for(const e of t.slice(0,-1))this.outputQueue.push(e);return this.carryover=t[t.length-1],!0}}class DS extends ZN{decodeUTF8(){return new _S(this)}}class _S extends RS{constructor(e){super(),this.upstream=e,this.impl=new OS(e)}summary(){return this.impl.summary()}async next(){return this.impl.next()}}class OS extends lS{constructor(e){if(super(),this.upstream=e,He().get("IS_BROWSER"))this.decoder=new TextDecoder("utf-8");else{const{StringDecoder:e}=n(4589);this.decoder=new e("utf8")}}summary(){return`${this.upstream.summary()} -> Utf8`}async pump(){const e=await this.upstream.next();let t,n;return!e.done&&(t=e.value,n=He().get("IS_BROWSER")?this.decoder.decode(t,{stream:!0}):this.decoder.write(Buffer.from(t.buffer)),this.outputQueue.push(n),!0)}}class LS extends DS{constructor(e,t={}){super(),this.file=e,this.options=t,re(e instanceof Uint8Array||!!He().get("IS_BROWSER")&&(e instanceof File||e instanceof Blob),(()=>"FileChunkIterator only supports File, Blob and Uint8Array right now.")),this.offset=t.offset||0,this.chunkSize=t.chunkSize||1048576}summary(){return`FileChunks ${this.file}`}async next(){if(this.offset>=(this.file instanceof Uint8Array?this.file.byteLength:this.file.size))return{value:null,done:!0};const e=new Promise(((e,t)=>{const n=this.offset+this.chunkSize;if(this.file instanceof Uint8Array)e(new Uint8Array(this.file.slice(this.offset,n)));else{const r=new FileReader;r.onload=n=>{let s=r.result;if(s instanceof ArrayBuffer&&(s=new Uint8Array(s)),!(s instanceof Uint8Array))return t(new TypeError("FileReader returned unknown type."));e(s)},r.onabort=e=>t(new Error("Aborted")),r.onerror=e=>t(new Error(e.type));const s=this.file.slice(this.offset,n);r.readAsArrayBuffer(s)}this.offset=n}));return{value:await e,done:!1}}}function zS(e){return"string"==typeof e&&"file://"===e.substr(0,7)}class PS extends AS{constructor(e,t={}){super(),this.input=e,this.options=t}async iterator(){if(zS(this.input)&&He().get("IS_NODE")){const e=n(2993);this.input=e.readFileSync(this.input.substr(7))}return new LS(this.input,this.options)}}class BS extends AS{constructor(e,t={}){super(),this.url=e,this.fileOptions=t}async iterator(){return zS(this.url)?new PS(this.url,this.fileOptions).iterator():async function(e,t={},n){let r,s;var a;"string"==typeof e?r=e:(r=e.url,s={method:(a=e).method,headers:a.headers,body:a.body,mode:a.mode,credentials:a.credentials,cache:a.cache,redirect:a.redirect,referrer:a.referrer,integrity:a.integrity});const i=await(n||Ms)(r,s);if(i.ok){const e=new Uint8Array(await i.arrayBuffer());return new LS(e,t)}throw new Error(i.statusText)}(this.url,this.fileOptions)}}function VS(e,t={}){return new CS(new BS(e),t)}function US(e){const t=YN(e);return gS((async()=>t))}function WS(e){return gS((async()=>{const t=await e();return YN((()=>t.next()))}))}async function GS(e,t){return $S.create(e,t)}async function HS(e){return ES.create(e)}const jS="3.13.0";function qS(e,t){Array.isArray(e)||(e=[e]),e.forEach((e=>{null!=e&&re("complex64"!==e.dtype,(()=>`${t} does not support complex64 tensors in the CPU backend.`))}))}const KS=up;class XS extends q{constructor(){super(),this.blockSize=48,this.firstUse=!0,this.data=new j(this,jo())}nextDataId(){return XS.nextDataId++}write(e,t,n){this.firstUse&&(this.firstUse=!1,He().get("IS_NODE")&&ns("\n============================\nHi there 👋. Looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, which binds to TensorFlow C++, by running npm i @tensorflow/tfjs-node, or npm i @tensorflow/tfjs-node-gpu if you have CUDA. Then call require('@tensorflow/tfjs-node'); (-gpu suffix for CUDA) at the start of your program. Visit https://github.com/tensorflow/tfjs-node for more details.\n============================"));const r={id:this.nextDataId()};return this.data.set(r,{values:e,dtype:n,refCount:1}),r}makeTensorInfo(e,t,n){let r;if("string"===t&&null!=n&&n.length>0&&Ce(n[0])){const s=n.map((e=>Fs(e)));r=this.write(s,e,t)}else r=this.write(n,e,t);return{dataId:r,shape:e,dtype:t}}refCount(e){return this.data.has(e)?this.data.get(e).refCount:0}incRef(e){this.data.get(e).refCount++}decRef(e){this.data.has(e)&&this.data.get(e).refCount--}move(e,t,n,r,s){this.data.set(e,{values:t,dtype:r,refCount:s})}numDataIds(){return this.data.numDataIds()}async read(e){return this.readSync(e)}readSync(e){const{dtype:t,complexTensorInfos:n}=this.data.get(e);return"complex64"===t?Jd(this.readSync(n.real.dataId),this.readSync(n.imag.dataId)):this.data.get(e).values}bufferSync(e){const t=this.readSync(e.dataId);let n=t;if("string"===e.dtype)try{n=t.map((e=>Ds(e)))}catch(e){throw new Error("Failed to decode encoded string bytes into utf-8")}return Ni(e.shape,e.dtype,n)}makeOutput(e,t,n){const r=this.write(e,t,n);return jo().makeTensorFromDataId(r,t,n,this)}disposeData(e,t=!1){if(this.data.has(e)){if(this.data.get(e).refCount--,!t&&this.data.get(e).refCount>0)return!1;const{complexTensorInfos:n}=this.data.get(e);null!=n&&(this.disposeData(n.real.dataId,!0),this.disposeData(n.imag.dataId,!0)),this.data.delete(e)}return!0}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}async time(e){const t=Rs();return e(),{kernelMs:Rs()-t}}memory(){return{unreliable:!0,reasons:["The reported memory is an upper bound. Due to automatic garbage collection, the true allocated memory may be less."]}}where(e){qS([e],"where");const t=this.readSync(e.dataId);return KS(e.shape,t)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}}function YS(e,t,n){return({inputs:r,attrs:s,backend:a})=>{const{x:i}=r;if(qS(i,e),"string"===i.dtype||"string"===n)throw new Error("unaryKernelFunc does not support string input/output");const o=a,l=o.data.get(i.dataId).values,u=oe(i.shape),c=n||i.dtype,h=we(c,u);for(let e=0;e{const{x:i}=r;if(qS(i,e),"string"===i.dtype||"string"===n)throw new Error("unaryKernelFunc does not support string input/output");const o=a,l=o.data.get(i.dataId).values,u=n||i.dtype,c=t(l,u,s);return o.makeTensorInfo(i.shape,u,c)}}XS.nextDataId=0,al("cpu",(()=>new XS),1);const JS=YS(jt,(e=>e>=0?e:Math.exp(e)-1)),QS={kernelName:jt,backendName:"cpu",kernelFunc:JS};function eT(e){const{inputs:t,backend:n}=e,{x:r}=t;return n.incRef(r.dataId),{dataId:r.dataId,shape:r.shape,dtype:r.dtype}}const tT={kernelName:cn,backendName:"cpu",kernelFunc:eT};function nT(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{alpha:a}=r;qS([s],"leakyRelu");const i=oe(s.shape),o=n.data.get(s.dataId).values,l=xe("float32",i);for(let e=0;e{const i=Zi(t,n),o=i.length,l=Fe(i),u=xe(a,oe(i)),c=t.length,h=n.length,p=Fe(t),d=Fe(n),f=Xi(t,i),m=Xi(n,i);if(f.length+m.length===0)for(let t=0;ta[e]=0));const i=Be(a,c,p),g=n.slice(-h);m.forEach((e=>g[e]=0));const y=Be(g,h,d);u[t]=e(r[i],s[y])}return[u,i]}}const aT=sT(((e,t)=>e<0?t*e:e));function iT(e){const{inputs:t,backend:n}=e,{x:r,alpha:s}=t;qS([r,s],"prelu");const a=n.data.get(r.dataId).values,i=n.data.get(s.dataId).values,[o,l]=aT(r.shape,s.shape,a,i,"float32");return n.makeTensorInfo(l,"float32",o)}const oT={kernelName:Qn,backendName:"cpu",kernelFunc:iT},lT=YS(sr,(e=>Math.max(0,e))),uT={kernelName:sr,backendName:"cpu",kernelFunc:lT},cT=YS(cr,(e=>Math.min(Math.max(0,e),6))),hT={kernelName:cr,backendName:"cpu",kernelFunc:cT};function pT(e){return(t,n,r)=>{const s=xe(n,t.length);for(let n=0;n1/(1+Math.exp(-e)))),fT=YS(vr,(e=>1/(1+Math.exp(-e)))),mT={kernelName:vr,backendName:"cpu",kernelFunc:fT};function gT(e,t,n,r,s){if("linear"===n)return eT({inputs:{x:t},backend:e});if("relu"===n)return lT({inputs:{x:t},backend:e});if("elu"===n)return JS({inputs:{x:t},backend:e});if("relu6"===n)return cT({inputs:{x:t},backend:e});if("prelu"===n)return iT({inputs:{x:t,alpha:r},backend:e});if("leakyrelu"===n)return nT({inputs:{x:t},backend:e,attrs:{alpha:s}});if("sigmoid"===n)return fT({inputs:{x:t},backend:e});throw new Error(`Activation ${n} has not been implemented for the CPU backend.`)}function yT(e){const{inputs:t,backend:n}=e,{real:r,imag:s}=t,a=n.data.get(r.dataId).values,i=n.data.get(s.dataId).values,o=n.makeTensorInfo(r.shape,"complex64");return n.data.get(o.dataId).complexTensorInfos={real:n.makeTensorInfo(r.shape,"float32",a),imag:n.makeTensorInfo(s.shape,"float32",i)},o}const bT={kernelName:kt,backendName:"cpu",kernelFunc:yT};function xT(e,t,n="float32"){if("complex64"===n)return yT({inputs:{real:xT(e,t,"float32"),imag:xT(e,t,"float32")},backend:e});const r=Le(oe(t),n);return e.makeTensorInfo(t,n,r)}function wT(e){const{inputs:t,backend:n}=e,{input:r}=t,s=n.data.get(r.dataId).complexTensorInfos.real,a=n.data.get(s.dataId).values;return n.makeTensorInfo(s.shape,s.dtype,a)}const vT={kernelName:nr,backendName:"cpu",kernelFunc:wT};function kT(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{dtype:a}=r;if("complex64"===a){if("complex64"===s.dtype)return eT({inputs:{x:s},backend:n});const e=xT(n,s.shape,s.dtype),t=kT({inputs:{x:s},backend:n,attrs:{dtype:"float32"}}),r=yT({inputs:{real:t,imag:e},backend:n});return n.disposeIntermediateTensorInfo(e),n.disposeIntermediateTensorInfo(t),r}if("complex64"===s.dtype){const e=wT({inputs:{input:s},backend:n}),t=kT({inputs:{x:e},backend:n,attrs:{dtype:a}});return n.disposeIntermediateTensorInfo(e),t}if(!Ie(s.dtype,a)){const e=eT({inputs:{x:s},backend:n});return{dataId:e.dataId,shape:e.shape,dtype:a}}if("int32"===a){const e=n.data.get(s.dataId).values,t=Int32Array.from(e);return n.makeTensorInfo(s.shape,"int32",t)}if("bool"===a){const e=n.data.get(s.dataId).values,t=As([0],s.dtype),[r,a]=sT(((e,t)=>e!==t?1:0))(s.shape,[],e,t,"bool");return n.makeTensorInfo(a,"bool",r)}throw new Error(`Error in Cast: failed to cast ${s.dtype} to ${a}`)}const IT={kernelName:xt,backendName:"cpu",kernelFunc:kT};function NT(e,t,n,r){return null==n?({inputs:n,backend:s})=>{const{a,b:i}=n,o=s;qS([a,i],e);const l=o.data.get(a.dataId).values,u=o.data.get(i.dataId).values,c="string"===a.dtype?Af(l):l,h="string"===a.dtype?Af(u):u,p=r||a.dtype,[d,f]=t(a.shape,i.shape,c,h,p);return o.makeTensorInfo(f,p,d)}:({inputs:e,backend:s})=>{const{a,b:i}=e,o=s;if("complex64"===a.dtype||"complex64"===i.dtype){const e=kT({inputs:{x:a},backend:o,attrs:{dtype:"complex64"}}),t=o.data.get(e.dataId),r=t.complexTensorInfos.real,s=t.complexTensorInfos.imag,l=o.data.get(r.dataId).values,u=o.data.get(s.dataId).values,c=kT({inputs:{x:i},backend:o,attrs:{dtype:"complex64"}}),h=o.data.get(c.dataId),p=h.complexTensorInfos.real,d=h.complexTensorInfos.imag,f=o.data.get(p.dataId).values,m=o.data.get(d.dataId).values,[g,y,b]=n(a.shape,i.shape,l,u,f,m),x=o.makeTensorInfo(b,"float32",g),w=o.makeTensorInfo(b,"float32",y),v=yT({inputs:{real:x,imag:w},backend:o});return o.disposeIntermediateTensorInfo(e),o.disposeIntermediateTensorInfo(c),o.disposeIntermediateTensorInfo(x),o.disposeIntermediateTensorInfo(w),v}{const e=o.data.get(a.dataId).values,n=o.data.get(i.dataId).values,s=r||a.dtype,[l,u]=t(a.shape,i.shape,e,n,s);return o.makeTensorInfo(u,s,l)}}}function ST(e){return(t,n,r,s,a,i)=>{const o=Zi(t,n),l=oe(o),u=o.length,c=Fe(o),h=xe("float32",l),p=xe("float32",l),d=Xi(t,o),f=Xi(n,o),m=Jd(r,s),g=Jd(a,i),y=t.length,b=Fe(t),x=n.length,w=Fe(n);if(d.length+f.length===0)for(let t=0;tr[e]=0));const s=Be(r,y,b),a=n.slice(-x);f.forEach((e=>a[e]=0));const i=Be(a,x,w),o=e(m[2*s],m[2*s+1],g[2*i],g[2*i+1]);h[t]=o.real,p[t]=o.imag}return[h,p,o]}}const TT=sT(((e,t)=>e+t)),CT=ST(((e,t,n,r)=>({real:e+n,imag:t+r}))),ET=NT(Qe,TT,CT),$T={kernelName:Qe,backendName:"cpu",kernelFunc:ET};function AT(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{shape:a}=r,i=oe(s.shape),o=ge(a,i),l=oe(o);re(i===l,(()=>`The new shape (${o}) has ${l} elements and the old shape (${s.shape}) has ${i} elements. The new shape and old shape must have the same number of elements.`)),n.incRef(s.dataId);const u=n.data.get(s.dataId);if(null!=u.complexTensorInfos){const e=u.complexTensorInfos.real,t=u.complexTensorInfos.imag;e.shape=o,t.shape=o}return{dataId:s.dataId,shape:o,dtype:s.dtype}}const RT={kernelName:ar,backendName:"cpu",kernelFunc:AT};function MT(e){const{inputs:t,backend:n,attrs:r}=e,{a:s,b:a}=t,{transposeA:i,transposeB:o}=r;qS([s,a],"matMul");const l=s.shape.length,u=a.shape.length,c=i?s.shape[l-2]:s.shape[l-1],h=o?a.shape[u-1]:a.shape[u-2],p=i?s.shape[l-1]:s.shape[l-2],d=o?a.shape[u-2]:a.shape[u-1],f=s.shape.slice(0,-2),m=a.shape.slice(0,-2),g=oe(f),y=oe(m),b=Zi(s.shape.slice(0,-2),a.shape.slice(0,-2)).concat([p,d]);re(c===h,(()=>`Error in matMul: inner shapes (${c}) and (${h}) of Tensors with shapes ${s.shape} and ${a.shape} and transposeA=${i} and transposeB=${o} must match.`));const x=o?[y,d,h]:[y,h,d],w=AT({inputs:{x:s},backend:n,attrs:{shape:i?[g,c,p]:[g,p,c]}}),v=AT({inputs:{x:a},backend:n,attrs:{shape:x}}),k=i?w.shape[1]:w.shape[2],I=i?w.shape[2]:w.shape[1],N=o?v.shape[1]:v.shape[2],S=Math.max(g,y),T=n.data.get(w.dataId).values,C=n.data.get(v.dataId).values,E=Fe(w.shape),$=Fe(v.shape),[A,R,M]=i?[E[0],1,E[1]]:[E[0],E[1],1],[F,D,_]=o?[1,$[1],$[0]]:[$[1],1,$[0]],O=I*N,L=Ni([S,I,N],w.dtype),z=L.values,P=n.blockSize;for(let e=0;e{const{x:t}=e.inputs,n=e.backend;qS(t,"abs");let r=new Float32Array(oe(t.shape));return r=_T(n.data.get(t.dataId).values),n.makeOutput(r,t.shape,t.dtype)}},LT=YS(Ze,(e=>Math.acos(e))),zT={kernelName:Ze,backendName:"cpu",kernelFunc:LT},PT=YS(Je,(e=>Math.acosh(e))),BT={kernelName:Je,backendName:"cpu",kernelFunc:PT},VT={kernelName:et,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,r=t;qS(t,"addN");const s=r.map((e=>n.data.get(e.dataId).values)),a=Ni(r[0].shape,r[0].dtype),i=a.values;for(let e=0;en&&(n=s,r=e)}p[e]=r}return u.forEach((e=>n.disposeIntermediateTensorInfo(e))),n.makeTensorInfo(c,"int32",p)}},KT={kernelName:st,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a}=r;qS(s,"argMin");let i=ye(a,s.shape);const o=Ac(i,s.shape.length);let l=s;const u=[];null!=o&&(l=WT({inputs:{x:s},backend:n,attrs:{perm:o}}),u.push(l),i=Mc(i.length,l.shape.length)),i=[i[0]],$c("argMin",i,l.shape.length);const[c,h]=Cc(l.shape,i),p=Le(oe(c),"int32"),d=oe(h),f=n.data.get(l.dataId).values;for(let e=0;en.disposeIntermediateTensorInfo(e))),n.makeTensorInfo(c,"int32",p)}},XT=YS(at,(e=>Math.asin(e))),YT={kernelName:at,backendName:"cpu",kernelFunc:XT},ZT=YS(it,(e=>Math.asinh(e))),JT={kernelName:it,backendName:"cpu",kernelFunc:ZT},QT=YS(ot,(e=>Math.atan(e))),eC={kernelName:ot,backendName:"cpu",kernelFunc:QT},tC=sT(((e,t)=>Math.atan2(e,t))),nC=NT(ut,tC),rC={kernelName:ut,backendName:"cpu",kernelFunc:nC},sC=YS(lt,(e=>Math.atanh(e))),aC={kernelName:lt,backendName:"cpu",kernelFunc:sC};function iC(e,t,n,r,s,a){const i=s.strideHeight,o=s.strideWidth,l=s.dilationHeight,u=s.dilationWidth,c=s.effectiveFilterHeight,h=s.effectiveFilterWidth,p=s.padInfo.top,d=s.padInfo.left,f="max"===a?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,m=Ni(s.outShape,n),g=m.values,y=s.outShape[1]*s.outShape[2]*s.outShape[3],b=s.outShape[2]*s.outShape[3],x=s.outShape[3];for(let t=0;ty?y=i:"avg"===a&&(b+=i,w++)}if(isNaN(y))break}g[I+n*x+t]="avg"===a?b/w:y}}}return m}function oC(e,t,n,r,s=!1,a=!1){const i=Ni(r.outShape,"int32"),o=r.strideHeight,l=r.strideWidth,u=r.dilationHeight,c=r.dilationWidth,h=r.effectiveFilterHeight,p=r.effectiveFilterWidth,d=r.padInfo.top,f=r.padInfo.left,m=Ni(t,n,e);for(let e=0;ew&&(w=u,v=s?a?((e*r.inHeight+n)*r.inWidth+o)*r.inChannels+t:(n*r.inWidth+o)*r.inChannels+t:i*p+l)}}i.set(v,e,n,o,t)}}return i}function lC(e,t,n,r,s,a){const i=s.strideDepth,o=s.strideHeight,l=s.strideWidth,u=s.dilationDepth,c=s.dilationHeight,h=s.dilationWidth,p=s.effectiveFilterDepth,d=s.effectiveFilterHeight,f=s.effectiveFilterWidth,m=s.padInfo.front,g=s.padInfo.top,y=s.padInfo.left,b="max"===a?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,x=Ni(s.outShape,n),w=x.values,v=s.outShape[1]*s.outShape[2]*s.outShape[3]*s.outShape[4],k=s.outShape[2]*s.outShape[3]*s.outShape[4],I=s.outShape[3]*s.outShape[4],N=s.outShape[4];for(let t=0;tk?k=s:"avg"===a&&(I+=s,S++),isNaN(k))break}if(isNaN(k))break}if(isNaN(k))break}w[g+t]="avg"===a?I/S:k}}}}return x}const uC={kernelName:ct,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t;qS(s,"avgPool");const{filterSize:a,strides:i,pad:o,dimRoundingMode:l}=r;re(iu(i,1),(()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${i} and dilations '1'`));const u=Yl(s.shape,a,i,1,o,l);let c;if(1===u.filterWidth&&1===u.filterHeight&&ue(u.inShape,u.outShape))c=eT({inputs:{x:s},backend:n});else{const e=n.data.get(s.dataId).values,t=Fe(s.shape),r=iC(e,s.shape,s.dtype,t,u,"avg");c=n.makeTensorInfo(u.outShape,s.dtype,r.values)}return c}},cC={kernelName:pt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{filterSize:a,strides:i,pad:o,dimRoundingMode:l,dataFormat:u}=r;qS(s,"avgPool3d");const c=Zl(s.shape,a,i,1,o,l,u),h=lC(n.data.get(s.dataId).values,s.shape,s.dtype,Fe(s.shape),c,"avg");return n.makeTensorInfo(h.shape,"float32",h.values)}},hC={kernelName:dt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a}=t,{filterSize:i,strides:o,pad:l,dimRoundingMode:u}=r;qS([s,a],"avgPool3DGrad");const c=Zl(a.shape,i,o,1,l,u),h=c.strideDepth,p=c.strideHeight,d=c.strideWidth,f=c.filterDepth,m=c.filterHeight,g=c.filterWidth,y=c.dilationDepth,b=c.dilationHeight,x=c.dilationWidth,w=c.effectiveFilterDepth,v=c.effectiveFilterHeight,k=c.effectiveFilterWidth,I=w-1-c.padInfo.front,N=k-1-c.padInfo.left,S=v-1-c.padInfo.top,T=Ni(a.shape,"float32"),C=1/(f*m*g),E=n.bufferSync(s);for(let e=0;e=c.outDepth||Math.floor(r)!==r))for(let n=0;n=c.outHeight||Math.floor(s)!==s))for(let n=0;n=c.outWidth||Math.floor(a)!==a||(l+=E.get(e,r,s,a,t))}}}T.set(l*C,e,n,r,s,t)}return n.makeTensorInfo(T.shape,T.dtype,T.values)}},pC={kernelName:ht,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a}=t,i=a;qS([s,a],"avgPoolGrad");const{filterSize:o,strides:l,pad:u}=r,c=Yl(i.shape,o,l,1,u),h=c.strideHeight,p=c.strideWidth,d=c.filterHeight,f=c.filterWidth,m=c.dilationHeight,g=c.dilationWidth,y=c.effectiveFilterHeight,b=c.effectiveFilterWidth,x=b-1-c.padInfo.left,w=y-1-c.padInfo.top,v=Ni(i.shape,"float32"),k=1/(d*f),I=n.data.get(s.dataId).values,N=Ni(s.shape,"float32",I);for(let e=0;e=c.outHeight||Math.floor(r)!==r))for(let n=0;n=c.outWidth||Math.floor(s)!==s||(i+=N.get(e,r,s,t))}}v.set(i*k,e,n,r,t)}return n.makeTensorInfo(v.shape,v.dtype,v.values)}},dC={kernelName:sn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,scale:a,offset:i,mean:o,variance:l}=t;re(o.shape.length===l.shape.length,(()=>"Batch normalization gradient requires mean and variance to have equal ranks.")),re(null==i||o.shape.length===i.shape.length,(()=>"Batch normalization gradient requires mean and offset to have equal ranks.")),re(null==a||o.shape.length===a.shape.length,(()=>"Batch normalization gradient requires mean and scale to have equal ranks.")),qS([s,o,l,a,i],"batchNorm");let{varianceEpsilon:u}=r;null==u&&(u=.001);const c=n.data.get(s.dataId).values,h=n.data.get(o.dataId).values,p=n.data.get(l.dataId).values,d=a?n.data.get(a.dataId).values:new Float32Array([1]),f=i?n.data.get(i.dataId).values:new Float32Array([0]),m=new Float32Array(c.length),g=f.length,y=d.length,b=p.length,x=h.length;let w=0,v=0,k=0,I=0;for(let e=0;e=g&&(w=0),v>=x&&(v=0),k>=y&&(k=0),I>=b&&(I=0);return n.makeTensorInfo(s.shape,s.dtype,m)}};function fC(e,t,n,r,s){const a=vo(r,t,n),i=oe(n),o=Fe(r);if(a){const n=ko(t,o);return"string"===s?e.slice(n,n+i):e.subarray(n,n+i)}const l=Ni(r,s,"string"===s?Af(e):e),u=Ni(n,s);for(let e=0;ee+t[n]));u.set(l.get(...r),...n)}return"string"===s?Rf(u.values):u.values}function mC(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{begin:a,size:i}=r;qS(s,"slice");const[o,l]=Io(s,a,i);lo(s,o,l);const u=fC(n.data.get(s.dataId).values,o,l,s.shape,s.dtype);return n.makeTensorInfo(l,s.dtype,u)}const gC={kernelName:yr,backendName:"cpu",kernelFunc:mC},yC={kernelName:mt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{blockShape:a,crops:i}=r;qS([s],"batchToSpaceND");const o=a.reduce(((e,t)=>e*t)),l=Pd(s.shape,a,o),u=Bd(l.length,a.length),c=Vd(s.shape,a,o),h=Ud(i,a.length),p=Wd(c,i,a.length),d=AT({inputs:{x:s},backend:n,attrs:{shape:l}}),f=WT({inputs:{x:d},backend:n,attrs:{perm:u}}),m=AT({inputs:{x:f},backend:n,attrs:{shape:c}}),g=mC({inputs:{x:m},backend:n,attrs:{begin:h,size:p}});return n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),g}};function bC(e,t,n,r,s){const a=oe(r),i=Le(s,n);for(let n=0;n=s||(i[r]+=a>0?t[n]:1)}return i}function xC(e,t,n,r=!1){const s=e.shape[0],a=e.shape[1],i=Ni([s,n],t.dtype);for(let o=0;o=n||(r?i.set(1,o,a):t.size>0?i.set(i.get(o,a)+t.get(o,s),o,a):i.set(i.get(o,a)+1,o,a))}return i}const wC={kernelName:gt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,weights:a}=t,{size:i}=r,o=bC(n.data.get(s.dataId).values,n.data.get(a.dataId).values,a.dtype,a.shape,i);return n.makeTensorInfo([i],a.dtype,o)}},vC={kernelName:bt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{s0:r,s1:s}=t,a=n.data.get(r.dataId).values,i=n.data.get(s.dataId).values,o=Zi(Array.from(a),Array.from(i));return n.makeTensorInfo([o.length],"int32",Int32Array.from(o))}},kC=pT((e=>Math.ceil(e))),IC=ZS(wt,kC),NC={kernelName:wt,backendName:"cpu",kernelFunc:IC},SC=YS(vt,((e,t)=>{const n=t;return e>n.clipValueMax?n.clipValueMax:e{const{x:t}=e.inputs,n=e.backend,r=new Float32Array(oe(t.shape)),s=n.data.get(t.dataId),a=s.complexTensorInfos.real,i=s.complexTensorInfos.imag,o=n.data.get(a.dataId).values,l=n.data.get(i.dataId).values;for(let e=0;e{const n=oe(e.shape);s.set(e.vals,t),t+=n}))}else{let r=0;e.forEach((e=>{const a="string"===n?Af(e.vals):e.vals;let i=0;for(let n=0;ne.shape)),a);if(0===oe(i))return n.makeTensorInfo(i,t[0].dtype,[]);const o=t.filter((e=>oe(e.shape)>0));if(1===o.length)return eT({inputs:{x:o[0]},backend:n});if(Dd(o.map((e=>e.shape)),a),"complex64"===o[0].dtype){const e=o.map((e=>wT({inputs:{input:e},backend:n}))),t=o.map((e=>$C({inputs:{input:e},backend:n}))),r=RC({inputs:e,backend:n,attrs:{axis:a}}),s=RC({inputs:t,backend:n,attrs:{axis:a}}),i=yT({inputs:{real:r,imag:s},backend:n});return e.forEach((e=>n.disposeIntermediateTensorInfo(e))),t.forEach((e=>n.disposeIntermediateTensorInfo(e))),n.disposeIntermediateTensorInfo(r),n.disposeIntermediateTensorInfo(s),i}const l=o.map((e=>{const t=oe(e.shape.slice(a));return AT({inputs:{x:e},backend:n,attrs:{shape:[-1,t]}})})),u=l.map((e=>({vals:n.data.get(e.dataId).values,shape:e.shape})));i=_d(l.map((e=>e.shape)),1);const c=1===l[0].shape[0],h=EC(u,i,t[0].dtype,c),p=_d(o.map((e=>e.shape)),a),d=n.makeTensorInfo(p,t[0].dtype,h);return l.forEach((e=>n.disposeIntermediateTensorInfo(e))),d}const MC={kernelName:Nt,backendName:"cpu",kernelFunc:RC};function FC(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a}=t,{strides:i,pad:o,dataFormat:l,dilations:u,dimRoundingMode:c}=r;qS([s,a],"conv2d");const h=ou(l),p=Jl(s.shape,a.shape,i,u,o,c,!1,h),d=p.filterHeight,f=p.filterWidth,m=p.dilationHeight,g=p.dilationWidth,y=p.padInfo.left,b=p.padInfo.top,x="channelsLast"===p.dataFormat,w=new Ws(p.outShape,s.dtype),v=Fe(s.shape),k=Fe(a.shape),I=v[0],N=x?v[1]:v[2],S=x?v[2]:1,T=x?1:v[1],C=w.strides[0],E=x?w.strides[1]:w.strides[2],$=x?w.strides[2]:1,A=x?1:w.strides[1],R=n.data.get(s.dataId).values,M=n.data.get(a.dataId).values,F=w.values;for(let e=0;e=p.inHeight)continue;const a=e*k[0],i=t+n*N;for(let e=0;e=p.inWidth)continue;const s=i+r*S;let o=a+e*k[1];for(let e=0;e=u.inDepth)continue;const a=e*S[0],i=t+n*N[1];for(let e=0;e=u.inHeight)continue;const s=a+e*S[1],o=i+r*N[2];for(let e=0;e=u.inWidth)continue;const a=s+e*S[2],i=o+t*u.inChannels;let l=a;for(let e=0;eMath.cos(e))),VC={kernelName:Rt,backendName:"cpu",kernelFunc:BC},UC=YS(Mt,(e=>Math.cosh(e))),WC={kernelName:Mt,backendName:"cpu",kernelFunc:UC},GC={kernelName:Dt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{image:s,boxes:a,boxInd:i}=t,{cropSize:o,method:l,extrapolationValue:u}=r,[c,h,p,d]=s.shape,f=a.shape[0],[m,g]=o,y=Ni([f,m,g,d],"float32"),b=n.data.get(a.dataId).values,x=n.data.get(i.dataId).values,w=n.data.get(s.dataId).values,v=Fe(s.shape),k=Fe(y.shape);for(let e=0;e=c)continue;const o=m>1?(s-n)*(h-1)/(m-1):0,f=g>1?(a-r)*(p-1)/(g-1):0;for(let t=0;t1?n*(h-1)+t*o:.5*(n+s)*(h-1);if(c<0||c>h-1)for(let n=0;n1?r*(p-1)+l*f:.5*(r+a)*(p-1);if(c<0||c>p-1){for(let n=0;n1?r*(p-1)+n*f:.5*(r+a)*(p-1);if(s<0||s>p-1){for(let r=0;re+f-t-1:(e,t)=>e+t;for(let e=0;e`Only NHWC dataFormat supported on CPU for depthToSpace. Got ${i}`));const o=s.shape[0],l=s.shape[1],u=s.shape[2],c=s.shape[3],h=l*a,p=u*a,d=c/(a*a),f=n.data.get(s.dataId).values,m=new Float32Array(o*h*p*d);let g=0;for(let e=0;e`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${i} and dilations '${p}'`));const d=Jl(s.shape,a.shape,i,p,o,u,!0),{filterHeight:f,filterWidth:m,dilationHeight:g,dilationWidth:y,padInfo:b}=d,x=b.left,w=b.top,v=d.outChannels/d.inChannels,k=new Ws(d.outShape,s.dtype),I=n.data.get(s.dataId).values,N=n.data.get(a.dataId).values,S=k.values;for(let e=0;e=d.inHeight)continue;const a=e*h[0],i=t+n*c[1];for(let e=0;e=d.inWidth)continue;const s=a+e*h[1],o=i+r*d.inChannels;let l=t,u=s;for(let e=0;e{const{x:r,filter:s}=e,{strides:a,pad:i,dilations:o}=n,l=t,u=l.data.get(r.dataId).values,c=r.shape.length,h=l.data.get(s.dataId).values,p=s.shape.length,{batchSize:d,inHeight:f,inWidth:m,inChannels:g,outHeight:y,outWidth:b,padInfo:x,strideHeight:w,strideWidth:v,filterHeight:k,filterWidth:I,dilationHeight:N,dilationWidth:S,outShape:T}=Xl(r.shape,s.shape,a,i,"NHWC",o),C=oe(T),E=T.length,$=we(r.dtype,C);for(let e=0;e=0&&a=0&&dl&&(l=m)}}}$[Be([e,t,a,o],E,Fe(T))]=l}}}return{dataId:l.write(As($,r.dtype),T,r.dtype),shape:T,dtype:r.dtype}}},eE={kernelName:Wt,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:r,filter:s,dy:a}=e,{strides:i,pad:o,dilations:l}=n,u=t,c=_e(r.shape,u.data.get(r.dataId).values),h=_e(s.shape,u.data.get(s.dataId).values),{batchSize:p,inHeight:d,inWidth:f,inChannels:m,outHeight:g,outWidth:y,padInfo:b,strideHeight:x,strideWidth:w,filterHeight:v,filterWidth:k,dilationHeight:I,dilationWidth:N,outShape:S}=Xl(r.shape,s.shape,i,o,"NHWC",l);re(a.rank===S.length,(()=>`Error in ${Wt}, dy must have the same rank as output ${S.length}, but got ${a.rank}`));const T=_e(S,u.data.get(a.dataId).values),C=ze(s.shape,s.dtype);for(let e=0;e=0&&r=0&&ui&&(i=s,o=t,l=n)}}}C[o][l][a]+=T[e][t][r][a]}}}return{dataId:u.write(As(C,r.dtype),s.shape,s.dtype),shape:s.shape,dtype:s.dtype}}},tE={kernelName:Ut,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:r,filter:s,dy:a}=e,{strides:i,pad:o,dilations:l}=n,u=t,c=_e(r.shape,u.data.get(r.dataId).values),h=_e(s.shape,u.data.get(s.dataId).values),{batchSize:p,inHeight:d,inWidth:f,inChannels:m,outHeight:g,outWidth:y,padInfo:b,strideHeight:x,strideWidth:w,filterHeight:v,filterWidth:k,dilationHeight:I,dilationWidth:N,outShape:S}=Xl(r.shape,s.shape,i,o,"NHWC",l);re(a.rank===S.length,(()=>`Error in ${Ut}, dy must have the same rank as output ${S.length}, but got ${a.rank}`));const T=_e(S,u.data.get(a.dataId).values),C=ze(r.shape,r.dtype);for(let e=0;e=0&&r=0&&ui&&(i=s,o=r,l=u)}}}C[e][o][l][a]+=T[e][t][r][a]}}}return{dataId:u.write(As(C,r.dtype),r.shape,r.dtype),shape:r.shape,dtype:r.dtype}}},nE=sT(((e,t)=>e*t)),rE=ST(((e,t,n,r)=>({real:e*n-t*r,imag:e*r+t*n}))),sE=NT(Vn,nE,rE),aE={kernelName:Vn,backendName:"cpu",kernelFunc:sE};function iE(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:i}=r;let o;qS(s,"sum"),o="bool"===s.dtype?kT({inputs:{x:s},backend:n,attrs:{dtype:"int32"}}):eT({inputs:{x:s},backend:n});const l=o.shape.length,u=ye(a,o.shape),c=Ac(u,l);let h=u,p=o;null!=c&&(p=WT({inputs:{x:o},backend:n,attrs:{perm:c}}),h=Mc(h.length,l)),$c("sum",h,p.shape.length);const[d,f]=Cc(p.shape,h);let m=xT(n,d,na(p.dtype,"int32"));const g=oe(f),y=n.data.get(m.dataId).values,b=n.data.get(p.dataId).values;for(let e=0;e=0&&(p=iE({inputs:{x:p},backend:n,attrs:{axis:u[e]-(i.length-d),keepDims:!1}}),f.push(p)),d--)}for(const e of f)e!==p&&n.disposeIntermediateTensorInfo(e);return p}},uE={kernelName:qt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{dy:r,y:s}=t;qS([r,s],"eluGrad");const a=new Float32Array(oe(s.shape)),i=n.data.get(s.dataId).values,o=n.data.get(r.dataId).values;for(let e=0;e=1?o[e]:o[e]*(t+1)}return n.makeTensorInfo(s.shape,"float32",a)}},cE=sT(((e,t)=>e===t?1:0)),hE=NT(Xt,cE,null,"bool"),pE={kernelName:Xt,backendName:"cpu",kernelFunc:hE},dE=jd,fE=qd,mE=Kd,gE=Xd,yE=Yd,bE=Zd,xE=YS(Kt,(e=>{const t=Math.sign(e),n=Math.abs(e),r=1/(1+dE*n);return t*(1-((((bE*r+yE)*r+gE)*r+mE)*r+fE)*r*Math.exp(-n*n))})),wE={kernelName:Kt,backendName:"cpu",kernelFunc:xE},vE=pT((e=>Math.exp(e))),kE=ZS(Yt,vE,"float32"),IE={kernelName:Yt,backendName:"cpu",kernelFunc:kE};function NE(e){const{inputs:t,backend:n,attrs:r}=e,{input:s}=t,{dim:a}=r,i=s.shape.length,o=s.shape.slice();let l=a;return a<0&&(re(-(i+1)<=a,(()=>`Axis must be in the interval [${-(i+1)}, ${i}]`)),l=i+a+1),o.splice(l,0,1),AT({inputs:{x:s},backend:n,attrs:{shape:o}})}const SE={kernelName:Zt,backendName:"cpu",kernelFunc:NE},TE=pT((e=>Math.expm1(e))),CE=ZS(Jt,TE),EE={kernelName:Jt,backendName:"cpu",kernelFunc:CE},$E=sT(((e,t)=>e/t)),AE=NT(Gt,$E),RE={kernelName:Gt,backendName:"cpu",kernelFunc:AE},ME=sT(((e,t)=>e-t)),FE=ST(((e,t,n,r)=>({real:e-n,imag:t-r}))),DE=NT(Pr,ME,FE),_E={kernelName:Pr,backendName:"cpu",kernelFunc:DE};function OE(e,t,n){const r=e.shape,s=r[0],a=r[1],i=n.data.get(e.dataId),o=i.complexTensorInfos.real,l=i.complexTensorInfos.imag,u=[s,a],c=oe(u),h=xe("float32",c),p=xe("float32",c);for(let e=0;e{const{image:r}=e,s=n,a=xe(r.dtype,oe(r.shape)),[i,o,l,u]=r.shape,c=s.data.get(r.dataId).values;for(let e=0;e=0&&iMath.floor(e))),GE=ZS(nn,WE),HE={kernelName:nn,backendName:"cpu",kernelFunc:GE},jE=sT(((e,t)=>Math.floor(e/t))),qE=NT(rn,jE,null,"int32"),KE={kernelName:rn,backendName:"cpu",kernelFunc:qE},XE={kernelName:es,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dataFormat:c,dilations:h,dimRoundingMode:p,activation:d,leakyreluAlpha:f}=r;let m=FC({inputs:{x:s,filter:a},backend:n,attrs:{strides:l,pad:u,dataFormat:c,dilations:h,dimRoundingMode:p}});if(i){const e=m;m=ET({inputs:{a:m,b:i},backend:n}),n.disposeIntermediateTensorInfo(e)}if(d){const e=m;m=gT(n,m,d,o,f),n.disposeIntermediateTensorInfo(e)}return m}},YE={kernelName:ts,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dataFormat:c,dilations:h,dimRoundingMode:p,activation:d,leakyreluAlpha:f}=r;let m=KC({inputs:{x:s,filter:a},backend:n,attrs:{strides:l,pad:u,dataFormat:c,dilations:h,dimRoundingMode:p}});if(i){const e=m;m=ET({inputs:{a:m,b:i},backend:n}),n.disposeIntermediateTensorInfo(e)}if(d){const e=m;m=gT(n,m,d,o,f),n.disposeIntermediateTensorInfo(e)}return m}};function ZE(e,t,n,r,s,a,i,o,l){const u=Ni([r,a],n);for(let n=0;n=l/a)throw new Error(`Invalid indices: ${r} does not index into ${o}`);for(let e=0;e=0,(()=>`GatherV2: the index value ${t} is not in [0, ${c-1}]`))}let h=o;null==o&&(h=0);const p=oe(a.shape),d=$f(s,a,l,h),f=AT({inputs:{x:s},backend:n,attrs:{shape:[d.batchSize,d.outerSize,d.dimSize,d.sliceSize]}}),m=AT({inputs:{x:a},backend:n,attrs:{shape:[d.batchSize,p/d.batchSize]}}),g=[d.batchSize,d.outerSize,p/d.batchSize,d.sliceSize],y=n.bufferSync(m),b=QE(n.bufferSync(f),y,g);return n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),n.makeTensorInfo(d.outputShape,b.dtype,b.values)}},t$=sT(((e,t)=>e>t?1:0)),n$=NT(ln,t$,null,"bool"),r$={kernelName:ln,backendName:"cpu",kernelFunc:n$},s$=sT(((e,t)=>e>=t?1:0)),a$=NT(un,s$,null,"bool"),i$={kernelName:un,backendName:"cpu",kernelFunc:a$},o$={kernelName:hn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{input:r}=t,s=oe(r.shape),a=r.shape[r.shape.length-1],i=AT({inputs:{x:r},backend:n,attrs:{shape:[s/a,a]}}),o=OE(i,!0,n),l=AT({inputs:{x:o},backend:n,attrs:{shape:r.shape}});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(o),l}},l$=YS(dn,(e=>Number.isFinite(e)?1:0),"bool"),u$={kernelName:dn,backendName:"cpu",kernelFunc:l$},c$=YS(fn,(e=>Math.abs(e)===1/0?1:0),"bool"),h$={kernelName:fn,backendName:"cpu",kernelFunc:c$},p$=YS(mn,(e=>Number.isNaN(e)?1:0),"bool"),d$={kernelName:mn,backendName:"cpu",kernelFunc:p$},f$=sT(((e,t)=>ee<=t?1:0)),b$=NT(bn,y$,null,"bool"),x$={kernelName:bn,backendName:"cpu",kernelFunc:b$};function w$(e,t,n){const r=(t-e)/(n-1),s=Le(n,"float32");s[0]=e;for(let e=1;eMath.log(e))),I$=ZS(wn,k$),N$={kernelName:wn,backendName:"cpu",kernelFunc:I$},S$=YS(vn,(e=>Math.log1p(e))),T$={kernelName:vn,backendName:"cpu",kernelFunc:S$},C$=sT(((e,t)=>e&&t)),E$=NT(kn,C$,null,"bool"),$$={kernelName:kn,backendName:"cpu",kernelFunc:E$},A$=YS(In,(e=>e?0:1),"bool"),R$={kernelName:In,backendName:"cpu",kernelFunc:A$},M$=sT(((e,t)=>e||t)),F$=NT(Nn,M$,null,"bool"),D$={kernelName:Nn,backendName:"cpu",kernelFunc:F$},_$={kernelName:Tn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{depthRadius:a,bias:i,alpha:o,beta:l}=r;qS(s,"LRN");const u=s.shape[3],c=u-1,h=n.data.get(s.dataId).values,p=oe(s.shape),d=new Float32Array(p);function f(e){const t=e%u;let n=e-t+Math.max(0,t-a);const r=e-t+Math.min(t+a,c);let s=0;for(;n<=r;n++){const e=h[n];s+=e*e}return s}for(let e=0;ea)&&(a=t)}s[n]=a}return s}function z$(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{reductionIndices:a,keepDims:i}=r,o=n;let l=s.shape;const u=l.length,c=ye(a,l);let h=c;const p=Ac(h,u);let d=o.data.get(s.dataId).values;if(null!=p){const e=new Array(u);for(let t=0;tMath.max(e,t))),V$=NT($n,B$),U$={kernelName:$n,backendName:"cpu",kernelFunc:V$},W$={kernelName:An,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t;qS(s,"maxPool");const{filterSize:a,strides:i,pad:o,dimRoundingMode:l}=r;re(iu(i,1),(()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${i} and dilations '1'`));const u=Yl(s.shape,a,i,1,o,l);let c;if(1===u.filterWidth&&1===u.filterHeight&&ue(u.inShape,u.outShape))c=eT({inputs:{x:s},backend:n});else{const e=n.data.get(s.dataId).values,t=Fe(s.shape),r=iC(e,s.shape,s.dtype,t,u,"max");c=n.makeTensorInfo(u.outShape,s.dtype,r.values)}return c}},G$={kernelName:Mn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{filterSize:a,strides:i,pad:o,dimRoundingMode:l,dataFormat:u}=r;qS(s,"maxPool3d");const c=Zl(s.shape,a,i,1,o,l,u),h=lC(n.data.get(s.dataId).values,s.shape,s.dtype,Fe(s.shape),c,"max");return n.makeTensorInfo(h.shape,"float32",h.values)}},H$={kernelName:Fn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a}=t,{filterSize:i,strides:o,pad:l,dimRoundingMode:u}=r;qS([s,a],"maxPool3DGrad");const c=Zl(a.shape,i,o,1,l,u),h=function(e,t){const n=Ni(t.outShape,"int32"),r=t.strideDepth,s=t.strideHeight,a=t.strideWidth,i=t.dilationDepth,o=t.dilationHeight,l=t.dilationWidth,u=t.effectiveFilterDepth,c=t.effectiveFilterHeight,h=t.effectiveFilterWidth,p=t.padInfo.front,d=t.padInfo.top,f=t.padInfo.left;for(let m=0;m=N&&(N=o,S=n*c*h+s*c+i)}}}n.set(S,m,y,r,s,g)}}}return n}(n.bufferSync(a),c),p=c.strideDepth,d=c.strideHeight,f=c.strideWidth,m=c.dilationDepth,g=c.dilationHeight,y=c.dilationWidth,b=c.effectiveFilterDepth,x=c.effectiveFilterHeight,w=c.effectiveFilterWidth,v=b-1-c.padInfo.front,k=w-1-c.padInfo.left,I=x-1-c.padInfo.top,N=Ni(a.shape,"float32"),S=n.bufferSync(s);for(let e=0;e=c.outDepth||Math.floor(r)!==r))for(let s=0;s=c.outHeight||Math.floor(a)!==a))for(let i=0;i=c.outWidth||Math.floor(u)!==u)continue;const p=b*x*w-1-h.get(e,r,a,u,t)===n*x*w+s*w+i?1:0;0!==p&&(l+=S.get(e,r,a,u,t)*p)}}}N.set(l,e,n,r,s,t)}return n.makeTensorInfo(N.shape,N.dtype,N.values)}},j$={kernelName:Rn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a,output:i}=t,o=a;qS([a,i],"maxPoolGrad");const{filterSize:l,strides:u,pad:c,dimRoundingMode:h}=r,p=Yl(o.shape,l,u,1,c,h),d=n.data.get(o.dataId).values,f=Ni(p.outShape,o.dtype,oC(d,o.shape,o.dtype,p).values),m=p.strideHeight,g=p.strideWidth,y=p.dilationHeight,b=p.dilationWidth,x=p.effectiveFilterHeight,w=p.effectiveFilterWidth,v=w-1-p.padInfo.left,k=x-1-p.padInfo.top,I=Ni(o.shape,"float32"),N=n.data.get(s.dataId).values,S=Ni(s.shape,"float32",N);for(let e=0;e=p.outHeight||Math.floor(r)!==r))for(let s=0;s=p.outWidth||Math.floor(o)!==o)continue;const l=x*w-1-f.get(e,r,o,t)===n*w+s?1:0;0!==l&&(i+=S.get(e,r,o,t)*l)}}I.set(i,e,n,r,t)}return n.makeTensorInfo(I.shape,I.dtype,I.values)}},q$={kernelName:Dn,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:r}=e,{filterSize:s,strides:a,pad:i,includeBatchInIndex:o}=t,l=n;qS(r,"MaxPoolWithArgmax");const u=l.data.get(r.dataId).values,c=Yl(r.shape,s,a,[1,1],i),[h,p]=function(e,t,n,r,s){const a=iC(e,0,n,Fe(t),s,"max"),i=oC(e,t,n,s,!0,r);return[a.values,i.values]}(u,r.shape,r.dtype,o,c),d=l.write(h,c.outShape,r.dtype),f=l.write(p,c.outShape,r.dtype);return[{dataId:d,shape:c.outShape,dtype:r.dtype},{dataId:f,shape:c.outShape,dtype:"int32"}]}},K$={kernelName:_n,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:i}=r,o=ye(a,s.shape),l=oe(Cc(s.shape,o)[1]),u=[],c=n.makeTensorInfo([],"float32",new Float32Array([l]));u.push(c);const h=kT({inputs:{x:s},backend:n,attrs:{dtype:"float32"}});u.push(h);const p=AE({inputs:{a:h,b:c},backend:n});u.push(p);const d=iE({inputs:{x:p},backend:n,attrs:{axis:a,keepDims:i}});return u.forEach((e=>n.disposeIntermediateTensorInfo(e))),d}},X$={kernelName:On,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:i}=r;qS(s,"min");const o=ye(a,s.shape);let l=o;const u=Ac(l,s.shape.length);let c=s;null!=u&&(c=WT({inputs:{x:s},backend:n,attrs:{perm:u}}),l=Mc(l.length,s.shape.length)),$c("min",l,c.shape.length);const[h,p]=Cc(c.shape,l),d=oe(p),f=Le(oe(h),c.dtype),m=n.data.get(c.dataId).values;for(let e=0;eMath.min(e,t))),Z$=NT(Ln,Y$),J$={kernelName:Ln,backendName:"cpu",kernelFunc:Z$},Q$={kernelName:zn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{paddings:a,mode:i}=r;qS(s,"mirrorPad");const o=a.map(((e,t)=>e[0]+s.shape[t]+e[1])),l=a.map((e=>e[0])),u=a.map(((e,t)=>e[0]+s.shape[t])),c="reflect"===i?0:1,h=n.data.get(s.dataId).values,p=s.shape.length,d=Fe(s.shape),f=oe(o),m=o.length,g=Fe(o),y=xe(s.dtype,f);for(let e=0;e=u[e]&&(t[e]=2*(u[e]-1)-t[e]+c);t=t.map(((e,t)=>e-l[t]));const n=Be(t,p,d);y[e]=h[n]}return{dataId:n.write(y,o,s.dtype),shape:o,dtype:s.dtype}}},eA=sT(((e,t)=>{const n=e%t;return e<0&&t<0||e>=0&&t>=0?n:(n+t)%t})),tA=NT(Pn,eA),nA={kernelName:Pn,backendName:"cpu",kernelFunc:tA};function rA(e){const{inputs:t,backend:n,attrs:r}=e,{logits:s}=t,{dim:a}=r,i=s.shape.length;let o=a;if(-1===o&&(o=i-1),o!==i-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${i} and dim was ${o}`);const l=ye([o],s.shape),u=z$({inputs:{x:s},backend:n,attrs:{reductionIndices:l,keepDims:!1}}),c=Ec(u.shape,l),h=AT({inputs:{x:u},backend:n,attrs:{shape:c}}),p=DE({inputs:{a:s,b:h},backend:n}),d=kE({inputs:{x:p},backend:n}),f=iE({inputs:{x:d},backend:n,attrs:{axis:l,keepDims:!1}}),m=AT({inputs:{x:f},backend:n,attrs:{shape:c}}),g=AE({inputs:{a:d,b:m},backend:n});return n.disposeIntermediateTensorInfo(u),n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),g}const sA={kernelName:Cr,backendName:"cpu",kernelFunc:rA},aA={kernelName:Bn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{logits:s}=t,{numSamples:a,seed:i,normalized:o}=r;qS(s,"multinomial");const l=o?s:rA({inputs:{logits:s},backend:n,attrs:{dim:-1}}),u=l.shape[0],c=l.shape[1],h=n.data.get(l.dataId).values,p=[u,a],d=Le(oe(p),"int32");for(let e=0;ee!==t?1:0)),mA=NT(Wn,fA,null,"bool"),gA={kernelName:Wn,backendName:"cpu",kernelFunc:mA},yA={kernelName:Kn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{indices:s}=t,{depth:a,onValue:i,offValue:o}=r;qS(s,"oneHot");const l=oe(s.shape),u=new Float32Array(l*a);u.fill(o);const c=n.data.get(s.dataId).values;for(let e=0;e=0&&c[e]{se(a,e.shape,"All tensors passed to stack must have matching shapes"),re(i===e.dtype,(()=>"All tensors passed to stack must have matching dtypes"))}));const o=[],l=RC({inputs:t.map((e=>{const t=NE({inputs:{input:e},backend:n,attrs:{dim:s}});return o.push(t),t})),backend:n,attrs:{axis:s}});return o.forEach((e=>n.disposeIntermediateTensorInfo(e))),l}const kA={kernelName:Xn,backendName:"cpu",kernelFunc:vA},IA={kernelName:Yn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{paddings:a,constantValue:i}=r;qS(s,"pad");const o=a.map(((e,t)=>e[0]+s.shape[t]+e[1])),l=a.map((e=>e[0])),u=n.data.get(s.dataId).values,c=oe(s.shape),h=s.shape.length,p=Fe(s.shape),d=oe(o),f=o.length,m=Fe(o),g=xe(s.dtype,d);0!==i&&g.fill(i);for(let e=0;ee+l[t])),f,m)]=u[e];return{dataId:n.write(g,o,s.dtype),shape:o,dtype:s.dtype}}},NA=sT(((e,t)=>Math.pow(e,t))),SA=NT(Jn,NA),TA={kernelName:Jn,backendName:"cpu",kernelFunc:SA};function CA(e,t,n,r){const[s,a]=Cc(e,r),i=na(t,"int32"),o=Le(oe(s),i),l=oe(a);for(let e=0;en.disposeIntermediateTensorInfo(e))),n.makeTensorInfo(y,g,f)}};function $A(e,t,n,r){if(e===t||e1)return Le(0,r);const s=Le(Math.abs(Math.ceil((t-e)/n)),r);t1/e)),MA={kernelName:rr,backendName:"cpu",kernelFunc:RA},FA={kernelName:lr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{images:s}=t,{alignCorners:a,halfPixelCenters:i,size:o}=r;qS(s,"resizeBilinear");const l=Fe(s.shape),[u,c]=o,[h,p,d,f]=s.shape,m=n.data.get(s.dataId).values,g=new Float32Array(oe([h,u,c,f])),y=[a&&u>1?p-1:p,a&&c>1?d-1:d],b=[a&&u>1?u-1:u,a&&c>1?c-1:c];let x=0;const w=y[0]/b[0],v=y[1]/b[1];for(let e=0;e1?u-1:u,i&&d>1?c-1:c],g=[i&&p>1?p-1:p,i&&d>1?d-1:d],y=m[0]/g[0],b=m[1]/g[1],x=n.data.get(a.dataId).values;let w=0;for(let e=0;e1?p-1:p,a&&c>1?d-1:d],b=[a&&u>1?u-1:u,a&&c>1?c-1:c],x=y[0]/b[0],w=y[1]/b[1];let v=0;for(let e=0;e1?c-1:c,i&&f>1?h-1:h],b=[i&&d>1?d-1:d,i&&f>1?f-1:f],x=y[0]/b[0],w=y[1]/b[1],v=1/x,k=1/w,I=2*Math.ceil(v)+2,N=2*Math.ceil(k)+2;for(let e=0;e=d)continue;const p=t+u*l[1],m=u*x;if(e===Math.min(c-1,i?Math.round(m):Math.floor(m)))for(let e=0;e=f)continue;const s=p+t*l[2],a=t*w;r===Math.min(h-1,i?Math.round(a):Math.floor(a))&&(o+=g[s+n])}}m[a+n]=o}}}}return n.makeTensorInfo(s.shape,s.dtype,m)}},LA={kernelName:hr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{dims:a}=r;qS(s,"reverse");const i=s.shape.length,o=ye(a,s.shape);if(0===i)return eT({inputs:{x:s},backend:n});const l=new Ws(s.shape,s.dtype),u=n.bufferSync(s);for(let e=0;en[e]=s.shape[e]-1-n[e])),l.set(u.get(...n),...t)}return n.makeTensorInfo(l.shape,l.dtype,l.values)}},zA={kernelName:Jr,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{image:r}=e,{radians:s,fillValue:a,center:i}=t,o=n,l=xe(r.dtype,oe(r.shape)),[u,c,h,p]=r.shape,[d,f]=zd(i,c,h),m=Math.sin(s),g=Math.cos(s),y=o.data.get(r.dataId).values;for(let e=0;e=0&&w=0&&v{const t=Math.floor(e);return e-t<.5?Math.floor(e):e-t>.5?Math.ceil(e):t%2==0?t:t+1})),BA={kernelName:pr,backendName:"cpu",kernelFunc:PA},VA=pT((e=>1/Math.sqrt(e))),UA=ZS(dr,VA),WA={kernelName:dr,backendName:"cpu",kernelFunc:UA};function GA(e,t,n,r,s,a,i,o,l,u){const c=[r/s,s],h=e.values,p=t.values;if(0===r)return Ni(n,t.dtype);const d=Ni(c,t.dtype);d.values.fill(l);for(let e=0;e=r/s)throw new Error(`Invalid indices: ${a} does not index into ${n}`);for(let n=0;n1||1===s.shape.length?1:oe(s.shape.slice(1));for(let e=0;ee>=0?KA*e:qA*(Math.exp(e)-1))),YA={kernelName:gr,backendName:"cpu",kernelFunc:XA},ZA=YS(wr,(e=>e<0?-1:e>0?1:0)),JA={kernelName:wr,backendName:"cpu",kernelFunc:ZA},QA=YS(br,(e=>Math.sin(e))),eR={kernelName:br,backendName:"cpu",kernelFunc:QA},tR=YS(xr,(e=>Math.sinh(e))),nR={kernelName:xr,backendName:"cpu",kernelFunc:tR},rR=Math.log(1.1920928955078125e-7)+2,sR=YS(kr,(e=>{const t=e>-rR,n=e=l)throw new Error(yf(t,n,l));++f[n],p=p&&n>=d,d=n}let m=!0;for(let e=0;e0&&(f[e]+=f[e-1])}if(m&&p){const t=e,n=r;for(let e=0;eNumber(e))))),n.makeTensorInfo([m.length],r.dtype,new Int32Array(m))]}};function uR(e,t,n,r,s){const a=oe(r),i=t[0],o=s.length,l=[];let u=1,c=-1;for(let e=0;e0){p[h-1]=1;for(let e=h-2;e>=0;--e)p[e]=p[e+1]*r[e+1]}const d=[];if(o>0){d[o-1]=1;for(let e=o-2;e>=0;--e)d[e]=d[e+1]*l[e+1]}const f=we(n,i*o);for(let t=0;t0?s[o-1]+1:0;if(c<0)throw new Error("segment ids must be >= 0");const h=t.slice();h[0]=c;const p=we(n,h.reduce(((e,t)=>e*t),1));if(0===o)return c>0&&p.fill(i),[p,h];if(c<=0)throw new Error("segment ids must be >= 0");let d=0,f=1,m=0,g=s[d];for(;;){let t=0;if(f=t)throw new Error("segment ids are not increasing")}if(g<0||g>=c)throw new Error(Sf(g,c));g>m&&p.fill(i,m*u,g*u);for(let t=d;t=l[0])throw new Error(Tf(t,r[t],l[0]));for(let t=0;to)break}return m{const t=[...c];t[o]=e;const r=mC({inputs:{x:s},backend:n,attrs:{begin:u,size:t}});return u[o]+=e,r}))}},gR=pT((e=>Math.sqrt(e))),yR=YS(Ir,(e=>Math.sqrt(e))),bR={kernelName:Ir,backendName:"cpu",kernelFunc:yR},xR={kernelName:Dr,backendName:"cpu",kernelFunc:({inputs:e,backend:t})=>{const{x:n}=e,r=t;qS(n,"square");const s=r.data.get(n.dataId).values,a=new Float32Array(s.length);for(let e=0;e{const n=e-t;return n*n})),vR=NT(Fr,wR),kR={kernelName:Fr,backendName:"cpu",kernelFunc:vR},IR=YS(Yr,((e,t)=>{const n=t;return isNaN(e)?NaN:e>0?1:n.alpha})),NR={kernelName:Yr,backendName:"cpu",kernelFunc:IR};function SR(e,t,n,r){const s=Ni(e,t.dtype);for(let e=0;e=1,(()=>`Input must have rank at least 1, got: ${s.shape.length}`));const e=co(b,x,w),t=mC({inputs:{x:s},backend:n,attrs:{begin:b,size:e}});v=AT({inputs:{x:t},backend:n,attrs:{shape:f}}),n.disposeIntermediateTensorInfo(t)}else{const e=SR(d,n.bufferSync(s),w,b);v=n.makeTensorInfo(f,e.dtype,e.values)}return v}};class CR{constructor(e,t,n,r,s,a){this.separator=Fs(e),this.nGramWidths=t,this.leftPad=Fs(n),this.rightPad=Fs(r),this.padWidth=s,this.preserveShort=a}getPadWidth(e){return Math.min(this.padWidth<0?e-1:this.padWidth,e-1)}getNumNGrams(e,t){const n=this.getPadWidth(t);return Math.max(0,e+2*n-t+1)}createNGrams(e,t,n,r,s,a){for(let i=0;i0?0:i-o);let p=0;p+=l*this.leftPad.length;for(let t=0;te.forEach((e=>d[f++]=e));for(let e=0;e0){m(e[h+c-1]);for(let e=0;e0){let e=t[0];if(0!==e)throw new Error(`First split value must be 0, got ${e}`);for(let s=1;s=e;if(r=r&&t[s]<=n,!r)throw new Error(`Invalid split value ${t[s]}, must be in [${e}, ${n}]`);e=t[s]}if(e!==n)throw new Error(`Last split value must be data size. Expected ${n}, got ${e}`)}const s=r-1,a=we("int32",r);if(0===n||0===r){const e=new Array(n);for(let e=0;e<=s;++e)a[e]=0;return[e,a]}a[0]=0;for(let e=1;e<=s;++e){const n=t[e]-t[e-1];let r=0;this.nGramWidths.forEach((e=>{r+=this.getNumNGrams(n,e)})),this.preserveShort&&n>0&&0===r&&(r=1),a[e]=a[e-1]+r}const i=new Array(a[s]);for(let n=0;n{const o=t[n+1]-t[n],l=this.getNumNGrams(o,a);this.createNGrams(e,r,i,s,l,a),s+=l})),this.preserveShort&&s===a[n]){const a=t[n+1]-t[n];if(0===a)continue;const o=a+2*this.padWidth,l=1;this.createNGrams(e,r,i,s,l,o)}}return[i,a]}}function ER(e,t,n,r,s,a,i,o){return new CR(n,r,s,a,i,o).compute(e,t)}const $R={kernelName:Or,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{separator:s,nGramWidths:a,leftPad:i,rightPad:o,padWidth:l,preserveShortSequences:u}=r,{data:c,dataSplits:h}=t,p=n.data.get(c.dataId).values,d=n.data.get(h.dataId).values,[f,m]=ER(p,d,s,a,i,o,l,u);return[n.makeTensorInfo([f.length],"string",f),n.makeTensorInfo(h.shape,"int32",m)]}};function AR(e,t,n,r){if(!e.length)return;if(0===t.length){for(let t=0;tMath.tan(e))),OR={kernelName:Br,backendName:"cpu",kernelFunc:_R},LR=YS(Vr,(e=>Math.tanh(e)));function zR(e,t){const n=new Array(e.rank);for(let r=0;r{const n=t.value-e.value;return 0===n?e.index-t.index:n};function BR(e,t,n=0,r=e.length-1){for(;r>n;){if(r-n>600){const s=r-n+1,a=t-n+1,i=Math.log(s),o=.5*Math.exp(2*i/3),l=.5*Math.sqrt(i*o*(s-o)/s)*Math.sign(a-s/2);BR(e,t,Math.max(n,Math.floor(t-a*o/s+l)),Math.min(r,Math.floor(t+(s-a)*o/s+l)))}const s=e[t];let a=n,i=r;for(Q(e,n,t),PR(e[r],s)>0&&Q(e,n,r);a0;)i-=1}0===PR(e[n],s)?Q(e,n,i):(i+=1,Q(e,i,r)),i<=t&&(n=i+1),t<=i&&(r=i-1)}}function VR(e,t,n,r,s){const a=t[t.length-1],[i,o]=[e.length/a,a],l=xe(n,i*r),u=xe("int32",i*r);for(let t=0;ti[t]={value:e,index:t})),rt-1)if(t<=1)n=0;else{const e=2*t;n-=e*Math.trunc(n/e),n>=t&&(n=e-n-1)}return Z(0,n,t-1)}(e,t);case"wrap":return function(e,t){let n=e;if(n<0)if(t<=1)n=0;else{const e=t-1;n+=t*(Math.trunc(-n/e)+1)}else if(n>t-1)if(t<=1)n=0;else{const e=t-1;n-=t*Math.trunc(n/e)}return Z(0,n,t-1)}(e,t);case"nearest":return function(e,t){return Z(0,e,t-1)}(e,t);case"constant":default:return function(e,t){return e}(e)}}function WR(e,t,n,r,s,a,i,o,l,u,c){return 0<=o&&o{for(let n=0;nn.disposeIntermediateTensorInfo(e))),h}},xA];for(const e of qR)us(e);const KR={},XR={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function YR(e,t){if(!(e in KR)){const n=function(e,t){if(1!==e&&2!==e)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");const n=null==t?function(e){if("undefined"!=typeof OffscreenCanvas&&2===e)return new OffscreenCanvas(300,150);if("undefined"!=typeof document)return document.createElement("canvas");throw new Error("Cannot create a canvas in this context")}(e):t;return n.addEventListener("webglcontextlost",(t=>{t.preventDefault(),delete KR[e]}),!1),1===e?n.getContext("webgl",XR)||n.getContext("experimental-webgl",XR):n.getContext("webgl2",XR)}(e,t);if(null===n)return console.log("Could not get context for WebGL version",e),null;KR[e]=n}const n=KR[e];return null==n||n.isContextLost()?(delete KR[e],YR(e)):(n.disable(n.DEPTH_TEST),n.disable(n.STENCIL_TEST),n.disable(n.BLEND),n.disable(n.DITHER),n.disable(n.POLYGON_OFFSET_FILL),n.disable(n.SAMPLE_COVERAGE),n.enable(n.SCISSOR_TEST),n.enable(n.CULL_FACE),n.cullFace(n.BACK),KR[e])}var ZR,JR,QR;function eM(e,t){return[t,e]}function tM(e){const t=oe(e);return pe(Math.ceil(t/4))}function nM(e,t){return[Math.max(1,Math.ceil(t/2)),Math.max(1,Math.ceil(e/2))]}function rM(e,t){const n=e;let r,s,a,i,o,l,u,c,h,p;return 2===He().getNumber("WEBGL_VERSION")?(r=n.R32F,s=n.R16F,a=n.RGBA16F,i=n.RGBA32F,o=n.RED,u=4,c=1,h=n.HALF_FLOAT,p=n.FLOAT,l=n.RGBA8):(r=e.RGBA,s=e.RGBA,a=e.RGBA,i=n.RGBA,o=e.RGBA,u=4,c=4,h=null!=t?t.HALF_FLOAT_OES:null,p=e.FLOAT,l=e.RGBA),{internalFormatFloat:r,internalFormatHalfFloat:s,internalFormatPackedHalfFloat:a,internalFormatPackedFloat:i,textureFormatFloat:o,downloadTextureFormat:l,downloadUnpackNumChannels:u,defaultNumChannels:c,textureTypeHalfFloat:h,textureTypeFloat:p}}function sM(e,t){const n=t();return He().getBool("DEBUG")&&function(e){const t=e.getError();if(t!==e.NO_ERROR)throw new Error("WebGL Error: "+function(e,t){switch(t){case e.NO_ERROR:return"NO_ERROR";case e.INVALID_ENUM:return"INVALID_ENUM";case e.INVALID_VALUE:return"INVALID_VALUE";case e.INVALID_OPERATION:return"INVALID_OPERATION";case e.INVALID_FRAMEBUFFER_OPERATION:return"INVALID_FRAMEBUFFER_OPERATION";case e.OUT_OF_MEMORY:return"OUT_OF_MEMORY";case e.CONTEXT_LOST_WEBGL:return"CONTEXT_LOST_WEBGL";default:return`Unknown error code ${t}`}}(e,t))}(e),n}function aM(e){return!!(He().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||0===e||5.96e-8e.getExtension(t)),'Extension "'+t+'" not supported on this browser.')}!function(e){e[e.DENSE=0]="DENSE",e[e.SHARED_BATCH=1]="SHARED_BATCH"}(ZR||(ZR={})),function(e){e[e.RENDER=0]="RENDER",e[e.UPLOAD=1]="UPLOAD",e[e.PIXELS=2]="PIXELS",e[e.DOWNLOAD=3]="DOWNLOAD"}(JR||(JR={})),function(e){e[e.UNPACKED_FLOAT16=0]="UNPACKED_FLOAT16",e[e.UNPACKED_FLOAT32=1]="UNPACKED_FLOAT32",e[e.PACKED_4X1_UNSIGNED_BYTE=2]="PACKED_4X1_UNSIGNED_BYTE",e[e.PACKED_2X2_FLOAT32=3]="PACKED_2X2_FLOAT32",e[e.PACKED_2X2_FLOAT16=4]="PACKED_2X2_FLOAT16"}(QR||(QR={}));const oM=/ERROR: [0-9]+:([0-9]+):/g;function lM(e,t){if(sM(e,(()=>e.validateProgram(t))),!1===e.getProgramParameter(t,e.VALIDATE_STATUS))throw console.log(e.getProgramInfoLog(t)),new Error("Shader program validation failed.")}function uM(e,t,n,r,s,a,i){const o=e.getAttribLocation(t,n);return-1!==o&&(sM(e,(()=>e.bindBuffer(e.ARRAY_BUFFER,r))),sM(e,(()=>e.vertexAttribPointer(o,s,e.FLOAT,!1,a,i))),sM(e,(()=>e.enableVertexAttribArray(o))),!0)}function cM(e,t,n,r){sM(e,(()=>function(e,t,n){(function(e,t){const n=e.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,r=t+e.TEXTURE0;if(rn)throw new Error(`textureUnit must be in [gl.TEXTURE0, gl.TEXTURE${n}].`)})(e,n),sM(e,(()=>e.activeTexture(e.TEXTURE0+n))),sM(e,(()=>e.bindTexture(e.TEXTURE_2D,t)))}(e,t,r))),sM(e,(()=>e.uniform1i(n,r)))}function hM(e,t,n){sM(e,(()=>e.bindFramebuffer(e.FRAMEBUFFER,n))),sM(e,(()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0)))}function pM(e,t){sM(e,(()=>e.bindFramebuffer(e.FRAMEBUFFER,t))),sM(e,(()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0)))}function dM(e){const t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+function(e,t){switch(t){case e.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case e.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case e.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return"FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case e.FRAMEBUFFER_UNSUPPORTED:return"FRAMEBUFFER_UNSUPPORTED";default:return`unknown error ${t}`}}(e,t))}function fM(e,t,n){const r=sM(e,(()=>t()));if(null==r)throw new Error(n);return r}function mM(e,t=2){return oe(e.slice(0,e.length-t))}function gM(e){if(0===e.length)throw Error("Cannot get rows and columns of an empty shape array.");return[e.length>1?e[e.length-2]:1,e[e.length-1]]}function yM(e){let t=[1,1,1];return 0===e.length||1===e.length&&1===e[0]||(t=[mM(e),...gM(e)]),t}function bM(e){return e%2==0}function xM(e,t){if(ue(e=e.slice(-2),t=t.slice(-2)))return!0;if(!e.length||!t.length)return!0;if(0===e[0]||0===e[1]||0===t[0]||0===t[1])return!0;if(e.length!==t.length){const n=e.slice(-1)[0],r=t.slice(-1)[0];if(n===r)return!0;if(bM(n)&&bM(r)&&(1===e[0]||1===t[0]))return!0}return e[1]===t[1]&&bM(e[0])&&bM(t[0])}let wM,vM;function kM(e,t){return null!=e.getExtension(t)}function IM(e){try{if(null!=YR(e))return!0}catch(e){return console.log("Error when getting WebGL context: ",e),!1}return!1}function NM(e){const t=rM(e),n=e.createTexture();e.bindTexture(e.TEXTURE_2D,n),e.texImage2D(e.TEXTURE_2D,0,t.internalFormatFloat,1,1,0,t.textureFormatFloat,t.textureTypeFloat,null);const r=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,r),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,n,0);const s=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(n),e.deleteFramebuffer(r),s}function SM(e,t){Array.isArray(e)||(e=[e]),e.forEach((e=>{null!=e&&re("complex64"!==e.dtype,(()=>`${t} does not support complex64 tensors in the WebGL backend.`))}))}const TM=He();function CM(){let e,t,n,r,s,a,i,o,l,u;return 2===He().getNumber("WEBGL_VERSION")?(e="#version 300 es",t="in",n="out",r="in",s="texture",a="outputColor",i="out vec4 outputColor;",o="\n bool isnan_custom(float val) {\n return (val > 0.0 || val < 0.0) ? false : val != 0.0;\n }\n\n bvec4 isnan_custom(vec4 val) {\n return bvec4(isnan_custom(val.x),\n isnan_custom(val.y), isnan_custom(val.z), isnan_custom(val.w));\n }\n\n #define isnan(value) isnan_custom(value)\n ",l="",u="\n #define round(value) newRound(value)\n int newRound(float value) {\n return int(floor(value + 0.5));\n }\n\n ivec4 newRound(vec4 value) {\n return ivec4(floor(value + vec4(0.5)));\n }\n "):(e="",t="attribute",n="varying",r="varying",s="texture2D",a="gl_FragColor",i="",o="\n #define isnan(value) isnan_custom(value)\n bool isnan_custom(float val) {\n return (val > 0. || val < 1. || val == 0.) ? false : true;\n }\n bvec4 isnan_custom(vec4 val) {\n return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w));\n }\n ",l="\n uniform float INFINITY;\n\n bool isinf(float val) {\n return abs(val) == INFINITY;\n }\n bvec4 isinf(vec4 val) {\n return equal(abs(val), vec4(INFINITY));\n }\n ",u="\n int round(float value) {\n return int(floor(value + 0.5));\n }\n\n ivec4 round(vec4 value) {\n return ivec4(floor(value + vec4(0.5)));\n }\n "),{version:e,attribute:t,varyingVs:n,varyingFs:r,texture2D:s,output:a,defineOutput:i,defineSpecialNaN:o,defineSpecialInf:l,defineRound:u}}function EM(e,t,n="index"){const r=Fe(t);return r.map(((t,s)=>`int ${e[s]} = ${n} / ${t}; ${s===r.length-1?`int ${e[s+1]} = ${n} - ${e[s]} * ${t}`:`index -= ${e[s]} * ${t}`};`)).join("")}function $M(e,t,n="index"){const r=Fe(t);return r.map(((t,s)=>`int ${e[s]} = ${n} / outShapeStrides[${s}]; ${s===r.length-1?`int ${e[s+1]} = ${n} - ${e[s]} * outShapeStrides[${s}]`:`index -= ${e[s]} * outShapeStrides[${s}]`};`)).join("")}function AM(e){const t=Fe(e).map((e=>e.toString()));return`\n int getFlatIndex(ivec3 coords) {\n return coords.x * ${t[0]} + coords.y * ${t[1]} + coords.z;\n }\n`}TM.registerFlag("HAS_WEBGL",(()=>TM.getNumber("WEBGL_VERSION")>0)),TM.registerFlag("WEBGL_VERSION",(()=>IM(2)?2:IM(1)?1:0)),TM.registerFlag("WEBGL_CHECK_NUMERICAL_PROBLEMS",(()=>!1)),TM.registerFlag("WEBGL_BUFFER_SUPPORTED",(()=>2===TM.get("WEBGL_VERSION"))),TM.registerFlag("WEBGL_CPU_FORWARD",(()=>!0)),TM.registerFlag("WEBGL_FORCE_F16_TEXTURES",(()=>!1)),TM.registerFlag("WEBGL_PACK",(()=>TM.getBool("HAS_WEBGL"))),TM.registerFlag("WEBGL_PACK_NORMALIZATION",(()=>TM.getBool("WEBGL_PACK"))),TM.registerFlag("WEBGL_PACK_CLIP",(()=>TM.getBool("WEBGL_PACK"))),TM.registerFlag("WEBGL_PACK_DEPTHWISECONV",(()=>TM.getBool("WEBGL_PACK"))),TM.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",(()=>TM.getBool("WEBGL_PACK"))),TM.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",(()=>TM.getBool("WEBGL_PACK"))),TM.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",(()=>TM.getBool("WEBGL_PACK"))),TM.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",(()=>TM.getBool("WEBGL_PACK"))),TM.registerFlag("WEBGL_PACK_REDUCE",(()=>TM.getBool("WEBGL_PACK"))),TM.registerFlag("WEBGL_LAZILY_UNPACK",(()=>TM.getBool("WEBGL_PACK"))),TM.registerFlag("WEBGL_CONV_IM2COL",(()=>TM.getBool("WEBGL_PACK"))),TM.registerFlag("WEBGL_MAX_TEXTURE_SIZE",(()=>function(e){if(null==wM){const t=YR(e);wM=t.getParameter(t.MAX_TEXTURE_SIZE)}return wM}(TM.getNumber("WEBGL_VERSION")))),TM.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",(()=>function(e){if(null==vM){const t=YR(e);vM=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,vM)}(TM.getNumber("WEBGL_VERSION")))),TM.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",(()=>{const e=TM.getNumber("WEBGL_VERSION");return 0===e?0:function(e){if(0===e)return 0;let t;const n=YR(e);return t=kM(n,"EXT_disjoint_timer_query_webgl2")&&2===e?2:kM(n,"EXT_disjoint_timer_query")?1:0,t}(e)})),TM.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",(()=>TM.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!ya())),TM.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",(()=>function(e){if(0===e)return!1;const t=YR(e);if(1===e){if(!kM(t,"OES_texture_float"))return!1}else if(!kM(t,"EXT_color_buffer_float"))return!1;return NM(t)}(TM.getNumber("WEBGL_VERSION")))),TM.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",(()=>!TM.getBool("WEBGL_FORCE_F16_TEXTURES")&&TM.getBool("WEBGL_RENDER_FLOAT32_CAPABLE"))),TM.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",(()=>function(e){if(0===e)return!1;const t=YR(e);if(1!==e){if(kM(t,"EXT_color_buffer_float"))return NM(t);const e="EXT_color_buffer_half_float";if(kM(t,e)){const n=t.getExtension(e);return function(e,t){const n=rM(e,t),r=e.createTexture();e.bindTexture(e.TEXTURE_2D,r),e.texImage2D(e.TEXTURE_2D,0,n.internalFormatHalfFloat,1,1,0,n.textureFormatFloat,n.textureTypeHalfFloat,null);const s=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,s),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,r,0);const a=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(r),e.deleteFramebuffer(s),a}(t,n)}return!1}return!!kM(t,"OES_texture_float")&&!!kM(t,"WEBGL_color_buffer_float")&&NM(t)}(TM.getNumber("WEBGL_VERSION")))),TM.registerFlag("WEBGL_FENCE_API_ENABLED",(()=>{return 2===(e=TM.getNumber("WEBGL_VERSION"))&&null!=YR(e).fenceSync;var e})),TM.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",(()=>TM.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0)),TM.registerFlag("WEBGL_DELETE_TEXTURE_THRESHOLD",(()=>-1),(e=>{if(e<0&&-1!==e)throw new Error(`WEBGL_DELETE_TEXTURE_THRESHOLD must be -1 (indicating never delete) or at least 0, but got ${e}.`)})),TM.registerFlag("WEBGL_FLUSH_THRESHOLD",(()=>ya()?1:-1),(e=>{if(e<0&&-1!==e)throw new Error(`WEBGL_FLUSH_THRESHOLD must be -1 (indicating never manual flush) or at least 0, but got ${e}.`)})),TM.registerFlag("CPU_HANDOFF_SIZE_THRESHOLD",(()=>128)),TM.registerFlag("WEBGL_USE_SHAPES_UNIFORMS",(()=>!1)),TM.registerFlag("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD",(()=>1e5)),TM.registerFlag("TOPK_K_CPU_HANDOFF_THRESHOLD",(()=>128));const RM="\n const float FLOAT_MAX = 1.70141184e38;\n const float FLOAT_MIN = 1.17549435e-38;\n\n lowp vec4 encode_float(highp float v) {\n if (isnan(v)) {\n return vec4(255, 255, 255, 255);\n }\n\n highp float av = abs(v);\n\n if(av < FLOAT_MIN) {\n return vec4(0.0, 0.0, 0.0, 0.0);\n } else if(v > FLOAT_MAX) {\n return vec4(0.0, 0.0, 128.0, 127.0) / 255.0;\n } else if(v < -FLOAT_MAX) {\n return vec4(0.0, 0.0, 128.0, 255.0) / 255.0;\n }\n\n highp vec4 c = vec4(0,0,0,0);\n\n highp float e = floor(log2(av));\n highp float m = exp2(fract(log2(av))) - 1.0;\n\n c[2] = floor(128.0 * m);\n m -= c[2] / 128.0;\n c[1] = floor(32768.0 * m);\n m -= c[1] / 32768.0;\n c[0] = floor(8388608.0 * m);\n\n highp float ebias = e + 127.0;\n c[3] = floor(ebias / 2.0);\n ebias -= c[3] * 2.0;\n c[2] += floor(ebias) * 128.0;\n\n c[3] += 128.0 * step(0.0, -v);\n\n return c / 255.0;\n }\n",{getBroadcastDims:MM}=y;function FM(e,t,n){const r=[];if(e.forEach((e=>{const t=oe(e.shapeInfo.logicalShape);if(e.shapeInfo.isUniform?r.push(`uniform float ${e.name}${t>1?`[${t}]`:""};`):(r.push(`uniform sampler2D ${e.name};`),r.push(`uniform int offset${e.name};`)),n.enableShapeUniforms){const{uniformShape:t}=WM(n.packedInputs,e.shapeInfo.logicalShape,e.shapeInfo.texShape);switch(t.length){case 1:r.push(`uniform int ${e.name}Shape;`);break;case 2:r.push(`uniform ivec2 ${e.name}Shape;`);break;case 3:r.push(`uniform ivec3 ${e.name}Shape;`);break;case 4:r.push(`uniform ivec4 ${e.name}Shape;`)}r.push(`uniform ivec2 ${e.name}TexShape;`)}})),n.enableShapeUniforms){switch(t.logicalShape.length){case 1:r.push("uniform int outShape;");break;case 2:r.push("uniform ivec2 outShape;"),r.push("uniform int outShapeStrides;");break;case 3:r.push("uniform ivec3 outShape;"),r.push("uniform ivec2 outShapeStrides;");break;case 4:r.push("uniform ivec4 outShape;"),r.push("uniform ivec3 outShapeStrides;")}r.push("uniform ivec2 outTexShape;")}n.customUniforms&&n.customUniforms.forEach((e=>{r.push(`uniform ${e.type} ${e.name}${e.arrayIndex?`[${e.arrayIndex}]`:""};`)}));const s=r.join("\n"),a=e.map((e=>function(e,t,n=!1,r){let s="";s+=n?_M(e,r):DM(e,r);const a=e.shapeInfo.logicalShape,i=t.logicalShape;return a.length<=i.length&&(s+=n?function(e,t){const n=e.name,r=n.charAt(0).toUpperCase()+n.slice(1),s="get"+r+"AtOutCoords",a=e.shapeInfo.logicalShape.length,i=t.logicalShape.length,o=MM(e.shapeInfo.logicalShape,t.logicalShape),l=UM(i),u=i-a;let c;const h=["x","y","z","w","u","v"];c=0===a?"":i<2&&o.length>=1?"coords = 0;":o.map((e=>`coords.${h[e+u]} = 0;`)).join("\n");let p="";p=i<2&&a>0?"coords":e.shapeInfo.logicalShape.map(((e,t)=>`coords.${h[t+u]}`)).join(", ");let d="return outputValue;";const f=1===oe(e.shapeInfo.logicalShape),m=1===oe(t.logicalShape);if(1!==a||f||m){if(f&&!m)d=1===i?"\n return vec4(outputValue.x, outputValue.x, 0., 0.);\n ":"\n return vec4(outputValue.x);\n ";else if(o.length){const e=a-2,t=a-1;o.indexOf(e)>-1&&o.indexOf(t)>-1?d="return vec4(outputValue.x);":o.indexOf(e)>-1?d="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":o.indexOf(t)>-1&&(d="return vec4(outputValue.xx, outputValue.zz);")}}else d="\n return vec4(outputValue.xy, outputValue.xy);\n ";return`\n vec4 ${s}() {\n ${l} coords = getOutputCoords();\n ${c}\n vec4 outputValue = get${r}(${p});\n ${d}\n }\n `}(e,t):function(e,t){const n=e.name,r=n.charAt(0).toUpperCase()+n.slice(1),s="get"+r+"AtOutCoords",a=t.texShape,i=e.shapeInfo.texShape,o=e.shapeInfo.logicalShape.length,l=t.logicalShape.length;if(!e.shapeInfo.isUniform&&o===l&&null==e.shapeInfo.flatOffset&&ue(i,a))return`\n float ${s}() {\n return sampleTexture(${n}, resultUV);\n }\n `;const u=UM(l),c=MM(e.shapeInfo.logicalShape,t.logicalShape),h=l-o;let p;const d=["x","y","z","w","u","v"];p=0===o?"":l<2&&c.length>=1?"coords = 0;":c.map((e=>`coords.${d[e+h]} = 0;`)).join("\n");let f="";return f=l<2&&o>0?"coords":e.shapeInfo.logicalShape.map(((e,t)=>`coords.${d[t+h]}`)).join(", "),`\n float ${s}() {\n ${u} coords = getOutputCoords();\n ${p}\n return get${r}(${f});\n }\n `}(e,t)),s}(e,t,n.packedInputs,n.enableShapeUniforms))).join("\n"),i=t.texShape,o=CM(),l=function(e){return`\n float sampleTexture(sampler2D textureSampler, vec2 uv) {\n return ${e.texture2D}(textureSampler, uv).r;\n }\n `}(o);let u,c,h=function(e){return`${e.version}\n precision highp float;\n precision highp int;\n precision highp sampler2D;\n ${e.varyingFs} vec2 resultUV;\n ${e.defineOutput}\n const vec2 halfCR = vec2(0.5, 0.5);\n\n struct ivec5\n {\n int x;\n int y;\n int z;\n int w;\n int u;\n };\n\n struct ivec6\n {\n int x;\n int y;\n int z;\n int w;\n int u;\n int v;\n };\n\n uniform float NAN;\n ${e.defineSpecialNaN}\n ${e.defineSpecialInf}\n ${e.defineRound}\n\n int imod(int x, int y) {\n return x - y * (x / y);\n }\n\n int idiv(int a, int b, float sign) {\n int res = a / b;\n int mod = imod(a, b);\n if (sign < 0. && mod != 0) {\n res -= 1;\n }\n return res;\n }\n\n //Based on the work of Dave Hoskins\n //https://www.shadertoy.com/view/4djSRW\n #define HASHSCALE1 443.8975\n float random(float seed){\n vec2 p = resultUV * seed;\n vec3 p3 = fract(vec3(p.xyx) * HASHSCALE1);\n p3 += dot(p3, p3.yzx + 19.19);\n return fract((p3.x + p3.y) * p3.z);\n }\n\n ${OM}\n ${LM}\n ${zM}\n `}(o);return t.isPacked?(u=function(e,t,n){switch(e.length){case 0:return"\n int getOutputCoords() {\n return 0;\n }\n ";case 1:return function(e,t,n){const r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];return 1===r[0]?n?"\n int getOutputCoords() {\n return 2 * int(resultUV.x * ceil(float(outTexShape[1]) / 2.0));\n }\n ":`\n int getOutputCoords() {\n return 2 * int(resultUV.x * ${r[1]}.0);\n }\n `:1===r[1]?n?"\n int getOutputCoords() {\n return 2 * int(resultUV.y * ceil(float(outTexShape[0]) / 2.0));\n }\n ":`\n int getOutputCoords() {\n return 2 * int(resultUV.y * ${r[0]}.0);\n }\n `:n?"\n int getOutputCoords() {\n ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(packedTexShape[0], packedTexShape[1]));\n return 2 * (resTexRC.x * packedTexShape[1] + resTexRC.y);\n }\n ":`\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${r[0]}, ${r[1]}));\n return 2 * (resTexRC.x * ${r[1]} + resTexRC.y);\n }\n `}(0,t,n);case 2:return function(e,t,n){const r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(ue(e,t))return n?"\n ivec2 getOutputCoords() {\n ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));\n return 2 * ivec2(resultUV.yx * vec2(packedTexShape[0], packedTexShape[1]));\n }\n ":`\n ivec2 getOutputCoords() {\n return 2 * ivec2(resultUV.yx * vec2(${r[0]}, ${r[1]}));\n }\n `;const s=Math.ceil(e[1]/2);return n?"\n ivec2 getOutputCoords() {\n ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));\n int texelsInLogicalRow = int(ceil(float(outShape[1]) / 2.0));\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(packedTexShape[0], packedTexShape[1]));\n\n int index = resTexRC.x * packedTexShape[1] + resTexRC.y;\n int r = 2 * (index / texelsInLogicalRow);\n int c = imod(index, texelsInLogicalRow) * 2;\n\n return ivec2(r, c);\n }\n ":`\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${r[0]}, ${r[1]}));\n\n int index = resTexRC.x * ${r[1]} + resTexRC.y;\n int r = 2 * (index / ${s});\n int c = imod(index, ${s}) * 2;\n\n return ivec2(r, c);\n }\n `}(e,t,n);case 3:return function(e,t,n){if(n)return"\n ivec3 getOutputCoords() {\n ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));\n int texelsInLogicalRow = int(ceil(float(outShape[2]) / 2.0));\n int texelsInBatch = texelsInLogicalRow * int(ceil(float(outShape[1]) / 2.0));\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(packedTexShape[0], packedTexShape[1]));\n int index = resTexRC.x * packedTexShape[1] + resTexRC.y;\n\n int b = index / texelsInBatch;\n index -= b * texelsInBatch;\n\n int r = 2 * (index / texelsInLogicalRow);\n int c = imod(index, texelsInLogicalRow) * 2;\n\n return ivec3(b, r, c);\n }\n ";const r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],s=Math.ceil(e[2]/2),a=s*Math.ceil(e[1]/2);return`\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${r[0]}, ${r[1]}));\n int index = resTexRC.x * ${r[1]} + resTexRC.y;\n\n int b = index / ${a};\n index -= b * ${a};\n\n int r = 2 * (index / ${s});\n int c = imod(index, ${s}) * 2;\n\n return ivec3(b, r, c);\n }\n `}(e,t,n);default:return function(e,t,n){if(n)return"\n ivec4 getOutputCoords() {\n ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(packedTexShape[0], packedTexShape[1]));\n int index = resTexRC.x * packedTexShape[1] + resTexRC.y;\n\n int texelsInLogicalRow = int(ceil(float(outShape[3]) / 2.0));\n int texelsInBatch = texelsInLogicalRow * int(ceil(float(outShape[2]) / 2.0));\n int texelsInBatchN = texelsInBatch * outShape[1];\n\n int b2 = index / texelsInBatchN;\n index -= b2 * texelsInBatchN;\n\n int b = index / texelsInBatch;\n index -= b * texelsInBatch;\n\n int r = 2 * (index / texelsInLogicalRow);\n int c = imod(index, texelsInLogicalRow) * 2;\n\n return ivec4(b2, b, r, c);\n }\n ";const r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],s=Math.ceil(e[e.length-1]/2),a=s*Math.ceil(e[e.length-2]/2);let i=a,o="",l="b, r, c";for(let t=2;t1&&!ue(t,n)&&r.lengthe[t])).join(", ")}function jM(e,t){if(e.length!==t.length)throw Error(`Binary was compiled with ${e.length} inputs, but was executed with ${t.length} inputs`);e.forEach(((e,n)=>{const r=e.logicalShape,s=t[n],a=s.shape;if(!ue(r,a))throw Error(`Binary was compiled with different shapes than the current args. Shapes ${r} and ${a} must match`);if(e.isUniform&&s.isUniform)return;const i=e.texShape,o=s.isUniform?null:s.texData.texShape;if(!ue(i,o))throw Error(`Binary was compiled with different texture shapes than the current args. Shape ${i} and ${o} must match`)}))}function qM(e){return He().getBool("WEBGL_USE_SHAPES_UNIFORMS")&&e<=4}class KM{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=ZR.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];const t=CM();this.outputShape=e,this.enableShapeUniforms=qM(this.outputShape.length),this.userCode=`\n ivec3 outCoordsFromFlatIndex(int index) {\n ${this.enableShapeUniforms?$M(["r","c","d"],e):EM(["r","c","d"],e)}\n return ivec3(r, c, d);\n }\n\n void main() {\n ivec2 resTexRC = ivec2(resultUV.yx * vec2(texShape[0], texShape[1]));\n int index = 4 * (resTexRC.x * texShape[1] + resTexRC.y);\n\n vec4 result = vec4(0.);\n\n for (int i=0; i<4; i++) {\n int flatIndex = index + i;\n ivec3 rc = outCoordsFromFlatIndex(flatIndex);\n result[i] = getA(rc.x, rc.y, rc.z);\n }\n\n ${t.output} = result;\n }\n `}}class XM{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=ZR.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];const t=CM();this.outputShape=e,this.enableShapeUniforms=qM(this.outputShape.length),this.userCode=`\n ivec3 outCoordsFromFlatIndex(int index) {\n ${this.enableShapeUniforms?$M(["r","c","d"],e):EM(["r","c","d"],e)}\n return ivec3(r, c, d);\n }\n\n void main() {\n ivec2 resTexRC = ivec2(resultUV.yx * vec2(texShape[0], texShape[1]));\n int index = 4 * (resTexRC.x * texShape[1] + resTexRC.y);\n\n vec4 result = vec4(0.);\n\n for (int i=0; i<4; i++) {\n int flatIndex = index + i;\n ivec3 rc = outCoordsFromFlatIndex(flatIndex);\n result[i] = getChannel(getA(rc.x, rc.y, rc.z), vec2(rc.y, rc.z));\n }\n\n ${t.output} = result;\n }\n `}}class YM{constructor(e){this.variableNames=["A"],this.outTexUsage=JR.DOWNLOAD;const t=CM();this.outputShape=e,this.userCode=`\n ${RM}\n\n void main() {\n float x = getAAtOutCoords();\n ${t.output} = encode_float(x);\n }\n `}}class ZM{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=JR.DOWNLOAD;const t=CM();this.outputShape=e,this.userCode=`\n ${RM}\n\n void main() {\n ivec3 coords = getOutputCoords();\n float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));\n ${t.output} = encode_float(x);\n }\n `}}class JM{constructor(e,t=!1){this.variableNames=["A"],this.customUniforms=[{name:"texShape",type:"ivec2"}];const n=CM();this.outputShape=e,this.enableShapeUniforms=qM(this.outputShape.length);let r="result";t&&(r="floor(result * 255. + 0.5)"),this.userCode=`\n ${this.enableShapeUniforms?"\n int getFlatIndex(ivec3 coords) {\n return coords.x * outShapeStrides[0] + coords.y * outShapeStrides[1] + coords.z;\n }\n":AM(e)}\n\n void main() {\n ivec3 coords = getOutputCoords();\n\n int flatIndex = getFlatIndex(coords);\n int offset = imod(flatIndex, 4);\n\n flatIndex = idiv(flatIndex, 4, 1.);\n\n int r = flatIndex / texShape[1];\n int c = imod(flatIndex, texShape[1]);\n vec2 uv = (vec2(c, r) + halfCR) / vec2(texShape[1], texShape[0]);\n vec4 values = ${n.texture2D}(A, uv);\n\n float result;\n\n if(offset == 0) {\n result = values[0];\n } else if(offset == 1) {\n result = values[1];\n } else if(offset == 2) {\n result = values[2];\n } else {\n result = values[3];\n }\n\n ${n.output} = vec4(${r}, 0., 0., 0.);\n }\n `}}class QM{constructor(e,t=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.customUniforms=[{name:"texShape",type:"ivec2"}];const n=CM();this.outputShape=e,this.enableShapeUniforms=qM(this.outputShape.length);let r="",s="result";t&&(s="floor(result * 255. + 0.5)");for(let t=0;t<=1;t++)for(let s=0;s<=1;s++){const a=2*t+s;r+=`\n localCoords = coords;\n if(localCoords[2] + ${s} < ${this.enableShapeUniforms?"outShape[2]":`${e[2]}`}) {\n localCoords[2] += ${s};\n if (localCoords[1] + ${t} < ${this.enableShapeUniforms?"outShape[1]":`${e[1]}`}) {\n localCoords[1] += ${t};\n\n flatIndex = getFlatIndex(localCoords);\n offset = imod(flatIndex, 4);\n\n flatIndex = idiv(flatIndex, 4, 1.);\n\n int r = flatIndex / texShape[1];\n int c = imod(flatIndex, texShape[1]);\n vec2 uv = (vec2(c, r) + halfCR) / vec2(texShape[1], texShape[0]);\n values = ${n.texture2D}(A, uv);\n\n if (offset == 0) {\n result[${a}] = values[0];\n } else if (offset == 1) {\n result[${a}] = values[1];\n } else if (offset == 2) {\n result[${a}] = values[2];\n } else {\n result[${a}] = values[3];\n }\n }\n }\n `}this.userCode=`\n ${this.enableShapeUniforms?"\n int getFlatIndex(ivec3 coords) {\n return coords.x * outShapeStrides[0] + coords.y * outShapeStrides[1] + coords.z;\n }\n":AM(e)}\n\n void main() {\n ivec3 coords = getOutputCoords();\n\n vec4 result = vec4(0.);\n int flatIndex, r, c, offset;\n ivec3 localCoords;\n vec2 uv;\n vec4 values;\n\n ${r}\n\n ${n.output} = ${s};\n }\n `}}function eF(e,t,n,r,s,a){!function(e,t){const n=He().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(e<=0||t<=0)throw new Error(`Requested texture size [${e}x${t}] is invalid.`);if(e>n||t>n)throw new Error(`Requested texture size [${e}x${t}] greater than WebGL maximum on this browser / GPU [${n}x${n}].`)}(t,n);const i=function(e){return fM(e,(()=>e.createTexture()),"Unable to create WebGLTexture.")}(e),o=e.TEXTURE_2D;return sM(e,(()=>e.bindTexture(o,i))),sM(e,(()=>e.texParameteri(o,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE))),sM(e,(()=>e.texParameteri(o,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE))),sM(e,(()=>e.texParameteri(o,e.TEXTURE_MIN_FILTER,e.NEAREST))),sM(e,(()=>e.texParameteri(o,e.TEXTURE_MAG_FILTER,e.NEAREST))),1===He().getNumber("WEBGL_VERSION")?sM(e,(()=>e.texImage2D(o,0,r,t,n,0,s,a,null))):sM(e,(()=>e.texStorage2D(o,1,r,t,n))),sM(e,(()=>e.bindTexture(e.TEXTURE_2D,null))),{texture:i,texShape:[n,t]}}function tF(e){return e.internalFormatFloat}function nF(e){return e.internalFormatHalfFloat}function rF(e){return e.downloadTextureFormat}function sF(e){return e.internalFormatPackedFloat}function aF(e){return e.internalFormatPackedHalfFloat}class iF{constructor(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];const t=He().getNumber("WEBGL_VERSION");null!=e?(this.gl=e,function(e,t){KR[e]=t}(t,e)):this.gl=YR(t);let n="WEBGL_color_buffer_float";const r="EXT_color_buffer_half_float";if(1===He().getNumber("WEBGL_VERSION")){const e="OES_texture_float",t="OES_texture_half_float";if(this.textureFloatExtension=iM(this.gl,e),kM(this.gl,t))this.textureHalfFloatExtension=iM(this.gl,t);else if(He().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support half float textures, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.");if(this.colorBufferFloatExtension=this.gl.getExtension(n),kM(this.gl,r))this.colorBufferHalfFloatExtension=iM(this.gl,r);else if(He().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support color renderable half floats, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.")}else if(n="EXT_color_buffer_float",kM(this.gl,n))this.colorBufferFloatExtension=this.gl.getExtension(n);else{if(!kM(this.gl,r))throw new Error("GL context does not support color renderable floats");this.colorBufferHalfFloatExtension=this.gl.getExtension(r)}this.vertexBuffer=function(e){return function(e,t){const n=fM(e,(()=>e.createBuffer()),"Unable to create WebGLBuffer");return sM(e,(()=>e.bindBuffer(e.ARRAY_BUFFER,n))),sM(e,(()=>e.bufferData(e.ARRAY_BUFFER,t,e.STATIC_DRAW))),n}(e,new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]))}(this.gl),this.indexBuffer=function(e){return function(e,t){const n=fM(e,(()=>e.createBuffer()),"Unable to create WebGLBuffer");return sM(e,(()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,n))),sM(e,(()=>e.bufferData(e.ELEMENT_ARRAY_BUFFER,t,e.STATIC_DRAW))),n}(e,new Uint16Array([0,1,2,2,1,3]))}(this.gl),this.framebuffer=function(e){return fM(e,(()=>e.createFramebuffer()),"Unable to create WebGLFramebuffer.")}(this.gl),this.textureConfig=rM(this.gl,this.textureHalfFloatExtension)}get debug(){return He().getBool("DEBUG")}dispose(){if(this.disposed)return;null!=this.program&&console.warn("Disposing a GPGPUContext that still has a bound WebGLProgram. This is probably a resource leak, delete the program with GPGPUContext.deleteProgram before disposing."),null!=this.outputTexture&&console.warn("Disposing a GPGPUContext that still has a bound output matrix texture. This is probably a resource leak, delete the output matrix texture with GPGPUContext.deleteMatrixTexture before disposing.");const e=this.gl;sM(e,(()=>e.finish())),sM(e,(()=>e.bindFramebuffer(e.FRAMEBUFFER,null))),sM(e,(()=>e.deleteFramebuffer(this.framebuffer))),sM(e,(()=>e.bindBuffer(e.ARRAY_BUFFER,null))),sM(e,(()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null))),sM(e,(()=>e.deleteBuffer(this.indexBuffer))),this.disposed=!0}createFloat32MatrixTexture(e,t){return this.throwIfDisposed(),function(e,t,n,r){const[s,a]=eM(t,n);return eF(e,s,a,tF(r),r.textureFormatFloat,e.FLOAT)}(this.gl,e,t,this.textureConfig)}createFloat16MatrixTexture(e,t){return this.throwIfDisposed(),function(e,t,n,r){const[s,a]=eM(t,n);return eF(e,s,a,nF(r),r.textureFormatFloat,r.textureTypeHalfFloat)}(this.gl,e,t,this.textureConfig)}createUnsignedBytesMatrixTexture(e,t){return this.throwIfDisposed(),function(e,t,n,r){const[s,a]=eM(t,n);return eF(e,s,a,rF(r),e.RGBA,e.UNSIGNED_BYTE)}(this.gl,e,t,this.textureConfig)}uploadPixelDataToTexture(e,t){this.throwIfDisposed(),function(e,t,n){sM(e,(()=>e.bindTexture(e.TEXTURE_2D,t))),n.data instanceof Uint8Array?2===He().getNumber("WEBGL_VERSION")?sM(e,(()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,n.width,n.height,e.RGBA,e.UNSIGNED_BYTE,n.data))):sM(e,(()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,n.width,n.height,0,e.RGBA,e.UNSIGNED_BYTE,n.data))):2===He().getNumber("WEBGL_VERSION")?sM(e,(()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,e.RGBA,e.UNSIGNED_BYTE,n))):sM(e,(()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,n))),sM(e,(()=>e.bindTexture(e.TEXTURE_2D,null)))}(this.gl,e,t)}uploadDenseMatrixToTexture(e,t,n,r){this.throwIfDisposed(),function(e,t,n,r,s,a){let i,o,l;sM(e,(()=>e.bindTexture(e.TEXTURE_2D,t))),s instanceof Uint8Array?(i=new Uint8Array(n*r*4),o=e.UNSIGNED_BYTE,l=e.RGBA):(i=new Float32Array(n*r*4),o=e.FLOAT,l=a.internalFormatPackedFloat),i.set(s),2===He().getNumber("WEBGL_VERSION")?sM(e,(()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,r,e.RGBA,o,i))):sM(e,(()=>e.texImage2D(e.TEXTURE_2D,0,l,n,r,0,e.RGBA,o,i))),sM(e,(()=>e.bindTexture(e.TEXTURE_2D,null)))}(this.gl,e,t,n,r,this.textureConfig)}createFloat16PackedMatrixTexture(e,t){return this.throwIfDisposed(),function(e,t,n,r){const[s,a]=nM(t,n);return eF(e,s,a,aF(r),e.RGBA,r.textureTypeHalfFloat)}(this.gl,e,t,this.textureConfig)}createPackedMatrixTexture(e,t){return this.throwIfDisposed(),function(e,t,n,r){const[s,a]=nM(t,n);return eF(e,s,a,sF(r),e.RGBA,e.FLOAT)}(this.gl,e,t,this.textureConfig)}deleteMatrixTexture(e){this.throwIfDisposed(),this.outputTexture===e&&(pM(this.gl,this.framebuffer),this.outputTexture=null),sM(this.gl,(()=>this.gl.deleteTexture(e)))}downloadByteEncodedFloatMatrixFromOutputTexture(e,t,n){return this.downloadMatrixDriver(e,(()=>function(e,t,n,r){const[s,a]=eM(t,n),i=new Uint8Array(t*n*4);return sM(e,(()=>e.readPixels(0,0,s,a,r.downloadTextureFormat,e.UNSIGNED_BYTE,i))),new Float32Array(i.buffer)}(this.gl,t,n,this.textureConfig)))}downloadPackedMatrixFromBuffer(e,t,n,r,s,a){return function(e,t,n,r,s,a,i,o){const l=e,u=new Float32Array(function(e,t){const[n,r]=nM(e,t);return n*r*4}(a,i));return l.bindBuffer(l.PIXEL_PACK_BUFFER,t),l.getBufferSubData(l.PIXEL_PACK_BUFFER,0,u),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),u}(this.gl,e,0,0,0,s,a,this.textureConfig)}downloadFloat32MatrixFromBuffer(e,t){return function(e,t,n){const r=e,s=new Float32Array(n);return r.bindBuffer(r.PIXEL_PACK_BUFFER,t),r.getBufferSubData(r.PIXEL_PACK_BUFFER,0,s),r.bindBuffer(r.PIXEL_PACK_BUFFER,null),s}(this.gl,e,t)}createBufferFromTexture(e,t,n){this.bindTextureToFrameBuffer(e);const r=function(e,t,n,r){const s=e.createBuffer();sM(e,(()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,s)));const a=16*t*n;return sM(e,(()=>e.bufferData(e.PIXEL_PACK_BUFFER,a,e.STREAM_READ))),sM(e,(()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,0))),sM(e,(()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,null))),s}(this.gl,t,n,this.textureConfig);return this.unbindTextureToFrameBuffer(),r}createAndWaitForFence(){const e=this.createFence(this.gl);return this.pollFence(e)}createFence(e){let t,n;if(He().getBool("WEBGL_FENCE_API_ENABLED")){const r=e,s=r.fenceSync(r.SYNC_GPU_COMMANDS_COMPLETE,0);e.flush(),n=()=>{const e=r.clientWaitSync(s,0,0);return e===r.ALREADY_SIGNALED||e===r.CONDITION_SATISFIED},t=s}else He().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(t=this.beginQuery(),this.endQuery(),n=()=>this.isQueryAvailable(t,He().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))):n=()=>!0;return{query:t,isFencePassed:n}}downloadMatrixFromPackedTexture(e,t,n){return this.downloadMatrixDriver(e,(()=>function(e,t,n){const r=new Float32Array(t*n*4);return sM(e,(()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,r))),r}(this.gl,t,n)))}createProgram(e){this.throwIfDisposed();const t=this.gl;null==this.vertexShader&&(this.vertexShader=function(e){const t=CM();return function(e,t){const n=fM(e,(()=>e.createShader(e.VERTEX_SHADER)),"Unable to create vertex WebGLShader.");if(sM(e,(()=>e.shaderSource(n,t))),sM(e,(()=>e.compileShader(n))),!1===e.getShaderParameter(n,e.COMPILE_STATUS))throw console.log(e.getShaderInfoLog(n)),new Error("Failed to compile vertex shader.");return n}(e,`${t.version}\n precision highp float;\n ${t.attribute} vec3 clipSpacePos;\n ${t.attribute} vec2 uv;\n ${t.varyingVs} vec2 resultUV;\n\n void main() {\n gl_Position = vec4(clipSpacePos, 1);\n resultUV = uv;\n }`)}(t));const n=function(e){return fM(e,(()=>e.createProgram()),"Unable to create WebGLProgram.")}(t);return sM(t,(()=>t.attachShader(n,this.vertexShader))),sM(t,(()=>t.attachShader(n,e))),function(e,t){if(sM(e,(()=>e.linkProgram(t))),!1===e.getProgramParameter(t,e.LINK_STATUS))throw console.log(e.getProgramInfoLog(t)),new Error("Failed to link vertex and fragment shaders.")}(t,n),this.debug&&lM(t,n),this.vertexAttrsAreBound||(this.setProgram(n),this.vertexAttrsAreBound=function(e,t,n){return sM(e,(()=>e.bindBuffer(e.ARRAY_BUFFER,n))),uM(e,t,"clipSpacePos",n,3,20,0)&&uM(e,t,"uv",n,2,20,12)}(t,this.program,this.vertexBuffer)),n}deleteProgram(e){this.throwIfDisposed(),e===this.program&&(this.program=null),null!=e&&sM(this.gl,(()=>this.gl.deleteProgram(e)))}setProgram(e){this.throwIfDisposed(),this.program=e,null!=this.program&&this.debug&&lM(this.gl,this.program),sM(this.gl,(()=>this.gl.useProgram(e)))}getUniformLocation(e,t,n=!0){return this.throwIfDisposed(),n?function(e,t,n){return fM(e,(()=>e.getUniformLocation(t,n)),'uniform "'+n+'" not present in program.')}(this.gl,e,t):function(e,t,n){return e.getUniformLocation(t,n)}(this.gl,e,t)}getAttributeLocation(e,t){return this.throwIfDisposed(),sM(this.gl,(()=>this.gl.getAttribLocation(e,t)))}getUniformLocationNoThrow(e,t){return this.throwIfDisposed(),this.gl.getUniformLocation(e,t)}setInputMatrixTexture(e,t,n){this.throwIfDisposed(),this.throwIfNoProgram(),cM(this.gl,e,t,n)}setOutputMatrixTexture(e,t,n){this.setOutputMatrixTextureDriver(e,n,t)}setOutputPackedMatrixTexture(e,t,n){this.throwIfDisposed();const[r,s]=nM(t,n);this.setOutputMatrixTextureDriver(e,r,s)}setOutputMatrixWriteRegion(e,t,n,r){this.setOutputMatrixWriteRegionDriver(n,e,r,t)}setOutputPackedMatrixWriteRegion(e,t,n,r){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")}debugValidate(){null!=this.program&&lM(this.gl,this.program),dM(this.gl)}executeProgram(){this.throwIfDisposed(),this.throwIfNoProgram();const e=this.gl;this.debug&&this.debugValidate(),sM(e,(()=>e.drawElements(e.TRIANGLES,6,e.UNSIGNED_SHORT,0)))}blockUntilAllProgramsCompleted(){this.throwIfDisposed(),sM(this.gl,(()=>this.gl.finish()))}getQueryTimerExtension(){return null==this.disjointQueryTimerExtension&&(this.disjointQueryTimerExtension=iM(this.gl,2===He().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")?"EXT_disjoint_timer_query_webgl2":"EXT_disjoint_timer_query")),this.disjointQueryTimerExtension}getQueryTimerExtensionWebGL2(){return this.getQueryTimerExtension()}getQueryTimerExtensionWebGL1(){return this.getQueryTimerExtension()}beginQuery(){if(2===He().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){const e=this.gl,t=this.getQueryTimerExtensionWebGL2(),n=e.createQuery();return e.beginQuery(t.TIME_ELAPSED_EXT,n),n}const e=this.getQueryTimerExtensionWebGL1(),t=e.createQueryEXT();return e.beginQueryEXT(e.TIME_ELAPSED_EXT,t),t}endQuery(){if(2===He().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){const e=this.gl,t=this.getQueryTimerExtensionWebGL2();return void e.endQuery(t.TIME_ELAPSED_EXT)}const e=this.getQueryTimerExtensionWebGL1();e.endQueryEXT(e.TIME_ELAPSED_EXT)}async waitForQueryAndGetTime(e){return await me((()=>this.disposed||this.isQueryAvailable(e,He().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")))),this.getQueryTime(e,He().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}getQueryTime(e,t){if(0===t)return null;if(2===t){const t=this.gl;return t.getQueryParameter(e,t.QUERY_RESULT)/1e6}{const t=this.getQueryTimerExtensionWebGL1();return t.getQueryObjectEXT(e,t.QUERY_RESULT_EXT)/1e6}}isQueryAvailable(e,t){if(0===t)return!0;if(2===t){const t=this.gl,n=this.getQueryTimerExtensionWebGL2(),r=t.getQueryParameter(e,t.QUERY_RESULT_AVAILABLE);return null==this.disjoint&&(this.disjoint=this.gl.getParameter(n.GPU_DISJOINT_EXT)),r&&!this.disjoint}{const t=this.getQueryTimerExtensionWebGL1(),n=t.getQueryObjectEXT(e,t.QUERY_RESULT_AVAILABLE_EXT);return null==this.disjoint&&(this.disjoint=this.gl.getParameter(t.GPU_DISJOINT_EXT)),n&&!this.disjoint}}pollFence(e){return new Promise((t=>{this.addItemToPoll((()=>e.isFencePassed()),(()=>t()))}))}pollItems(){const e=function(e){let t=0;for(;te.isDoneFn)));for(let t=0;t<=e;++t){const{resolveFn:e}=this.itemsToPoll[t];e()}this.itemsToPoll=this.itemsToPoll.slice(e+1)}addItemToPoll(e,t){this.itemsToPoll.push({isDoneFn:e,resolveFn:t}),this.itemsToPoll.length>1||me((()=>(this.pollItems(),0===this.itemsToPoll.length)))}bindTextureToFrameBuffer(e){this.throwIfDisposed(),hM(this.gl,e,this.framebuffer),this.debug&&dM(this.gl)}unbindTextureToFrameBuffer(){null!=this.outputTexture?(hM(this.gl,this.outputTexture,this.framebuffer),this.debug&&dM(this.gl)):pM(this.gl,this.framebuffer)}downloadMatrixDriver(e,t){this.bindTextureToFrameBuffer(e);const n=t();return this.unbindTextureToFrameBuffer(),n}setOutputMatrixTextureDriver(e,t,n){this.throwIfDisposed();const r=this.gl;hM(r,e,this.framebuffer),this.debug&&dM(r),this.outputTexture=e,sM(r,(()=>r.viewport(0,0,t,n))),sM(r,(()=>r.scissor(0,0,t,n)))}setOutputMatrixWriteRegionDriver(e,t,n,r){this.throwIfDisposed(),sM(this.gl,(()=>this.gl.scissor(e,t,n,r)))}throwIfDisposed(){if(this.disposed)throw new Error("Attempted to use disposed GPGPUContext.")}throwIfNoProgram(){if(null==this.program)throw new Error("No GPU program is currently set.")}}const{addImpl:oF,bincountImpl:lF,bincountReduceImpl:uF,ceilImpl:cF,concatImpl:hF,equalImpl:pF,expImpl:dF,expm1Impl:fF,floorImpl:mF,gatherNdImpl:gF,gatherV2Impl:yF,greaterImpl:bF,greaterEqualImpl:xF,lessImpl:wF,lessEqualImpl:vF,linSpaceImpl:kF,logImpl:IF,maxImpl:NF,maximumImpl:SF,minimumImpl:TF,multiplyImpl:CF,negImpl:EF,notEqualImpl:$F,prodImpl:AF,rangeImpl:RF,rsqrtImpl:MF,sigmoidImpl:FF,simpleAbsImpl:DF,sliceImpl:_F,sparseFillEmptyRowsImpl:OF,sparseReshapeImpl:LF,sparseSegmentReductionImpl:zF,sqrtImpl:PF,stridedSliceImpl:BF,stringNGramsImpl:VF,stringSplitImpl:UF,stringToHashBucketFastImpl:WF,subImpl:GF,tileImpl:HF,topKImpl:jF,transposeImpl:qF,uniqueImpl:KF}=H;function XF(e,t){return["x","y","z","w","u","v"].slice(0,t).map((t=>`${e}.${t}`))}function YF(e,t){return 1===t?[e]:XF(e,t)}class ZF{constructor(e){if(this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outputShape=e,this.rank=e.length,this.enableShapeUniforms=qM(this.outputShape.length),0===this.rank)this.userCode="\n void main() {\n setOutput(vec4(getA(), 0., 0., 0.));\n }\n ";else{const e=YF("rc",this.rank),t=UM(this.rank),n=this.getOutOfBoundsCondition(e),r=this.getSetup(e),s=this.getOutput(e);this.userCode=`\n void main() {\n ${t} rc = getOutputCoords();\n\n if(${n}) {\n setOutput(vec4(0));\n } else {\n ${r}\n\n setOutput(vec4(${s}));\n }\n }\n `}}getSourceCoordsArr(e){const t=[];for(let n=0;n<=1;n++)for(let r=0;r<=1;r++){let s=`${0===n?"r":"rp1"}, ${0===r?"c":"cp1"}`;for(let t=2;t ${this.enableShapeUniforms?"outShape":this.outputShape[0]}`;let t="";for(let n=this.rank-2;n= ${this.enableShapeUniforms?`outShape[${n}]`:this.outputShape[n]}`,n= ${n};\n bool rEdge = rp1 >= ${r};\n `}getOutput(e){const t=this.getSourceCoordsArr(e);return 1===this.rank?`getA(rc), (rc + 1 >= ${this.enableShapeUniforms?"outShape":this.outputShape[0]} ? 0. : getA(rc + 1)), 0, 0`:`getA(${t[0]}),\n cEdge ? 0. : getA(${t[1]}),\n rEdge ? 0. : getA(${t[2]}),\n rEdge || cEdge ? 0. : getA(${t[3]})`}}class JF{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec3"}],this.outputShape=e,this.enableShapeUniforms=qM(this.outputShape.length);let n="";for(let e=0;e<4;e++){let t="thisRC = rc;";e%2==1&&(t+="thisRC.z += 1;"),e>1&&(t+="thisRC.y += 1;"),n+=`\n ${t}\n ${e>0?"if(thisRC.y < rows && thisRC.z < cols){":""}\n int flatIndex = getFlatIndex(thisRC);\n\n ivec3 inputRC = inputCoordsFromReshapedOutCoords(flatIndex);\n vec2 inputRCInnerDims = vec2(float(inputRC.y),float(inputRC.z));\n\n result[${e}] =\n getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);\n ${e>0?"}":""}\n `}var r,s;this.userCode=`\n ${r=t,s=this.enableShapeUniforms,`\n ivec3 inputCoordsFromReshapedOutCoords(int index) {\n ${s?function(e,t,n="index"){const r=function(e,t){const n=e.length,r=e.map((e=>`${t}[${e}]`)),s=new Array(n-1);s[n-2]=r[n-1];for(let e=n-3;e>=0;--e)s[e]=`(${s[e+1]} * ${r[e+1]})`;return s}(e.map(((e,t)=>t)),t);return r.map(((t,s)=>`int ${e[s]} = ${n} / ${r[s]}; ${s===r.length-1?`int ${e[s+1]} = ${n} - ${e[s]} * ${r[s]}`:`index -= ${e[s]} * ${r[s]}`};`)).join("")}(["r","c","d"],"inputShape"):EM(["r","c","d"],r)}\n return ivec3(r, c, d);\n }\n `}\n ${this.enableShapeUniforms?"\n int getFlatIndex(ivec3 coords) {\n return coords.x * outShapeStrides[0] + coords.y * outShapeStrides[1] + coords.z;\n }\n":AM(e)}\n\n void main() {\n ivec3 rc = getOutputCoords();\n\n vec4 result = vec4(0.);\n\n ivec3 thisRC;\n int rows = ${this.enableShapeUniforms?"outShape[1]":e[1]};\n int cols = ${this.enableShapeUniforms?"outShape[2]":e[2]};\n\n ${n}\n\n setOutput(result);\n }\n `}}class QF{constructor(e){this.gpgpu=e,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0,this.freeTextures={},this.logEnabled=!1,this.usedTextures={}}acquireTexture(e,t,n){const r=tD(t,n),s=nD(e,r,n);s in this.freeTextures||(this.freeTextures[s]=[]),s in this.usedTextures||(this.usedTextures[s]=[]);const a=eD(e,r,this.gpgpu.gl,this.gpgpu.textureConfig,n);if(this.freeTextures[s].length>0){this.numFreeTextures--,this.numUsedTextures++,this._numBytesFree-=a,this.log();const e=this.freeTextures[s].shift();return this.usedTextures[s].push(e),e}let i;return r===QR.PACKED_2X2_FLOAT32?i=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):r===QR.PACKED_2X2_FLOAT16?i=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):r===QR.UNPACKED_FLOAT32?i=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):r===QR.UNPACKED_FLOAT16?i=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):r===QR.PACKED_4X1_UNSIGNED_BYTE&&(i=this.gpgpu.createUnsignedBytesMatrixTexture(e[0],e[1])),this.usedTextures[s].push(i),this.numUsedTextures++,this._numBytesAllocated+=a,this.log(),i}releaseTexture(e,t,n,r){if(null==this.freeTextures)return;const s=tD(n,r),a=nD(t,s,r);a in this.freeTextures||(this.freeTextures[a]=[]);const i=eD(t,s,this.gpgpu.gl,this.gpgpu.textureConfig,r),o=He().get("WEBGL_DELETE_TEXTURE_THRESHOLD");-1!==o&&this._numBytesAllocated>o?(this.gpgpu.deleteMatrixTexture(e.texture),this._numBytesAllocated-=i):(this.freeTextures[a].push(e),this.numFreeTextures++,this._numBytesFree+=i),this.numUsedTextures--;const l=this.usedTextures[a],u=l.indexOf(e);if(u<0)throw new Error("Cannot release a texture that was never provided by this texture manager");l.splice(u,1),this.log()}log(){if(!this.logEnabled)return;const e=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",`${this.numFreeTextures} / ${this.numUsedTextures}`,`(${e})`);const t=this._numBytesFree/this._numBytesAllocated;console.log(`Bytes allocated: ${this._numBytesAllocated}`),console.log(`Bytes unused: ${this._numBytesFree} (${Math.round(100*t)}%)`)}get numBytesAllocated(){return this._numBytesAllocated}get numBytesFree(){return this._numBytesFree}getNumUsedTextures(){return this.numUsedTextures}getNumFreeTextures(){return this.numFreeTextures}dispose(){if(null!=this.freeTextures){for(const e in this.freeTextures)this.freeTextures[e].forEach((e=>{this.gpgpu.deleteMatrixTexture(e.texture)}));for(const e in this.usedTextures)this.usedTextures[e].forEach((e=>{this.gpgpu.deleteMatrixTexture(e.texture)}));this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0}}}function eD(e,t,n,r,s){const a=function(e,t){switch(e){case QR.PACKED_2X2_FLOAT32:return sF(t);case QR.PACKED_2X2_FLOAT16:return aF(t);case QR.UNPACKED_FLOAT32:return tF(t);case QR.UNPACKED_FLOAT16:return nF(t);case QR.PACKED_4X1_UNSIGNED_BYTE:return rF(t);default:throw new Error(`Unknown physical texture type ${e}`)}}(t,r);let i;if(s){const[t,n]=nM(e[0],e[1]);i=t*n}else{const[t,n]=eM(e[0],e[1]);i=t*n}return i*function(e,t){const n=e;if(t===n.R32F)return 4;if(t===n.R16F)return 2;if(t===n.RGBA32F)return 16;if(t===e.RGBA)return 16;if(t===n.RGBA16F)return 8;if(t===n.RGBA8)return 4;throw new Error(`Unknown internal format ${t}`)}(n,a)}function tD(e,t){if(e===JR.UPLOAD)return QR.PACKED_2X2_FLOAT32;if(e===JR.RENDER||null==e)return function(e){return He().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?QR.PACKED_2X2_FLOAT32:QR.UNPACKED_FLOAT32:e?QR.PACKED_2X2_FLOAT16:QR.UNPACKED_FLOAT16}(t);if(e===JR.DOWNLOAD||e===JR.PIXELS)return QR.PACKED_4X1_UNSIGNED_BYTE;throw new Error(`Unknown logical texture type ${e}`)}function nD(e,t,n){return`${e[0]}_${e[1]}_${t}_${n}`}class rD{constructor(e,t){this.variableNames=["A"],this.outputShape=e,this.enableShapeUniforms=qM(this.outputShape.length),this.userCode=`\n float unaryOperation(float x) {\n ${t}\n }\n\n void main() {\n float x = getAAtOutCoords();\n float y = unaryOperation(x);\n\n setOutput(y);\n }\n `}}const sD="return abs(x);",aD="return x;";class iD{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.enableShapeUniforms=qM(this.outputShape.length),this.userCode=`\n vec4 unaryOperation(vec4 x) {\n ${t}\n }\n\n void main() {\n vec4 x = getAAtOutCoords();\n vec4 y = unaryOperation(x);\n\n setOutput(y);\n }\n `}}class oD{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e,this.enableShapeUniforms=qM(this.outputShape.length);const t=e.length,n=YF("rc",t),r=UM(t),s=function(e,t){if(1===e)return"rc";let n="";for(let r=0;rt.push(e)))}const t=this.texData.get(e),{values:n,shape:r,slice:s,dtype:a,complexTensorInfos:i,isPacked:o}=t;if(null!=s){let t;t=o?new iD(r,aD):new rD(r,aD);const n=this.runWebGLProgram(t,[{dataId:e,shape:r,dtype:a}],a),s=this.read(n.dataId);return this.disposeIntermediateTensorInfo(n),s}if(null!=n)return this.convertAndCacheOnCPU(e);if(He().getBool("DEBUG")&&!He().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&2===He().getNumber("WEBGL_VERSION"))throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");let l,u,c=null;if("complex64"!==a&&He().get("WEBGL_BUFFER_SUPPORTED")){l=this.decode(e);const t=this.texData.get(l.dataId);c=this.gpgpu.createBufferFromTexture(t.texture.texture,...tM(r))}if(this.pendingRead.set(e,[]),"complex64"!==a&&await this.gpgpu.createAndWaitForFence(),"complex64"===a){const e=await Promise.all([this.read(i.real.dataId),this.read(i.imag.dataId)]);u=Jd(e[0],e[1])}else if(null==c)u=this.getValuesFromTexture(e);else{const e=oe(r);u=this.gpgpu.downloadFloat32MatrixFromBuffer(c,e)}if(null!=l&&this.disposeIntermediateTensorInfo(l),null!=c){const e=this.gpgpu.gl;sM(e,(()=>e.deleteBuffer(c)))}const h=this.convertAndCacheOnCPU(e,u),p=this.pendingRead.get(e);return this.pendingRead.delete(e),p.forEach((e=>e(h))),this.pendingDisposal.has(e)&&(this.pendingDisposal.delete(e),this.disposeData(e)&&jo().removeDataId(e,this),this.pendingDeletes--),h}readToGPU(e,t={}){const n=this.texData.get(e),{values:r,shape:s,slice:a,dtype:i,isPacked:o,texture:l}=n;if("complex64"===i)throw new Error("Does not support reading texture for complex64 dtype.");if(null!=a){let n;n=o?new iD(s,aD):new rD(s,aD);const r=this.runWebGLProgram(n,[{dataId:e,shape:s,dtype:i}],i),a=this.readToGPU(r,t);return this.disposeIntermediateTensorInfo(r),a}if(null==l)throw null!=r?new Error("Data is not on GPU but on CPU."):new Error("There is no data on GPU or CPU.");const u=this.decode(e,t.customTexShape),c=jo().makeTensorFromDataId(u.dataId,u.shape,u.dtype),h=this.texData.get(u.dataId);return Object.assign({tensorRef:c},h.texture)}bufferSync(e){const t=this.readSync(e.dataId);let n=t;if("string"===e.dtype)try{n=t.map((e=>Ds(e)))}catch(e){throw new Error("Failed to decode encoded string bytes into utf-8")}return Ni(e.shape,e.dtype,n)}checkNumericalProblems(e){if(null!=e)for(let t=0;t0}time(e){const t=this.activeTimers,n=[];let r=!1;null==this.programTimersStack?(this.programTimersStack=n,r=!0):this.activeTimers.push(n),this.activeTimers=n,e();const s=ie(this.activeTimers.map((e=>e.query))).filter((e=>null!=e)),a=ie(this.activeTimers.map((e=>e.name))).filter((e=>null!=e));this.activeTimers=t,r&&(this.programTimersStack=null);const i={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null};return(async()=>{if(He().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0){const e=await Promise.all(s);i.kernelMs=ee(e),i.getExtraProfileInfo=()=>e.map(((e,t)=>({name:a[t],ms:e}))).map((e=>`${e.name}: ${e.ms}`)).join(", ")}else i.kernelMs={error:"WebGL query timers are not supported in this environment."};return this.uploadWaitMs=0,this.downloadWaitMs=0,i})()}memory(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU,numBytesInGPUAllocated:this.textureManager.numBytesAllocated,numBytesInGPUFree:this.textureManager.numBytesFree}}startTimer(){return He().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:Rs(),endMs:null}}endTimer(e){return He().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),e):(e.endMs=Rs(),e)}async getQueryTime(e){if(He().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0)return this.gpgpu.waitForQueryAndGetTime(e);const t=e;return t.endMs-t.startMs}disposeData(e,t=!1){if(this.pendingDisposal.has(e))return!1;if(!this.texData.has(e))return!0;if(t?this.texData.get(e).refCount=0:this.texData.get(e).refCount--,!t&&this.texData.get(e).refCount>0)return!1;if(this.pendingRead.has(e))return this.pendingDisposal.add(e),this.pendingDeletes++,!1;this.releaseGPUData(e);const{complexTensorInfos:n}=this.texData.get(e);return null!=n&&(this.disposeData(n.real.dataId,t),this.disposeData(n.imag.dataId,t)),this.texData.delete(e),!0}releaseGPUData(e){const{texture:t,dtype:n,texShape:r,usage:s,isPacked:a,slice:i}=this.texData.get(e),o=i&&i.origDataId||e,l=this.dataRefCount.get(o);l>1?this.dataRefCount.set(o,l-1):(this.dataRefCount.delete(o),null!=t&&(this.numBytesInGPU-=this.computeBytes(r,n),this.textureManager.releaseTexture(t,r,s,a)));const u=this.texData.get(e);u.texture=null,u.texShape=null,u.isPacked=!1,u.slice=null}getTexture(e){return this.uploadToGPU(e),this.texData.get(e).texture.texture}getDataInfo(e){return this.texData.get(e)}shouldExecuteOnCPU(e,t=cD){return He().getBool("WEBGL_CPU_FORWARD")&&e.every((e=>null==this.texData.get(e.dataId).texture&&oe(e.shape)0&&Ce(n[0])){const s=n.map((e=>Fs(e)));r=this.write(s,e,t)}else r=this.write(n,e,t);return this.texData.get(r).usage=null,{dataId:r,shape:e,dtype:t}}makeOutput(e,t,n){const{dataId:r}=this.makeTensorInfo(e,t,n);return jo().makeTensorFromDataId(r,e,t,this)}unpackTensor(e){const t=new oD(e.shape);return this.runWebGLProgram(t,[e],e.dtype)}packTensor(e){const t=new ZF(e.shape);return this.runWebGLProgram(t,[e],e.dtype,null,!0)}packedReshape(e,t){const n=[mM(e.shape),...gM(e.shape)],r={dtype:e.dtype,shape:n,dataId:e.dataId},s=[mM(t),...gM(t)],a=new JF(s,n),i=[n],o=this.runWebGLProgram(a,[r],e.dtype,i,!0);return{dataId:o.dataId,shape:t,dtype:o.dtype}}decode(e,t){const n=this.texData.get(e),{isPacked:r,shape:s,dtype:a}=n;null!=t&&re(oe(s)<=t[0]*t[1]*4,(()=>"customTexShape is too small. Row * Column * 4 should be equal or larger than the size of the tensor data."));const i=yM(s);let o;o=r?new XM(i):new KM(i);const l=[null!=t?t:tM(i)];return{dtype:a,shape:s,dataId:this.runWebGLProgram(o,[{shape:i,dtype:a,dataId:e}],a,l,!0,t).dataId}}runWebGLProgram(e,t,n,r,s=!1,a){const i=this.makeTensorInfo(e.outputShape,n),o=this.texData.get(i.dataId);if(e.packedOutput&&(o.isPacked=!0),e.outPackingScheme===ZR.DENSE){const t=null!=a?a:tM(e.outputShape);o.texShape=t.map((e=>2*e))}if(null!=e.outTexUsage&&(o.usage=e.outTexUsage),0===oe(i.shape))return o.values=xe(i.dtype,0),i;const l=[],u=t.map((t=>{if("complex64"===t.dtype)throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");let n=this.texData.get(t.dataId);if(null==n.texture){if(!e.packedInputs&&oe(t.shape)<=He().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:t.shape,texData:null,isUniform:!0,uniformValues:n.values};e.packedInputs&&(n.isPacked=!0,n.shape=t.shape)}if(this.uploadToGPU(t.dataId),!!n.isPacked!=!!e.packedInputs)t=n.isPacked?this.unpackTensor(t):this.packTensor(t),l.push(t),n=this.texData.get(t.dataId);else if(n.isPacked&&!xM(n.shape,t.shape)){const e=t,r=t.shape;t.shape=n.shape,t=this.packedReshape(t,r),l.push(t),n=this.texData.get(t.dataId),e.shape=r}return{shape:t.shape,texData:n,isUniform:!1}}));this.uploadToGPU(i.dataId);const c={shape:i.shape,texData:o,isUniform:!1},h=function(e,t,n){let r="";t.concat(n).forEach((t=>{const s=null!=t.texData&&null!=t.texData.slice&&t.texData.slice.flatOffset>0;if(e.enableShapeUniforms&&!t.isUniform){const a=t.texData.texShape,{useSqueezeShape:i,uniformShape:o,keptDims:l}=WM(e.packedInputs,t.shape,a);let u="",c="",h="";if(1===o.length&&e.packedInputs){const e=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)];u=`${e[0]>1}_${e[1]>1}`}else if(2!==o.length||e.packedInputs){if(o.length>2&&!e.packedInputs){const e=Fe(o);h=`${e[0]===a[1]}_${e[e.length-1]===a[1]}`}}else c=`${o[0]>1}_${o[1]>1}`;const p=t.shape.length,d=2===o.length&&ue(t.shape,a),f=1===oe(t.shape),m=Xi(t.shape,n.shape),g=!e.packedInputs&&p===n.shape.length&&ue(a,n.texData.texShape),y=e.packedInputs||o.length>2?"":`${a[0]>1}_${a[1]>1}`;r+=`${p}_${g}_${i?l:""}_${o.length}_${f}_${m}_${d}_${u}_${c}_${h}_${y}_${s}`}else{const e=t.isUniform?"uniform":t.texData.texShape;r+=`${t.shape}_${e}_${s}`}}));const s=e.userCode;let a=e.constructor.name;return a+="_"+r+"_"+s+`${He().getNumber("WEBGL_VERSION")}`,a}(e,u,c),p=this.getAndSaveBinary(h,(()=>function(e,t,n,r){const s=n.map(((e,n)=>{const r={logicalShape:e.shape,texShape:e.isUniform?null:e.texData.texShape,isUniform:e.isUniform,isPacked:!e.isUniform&&e.texData.isPacked,flatOffset:null};return null!=e.texData&&null!=e.texData.slice&&e.texData.slice.flatOffset>0&&(r.flatOffset=e.texData.slice.flatOffset),{name:t.variableNames[n],shapeInfo:r}})),a=s.map((e=>e.shapeInfo)),i={logicalShape:r.shape,texShape:r.texData.texShape,isUniform:!1,isPacked:r.texData.isPacked,flatOffset:null},o=FM(s,i,t),l=function(e,t){const n=fM(e,(()=>e.createShader(e.FRAGMENT_SHADER)),"Unable to create fragment WebGLShader.");if(sM(e,(()=>e.shaderSource(n,t))),sM(e,(()=>e.compileShader(n))),!1===e.getShaderParameter(n,e.COMPILE_STATUS))throw function(e,t){const n=oM.exec(t);if(null==n)return console.log(`Couldn't parse line number in error: ${t}`),void console.log(e);const r=+n[1],s=e.split("\n"),a=s.length.toString().length+2,i=s.map(((e,t)=>fe((t+1).toString(),a)+e));let o=0;for(let e=0;e{x[n]=e.getUniformLocation(u,t.name,p)})),{program:t,fragmentShader:l,source:o,webGLProgram:u,uniformLocations:d,customUniformLocations:x,inShapeInfos:a,outShapeInfo:i,infLoc:c,nanLoc:h,inShapesLocations:f,inTexShapesLocations:m,outShapeLocation:g,outShapeStridesLocation:b,outTexShapeLocation:y}}(this.gpgpu,e,u,c))),d=null!=this.activeTimers;let f;d&&(f=this.startTimer()),function(e,t,n,r,s){t.program.enableShapeUniforms||(jM(t.inShapeInfos,n),jM([t.outShapeInfo],[r]));const a=r.texData.texture,i=r.texData.texShape;r.texData.isPacked?e.setOutputPackedMatrixTexture(a.texture,i[0],i[1]):e.setOutputMatrixTexture(a.texture,i[0],i[1]),e.setProgram(t.webGLProgram),1===He().getNumber("WEBGL_VERSION")&&null!==t.infLoc&&e.gl.uniform1f(t.infLoc,1/0),null!==t.nanLoc&&e.gl.uniform1f(t.nanLoc,NaN),n.forEach(((n,r)=>{const s=t.program.variableNames[r],a=t.uniformLocations[s],i=t.uniformLocations[`offset${s}`],o=t.inShapesLocations[`${s}Shape`],l=t.inTexShapesLocations[`${s}TexShape`];if(o){const{uniformShape:r}=WM(t.program.packedInputs,n.shape,n.texData.texShape);switch(r.length){case 1:e.gl.uniform1iv(o,new Int32Array(r));break;case 2:e.gl.uniform2iv(o,new Int32Array(r));break;case 3:e.gl.uniform3iv(o,new Int32Array(r));break;case 4:e.gl.uniform4iv(o,new Int32Array(r))}}if(l&&e.gl.uniform2i(l,n.texData.texShape[0],n.texData.texShape[1]),null!=a)if(n.isUniform)if(oe(n.shape)<2)e.gl.uniform1f(a,n.uniformValues[0]);else{let t=n.uniformValues;t instanceof Float32Array||(t=new Float32Array(t)),e.gl.uniform1fv(a,t)}else null!=n.texData.slice&&null!=i&&e.gl.uniform1i(i,n.texData.slice.flatOffset),e.setInputMatrixTexture(n.texData.texture.texture,a,r)}));const o=t.outShapeLocation;if(o)switch(r.shape.length){case 1:e.gl.uniform1iv(o,new Int32Array(r.shape));break;case 2:e.gl.uniform2iv(o,new Int32Array(r.shape));break;case 3:e.gl.uniform3iv(o,new Int32Array(r.shape));break;case 4:e.gl.uniform4iv(o,new Int32Array(r.shape))}if(t.outShapeStridesLocation){const n=Fe(r.shape);switch(r.shape.length){case 2:e.gl.uniform1iv(t.outShapeStridesLocation,new Int32Array(n));break;case 3:e.gl.uniform2iv(t.outShapeStridesLocation,new Int32Array(n));break;case 4:e.gl.uniform3iv(t.outShapeStridesLocation,new Int32Array(n))}}t.outTexShapeLocation&&e.gl.uniform2i(t.outTexShapeLocation,r.texData.texShape[0],r.texData.texShape[1]),t.program.customUniforms&&s&&t.program.customUniforms.forEach(((n,r)=>{const a=t.customUniformLocations[r],i=s[r];if("float"===n.type)e.gl.uniform1fv(a,i);else if("vec2"===n.type)e.gl.uniform2fv(a,i);else if("vec3"===n.type)e.gl.uniform3fv(a,i);else if("vec4"===n.type)e.gl.uniform4fv(a,i);else if("int"===n.type)e.gl.uniform1iv(a,i);else if("ivec2"===n.type)e.gl.uniform2iv(a,i);else if("ivec3"===n.type)e.gl.uniform3iv(a,i);else{if("ivec4"!==n.type)throw Error(`uniform type ${n.type} is not supported yet.`);e.gl.uniform4iv(a,i)}})),e.executeProgram()}(this.gpgpu,p,u,c,r),l.forEach((e=>this.disposeIntermediateTensorInfo(e))),d&&(f=this.endTimer(f),this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(f)}));const m=He().get("WEBGL_FLUSH_THRESHOLD");if(m>0){const e=Rs();e-this.lastGlFlushTime>m&&(this.gpgpu.gl.flush(),this.lastGlFlushTime=e)}if(!He().getBool("WEBGL_LAZILY_UNPACK")&&o.isPacked&&!1===s){const e=this.unpackTensor(i);return this.disposeIntermediateTensorInfo(i),e}return i}compileAndRun(e,t,n,r,s=!1){return n=n||t[0].dtype,this.runWebGLProgram(e,t,n,r,s)}getAndSaveBinary(e,t){return e in this.binaryCache||(this.binaryCache[e]=t()),this.binaryCache[e]}getTextureManager(){return this.textureManager}dispose(){this.disposed||(He().getBool("IS_TEST")||Object.keys(this.binaryCache).forEach((e=>{this.gpgpu.deleteProgram(this.binaryCache[e].webGLProgram),delete this.binaryCache[e]})),this.textureManager.dispose(),null!=this.canvas&&"undefined"!=typeof HTMLCanvasElement&&this.canvas instanceof HTMLCanvasElement?this.canvas.remove():this.canvas=null,this.gpgpuCreatedLocally&&(this.gpgpu.program=null,this.gpgpu.dispose()),this.disposed=!0)}floatPrecision(){return null==this.floatPrecisionValue&&(this.floatPrecisionValue=Xo((()=>{if(!He().get("WEBGL_RENDER_FLOAT32_ENABLED")){const e=He().getBool("DEBUG");He().set("DEBUG",!1);const t=this.abs(kl(1e-8)).dataSync()[0];if(He().set("DEBUG",e),t>0)return 32}return 16}))),this.floatPrecisionValue}epsilon(){return 32===this.floatPrecision()?1e-7:1e-4}uploadToGPU(e){const t=this.texData.get(e),{shape:n,dtype:r,values:s,texture:a,usage:i,isPacked:o}=t;if(null!=a)return;const l=null!=this.activeTimers;let u;l&&(u=Rs());let c=t.texShape;if(null==c&&(c=function(e,t=!1){let n=He().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(t&&(n*=2,1===(e=e.map(((t,n)=>n>=e.length-2?J(e[n]):e[n]))).length&&(e=[2,e[0]])),2!==e.length){const t=be(e);e=t.newShape}let r=oe(e);if(e.length<=1&&r<=n)return[1,r];if(2===e.length&&e[0]<=n&&e[1]<=n)return e;if(3===e.length&&e[0]*e[1]<=n&&e[2]<=n)return[e[0]*e[1],e[2]];if(3===e.length&&e[0]<=n&&e[1]*e[2]<=n)return[e[0],e[1]*e[2]];if(4===e.length&&e[0]*e[1]*e[2]<=n&&e[3]<=n)return[e[0]*e[1]*e[2],e[3]];if(4===e.length&&e[0]<=n&&e[1]*e[2]*e[3]<=n)return[e[0],e[1]*e[2]*e[3]];if(t){const t=mM(e);let n=2,s=2;return e.length&&([n,s]=gM(e)),r=t*(n/2)*(s/2),pe(r).map((e=>2*e))}return pe(r)}(n,o),t.texShape=c),null!=s){const e=yM(n);let a,i=c[1],h=c[0];const p=s instanceof Uint8Array||s instanceof Uint8ClampedArray;!o&&p||([i,h]=nM(c[0],c[1])),a=o?new QM(e,p):new JM(e,p);const d=p?[h,i]:c,f=this.makeTensorInfo(d,r),m=this.texData.get(f.dataId);m.usage=p?JR.PIXELS:JR.UPLOAD,m.texShape=d,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(f.dataId),i,h,s);const g=[[h,i]],y=!0,b=this.runWebGLProgram(a,[f],r,g,y),x=this.texData.get(b.dataId);t.texture=x.texture,t.texShape=x.texShape,t.isPacked=x.isPacked,t.usage=x.usage,this.disposeIntermediateTensorInfo(f),this.texData.delete(b.dataId),t.values=null,l&&(this.uploadWaitMs+=Rs()-u)}else{const e=this.acquireTexture(c,i,r,o);t.texture=e}}convertAndCacheOnCPU(e,t){const n=this.texData.get(e),{dtype:r}=n;return this.releaseGPUData(e),null!=t&&(n.values=function(e,t){if("float32"===t||"complex64"===t)return e;if("int32"===t||"bool"===t){const n="int32"===t?new Int32Array(e.length):new Uint8Array(e.length);for(let t=0;t1024*this.numMBBeforeWarning*1024){const e=(this.numBytesInGPU/1024/1024).toFixed(2);this.warnedAboutMemory=!0,console.warn(`High memory usage in GPU: ${e} MB, most likely due to a memory leak`)}return this.textureManager.acquireTexture(e,t,r)}computeBytes(e,t){return e[0]*e[1]*Se(t)}}hD.nextDataId=0,ba()&&al("webgl",(()=>new hD),2);class pD{constructor(e,t,n){this.variableNames=["A","B"],this.outputShape=Zi(t,n),this.enableShapeUniforms=qM(this.outputShape.length),this.userCode=`\n float binaryOperation(float a, float b) {\n ${e}\n }\n\n void main() {\n float a = getAAtOutCoords();\n float b = getBAtOutCoords();\n setOutput(binaryOperation(a, b));\n }\n `}}class dD{constructor(e,t,n,r=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=Zi(t,n);const s=this.outputShape.length;this.enableShapeUniforms=qM(s);let a="";if(r)if(0===s||1===oe(this.outputShape))a="\n result.y = 0.;\n result.z = 0.;\n result.w = 0.;\n ";else if(a=`\n ${UM(s)} coords = getOutputCoords();\n `,1===s)this.enableShapeUniforms?a+="\n result.y = (coords + 1) >= outShape ? 0. : result.y;\n result.z = 0.;\n result.w = 0.;\n ":a+=`\n result.y = (coords + 1) >= ${this.outputShape[0]} ? 0. : result.y;\n result.z = 0.;\n result.w = 0.;\n `;else{const e=YF("coords",s);this.enableShapeUniforms?a+=`\n bool nextRowOutOfBounds =\n (${e[s-2]} + 1) >= outShape[${s} - 2];\n bool nextColOutOfBounds =\n (${e[s-1]} + 1) >= outShape[${s} - 1];\n result.y = nextColOutOfBounds ? 0. : result.y;\n result.z = nextRowOutOfBounds ? 0. : result.z;\n result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;\n `:a+=`\n bool nextRowOutOfBounds =\n (${e[s-2]} + 1) >= ${this.outputShape[s-2]};\n bool nextColOutOfBounds =\n (${e[s-1]} + 1) >= ${this.outputShape[s-1]};\n result.y = nextColOutOfBounds ? 0. : result.y;\n result.z = nextRowOutOfBounds ? 0. : result.z;\n result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;\n `}this.userCode=`\n vec4 binaryOperation(vec4 a, vec4 b) {\n ${e}\n }\n\n void main() {\n vec4 a = getAAtOutCoords();\n vec4 b = getBAtOutCoords();\n\n vec4 result = binaryOperation(a, b);\n ${a}\n\n setOutput(result);\n }\n `}}function fD(e){const{inputs:t,backend:n}=e,{x:r}=t;return n.incRef(r.dataId),{dataId:r.dataId,shape:r.shape,dtype:r.dtype}}const mD={kernelName:cn,backendName:"webgl",kernelFunc:fD};function gD(e){const{inputs:t,backend:n}=e,{real:r,imag:s}=t,a=n.makeTensorInfo(r.shape,"complex64"),i=n.texData.get(a.dataId),o=fD({inputs:{x:r},backend:n}),l=fD({inputs:{x:s},backend:n});return i.complexTensorInfos={real:o,imag:l},a}const yD={kernelName:kt,backendName:"webgl",kernelFunc:gD},bD="return (a < 0.) ? b * a : a;",xD="\n vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));\n return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\n",wD={kernelName:gn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{alpha:a}=r,i=n.makeTensorInfo([],"float32",$s(a,"float32")),o=He().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new dD(xD,s.shape,i.shape):new pD(bD,s.shape,i.shape),l=n.runWebGLProgram(o,[s,i],"float32");return n.disposeIntermediateTensorInfo(i),l}},vD="return (a < 0.) ? b * a : a;",kD="\n vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));\n return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\n",ID={kernelName:Qn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:r,alpha:s}=t,a=He().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new dD(kD,r.shape,s.shape):new pD(vD,r.shape,s.shape);return n.runWebGLProgram(a,[r,s],"float32")}};function ND({opSnippet:e,packedOpSnippet:t,cpuKernelImpl:n,dtype:r}){return({inputs:s,backend:a})=>{const{x:i}=s,o=a,l=r||i.dtype;if(o.shouldExecuteOnCPU([i])&&null!=n){const e=o.texData.get(i.dataId),t=n(e.values,l);return o.makeTensorInfo(i.shape,l,t)}let u;return u=He().getBool("WEBGL_PACK_UNARY_OPERATIONS")&&null!=t?new iD(i.shape,t):new rD(i.shape,e),o.runWebGLProgram(u,[i],l)}}function SD({opSnippet:e,packedOpSnippet:t,checkOutOfBounds:n=!1,supportsComplex:r=!1,cpuKernelImpl:s,dtype:a}){return({inputs:i,backend:o})=>{const{a:l,b:u}=i,c=o;if(r&&"complex64"===l.dtype){const t=c.texData.get(l.dataId),n=c.texData.get(u.dataId),[r,s]=[[t.complexTensorInfos.real,n.complexTensorInfos.real],[t.complexTensorInfos.imag,n.complexTensorInfos.imag]].map((t=>{const[n,r]=t,s={dataId:n.dataId,dtype:n.dtype,shape:l.shape},a={dataId:r.dataId,dtype:r.dtype,shape:u.shape},i=new pD(e,l.shape,u.shape);return c.runWebGLProgram(i,[s,a],na(n.dtype,r.dtype))})),a=gD({inputs:{real:r,imag:s},backend:c});return c.disposeIntermediateTensorInfo(r),c.disposeIntermediateTensorInfo(s),a}const h=a||na(l.dtype,u.dtype);if(("string"===l.dtype||"string"===u.dtype||c.shouldExecuteOnCPU([l,u]))&&null!=s){const e=c.texData.get(l.dataId).values,t=c.texData.get(u.dataId).values,n="string"===l.dtype?Af(e):e,r="string"===l.dtype?Af(t):t,[a,i]=s(l.shape,u.shape,n,r,h),o=c.makeTensorInfo(i,h);return c.texData.get(o.dataId).values=a,o}let p;return p=He().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&null!=t?new dD(t,l.shape,u.shape,n):new pD(e,l.shape,u.shape),c.runWebGLProgram(p,[l,u],h)}}function TD(e,t=!1){if("linear"===e)return"return x;";if("relu"===e)return t?"\n vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n":"if (isnan(x)) return x;\n return (x < 0.0) ? 0.0 : x;\n";if("elu"===e)return t?"\n vec4 result;\n\n result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);\n result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);\n result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);\n result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);\n\n return result;\n":"return (x >= 0.0) ? x : (exp(x) - 1.0);";if("relu6"===e)return t?"\n vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n":"if (isnan(x)) return x;\n return (x < 0.0) ? 0.0 : min(6.0, x);\n";if("prelu"===e)return t?kD:vD;if("leakyrelu"===e)return t?xD:bD;if("sigmoid"===e)return"return 1.0 / (1.0 + exp(-1.0 * x));";throw new Error(`Activation ${e} has not been implemented for the WebGL backend.`)}class CD{constructor(e,t,n,r=!1,s=!1,a=!1,i=null,o=!1,l=!1){this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=n,this.enableShapeUniforms=qM(this.outputShape.length);const u=r?e[1]:e[2],c=Math.ceil(u/2),h=r?"i * 2, rc.y":"rc.y, i * 2",p=s?"rc.z, i * 2":"i * 2, rc.z",d=r?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],f=s?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"];let m="",g="";i&&(m=o?`vec4 activation(vec4 a) {\n vec4 b = getPreluActivationWeightsAtOutCoords();\n ${i}\n }`:l?`vec4 activation(vec4 a) {\n vec4 b = getLeakyreluAlphaAtOutCoords();\n ${i}\n }`:`vec4 activation(vec4 x) {\n ${i}\n }`,g="result = activation(result);");const y=a?"result += getBiasAtOutCoords();":"";a&&this.variableNames.push("bias"),o&&this.variableNames.push("preluActivationWeights"),l&&this.variableNames.push("leakyreluAlpha");let b="rc.x",x="rc.x";e[0]`The new shape (${l}) has ${u} elements and the old shape (${s.shape}) has ${o} elements. The new shape and old shape must have the same number of elements.`));const c=i.texData.get(s.dataId);return!c.isPacked||xM(s.shape,l)||null!==c.texture&&xM(c.shape,l)?(i.incRef(s.dataId),{dataId:s.dataId,shape:l,dtype:s.dtype}):function(e,t,n){const r=[mM(e.shape),...gM(e.shape)],s={dtype:e.dtype,shape:r,dataId:e.dataId},a=[mM(t),...gM(t)],i=new JF(a,r),o=[r],l=n.runWebGLProgram(i,[s],e.dtype,o,!0);return{dataId:l.dataId,shape:t,dtype:l.dtype}}(s,l,i)}const FD={kernelName:ar,backendName:"webgl",kernelFunc:MD};class DD{constructor(e,t){this.variableNames=["x"];const{windowSize:n,batchSize:r,inSize:s,outSize:a}=e;this.outputShape=[r,a];const i=4*Math.floor(n/4),o=n%4;let l="sumValue += dot(values, ones);";if(null!=t){const e=1/t;l=`sumValue += dot(values * ${ce(e)?e.toPrecision(2):e}, ones);`}let u="";s%n>0&&(u=`\n if (inIdx < 0 || inIdx >= ${s}) {\n return 0.0;\n }\n `),this.userCode=`\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float getValue(int batch, int inIdx) {\n ${u}\n return getX(batch, inIdx);\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = outIdx * ${n};\n\n float sumValue = 0.0;\n\n for (int i = 0; i < ${i}; i += 4) {\n int inIdx = inOffset + i;\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n getValue(batch, inIdx + 3)\n );\n\n ${l}\n }\n\n int inIdx = inOffset + ${i};\n if (${1===o}) {\n vec4 values = vec4(getValue(batch, inIdx), 0.0, 0.0, 0.0);\n\n ${l}\n } else if (${2===o}) {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1), 0.0, 0.0);\n\n ${l}\n } else if (${3===o}) {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2), 0.0);\n\n ${l}\n }\n setOutput(sumValue);\n }\n `}}class _D{constructor(e,t){this.variableNames=["x"];const{windowSize:n,batchSize:r,inSize:s,outSize:a}=e;this.outputShape=[r,a];let i="0.0",o="";"prod"===t?i="1.0":"min"===t?(i="1.0 / 1e-20",o="min"):"max"===t&&(i="-1.0 / 1e-20",o="max");let l=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;"sum"===t?l="sumValue":"prod"===t?l="prodValue":"all"===t?l="allValue":"any"===t&&(l="anyValue");const u=4*Math.floor(n/4),c=n%4;let h=`\n if (${"sum"===t}) {\n sumValue += dot(values, ones);\n } else if (${"prod"===t}) {\n vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);\n prodValue *= tmp[0] * tmp[1];\n } else {\n minMaxValue = ${o}(values, minMaxValue);\n if (${"min"===t} || ${"max"===t}) {\n minMaxValue = ${o}(values, minMaxValue);\n bvec4 isNaN = isnan(values);\n if (isNaN.r || isNaN.g || isNaN.b || isNaN.a) {\n minMaxValue = vec4(NAN);\n }\n }\n }\n `,p="vec4";"all"===t?(i="1.0",h="\n bool reducedAllValue = all(values);\n float floatedReducedAllValue = float(reducedAllValue);\n allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);\n ",p="bvec4"):"any"===t&&(i="0.0",h="\n bool reducedAnyValue = any(values);\n float floatedReducedAnyValue = float(reducedAnyValue);\n anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);\n ",p="bvec4");let d="";s%n>0&&(d=`\n if (inIdx < 0 || inIdx >= ${s}) {\n return initializationValue;\n }\n `),this.userCode=`\n const float initializationValue = ${i};\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float getValue(int batch, int inIdx) {\n ${d}\n return getX(batch, inIdx);\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = outIdx * ${n};\n\n vec4 minMaxValue = vec4(${i});\n float prodValue = 1.0;\n float sumValue = 0.0;\n float allValue = 1.0;\n float anyValue = 0.0;\n\n for (int i = 0; i < ${u}; i += 4) {\n int inIdx = inOffset + i;\n ${p} values = ${p}(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n getValue(batch, inIdx + 3)\n );\n\n ${h}\n }\n\n int inIdx = inOffset + ${u};\n if (${1===c}) {\n ${p} values = ${p}(\n getValue(batch, inIdx),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n ${h}\n } else if (${2===c}) {\n ${p} values = ${p}(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n initializationValue,\n initializationValue\n );\n\n ${h}\n } else if (${3===c}) {\n ${p} values = ${p}(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n initializationValue\n );\n\n ${h}\n }\n setOutput(${l});\n }\n `}}function OD(e,t,n,r){const s=function(e){const t=[];for(;0===t.length||1!==t[t.length-1].outSize;){const n=t.length?t[t.length-1].outSize:e[1],r=Ld(n);t.push({inSize:n,windowSize:r,outSize:Math.ceil(n/r)})}return t}(e.shape);let a=e;for(let i=0;i6)throw Error(`Transpose for rank ${t} is not yet supported`);const n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],r=new Array(t);for(let t=0;t6)throw Error(`Packed transpose for rank ${this.rank} is not yet supported.`);const r=UM(this.rank),s=XF("rc",this.rank),a=new Array(this.rank);for(let e=0;e`Error in matMul: inner shapes (${h}) and (${p}) of Tensors with shapes ${e.shape} and ${t.shape} and transposeA=${n} and transposeB=${r} must match.`));const w=n?[y,h,d]:[y,d,h],v=r?[b,f,p]:[b,p,f],k=MD({inputs:{x:e},backend:s,attrs:{shape:w}}),I=MD({inputs:{x:t},backend:s,attrs:{shape:v}}),N=[k,I],S=Math.max(y,b),T=n?k.shape[1]:k.shape[2],C=null!=a,E=null!=i,$="leakyrelu"===l,A=null!=l?TD(l,!0):null;let R;if((1===d||1===f)&&T>1e3&&!1===(C||E||$||null!=A)){let e=k,t=I;n&&(e=UD({inputs:{x:k},backend:s,attrs:{perm:[0,2,1]}}),N.push(e)),r&&(t=UD({inputs:{x:I},backend:s,attrs:{perm:[0,2,1]}}),N.push(t));const a=1===f;let i=e;1!==f&&(i=MD({inputs:{x:e},backend:s,attrs:{shape:[S,T,1]}}),N.push(i));const o=1===f?2:1;let l=t;a&&(l=MD({inputs:{x:t},backend:s,attrs:{shape:[S,1,T]}}),N.push(l));const u=AD({inputs:{a:i,b:l},backend:s});R=BD({inputs:{x:u},backend:s,attrs:{axis:o,keepDims:!0}}),N.push(u)}else{const l=na(e.dtype,t.dtype),u=new CD(w,v,[S,d,f],n,r,C,A,E,$),c=[k,I];if(null!=a&&c.push(a),E&&c.push(i),$){const e=s.makeTensorInfo([],"float32",$s(o,"float32"));c.push(e),N.push(e)}R=s.runWebGLProgram(u,c,l)}const M=MD({inputs:{x:R},backend:s,attrs:{shape:x}});N.push(R);for(const e of N)s.disposeIntermediateTensorInfo(e);return M}const HD={kernelName:Qr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{a:s,b:a,bias:i,preluActivationWeights:o}=t,{transposeA:l,transposeB:u,activation:c,leakyreluAlpha:h}=r;return GD({a:s,b:a,transposeA:l,transposeB:u,backend:n,bias:i,preluActivationWeights:o,leakyreluAlpha:h,activation:c})}},jD="return abs(x);",qD={kernelName:Ye,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:r}=t;if(n.shouldExecuteOnCPU([r])&&"complex64"!==r.dtype){const e=n.texData.get(r.dataId),t=DF(e.values);return n.makeTensorInfo(r.shape,r.dtype,t)}let s;return s=He().getBool("WEBGL_PACK_UNARY_OPERATIONS")?new iD(r.shape,jD):new rD(r.shape,jD),n.runWebGLProgram(s,[r],r.dtype)}},KD=ND({opSnippet:"if (isnan(x)) return x;\n if (abs(x) > 1.) {\n return NAN;\n }\n return acos(x);\n"}),XD={kernelName:Ze,backendName:"webgl",kernelFunc:KD},YD=ND({opSnippet:"if (isnan(x)) return x;\n if (x < 1.0) return NAN;\nreturn log(x + sqrt(x * x - 1.0));"}),ZD={kernelName:Je,backendName:"webgl",kernelFunc:YD},JD="return a + b;",QD=SD({opSnippet:JD,packedOpSnippet:JD,supportsComplex:!0,cpuKernelImpl:oF}),e_={kernelName:Qe,backendName:"webgl",kernelFunc:QD};class t_{constructor(e,t){this.outputShape=[],this.outputShape=e,this.variableNames=t.map(((e,t)=>`T${t}`));const n=[];this.variableNames.forEach((e=>{n.push(`float v${e} = get${e}AtOutCoords();`)}));const r=this.variableNames.map((e=>`v${e}`)).join(" + ");this.userCode=`\n void main() {\n ${n.join("\n ")}\n\n float result = ${r};\n setOutput(result);\n }\n `}}class n_{constructor(e,t){this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.variableNames=t.map(((e,t)=>`T${t}`));const n=[];this.variableNames.forEach((e=>{n.push(`vec4 v${e} = get${e}AtOutCoords();`)}));const r=this.variableNames.map((e=>`v${e}`)).join(" + ");this.userCode=`\n void main() {\n ${n.join("\n ")}\n\n vec4 result = ${r};\n setOutput(result);\n }\n `}}const r_={kernelName:et,backendName:"webgl",kernelFunc:function e(t){const{inputs:n,backend:r}=t,s=n;if(1===s.length)return fD({inputs:{x:s[0]},backend:r});if(s.length>He().get("WEBGL_MAX_TEXTURES_IN_SHADER")){const t=Math.floor(s.length/2),n=e({inputs:s.slice(0,t),backend:r}),a=e({inputs:s.slice(t),backend:r});return e({inputs:[n,a],backend:r})}const a=s.map((e=>e.dtype)).reduce(((e,t)=>na(e,t))),i=s.map((e=>e.shape)),o=He().getBool("WEBGL_PACK")?new n_(s[0].shape,i):new t_(s[0].shape,i);return r.runWebGLProgram(o,s,a)}},s_={kernelName:tt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:i}=r,o=s.shape.length,l=ye(a,s.shape);let u=l;const c=Ac(u,o);let h=s;null!=c&&(h=UD({inputs:{x:s},backend:n,attrs:{perm:c}}),u=Mc(u.length,o)),$c("all",u,o);const[p,d]=Cc(h.shape,u),f=MD({inputs:{x:h},backend:n,attrs:{shape:[-1,oe(d)]}}),m=OD(f,f.dtype,"all",n);let g;return g=MD(i?{inputs:{x:m},backend:n,attrs:{shape:Ec(p,l)}}:{inputs:{x:m},backend:n,attrs:{shape:p}}),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),null!=c&&n.disposeIntermediateTensorInfo(h),g}},a_={kernelName:nt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:i}=r,o=s.shape.length,l=ye(a,s.shape);let u=l;const c=Ac(u,o);let h=s;null!=c&&(h=UD({inputs:{x:s},backend:n,attrs:{perm:c}}),u=Mc(u.length,o)),$c("any",u,o);const[p,d]=Cc(h.shape,u),f=MD({inputs:{x:h},backend:n,attrs:{shape:[-1,oe(d)]}}),m=OD(f,f.dtype,"any",n);let g;return g=MD(i?{inputs:{x:m},backend:n,attrs:{shape:Ec(p,l)}}:{inputs:{x:m},backend:n,attrs:{shape:p}}),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),null!=c&&n.disposeIntermediateTensorInfo(h),g}};class i_{constructor(e,t,n){this.variableNames=["A"];const{windowSize:r,batchSize:s,outSize:a}=e;n||this.variableNames.push("bestIndicesA"),this.outputShape=[s,a];const i="max"===t?">":"<",o=n?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode=`\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = outIdx * ${r};\n\n int bestIndex = inOffset;\n float bestValue = getA(batch, bestIndex);\n\n for (int i = 0; i < ${r}; i++) {\n int inIdx = ${o};\n float candidate = getA(batch, inIdx);\n if (candidate ${i} bestValue) {\n bestValue = candidate;\n bestIndex = inIdx;\n }\n }\n setOutput(float(bestIndex));\n }\n `}}class o_{constructor(e,t,n,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,re(e.length>2,(()=>`Packed arg${n.charAt(0).toUpperCase()+n.slice(1)} supports only inputs with rank above 2.`));const s=e[e.length-1],a=Math.ceil(s/t);this.outputShape=e.slice(0,-1),a>1&&this.outputShape.push(a),r||this.variableNames.push("bestIndicesA");const i=this.outputShape,o=i.length,l=UM(o),u=YF("coords",o);let c,h;if(1===a){h=o+1;const e=UM(h);c=`\n ${e} sourceLocR = ${e}(${u.join()}, 0);\n ++${u[o-1]};\n ${e} sourceLocG = ${e}(${u.join()}, 0);\n ++${u[o-2]};\n ${e} sourceLocA = ${e}(${u.join()}, 0);\n --${u[o-1]};\n ${e} sourceLocB = ${e}(${u.join()}, 0);\n --${u[o-2]};`}else h=o,c=`\n ${l} sourceLocR = coords;\n ++${u[o-1]};\n ${l} sourceLocG = coords;\n ++${u[o-2]};\n ${l} sourceLocA = coords;\n --${u[o-1]};\n ${l} sourceLocB = coords;\n --${u[o-2]};`;const p=["x","y","z","w","u","v"].slice(0,h),d="."+p[h-1],f=p.map((e=>"int "+e)),m=YF("sourceLocR",h-1).concat("inIdx.r"),g=YF("sourceLocG",h-1).concat("inIdx.g"),y=YF("sourceLocB",h-1).concat("inIdx.b"),b=YF("sourceLocA",h-1).concat("inIdx.a"),x="max"===n?"greaterThan":"lessThan",w=r?"":`\n inIdx = round(vec4(getBestIndicesAChannel(${m.join()}),\n getBestIndicesAChannel(${g.join()}),\n getBestIndicesAChannel(${y.join()}),\n getBestIndicesAChannel(${b.join()})));`,v=`vec4(\n getAChannel(${m.join()}),\n hasNextCol ? getAChannel(${g.join()}) : 0.,\n hasNextRow ? getAChannel(${y.join()}) : 0.,\n hasNextRow && hasNextCol ? getAChannel(${b.join()}) : 0.)`,k=r?"":`\n float getBestIndicesAChannel(${f.join()}) {\n return getChannel(getBestIndicesA(${p.join()}),\n vec2(${p.slice(-2).join()}));\n }`;this.userCode=`\n float getAChannel(${f.join()}) {\n return getChannel(getA(${p.join()}),\n vec2(${p.slice(-2).join()}));\n }\n ${k}\n void main() {\n ${l} coords = getOutputCoords();\n bool hasNextCol = ${u[o-1]} < ${i[o-1]-1};\n bool hasNextRow = ${u[o-2]} < ${i[o-2]-1};\n ${c}\n ivec4 srcIdx = ivec4(sourceLocR${d}, sourceLocG${d},\n sourceLocB${d}, sourceLocA${d}) * ${t};\n ivec4 inIdx = srcIdx;\n vec4 bestIndex = vec4(inIdx);\n vec4 bestValue = ${v};\n\n for (int i = 0; i < ${t}; i++) {\n inIdx = srcIdx;\n ${w}\n vec4 candidate = ${v};\n bvec4 nan = isnan(candidate);\n bvec4 replace = bvec4(\n vec4(${x}(candidate, bestValue)) * (vec4(1.0) - vec4(nan)));\n\n bestValue = vec4(replace.x ? candidate.x : bestValue.x,\n replace.y ? candidate.y : bestValue.y,\n replace.z ? candidate.z : bestValue.z,\n replace.w ? candidate.w : bestValue.w);\n bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace));\n srcIdx++;\n }\n setOutput(bestIndex);\n }\n `}}function l_(e,t,n,r=null){let s=t.shape[0],a=t.shape[1];null!=r&&(s=r.shape[0],a=r.shape[1]);const i=Ld(a),o={windowSize:i,inSize:a,batchSize:s,outSize:Math.ceil(a/i)},l=new i_(o,n,null==r),u=[t];null!=r&&u.push(r);const c=e.runWebGLProgram(l,u,"int32");if(1===c.shape[1])return c;const h=l_(e,t,n,c);return e.disposeIntermediateTensorInfo(c),h}function u_(e,t,n,r=null){const s=null!=r?r.shape:t.shape,a=Ld(s[s.length-1]),i=new o_(s,a,n,null==r),o=null==r?[t]:[t,r],l=e.runWebGLProgram(i,o,"int32");if(l.shape.length===t.shape.length){const r=u_(e,t,n,l);return e.disposeIntermediateTensorInfo(l),r}return l}function c_(e,t,n,r){const s=[n];if($c("arg"+r.charAt(0).toUpperCase()+r.slice(1),s,t.shape.length),!He().getBool("WEBGL_PACK_REDUCE")||t.shape.length<=2){const n=[],a=e.texData.get(t.dataId);let i=t;null!==a&&a.isPacked&&(i=e.unpackTensor(t),n.push(i));const[o,l]=Cc(i.shape,s),u=oe(l),c=MD({inputs:{x:i},backend:e,attrs:{shape:[-1,u]}});n.push(c);const h=l_(e,c,r);n.push(h);const p=MD({inputs:{x:h},backend:e,attrs:{shape:o}});return n.forEach((t=>e.disposeIntermediateTensorInfo(t))),p}return u_(e,t,r)}const h_={kernelName:rt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a}=r;let i=ye(a,s.shape);const o=Ac(i,s.shape.length);let l=s;const u=[];null!=o&&(l=UD({inputs:{x:s},backend:n,attrs:{perm:o}}),u.push(l),i=Mc(i.length,l.shape.length)),$c("argMax",[i[0]],l.shape.length);const c=c_(n,l,i[0],"max");return u.forEach((e=>n.disposeIntermediateTensorInfo(e))),c}},p_={kernelName:st,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a}=r;let i=ye(a,s.shape);const o=Ac(i,s.shape.length);let l=s;const u=[];null!=o&&(l=UD({inputs:{x:s},backend:n,attrs:{perm:o}}),u.push(l),i=Mc(i.length,l.shape.length)),$c("argMin",[i[0]],l.shape.length);const c=c_(n,l,i[0],"min");return u.forEach((e=>n.disposeIntermediateTensorInfo(e))),c}},d_=ND({opSnippet:"if (isnan(x)) return x;\n if (abs(x) > 1.) {\n return NAN;\n }\n return asin(x);\n"}),f_={kernelName:at,backendName:"webgl",kernelFunc:d_},m_=ND({opSnippet:"if (isnan(x)) return x;return log(x + sqrt(x * x + 1.0));"}),g_={kernelName:it,backendName:"webgl",kernelFunc:m_},y_=ND({opSnippet:"if (isnan(x)) return x;\n return atan(x);\n"}),b_={kernelName:ot,backendName:"webgl",kernelFunc:y_},x_=SD({opSnippet:"\n if (isnan(a)) return a;\n if (isnan(b)) return b;\n\n return atan(a, b);\n",packedOpSnippet:"\n vec4 result = atan(a, b);\n vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n"}),w_={kernelName:ut,backendName:"webgl",kernelFunc:x_},v_=ND({opSnippet:"if (isnan(x)) return x;\n if ((x < -1.0) || (x > 1.0)) return NAN;\nreturn (log(1.0 + x) - log(1.0 - x)) / 2.0;"}),k_={kernelName:lt,backendName:"webgl",kernelFunc:v_};class I_{constructor(e,t,n,r=!1,s=!1){if(this.variableNames=["x"],"avg"===t&&n)throw new Error("Cannot compute positions for average pool.");const a=e.filterWidth,i=e.strideHeight,o=e.strideWidth,l=e.dilationHeight,u=e.dilationWidth,c=e.effectiveFilterHeight,h=e.effectiveFilterWidth,p=e.padInfo.top,d=e.padInfo.left;this.outputShape=e.outShape;const f="avg"===t,m=`((batch * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + d`,g=`(xR * ${e.inWidth} + xC) * ${e.inChannels} + d`;let y="0.0";if(f||(y="-1.0 / 1e-20"),n){const t=">=";return void(this.userCode=`\n const ivec2 strides = ivec2(${i}, ${o});\n const ivec2 pads = ivec2(${p}, ${d});\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d = coords[3];\n\n ivec2 xRCCorner = coords.yz * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // max/min x(?, ?, d) to get y(yR, yC, d).\n // ? = to be determined\n float minMaxValue = 0.0;\n float minMaxValueFound = 0.0;\n int minMaxPosition = 0;\n float avgValue = 0.0;\n\n for (int wR = 0; wR < ${c};\n wR += ${l}) {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= ${e.inHeight}) {\n continue;\n }\n\n for (int wC = 0; wC < ${h};\n wC += ${u}) {\n int xC = xCCorner + wC;\n\n if (xC < 0 || xC >= ${e.inWidth}) {\n continue;\n }\n\n float value = getX(batch, xR, xC, d);\n\n // If a min / max value has already been found, use it. If not,\n // use the current value.\n float currMinMaxValue = mix(\n value, minMaxValue, minMaxValueFound);\n if (value ${t} currMinMaxValue) {\n minMaxValue = value;\n minMaxValueFound = 1.0;\n minMaxPosition = ${r?s?m:g:`wR * ${h} + wC`};\n }\n }\n }\n setOutput(float(minMaxPosition));\n }\n `)}let b=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;"avg"===t&&(b="avgValue / count");const x=4*Math.floor(a/4),w=a%4,v=`\n if (${f}) {\n avgValue += dot(values, ones);\n } else {\n minMaxValue = max(values, minMaxValue);\n }\n `;this.userCode=`\n const ivec2 strides = ivec2(${i}, ${o});\n const ivec2 pads = ivec2(${p}, ${d});\n const float initializationValue = ${y};\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float count = 0.0;\n\n float getValue(int batch, int xR, int xC, int d) {\n if (xC < 0 || xC >= ${e.inWidth}) {\n return initializationValue;\n }\n count += 1.0;\n return getX(batch, xR, xC, d);\n }\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d = coords[3];\n\n ivec2 xRCCorner = coords.yz * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // max/min x(?, ?, d) to get y(yR, yC, d).\n // ? = to be determined\n vec4 minMaxValue = vec4(${y});\n float avgValue = 0.0;\n count = 0.0;\n\n for (int wR = 0; wR < ${c};\n wR += ${l}) {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= ${e.inHeight}) {\n continue;\n }\n\n for (int wC = 0; wC < ${x}; wC += 4) {\n int xC = xCCorner + wC * ${u};\n\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + ${u}, d),\n getValue(batch, xR, xC + 2 * ${u}, d),\n getValue(batch, xR, xC + 3 * ${u}, d)\n );\n\n ${v}\n }\n\n int xC = xCCorner + ${x};\n if (${1===w}) {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n ${v}\n } else if (${2===w}) {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + ${u}, d),\n initializationValue,\n initializationValue\n );\n\n ${v}\n } else if (${3===w}) {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + ${u}, d),\n getValue(batch, xR, xC + 2 * ${u}, d),\n initializationValue\n );\n\n ${v}\n }\n }\n setOutput(${b});\n }\n `}}class N_{constructor(e,t,n,r=!1,s=!1){if(this.variableNames=["x"],"avg"===t&&n)throw new Error("Cannot compute positions for average pool.");const a=e.filterWidth,i=e.strideDepth,o=e.strideHeight,l=e.strideWidth,u=e.dilationDepth,c=e.dilationHeight,h=e.dilationWidth,p=e.effectiveFilterDepth,d=e.effectiveFilterHeight,f=e.effectiveFilterWidth,m=e.padInfo.front,g=e.padInfo.top,y=e.padInfo.left;this.outputShape=e.outShape;const b="avg"===t;let x="0.0";if(b||(x="-1.0 / 1e-20"),n){const t=">=";return void(this.userCode=`\n const ivec3 strides =\n ivec3(${i}, ${o}, ${l});\n const ivec3 pads = ivec3(${m}, ${g}, ${y});\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n int xDCorner = xCorner.x;\n int xRCorner = xCorner.y;\n int xCCorner = xCorner.z;\n\n // max/min x(?, ?, ?, ch) to get y(yD, yR, yC, ch).\n // ? = to be determined\n float minMaxValue = 0.0;\n float minMaxValueFound = 0.0;\n int minMaxPosition = 0;\n\n for (int wD = 0; wD < ${p};\n wD += ${u}) {\n int xD = xDCorner + wD;\n\n if (xD < 0 || xD >= ${e.inDepth}) {\n continue;\n }\n\n for (int wR = 0; wR < ${d};\n wR += ${c}) {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= ${e.inHeight}) {\n continue;\n }\n\n for (int wC = 0; wC < ${f};\n wC += ${h}) {\n int xC = xCCorner + wC;\n\n if (xC < 0 || xC >= ${e.inWidth}) {\n continue;\n }\n\n float value = getX(batch, xD, xR, xC, ch);\n\n // If a min / max value has already been found, use it. If not,\n // use the current value.\n float currMinMaxValue = mix(\n value, minMaxValue, minMaxValueFound);\n if (value ${t} currMinMaxValue) {\n minMaxValue = value;\n minMaxValueFound = 1.0;\n minMaxPosition = ${r?s?`(((batch * ${e.inDepth} + xD) * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch`:`((xD * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch`:`wD * ${d} * ${f} +\n wR * ${f} + wC`};\n }\n }\n }\n }\n setOutput(float(minMaxPosition));\n }\n `)}let w=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;"avg"===t&&(w="avgValue / count");const v=4*Math.floor(a/4),k=a%4,I=`\n if (${b}) {\n avgValue += dot(values, ones);\n } else {\n minMaxValue = max(values, minMaxValue);\n }\n `;this.userCode=`\n const ivec3 strides =\n ivec3(${i}, ${o}, ${l});\n const ivec3 pads = ivec3(${m}, ${g}, ${y});\n const float initializationValue = ${x};\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float count = 0.0;\n\n float getValue(int batch, int xD, int xR, int xC, int ch) {\n if (xC < 0 || xC >= ${e.inWidth}) {\n return initializationValue;\n }\n count += 1.0;\n return getX(batch, xD, xR, xC, ch);\n }\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n int xDCorner = xCorner.x;\n int xRCorner = xCorner.y;\n int xCCorner = xCorner.z;\n\n // max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch).\n // ? = to be determined\n vec4 minMaxValue = vec4(${x});\n float avgValue = 0.0;\n count = 0.0;\n\n for (int wD = 0; wD < ${p};\n wD += ${u}) {\n int xD = xDCorner + wD;\n\n if (xD < 0 || xD >= ${e.inDepth}) {\n continue;\n }\n\n for (int wR = 0; wR < ${d};\n wR += ${c}) {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= ${e.inHeight}) {\n continue;\n }\n\n for (int wC = 0; wC < ${v}; wC += 4) {\n int xC = xCCorner + wC * ${h};\n\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + ${h}, ch),\n getValue(batch, xD, xR, xC + 2 * ${h}, ch),\n getValue(batch, xD, xR, xC + 3 * ${h}, ch)\n );\n\n ${I}\n }\n\n int xC = xCCorner + ${v};\n if (${1===k}) {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n ${I}\n } else if (${2===k}) {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + ${h}, ch),\n initializationValue,\n initializationValue\n );\n\n ${I}\n } else if (${3===k}) {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + ${h}, ch),\n getValue(batch, xD, xR, xC + 2 * ${h}, ch),\n initializationValue\n );\n\n ${I}\n }\n }\n setOutput(${w});\n }\n }\n `}}const S_={kernelName:ct,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t;SM(s,"avgPool");const{filterSize:a,strides:i,pad:o,dimRoundingMode:l}=r;re(iu(i,1),(()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${i} and dilations '1'`));const u=Yl(s.shape,a,i,1,o,l);if(1===u.filterWidth&&1===u.filterHeight&&ue(u.inShape,u.outShape))return fD({inputs:{x:s},backend:n});const c=new I_(u,"avg",!1);return n.runWebGLProgram(c,[s],"float32")}},T_={kernelName:pt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{filterSize:a,strides:i,pad:o,dimRoundingMode:l,dataFormat:u}=r,c=Zl(s.shape,a,i,[1,1,1],o,l,u),h=new N_(c,"avg",!1);return n.runWebGLProgram(h,[s],"float32")}};class C_{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;const t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,s=e.strideWidth,a=e.dilationHeight,i=e.dilationWidth,o=e.effectiveFilterHeight,l=e.effectiveFilterWidth,u=o-1-e.padInfo.top,c=l-1-e.padInfo.left,h=1/(t*n);this.userCode=`\n const ivec2 pads = ivec2(${u}, ${c});\n const float avgMultiplier = float(${h});\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n\n ivec2 dyRCCorner = coords.yz - pads;\n int dyRCorner = dyRCCorner.x;\n int dyCCorner = dyRCCorner.y;\n\n // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < ${o};\n wR += ${a}) {\n float dyR = float(dyRCorner + wR) / ${r}.0;\n\n if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < ${l};\n wC+= ${i}) {\n float dyC = float(dyCCorner + wC) / ${s}.0;\n\n if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(b, idyR, idyC, d);\n\n dotProd += dyValue * avgMultiplier;\n }\n }\n setOutput(dotProd);\n }\n `}}class E_{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;const t=e.filterDepth,n=e.filterHeight,r=e.filterWidth,s=e.strideDepth,a=e.strideHeight,i=e.strideWidth,o=e.dilationDepth,l=e.dilationHeight,u=e.dilationWidth,c=e.effectiveFilterDepth,h=e.effectiveFilterHeight,p=e.effectiveFilterWidth,d=c-1-e.padInfo.front,f=h-1-e.padInfo.top,m=p-1-e.padInfo.left,g=1/(t*n*r);this.userCode=`\n const ivec3 pads = ivec3(${d}, ${f}, ${m});\n const float avgMultiplier = float(${g});\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n int dyDCorner = dyCorner.x;\n int dyRCorner = dyCorner.y;\n int dyCCorner = dyCorner.z;\n\n // Convolve dy(?, ?, ?, d) with pos mask(:, :, :, ch) to get\n // dx(xD, xR, xC, ch).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n\n for (int wD = 0; wD < ${c};\n wD += ${o}) {\n float dyD = float(dyDCorner + wD) / ${s}.0;\n\n if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) {\n continue;\n }\n int idyD = int(dyD);\n\n for (int wR = 0; wR < ${h};\n wR += ${l}) {\n float dyR = float(dyRCorner + wR) / ${a}.0;\n\n if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||\n fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < ${p};\n wC += ${u}) {\n float dyC = float(dyCCorner + wC) / ${i}.0;\n\n if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(batch, idyD, idyR, idyC, ch);\n\n dotProd += dyValue * avgMultiplier;\n }\n }\n }\n setOutput(dotProd);\n }\n `}}const $_={kernelName:dt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a}=t,i=a,{filterSize:o,strides:l,pad:u,dimRoundingMode:c}=r,h=Zl(i.shape,o,l,[1,1,1],u,c),p=new E_(h);return n.runWebGLProgram(p,[s],i.dtype)}},A_={kernelName:ht,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a}=t,i=a;SM([s,a],"avgPoolGrad");const{filterSize:o,strides:l,pad:u}=r,c=Yl(i.shape,o,l,1,u),h=new C_(c);return n.runWebGLProgram(h,[s],i.dtype)}},R_={kernelName:ft,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{a:s,b:a}=t,{transposeA:i,transposeB:o}=r;return GD({a:s,b:a,transposeA:i,transposeB:o,backend:n})}};class M_{constructor(e,t,n,r,s,a){this.outputShape=[],this.variableNames=["x","mean","variance"],Zi(e,t),Zi(e,n);let i="0.0";null!=r&&(Zi(e,r),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");let o="1.0";null!=s&&(Zi(e,s),this.variableNames.push("scale"),o="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`\n void main() {\n float x = getXAtOutCoords();\n float mean = getMeanAtOutCoords();\n float variance = getVarianceAtOutCoords();\n float offset = ${i};\n float scale = ${o};\n float inv = scale * inversesqrt(variance + float(${a}));\n setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));\n }\n `}}class F_{constructor(e,t,n,r,s,a){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],Zi(e,t),Zi(e,n);let i="vec4(0.0)";null!=r&&(Zi(e,r),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");let o="vec4(1.0)";null!=s&&(Zi(e,s),this.variableNames.push("scale"),o="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`\n void main() {\n vec4 offset = ${i};\n vec4 scale = ${o};\n\n vec4 x = getXAtOutCoords();\n vec4 mean = getMeanAtOutCoords();\n vec4 variance = getVarianceAtOutCoords();\n\n vec4 inv = scale * inversesqrt(variance + vec4(${a}));\n\n setOutput((x - mean) * inv + offset);\n }\n `}}const D_={kernelName:sn,backendName:"webgl",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:r,mean:s,variance:a,offset:i,scale:o}=e;re(s.shape.length===a.shape.length,(()=>"Batch normalization gradient requires mean and variance to have equal ranks.")),re(null==i||s.shape.length===i.shape.length,(()=>"Batch normalization gradient requires mean and offset to have equal ranks.")),re(null==o||s.shape.length===o.shape.length,(()=>"Batch normalization gradient requires mean and scale to have equal ranks."));let{varianceEpsilon:l}=n;null==l&&(l=.001);const u=[r,s,a];let c=null;null!=i&&(c=i.shape,u.push(i));let h=null;null!=o&&(h=o.shape,u.push(o));const p=He().getBool("WEBGL_PACK_NORMALIZATION")?new F_(r.shape,s.shape,a.shape,c,h,l):new M_(r.shape,s.shape,a.shape,c,h,l);return t.runWebGLProgram(p,u,u[0].dtype)}};class __{constructor(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;const t=UM(this.rank);this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];const n=function(e){if(1===e)return"sourceLoc";if(e<=6)return O_.slice(0,e).map((e=>"sourceLoc."+e)).join(",");throw Error(`Slicing for rank ${e} is not yet supported`)}(this.rank);let r;r=`\n ${t} sourceLoc;\n ${t} coords = getOutputCoords();\n ${e.map(((e,t)=>`sourceLoc.${O_[t]} = start[${t}] + coords.${O_[t]};`)).join("\n")}\n `,this.userCode=`\n void main() {\n ${r}\n setOutput(getSource(${n}));\n }\n `}}const O_=["x","y","z","w","u","v"];class L_{constructor(e){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.rank=e.length,this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];const t=UM(this.rank),n=YF("coords",this.rank),r=YF("sourceLoc",this.rank),s=1===this.rank?"sourceLoc":`vec2(${r.slice(-2).join()})`,a=`getChannel(getSource(${r.join()}), ${s})`,i=`\n result.x = ${a};\n if (++${n[this.rank-1]} < ${e[this.rank-1]}) {\n ++${r[this.rank-1]};\n result.y = ${a};\n --${r[this.rank-1]};\n }\n `,o=1===this.rank?"":`\n --${n[this.rank-1]};\n if (++${n[this.rank-2]} < ${e[this.rank-2]}) {\n ++${r[this.rank-2]};\n result.z = ${a};\n if (++${n[this.rank-1]} < ${e[this.rank-1]}) {\n ++${r[this.rank-1]};\n result.w = ${a};\n }\n }\n `,l=this.rank<=4?`sourceLoc = coords +\n ${t}(${e.map(((e,t)=>`start[${t}]`)).join()});`:e.map(((e,t)=>`${r[t]} = ${n[t]} + start[${t}];`)).join("\n");this.userCode=`\n void main() {\n ${t} coords = getOutputCoords();\n ${t} sourceLoc;\n ${l}\n vec4 result = vec4(0.);\n ${i}\n ${o}\n setOutput(result);\n }\n `}}function z_(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{begin:a,size:i}=r,[o,l]=Io(s,a,i);if(lo(s,o,l),0===oe(l))return n.makeTensorInfo(l,s.dtype,[]);if(n.shouldExecuteOnCPU([s])||"string"===s.dtype){const e=n.texData.get(s.dataId),t=_F(e.values,o,l,s.shape,s.dtype);return n.makeTensorInfo(l,s.dtype,t)}const{isPacked:u}=n.texData.get(s.dataId),c=vo(s.shape,o,l);if(u||!c){const e=He().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new L_(l):new __(l),t=[o];return n.runWebGLProgram(e,[s],s.dtype,t)}return n.uploadToGPU(s.dataId),function(e,t,n,r){const s=r.texData.get(e.dataId),a=r.makeTensorInfo(n,e.dtype),i=r.texData.get(a.dataId);Object.assign(i,s),i.refCount=1,i.shape=n,i.dtype=e.dtype;let o=ko(t,Fe(e.shape));s.slice&&(o+=s.slice.flatOffset),i.slice={flatOffset:o,origDataId:s.slice&&s.slice.origDataId||e.dataId};const l=r.dataRefCount.get(i.slice.origDataId)||1;return r.dataRefCount.set(i.slice.origDataId,l+1),a}(s,o,l,n)}const P_={kernelName:yr,backendName:"webgl",kernelFunc:z_},B_={kernelName:mt,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{blockShape:a,crops:i}=r;re(s.shape.length<=4,(()=>"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet"));const o=a.reduce(((e,t)=>e*t)),l=Pd(s.shape,a,o),u=Bd(l.length,a.length),c=Vd(s.shape,a,o),h=Ud(i,a.length),p=Wd(c,i,a.length),d=[],f=MD({inputs:{x:s},backend:n,attrs:{shape:l}}),m=UD({inputs:{x:f},backend:n,attrs:{perm:u}}),g=MD({inputs:{x:m},backend:n,attrs:{shape:c}}),y=z_({inputs:{x:g},backend:n,attrs:{begin:h,size:p}});return d.push(f),d.push(m),d.push(g),d.forEach((e=>n.disposeIntermediateTensorInfo(e))),y}},V_={kernelName:gt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,weights:a}=t,{size:i}=r,o=n.readSync(s.dataId),l=n.readSync(a.dataId),u=lF(o,l,a.dtype,a.shape,i);return n.makeTensorInfo([i],a.dtype,u)}},U_={kernelName:bt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{s0:r,s1:s}=t,a=n.readSync(r.dataId),i=n.readSync(s.dataId),o=Zi(Array.from(a),Array.from(i));return n.makeTensorInfo([o.length],"int32",Int32Array.from(o))}},W_=SD({opSnippet:"return float(a != b);",cpuKernelImpl:$F,dtype:"bool"}),G_={kernelName:Wn,backendName:"webgl",kernelFunc:W_};function H_(e){const{inputs:t,backend:n}=e,{input:r}=t;return fD({inputs:{x:n.texData.get(r.dataId).complexTensorInfos.real},backend:n})}const j_={kernelName:nr,backendName:"webgl",kernelFunc:H_},q_={kernelName:xt,backendName:"webgl",kernelFunc:function e(t){const{inputs:n,backend:r,attrs:s}=t,{x:a}=n,{dtype:i}=s;if("complex64"===i){if("complex64"===a.dtype)return fD({inputs:{x:a},backend:r});const t=Uc(a.shape),n=e({inputs:{x:a},backend:r,attrs:{dtype:"float32"}}),s=gD({inputs:{real:n,imag:t},backend:r});return t.dispose(),r.disposeIntermediateTensorInfo(n),s}if("complex64"===a.dtype){const t=H_({inputs:{input:a},backend:r}),n=e({inputs:{x:t},backend:r,attrs:{dtype:i}});return r.disposeIntermediateTensorInfo(t),n}if(!Ie(a.dtype,i)){const e=fD({inputs:{x:a},backend:r});return{dataId:e.dataId,shape:e.shape,dtype:i}}if("int32"===i)return function(e,t){const n=new rD(e.shape,"return float(int(x));"),r=t.runWebGLProgram(n,[e],"int32");return{dataId:r.dataId,shape:r.shape,dtype:r.dtype}}(a,r);if("bool"===i){const e=r.makeTensorInfo([],"bool",xe("bool",1)),t=W_({inputs:{a,b:e},backend:r});return r.disposeIntermediateTensorInfo(e),t}throw new Error(`Error in Cast: failed to cast ${a.dtype} to ${i}`)}},K_="return ceil(x);",X_=ND({opSnippet:K_,packedOpSnippet:K_,cpuKernelImpl:cF}),Y_={kernelName:wt,backendName:"webgl",kernelFunc:X_};class Z_{constructor(e){this.variableNames=["A"],this.customUniforms=[{name:"minVal",type:"float"},{name:"maxVal",type:"float"}],this.outputShape=e,this.userCode="\n\n void main() {\n float value = getAAtOutCoords();\n if (isnan(value)) {\n setOutput(value);\n return;\n }\n\n setOutput(clamp(value, minVal, maxVal));\n }\n "}}class J_{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"minVal",type:"float"},{name:"maxVal",type:"float"}],this.outputShape=e,this.userCode="\n void main() {\n vec4 value = getAAtOutCoords();\n\n if (any(isnan(value))) {\n setOutput(value);\n return;\n }\n\n setOutput(clamp(value, vec4(minVal), vec4(maxVal)));\n }\n "}}const Q_={kernelName:vt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{clipValueMin:a,clipValueMax:i}=r;let o;o=He().getBool("WEBGL_PACK_CLIP")?new J_(s.shape):new Z_(s.shape);const l=[[a],[i]];return n.runWebGLProgram(o,[s],s.dtype,l)}};class eO{constructor(e){this.variableNames=["real","imag"],this.outputShape=e,this.userCode="\n void main() {\n float re = abs(getRealAtOutCoords());\n float im = abs(getImagAtOutCoords());\n float mx = max(re, im);\n\n // sadly the length function in glsl is not underflow-safe\n // (at least not on Intel GPUs). So the safe solution is\n // to ensure underflow-safety in all cases.\n setOutput(\n mx == 0.0 ? 0.0 : mx * length(vec2(1, min(re, im)/mx))\n );\n }\n "}}function tO(e,t){return{dataId:t.dataId,dtype:t.dtype,shape:e.shape}}const nO={kernelName:It,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:r}=t,s=n.texData.get(r.dataId),a=new eO(r.shape),i=[tO(r,s.complexTensorInfos.real),tO(r,s.complexTensorInfos.imag)];return n.runWebGLProgram(a,i,i[0].dtype)}};class rO{constructor(e){this.outputShape=[],this.outputShape=_d(e,1),this.variableNames=e.map(((e,t)=>`T${t}`));const t=new Array(e.length-1);t[0]=e[0][1];for(let n=1;n`T${t}`));const o=new Array(e.length-1);o[0]=e[0][t];for(let n=1;n= ${o[e-1]}) {\n return getChannel(\n getT${e}(${aO(i,l,t)}),\n vec2(${aO(u,l,t)}));\n }`}const p=o.length,d=o[o.length-1];h+=`\n return getChannel(\n getT${p}(${aO(i,l,d)}),\n vec2(${aO(u,l,d)}));`,this.userCode=`\n float getValue(${i.map((e=>"int "+e))}) {\n ${h}\n }\n\n void main() {\n ${s} coords = getOutputCoords();\n vec4 result = vec4(getValue(${a}), 0., 0., 0.);\n\n ${a[r-1]} = ${a[r-1]} + 1;\n if (${a[r-1]} < ${n[r-1]}) {\n result.g = getValue(${a});\n }\n\n ${a[r-2]} = ${a[r-2]} + 1;\n if (${a[r-2]} < ${n[r-2]}) {\n result.a = getValue(${a});\n }\n\n ${a[r-1]} = ${a[r-1]} - 1;\n if (${a[r-2]} < ${n[r-2]} &&\n ${a[r-1]} < ${n[r-1]}) {\n result.b = getValue(${a});\n }\n setOutput(result);\n }\n `}}function aO(e,t,n){const r=e.indexOf(t);return e.map(((e,t)=>t===r?`${e} - ${n}`:e)).join()}function iO(e){const{inputs:t,backend:n}=e,{input:r}=t;return fD({inputs:{x:n.texData.get(r.dataId).complexTensorInfos.imag},backend:n})}const oO={kernelName:pn,backendName:"webgl",kernelFunc:iO};function lO(e,t,n){const r=e[0].dtype;if("complex64"===r){const r=e.map((e=>H_({inputs:{input:e},backend:n}))),s=e.map((e=>iO({inputs:{input:e},backend:n}))),a=lO(r,t,n),i=lO(s,t,n),o=gD({inputs:{real:a,imag:i},backend:n});return r.forEach((e=>n.disposeIntermediateTensorInfo(e))),s.forEach((e=>n.disposeIntermediateTensorInfo(e))),n.disposeIntermediateTensorInfo(a),n.disposeIntermediateTensorInfo(i),o}let s=n.shouldExecuteOnCPU(e);if("string"===r&&(s=!0),s){const s=e.map((e=>{const r=oe(e.shape.slice(t));return MD({inputs:{x:e},backend:n,attrs:{shape:[-1,r]}})})),a=s.map((e=>({vals:n.readSync(e.dataId),shape:e.shape}))),i=_d(s.map((e=>e.shape)),1),o=1===s[0].shape[0],l=hF(a,i,r,o),u=_d(e.map((e=>e.shape)),t),c=n.makeTensorInfo(u,r,l);return s.forEach((e=>n.disposeIntermediateTensorInfo(e))),c}if(e.length>He().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){const r=Math.floor(e.length/2),s=lO(e.slice(0,r),t,n),a=lO(e.slice(r),t,n),i=lO([s,a],t,n);return n.disposeIntermediateTensorInfo(s),n.disposeIntermediateTensorInfo(a),i}if(He().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&e[0].shape.length>1){const s=new sO(e.map((e=>e.shape)),t);return n.runWebGLProgram(s,e,r)}const{tensors2D:a,outShape:i}=function(e,t,n){const r=_d(e.map((e=>e.shape)),t);return{tensors2D:e.map((e=>MD({inputs:{x:e},attrs:{shape:[-1,oe(e.shape.slice(t))]},backend:n}))),outShape:r}}(e,t,n),o=new rO(a.map((e=>e.shape))),l=n.runWebGLProgram(o,a,r);a.forEach((e=>n.disposeIntermediateTensorInfo(e)));const u=MD({inputs:{x:l},attrs:{shape:i},backend:n});return n.disposeIntermediateTensorInfo(l),u}function uO(e){const{inputs:t,backend:n,attrs:r}=e,{axis:s}=r,a=ye(s,t[0].shape)[0],i=_d(t.map((e=>e.shape)),a);if(0===oe(i))return n.makeTensorInfo(i,t[0].dtype,[]);const o=t.filter((e=>oe(e.shape)>0));return 1===o.length?fD({inputs:{x:o[0]},backend:n}):(Dd(o.map((e=>e.shape)),a),lO(o,a,n))}const cO={kernelName:Nt,backendName:"webgl",kernelFunc:uO};class hO{constructor(e,t=!1,n=null,r=!1,s=!1){this.variableNames=["x","W"],this.outputShape=e.outShape;const a=e.padInfo.top,i=e.padInfo.left,o=e.strideHeight,l=e.strideWidth,u=e.dilationHeight,c=e.dilationWidth,h=e.filterHeight,p=e.filterWidth,d=4*Math.floor(e.inChannels/4),f=e.inChannels%4,m="channelsLast"===e.dataFormat,g=m?1:2,y=m?2:3,b=m?3:1;let x="",w="";n&&(x=r?`float activation(float a) {\n float b = getPreluActivationWeightsAtOutCoords();\n ${n}\n }`:s?`float activation(float a) {\n float b = getLeakyreluAlphaAtOutCoords();\n ${n}\n }`:`\n float activation(float x) {\n ${n}\n }\n `,w="result = activation(result);");const v=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),s&&this.variableNames.push("leakyreluAlpha"),this.userCode=`\n ${x}\n\n const ivec2 strides = ivec2(${o}, ${l});\n const ivec2 pads = ivec2(${a}, ${i});\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d2 = coords[${b}];\n\n ivec2 xRCCorner =\n ivec2(coords[${g}], coords[${y}]) * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < ${h}; wR++) {\n int xR = xRCorner + wR * ${u};\n\n if (xR < 0 || xR >= ${e.inHeight}) {\n continue;\n }\n\n for (int wC = 0; wC < ${p}; wC++) {\n int xC = xCCorner + wC * ${c};\n\n if (xC < 0 || xC >= ${e.inWidth}) {\n continue;\n }\n\n for (int d1 = 0; d1 < ${d}; d1 += 4) {\n vec4 wValues = vec4(\n getW(wR, wC, d1, d2),\n getW(wR, wC, d1 + 1, d2),\n getW(wR, wC, d1 + 2, d2),\n getW(wR, wC, d1 + 3, d2)\n );\n\n if (${m}) {\n vec4 xValues = vec4(\n getX(batch, xR, xC, d1),\n getX(batch, xR, xC, d1 + 1),\n getX(batch, xR, xC, d1 + 2),\n getX(batch, xR, xC, d1 + 3)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec4 xValues = vec4(\n getX(batch, d1, xR, xC),\n getX(batch, d1 + 1, xR, xC),\n getX(batch, d1 + 2, xR, xC),\n getX(batch, d1 + 3, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n }\n\n if (${1===f}) {\n\n if (${m}) {\n dotProd +=\n getX(batch, xR, xC, ${d}) *\n getW(wR, wC, ${d}, d2);\n } else {\n dotProd +=\n getX(batch, ${d}, xR, xC) *\n getW(wR, wC, ${d}, d2);\n }\n\n } else if (${2===f}) {\n vec2 wValues = vec2(\n getW(wR, wC, ${d}, d2),\n getW(wR, wC, ${d} + 1, d2)\n );\n\n if (${m}) {\n vec2 xValues = vec2(\n getX(batch, xR, xC, ${d}),\n getX(batch, xR, xC, ${d} + 1)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec2 xValues = vec2(\n getX(batch, ${d}, xR, xC),\n getX(batch, ${d} + 1, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n\n } else if (${3===f}) {\n vec3 wValues = vec3(\n getW(wR, wC, ${d}, d2),\n getW(wR, wC, ${d} + 1, d2),\n getW(wR, wC, ${d} + 2, d2)\n );\n\n if (${m}) {\n vec3 xValues = vec3(\n getX(batch, xR, xC, ${d}),\n getX(batch, xR, xC, ${d} + 1),\n getX(batch, xR, xC, ${d} + 2)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec3 xValues = vec3(\n getX(batch, ${d}, xR, xC),\n getX(batch, ${d} + 1, xR, xC),\n getX(batch, ${d} + 2, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n\n }\n }\n }\n\n float result = dotProd;\n ${v}\n ${w}\n setOutput(result);\n }\n `}}class pO{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;const t=e.padInfo.front,n=e.padInfo.top,r=e.padInfo.left,s=e.strideDepth,a=e.strideHeight,i=e.strideWidth,o=e.dilationDepth,l=e.dilationHeight,u=e.dilationWidth,c=e.filterDepth,h=e.filterHeight,p=e.filterWidth,d=4*Math.floor(e.inChannels/4),f=e.inChannels%4;this.userCode=`\n const ivec3 strides = ivec3(${s}, ${a}, ${i});\n const ivec3 pads = ivec3(${t}, ${n}, ${r});\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int d2 = coords.u;\n\n ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n int xFCorner = xFRCCorner.x;\n int xRCorner = xFRCCorner.y;\n int xCCorner = xFRCCorner.z;\n\n // Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get\n // y(yF, yR, yC, d2). ? = to be determined. : = across all\n // values in that axis.\n float dotProd = 0.0;\n for (int wF = 0; wF < ${c}; wF++) {\n int xF = xFCorner + wF * ${o};\n\n if (xF < 0 || xF >= ${e.inDepth}) {\n continue;\n }\n\n for (int wR = 0; wR < ${h}; wR++) {\n int xR = xRCorner + wR * ${l};\n\n if (xR < 0 || xR >= ${e.inHeight}) {\n continue;\n }\n\n for (int wC = 0; wC < ${p}; wC++) {\n int xC = xCCorner + wC * ${u};\n\n if (xC < 0 || xC >= ${e.inWidth}) {\n continue;\n }\n\n for (int d1 = 0; d1 < ${d}; d1 += 4) {\n vec4 xValues = vec4(\n getX(batch, xF, xR, xC, d1),\n getX(batch, xF, xR, xC, d1 + 1),\n getX(batch, xF, xR, xC, d1 + 2),\n getX(batch, xF, xR, xC, d1 + 3)\n );\n vec4 wValues = vec4(\n getW(wF, wR, wC, d1, d2),\n getW(wF, wR, wC, d1 + 1, d2),\n getW(wF, wR, wC, d1 + 2, d2),\n getW(wF, wR, wC, d1 + 3, d2)\n );\n\n dotProd += dot(xValues, wValues);\n }\n\n if (${1===f}) {\n dotProd +=\n getX(batch, xF, xR, xC, ${d}) *\n getW(wF, wR, wC, ${d}, d2);\n } else if (${2===f}) {\n vec2 xValues = vec2(\n getX(batch, xF, xR, xC, ${d}),\n getX(batch, xF, xR, xC, ${d} + 1)\n );\n vec2 wValues = vec2(\n getW(wF, wR, wC, ${d}, d2),\n getW(wF, wR, wC, ${d} + 1, d2)\n );\n dotProd += dot(xValues, wValues);\n } else if (${3===f}) {\n vec3 xValues = vec3(\n getX(batch, xF, xR, xC, ${d}),\n getX(batch, xF, xR, xC, ${d} + 1),\n getX(batch, xF, xR, xC, ${d} + 2)\n );\n vec3 wValues = vec3(\n getW(wF, wR, wC, ${d}, d2),\n getW(wF, wR, wC, ${d} + 1, d2),\n getW(wF, wR, wC, ${d} + 2, d2)\n );\n dotProd += dot(xValues, wValues);\n }\n }\n }\n }\n setOutput(dotProd);\n }\n `}}class dO{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec3"},{name:"pad",type:"ivec2"},{name:"stride",type:"ivec2"},{name:"dilation",type:"ivec2"},{name:"inChannels",type:"int"},{name:"itemsPerBlockRow",type:"int"},{name:"outWidth",type:"int"}],this.outputShape=e,this.enableShapeUniforms=qM(this.outputShape.length);const{dataFormat:n}=t,r=CM(),s="channelsLast"===n,a=s?0:1,i=s?1:2,o=this.enableShapeUniforms?"if(blockIndex < outShape[1] && pos < outShape[0]) {":`if(blockIndex < ${e[1]} && pos < ${e[0]}) {`;let l="";for(let e=0;e<=1;e++)for(let t=0;t<=1;t++)l+=`\n blockIndex = rc.y + ${t};\n pos = rc.x + ${e};\n\n ${o}\n offsetY = int(blockIndex / outWidth) * stride[0] - pad[0];\n d0 = offsetY + dilation[0] * (pos / itemsPerBlockRow);\n\n if(d0 < inputShape[${a}] && d0 >= 0) {\n // Use custom imod instead mod. On Intel GPU, mod may generate\n // unexpected value.\n // https://github.com/tensorflow/tfjs/issues/5447\n offsetX = imod(blockIndex, outWidth) * stride[1] - pad[1];\n d1 = offsetX + dilation[1] * (imod(pos, itemsPerBlockRow) /\n inChannels);\n\n if(d1 < inputShape[${i}] && d1 >= 0) {\n\n ch = imod(pos, inChannels);\n\n if (${s}) {\n innerDims = vec2(d1, ch);\n result[${2*e+t}] = getChannel(\n getA(d0, int(innerDims.x),\n int(innerDims.y)), innerDims);\n } else {\n innerDims = vec2(d0, d1);\n result[${2*e+t}] = getChannel(\n getA(ch, int(innerDims.x),\n int(innerDims.y)), innerDims);\n }\n }\n }\n }\n `;this.userCode=`\n void main() {\n ivec2 rc = getOutputCoords();\n\n vec4 result = vec4(0);\n\n int blockIndex, pos, offsetY, d0, offsetX, d1, ch;\n vec2 innerDims;\n\n ${l}\n\n ${r.output} = result;\n }\n `}}function fO({x:e,filter:t,convInfo:n,backend:r,bias:s=null,preluActivationWeights:a=null,leakyreluAlpha:i=0,activation:o=null}){const l=e.shape,u=r.texData.get(e.dataId),c=n.inChannels,h=l[0]*l[1]*l[2],p=n.outChannels,d="channelsLast"===n.dataFormat;let f;const m=[];if((1!==h&&1!==p||!(c>1e3))&&u.isPacked&&d&&null!=u.texture&&l[2]%2!=0&&ue(u.shape.slice(-3),l.slice(-3))){const c=l[0]*l[1]*(l[2]+1),h={dataId:e.dataId,shape:[1,c,n.inChannels],dtype:e.dtype},p=u.shape;u.shape=u.shape.slice(),u.shape[u.shape.length-2]++,re(xM(u.shape,h.shape),(()=>`packed reshape ${u.shape} to ${h.shape} isn't free`));const d=MD({inputs:{x:t},backend:r,attrs:{shape:[1,n.inChannels,n.outChannels]}});m.push(d);const g=GD({a:h,b:d,backend:r,transposeA:!1,transposeB:!1,bias:s,activation:o,preluActivationWeights:a,leakyreluAlpha:i}),y=r.texData.get(g.dataId);re(y.isPacked,(()=>"batchMatMul result is expected to be packed")),u.shape=p,y.shape=n.outShape,f=fD({inputs:{x:g},backend:r}),f.shape=n.outShape,m.push(g)}else{const u=MD({inputs:{x:e},backend:r,attrs:{shape:[1,d?l[0]*l[1]*l[2]:l[0]*l[2]*l[3],n.inChannels]}}),c=MD({inputs:{x:t},backend:r,attrs:{shape:[1,n.inChannels,n.outChannels]}}),h=GD({a:u,b:c,transposeA:!1,transposeB:!1,backend:r,bias:s,activation:o,preluActivationWeights:a,leakyreluAlpha:i});f=MD({inputs:{x:h},backend:r,attrs:{shape:n.outShape}}),m.push(u),m.push(c),m.push(h)}for(const e of m)r.disposeIntermediateTensorInfo(e);return f}function mO({x:e,filter:t,convInfo:n,backend:r,bias:s=null,preluActivationWeights:a=null,leakyreluAlpha:i=0,activation:o=null}){const{filterWidth:l,filterHeight:u,inChannels:c,outWidth:h,outHeight:p,dataFormat:d}=n,f="channelsLast"===d,m=l*u*c,g=p*h,y=[m,g],b=[],x=MD({inputs:{x:e},backend:r,attrs:{shape:e.shape.slice(1)}}),w=MD({inputs:{x:t},backend:r,attrs:{shape:[1,m,oe(t.shape)/m]}});b.push(x),b.push(w);const v=new dO(y,n),k=[x.shape,[n.padInfo.top,n.padInfo.left],[n.strideHeight,n.strideWidth],[n.dilationHeight,n.dilationWidth],[n.inChannels],[n.filterWidth*n.inChannels],[n.outWidth]],I=r.runWebGLProgram(v,[x],"float32",k),N=MD({inputs:{x:I},backend:r,attrs:{shape:[1,y[0],y[1]]}});b.push(I),b.push(N);const S=null!=s,T=null!=a,C="leakyrelu"===o,E=o?TD(o,!0):null,$=new CD(N.shape,w.shape,[1,g,n.outChannels],!0,!1,S,E,T,C),A=[N,w];if(s&&A.push(s),T&&A.push(a),C){const e=r.makeTensorInfo([],"float32",$s(i,"float32"));A.push(e),b.push(e)}const R=r.runWebGLProgram($,A,"float32"),M=MD({inputs:{x:R},backend:r,attrs:{shape:f?[1,p,h,n.outChannels]:[1,n.outChannels,p,h]}});b.push(R);for(const e of b)r.disposeIntermediateTensorInfo(e);return M}const gO={kernelName:St,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a}=t,{strides:i,pad:o,dataFormat:l,dilations:u,dimRoundingMode:c}=r,h=ou(l),p=Jl(s.shape,a.shape,i,u,o,c,!1,h);let d;if(1!==p.filterHeight||1!==p.filterWidth||1!==p.dilationHeight||1!==p.dilationWidth||1!==p.strideHeight||1!==p.strideWidth||"SAME"!==p.padInfo.type&&"VALID"!==p.padInfo.type)if(He().getBool("WEBGL_CONV_IM2COL")&&1===s.shape[0])d=mO({x:s,filter:a,convInfo:p,backend:n});else{const e=new hO(p);d=n.runWebGLProgram(e,[s,a],"float32")}else d=fO({x:s,filter:a,convInfo:p,backend:n});const f=MD({inputs:{x:d},backend:n,attrs:{shape:p.outShape}});return n.disposeIntermediateTensorInfo(d),f}};class yO{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;const t=e.strideHeight,n=e.strideWidth,r=e.padInfo.top,s=e.padInfo.left,a="channelsLast"===e.dataFormat;this.userCode=`\n void main() {\n ivec4 coords = getOutputCoords();\n int wR = coords.x;\n int wC = coords.y;\n int d1 = coords.z;\n int d2 = coords.w;\n\n // Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n\n for (int b = 0; b < ${e.batchSize}; b++) {\n for (int yR = 0; yR < ${e.outHeight}; yR++) {\n int xR = wR + yR * ${t} - ${r};\n\n if (xR < 0 || xR >= ${e.inHeight}) {\n continue;\n }\n\n for (int yC = 0; yC < ${e.outWidth}; yC++) {\n int xC = wC + yC * ${n} - ${s};\n\n if (xC < 0 || xC >= ${e.inWidth}) {\n continue;\n }\n\n if (${a}) {\n float dyValue = getDy(b, yR, yC, d2);\n float xValue = getX(b, xR, xC, d1);\n dotProd += (xValue * dyValue);\n } else {\n float dyValue = getDy(b, d2, yR, yC);\n float xValue = getX(b, d1, xR, xC);\n dotProd += (xValue * dyValue);\n }\n\n }\n }\n }\n setOutput(dotProd);\n }\n `}}class bO{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,s=e.strideWidth,a="channelsLast"===e.dataFormat,i=t-1-e.padInfo.top,o=n-1-e.padInfo.left,l=a?1:2,u=a?2:3,c=a?3:1;this.userCode=`\n const ivec2 pads = ivec2(${i}, ${o});\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords[${c}];\n\n ivec2 dyCorner = ivec2(coords[${l}], coords[${u}]) - pads;\n int dyRCorner = dyCorner.x;\n int dyCCorner = dyCorner.y;\n\n // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < ${t}; wR++) {\n float dyR = float(dyRCorner + wR) / ${r}.0;\n\n if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = ${t} - 1 - wR;\n\n for (int wC = 0; wC < ${n}; wC++) {\n float dyC = float(dyCCorner + wC) / ${s}.0;\n\n if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = ${n} - 1 - wC;\n\n for (int d2 = 0; d2 < ${e.outChannels}; d2++) {\n\n if (${a}) {\n float xValue = getDy(batch, idyR, idyC, d2);\n float wValue = getW(wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n } else {\n float xValue = getDy(batch, d2, idyR, idyC);\n float wValue = getW(wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n }\n\n }\n }\n }\n setOutput(dotProd);\n }\n `}}class xO{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;const t=e.strideDepth,n=e.strideHeight,r=e.strideWidth,s=e.padInfo.front,a=e.padInfo.top,i=e.padInfo.left;this.userCode=`\n void main() {\n ivec5 coords = getOutputCoords();\n int wF = coords.x;\n int wR = coords.y;\n int wC = coords.z;\n int d1 = coords.w;\n int d2 = coords.u;\n\n float dotProd = 0.0;\n\n for (int b = 0; b < ${e.batchSize}; b++) {\n for (int yF = 0; yF < ${e.outDepth}; yF++) {\n int xF = wF + yF * ${t} - ${s};\n\n if (xF < 0 || xF >= ${e.inDepth}) {\n continue;\n }\n\n for (int yR = 0; yR < ${e.outHeight}; yR++) {\n int xR = wR + yR * ${n} - ${a};\n\n if (xR < 0 || xR >= ${e.inHeight}) {\n continue;\n }\n\n for (int yC = 0; yC < ${e.outWidth}; yC++) {\n int xC = wC + yC * ${r} - ${i};\n\n if (xC < 0 || xC >= ${e.inWidth}) {\n continue;\n }\n\n float dyValue = getDy(b, yF, yR, yC, d2);\n float xValue = getX(b, xF, xR, xC, d1);\n dotProd += (xValue * dyValue);\n }\n }\n }\n }\n setOutput(dotProd);\n }\n `}}class wO{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterDepth,n=e.filterHeight,r=e.filterWidth,s=e.strideDepth,a=e.strideHeight,i=e.strideWidth,o=t-1-e.padInfo.front,l=n-1-e.padInfo.top,u=r-1-e.padInfo.left;this.userCode=`\n const ivec3 pads = ivec3(${o}, ${l}, ${u});\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int d1 = coords.u;\n\n\n ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n int dyFCorner = dyCorner.x;\n int dyRCorner = dyCorner.y;\n int dyCCorner = dyCorner.z;\n\n float dotProd = 0.0;\n for (int wF = 0; wF < ${t}; wF++) {\n float dyF = float(dyFCorner + wF) / ${s}.0;\n\n if (dyF < 0.0 || dyF >= ${e.outDepth}.0 || fract(dyF) > 0.0) {\n continue;\n }\n int idyF = int(dyF);\n\n int wFPerm = ${t} - 1 - wF;\n\n for (int wR = 0; wR < ${n}; wR++) {\n float dyR = float(dyRCorner + wR) / ${a}.0;\n\n if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||\n fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = ${n} - 1 - wR;\n\n for (int wC = 0; wC < ${r}; wC++) {\n float dyC = float(dyCCorner + wC) / ${i}.0;\n\n if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = ${r} - 1 - wC;\n\n for (int d2 = 0; d2 < ${e.outChannels}; d2++) {\n float xValue = getDy(batch, idyF, idyR, idyC, d2);\n float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n }\n }\n }\n }\n setOutput(dotProd);\n }\n `}}const vO={kernelName:Tt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,dy:a}=t,{strides:i,pad:o,dataFormat:l,dimRoundingMode:u,filterShape:c}=r,h=ou(l),p=Jl(s.shape,c,i,1,o,u,!1,h),d=new yO(p);return n.runWebGLProgram(d,[s,a],"float32")}},kO={kernelName:Ct,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:s,filter:a}=t,{inputShape:i,strides:o,pad:l,dataFormat:u,dimRoundingMode:c}=r,h=ou(u),p=Jl(i,a.shape,o,1,l,c,!1,h),d=new bO(p);return n.runWebGLProgram(d,[s,a],"float32")}},IO={kernelName:Et,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a}=t,{strides:i,pad:o,dilations:l}=r,u=Ql(s.shape,a.shape,i,l,o),c=new pO(u);return n.runWebGLProgram(c,[s,a],"float32")}},NO={kernelName:$t,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,dy:a}=t,{strides:i,pad:o,filterShape:l}=r,u=Ql(s.shape,l,i,1,o),c=new xO(u);return n.runWebGLProgram(c,[s,a],"float32")}},SO={kernelName:At,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:s,filter:a}=t,{pad:i,strides:o,inputShape:l}=r,u=Ql(l,a.shape,o,1,i),c=new wO(u);return n.runWebGLProgram(c,[s,a],"float32")}},TO=ND({opSnippet:"if (isnan(x)) return x;\n return cos(x);\n"}),CO={kernelName:Rt,backendName:"webgl",kernelFunc:TO},EO=ND({opSnippet:"\n float e2x = exp(-x);\n return (e2x + 1.0 / e2x) / 2.0;\n"}),$O={kernelName:Mt,backendName:"webgl",kernelFunc:EO};class AO{constructor(e,t,n,r,s){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];const[a,i,o,l]=e,[u]=t,[c,h]=n;this.outputShape=[u,c,h,l];const p="bilinear"===r?1:0,[d,f]=[i-1+".0",o-1+".0"],[m,g,y]=c>1?[""+(i-1)/(c-1),"(y2-y1) * height_ratio",`y1*${d} + float(y)*(height_scale)`]:["0.0","0.0",`0.5 * (y1+y2) * ${d}`],[b,x,w]=h>1?[""+(o-1)/(h-1),"(x2-x1) * width_ratio",`x1*${f} + float(x)*(width_scale)`]:["0.0","0.0",`0.5 * (x1+x2) * ${f}`];this.userCode=`\n const float height_ratio = float(${m});\n const float width_ratio = float(${b});\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int y = coords[1];\n int x = coords[2];\n int d = coords[3];\n\n // get box vals\n float y1 = getBoxes(b,0);\n float x1 = getBoxes(b,1);\n float y2 = getBoxes(b,2);\n float x2 = getBoxes(b,3);\n\n // get image in batch index\n int bInd = round(getBoxInd(b));\n if(bInd < 0 || bInd >= ${a}) {\n return;\n }\n\n float height_scale = ${g};\n float width_scale = ${x};\n\n float in_y = ${y};\n if( in_y < 0.0 || in_y > ${d} ) {\n setOutput(float(${s}));\n return;\n }\n float in_x = ${w};\n if( in_x < 0.0 || in_x > ${f} ) {\n setOutput(float(${s}));\n return;\n }\n\n vec2 sourceFracIndexCR = vec2(in_x,in_y);\n if(${p} == 1) {\n // Compute the four integer indices.\n ivec2 sourceFloorCR = ivec2(sourceFracIndexCR);\n ivec2 sourceCeilCR = ivec2(ceil(sourceFracIndexCR));\n\n float topLeft = getImage(b, sourceFloorCR.y, sourceFloorCR.x, d);\n float bottomLeft = getImage(b, sourceCeilCR.y, sourceFloorCR.x, d);\n float topRight = getImage(b, sourceFloorCR.y, sourceCeilCR.x, d);\n float bottomRight = getImage(b, sourceCeilCR.y, sourceCeilCR.x, d);\n\n vec2 fracCR = sourceFracIndexCR - vec2(sourceFloorCR);\n\n float top = topLeft + (topRight - topLeft) * fracCR.x;\n float bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x;\n float newValue = top + (bottom - top) * fracCR.y;\n setOutput(newValue);\n } else {\n // Compute the coordinators of nearest neighbor point.\n ivec2 sourceNearestCR = ivec2(floor(\n sourceFracIndexCR + vec2(0.5,0.5)));\n float newValue = getImage(b, sourceNearestCR.y, sourceNearestCR.x, d);\n setOutput(newValue);\n }\n }\n `}}const RO={kernelName:Dt,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:r}=e,{image:s,boxes:a,boxInd:i}=t,{cropSize:o,method:l,extrapolationValue:u}=r,c=new AO(s.shape,a.shape,o,l,u);return n.runWebGLProgram(c,[s,a,i],"float32")}};class MO{constructor(e,t,n){this.variableNames=["x"],this.customUniforms=[{name:"index",type:"float"}],this.outputShape=e;const r=e.length,s=t?"0.0":`getX(${FO(r,"coords")})`,a=e[e.length-1];let i="",o="";t?(i=n?"end != "+(a-1):"end != 0",o=n?"end + 1":"end - 1"):(i=n?`end + pow2 < ${a}`:"end >= pow2",o=n?"end + pow2":"end - pow2"),this.userCode=`\n void main() {\n ${UM(r)} coords = getOutputCoords();\n int end = ${DO(r,"coords")};\n float val = ${s};\n int pow2 = int(pow(2.0, index));\n if (${i}) {\n int idx = ${o};\n ${DO(r,"coords")} = idx;\n val += getX(${FO(r,"coords")});\n }\n setOutput(val);\n }\n `}}function FO(e,t){if(1===e)return`${t}`;if(2===e)return`${t}.x, ${t}.y`;if(3===e)return`${t}.x, ${t}.y, ${t}.z`;if(4===e)return`${t}.x, ${t}.y, ${t}.z, ${t}.w`;throw Error(`Cumulative sum for rank ${e} is not yet supported`)}function DO(e,t){if(1===e)return`${t}`;if(2===e)return`${t}.y`;if(3===e)return`${t}.z`;if(4===e)return`${t}.w`;throw Error(`Cumulative sum for rank ${e} is not yet supported`)}const _O={kernelName:Ft,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,exclusive:i,reverse:o}=r,l=s.shape.length,u=Ac([a],l);let c=s;null!=u&&(c=UD({inputs:{x:s},backend:n,attrs:{perm:u}}));const h=Mc(1,l)[0];if(h!==l-1)throw new Error(`WebGL cumsum shader expects an inner-most axis=${s.shape.length-1} but got axis=${a}`);const p=c.shape[h];let d=fD({inputs:{x:c},backend:n});for(let e=0;e<=Math.ceil(Math.log2(p))-1;e++){const t=new MO(c.shape,!1,o),r=[[e]],s=d;d=n.runWebGLProgram(t,[d],d.dtype,r),n.disposeIntermediateTensorInfo(s)}if(i){const e=new MO(c.shape,i,o),t=d;d=n.runWebGLProgram(e,[d],d.dtype),n.disposeIntermediateTensorInfo(t)}if(null!=u){const e=UD({inputs:{x:d},backend:n,attrs:{perm:Rc(u)}});return n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(c),e}return d}},OO={kernelName:_t,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,weights:a}=t,{size:i,binaryOutput:o}=r;if(1===s.shape.length){const e=n.readSync(s.dataId),t=n.readSync(a.dataId),r=lF(e,t,a.dtype,a.shape,i);return n.makeTensorInfo([i],a.dtype,r)}if(2===s.shape.length){const e=n.bufferSync(s),t=n.bufferSync(a),r=uF(e,t,i,o);return n.makeTensorInfo(r.shape,a.dtype,r.values)}throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${s.shape.length}.`)}};class LO{constructor(e,t,n){this.variableNames=["x"],this.outputShape=[],this.outputShape=e,this.blockSize=t,this.dataFormat=n,this.userCode=`\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int h = ${this.getHeightCoordString()};\n int w = ${this.getWidthCoordString()};\n int d = ${this.getDepthCoordString()};\n\n int in_h = h / ${t};\n int offset_h = imod(h, ${t});\n int in_w = w / ${t};\n int offset_w = imod(w, ${t});\n int offset_d = (offset_h * ${t} + offset_w) *\n ${this.getOutputDepthSize()};\n int in_d = d + offset_d;\n\n float result = ${this.getInputSamplingString()};\n setOutput(result);\n }\n `}getHeightCoordString(){return"NHWC"===this.dataFormat?"coords[1]":"coords[2]"}getWidthCoordString(){return"NHWC"===this.dataFormat?"coords[2]":"coords[3]"}getDepthCoordString(){return"NHWC"===this.dataFormat?"coords[3]":"coords[1]"}getOutputDepthSize(){return"NHWC"===this.dataFormat?this.outputShape[3]:this.outputShape[1]}getInputSamplingString(){return"NHWC"===this.dataFormat?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"}}const zO={kernelName:Ot,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{blockSize:a,dataFormat:i}=r,o=s.shape[0],l=("NHWC"===i?s.shape[1]:s.shape[2])*a,u=("NHWC"===i?s.shape[2]:s.shape[3])*a,c=("NHWC"===i?s.shape[3]:s.shape[1])/(a*a),h=new LO("NHWC"===i?[o,l,u,c]:[o,c,l,u],a,i);return n.runWebGLProgram(h,[s],s.dtype)}};class PO{constructor(e,t=!1,n=null,r=!1,s=!1){this.variableNames=["x","W"],this.customUniforms=[{name:"pads",type:"ivec2"},{name:"strides",type:"ivec2"},{name:"dilations",type:"ivec2"},{name:"inDims",type:"ivec2"}],this.outputShape=e.outShape,this.enableShapeUniforms=qM(this.outputShape.length);const a=e.filterHeight,i=e.filterWidth,o=e.outChannels/e.inChannels;let l="",u="";n&&(l=r?`float activation(float a) {\n float b = getPreluActivationWeightsAtOutCoords();\n ${n}\n }`:s?`float activation(float a) {\n float b = getLeakyreluAlphaAtOutCoords();\n ${n}\n }`:`\n float activation(float x) {\n ${n}\n }\n `,u="result = activation(result);");const c=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),s&&this.variableNames.push("leakyreluAlpha"),this.userCode=`\n ${l}\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords.x;\n ivec2 xRCCorner = coords.yz * strides - pads;\n int d2 = coords.w;\n int d1 = d2 / ${o};\n int q = d2 - d1 * ${o};\n\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n // TO DO(dsmilkov): Flatten the two for loops and vec4 the operations.\n for (int wR = 0; wR < ${a}; wR++) {\n int xR = xRCorner + wR * dilations[0];\n\n if (xR < 0 || xR >= inDims[0]) {\n continue;\n }\n\n for (int wC = 0; wC < ${i}; wC++) {\n int xC = xCCorner + wC * dilations[1];\n\n if (xC < 0 || xC >= inDims[1]) {\n continue;\n }\n\n float xVal = getX(batch, xR, xC, d1);\n float wVal = getW(wR, wC, d1, q);\n dotProd += xVal * wVal;\n }\n }\n\n float result = dotProd;\n ${c}\n ${u}\n setOutput(result);\n }\n `}}class BO{constructor(e,t=!1,n=null,r=!1,s=!1){this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"pads",type:"ivec2"},{name:"strides",type:"ivec2"},{name:"dilations",type:"ivec2"},{name:"inDims",type:"ivec2"}],this.outputShape=e.outShape,this.enableShapeUniforms=qM(this.outputShape.length);const a=e.outChannels/e.inChannels,i=e.padInfo.left,o=e.strideWidth,l=e.dilationWidth,u=e.filterHeight,c=e.filterWidth,h=c;let p="\n int xR; int xC; int xCOffset;\n vec4 wTexel; vec4 previous; vec4 final;";for(let e=0;e=0 && xR < inDims[0]) {\n ";for(let e=0;e<(h+1)/2;e++){const t=2*e;if(p+=`\n xC = xCCorner + ${t*l};\n `,1===o){if(t= 0 && xCOffset < inDims[1] && xTexelC${t}Ready == 0) {\n xTexelC${t} = getX(batch, xR, xCOffset, d1);\n\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xCOffset + 1 >= inDims[1]) {\n xTexelC${t}.zw = vec2(0.0);\n }\n xTexelC${t}Ready = 1;\n }\n `,p+=1===l&&t>0?`\n xC${t} = vec4(xTexelC${t-2}.zw, xTexelC${t}.xy);\n `:`\n xCOffset = xC + 1 - 2;\n\n if (xCOffset >= 0 && xCOffset < inDims[1]) {\n previous = getX(batch, xR, xCOffset, d1);\n\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xCOffset + 1 >= inDims[1]) {\n previous.zw = vec2(0.0);\n }\n\n xC${t} = vec4(previous.zw, xTexelC${t}.xy);\n } else {\n xC${t} = vec4(0.0, 0.0, xTexelC${t}.xy);\n }\n `):p+=`\n if (xC >= 0 && xC < inDims[1] && xTexelC${t}Ready == 0) {\n xTexelC${t} = getX(batch, xR, xC, d1);\n if (xC + 1 >= inDims[1]) {\n xTexelC${t}.zw = vec2(0.0);\n }\n xTexelC${t}Ready = 1;\n }\n\n xC${t} = xTexelC${t};\n `,t+1= 0 && xCOffset < inDims[1] && xTexelC${t+1}Ready == 0) {\n xTexelC${t+1} = getX(batch, xR, xCOffset, d1);\n\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xCOffset + 1 >= inDims[1]) {\n xTexelC${t+1}.zw = vec2(0.0);\n }\n xTexelC${t+1}Ready = 1;\n }\n `,l>1&&(p+=`\n xCOffset -= 2;\n if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${t}Ready == 0) {\n xTexelC${t} = getX(batch, xR, xCOffset, d1);\n xTexelC${t}Ready = 1;\n }\n `),p+=`\n xC${t+1} = vec4(xTexelC${t}.zw, xTexelC${t+1}.xy);\n `):p+=1===e?`\n xC${t+1} = xTexelC${t};\n `:`\n xCOffset = xC + ${e};\n\n if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${t+1}Ready == 0) {\n xTexelC${t+1} = getX(batch, xR, xCOffset, d1);\n if (xCOffset + 1 >= inDims[1]) {\n xTexelC${t+1}.zw = vec2(0.0);\n }\n xTexelC${t+1}Ready = 1;\n }\n\n xC${t+1} = xTexelC${t+1};\n `}}else t= 0 && xCOffset < inDims[1] && xTexelC${t}Ready == 0) {\n xTexelC${t} = getX(batch, xR, xCOffset, d1);\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xCOffset + 1 >= inDims[1]) {\n xTexelC${t}.zw = vec2(0.0);\n }\n xTexelC${t}Ready = 1;\n }\n\n if(xC + 1 >= 0 && xC + 1 < inDims[1] && xTexelC${t+1}Ready == 0) {\n xTexelC${t+1} = getX(batch, xR, xC + 1, d1);\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xC + 2 >= inDims[1]) {\n xTexelC${t+1}.zw = vec2(0.0);\n }\n xTexelC${t+1}Ready = 1;\n }\n\n xC${t} = vec4(xTexelC${t}.zw, xTexelC${t+1}.zw);\n `,t+1= 0 && xCOffset < inDims[1]) {\n final = getX(batch, xR, xCOffset, d1);\n }\n xC${t+1} = vec4(xTexelC${t+1}.xy, final.xy);\n `)):(p+=`\n if(xC >= 0 && xC < inDims[1] && xTexelC${t}Ready == 0) {\n xTexelC${t} = getX(batch, xR, xC, d1);\n if (xC + 1 >= inDims[1]) {\n xTexelC${t}.zw = vec2(0.0);\n }\n xTexelC${t}Ready = 1;\n }\n\n xCOffset = xC + strides[1];\n if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${t+1}Ready == 0) {\n xTexelC${t+1} = getX(batch, xR, xCOffset, d1);\n if (xCOffset + 1 >= inDims[1]) {\n xTexelC${t+1}.zw = vec2(0.);\n }\n xTexelC${t+1}Ready = 1;\n }\n\n xC${t} = vec4(\n xTexelC${t}.xy, xTexelC${t+1}.xy);\n `,t+1`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${i} and dilations '${c}'`));const h=Jl(s.shape,a.shape,i,c,o,u,!0);let p;p=He().getBool("WEBGL_PACK_DEPTHWISECONV")&&h.strideWidth<=2&&h.outChannels/h.inChannels==1?new BO(h):new PO(h);const d=[[h.padInfo.top,h.padInfo.left],[h.strideHeight,h.strideWidth],[h.dilationHeight,h.dilationWidth],[h.inHeight,h.inWidth]];return n.runWebGLProgram(p,[s,a],"float32",d)}};class UO{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;const t=e.strideHeight,n=e.strideWidth,r=e.padInfo.top,s=e.padInfo.left,a=e.outChannels/e.inChannels;this.userCode=`\n void main() {\n ivec4 coords = getOutputCoords();\n int wR = coords.x;\n int wC = coords.y;\n int d1 = coords.z;\n int dm = coords.w;\n int d2 = d1 * ${a} + dm;\n\n float dotProd = 0.0;\n\n // TO DO: Vec4 over the batch size\n for (int b = 0; b < ${e.batchSize}; b++) {\n for (int yR = 0; yR < ${e.outHeight}; yR++) {\n int xR = wR + yR * ${t} - ${r};\n\n if (xR < 0 || xR >= ${e.inHeight}) {\n continue;\n }\n\n for (int yC = 0; yC < ${e.outWidth}; yC++) {\n int xC = wC + yC * ${n} - ${s};\n\n if (xC < 0 || xC >= ${e.inWidth}) {\n continue;\n }\n\n float dyValue = getDy(b, yR, yC, d2);\n float xValue = getX(b, xR, xC, d1);\n dotProd += (xValue * dyValue);\n }\n }\n }\n setOutput(dotProd);\n }\n `}}class WO{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,s=e.strideWidth,a=t-1-e.padInfo.top,i=n-1-e.padInfo.left,o=e.outChannels/e.inChannels;this.userCode=`\n const ivec2 pads = ivec2(${a}, ${i});\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords[3];\n ivec2 dyCorner = coords.yz - pads;\n int dyRCorner = dyCorner.x;\n int dyCCorner = dyCorner.y;\n\n float dotProd = 0.0;\n\n for (int wR = 0; wR < ${t}; wR++) {\n float dyR = float(dyRCorner + wR) / ${r}.0;\n\n if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = ${t} - 1 - wR;\n\n for (int wC = 0; wC < ${n}; wC++) {\n float dyC = float(dyCCorner + wC) / ${s}.0;\n\n if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = ${n} - 1 - wC;\n\n // TO DO: Vec4 over the channelMul\n for (int dm = 0; dm < ${o}; dm++) {\n int d2 = d1 * ${o} + dm;\n float xValue = getDy(batch, idyR, idyC, d2);\n float wValue = getW(wRPerm, wCPerm, d1, dm);\n dotProd += xValue * wValue;\n }\n }\n }\n setOutput(dotProd);\n }\n `}}const GO={kernelName:zt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,dy:a}=t,{strides:i,dilations:o,pad:l,dimRoundingMode:u,filterShape:c}=r,h=Jl(s.shape,c,i,o,l,u,!0),p=new UO(h);return n.runWebGLProgram(p,[s,a],"float32")}},HO={kernelName:Pt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:s,filter:a}=t,{strides:i,dilations:o,pad:l,dimRoundingMode:u,inputShape:c}=r,h=Jl(c,a.shape,i,o,l,u,!0),p=new WO(h);return n.runWebGLProgram(p,[s,a],"float32")}};class jO{constructor(e){this.variableNames=["X"],this.outputShape=[e,e],this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n float val = coords[0] == coords[1] ? getX(coords[0]) : 0.0;\n setOutput(val);\n }\n "}}const qO={kernelName:Bt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:r}=t,s=[...r.shape,...r.shape],a=oe(r.shape),i=MD({inputs:{x:r},backend:n,attrs:{shape:[a]}}),o=new jO(a),l=n.runWebGLProgram(o,[i],i.dtype),u=MD({inputs:{x:l},backend:n,attrs:{shape:s}});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(l),u}};class KO{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;const{inHeight:t,inWidth:n,padInfo:r,strideHeight:s,strideWidth:a,filterHeight:i,filterWidth:o,dilationHeight:l,dilationWidth:u}=e,{top:c,left:h}=r;this.userCode=`\n const ivec2 strides = ivec2(${s}, ${a});\n const ivec2 pads = ivec2(${c}, ${h});\n const float neg_infinity = -3.4e38;\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords.x;\n int d1 = coords.w;\n ivec2 outTopLeftCorner =\n coords.yz * strides - pads;\n int hBeg = outTopLeftCorner.x;\n int wBeg = outTopLeftCorner.y;\n\n float curVal = neg_infinity;\n for (int h = 0; h < ${i}; h++) {\n int hIn = hBeg + h * ${l};\n\n if (hIn >= 0 && hIn < ${t}) {\n for (int w = 0; w < ${o}; w++) {\n int wIn = wBeg + w * ${u};\n\n if (wIn >= 0 && wIn < ${n}) {\n float xVal = getX(batch, hIn, wIn, d1);\n float wVal = getW(h, w, d1);\n\n float val = xVal + wVal;\n if (val > curVal) {\n curVal = val;\n }\n }\n }\n }\n }\n\n float result = curVal;\n setOutput(result);\n }\n `}}const XO={kernelName:Vt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a}=t,{strides:i,pad:o,dilations:l}=r,u=Xl(s.shape,a.shape,i,o,"NHWC",l);let c;const h=new KO(u);c=n.runWebGLProgram(h,[s,a],"float32");const p=MD({inputs:{x:c},backend:n,attrs:{shape:u.outShape}});return n.disposeIntermediateTensorInfo(c),p}},YO={kernelName:Ht,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{equation:s}=r,a=t,{allDims:i,summedDims:o,idDims:l}=lf(s,a.length);cf(i.length,l,a);const{path:u,steps:c}=hf(o,l),h=c.length;let p=null,d=i.length;const f=[];for(let e=0;e=0&&(p=BD({inputs:{x:p},backend:n,attrs:{axis:u[e]-(i.length-d),keepDims:!1}}),f.push(p)),d--)}for(const e of f)e!==p&&n.disposeIntermediateTensorInfo(e);return p}},ZO=ND({opSnippet:"return (x >= 0.0) ? x : (exp(x) - 1.0);",packedOpSnippet:"\n vec4 result;\n\n result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);\n result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);\n result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);\n result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);\n\n return result;\n"}),JO={kernelName:jt,backendName:"webgl",kernelFunc:ZO},QO={kernelName:qt,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n}=e,{dy:r,y:s}=t,a=He().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new dD("\n vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));\n return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));\n",r.shape,s.shape):new pD("return (b >= 1.0) ? a : a * (b + 1.0);",r.shape,s.shape);return n.runWebGLProgram(a,[r,s],r.dtype)}},eL=SD({opSnippet:"return float(a == b);",packedOpSnippet:"\n return vec4(equal(a, b));\n",dtype:"bool",cpuKernelImpl:pF}),tL={kernelName:Xt,backendName:"webgl",kernelFunc:eL},nL=ND({opSnippet:`\n // Error function is calculated approximately with elementary function.\n // See "Handbook of Mathematical Functions with Formulas,\n // Graphs, and Mathematical Tables", Abramowitz and Stegun.\n float p = ${jd};\n float a1 = ${qd};\n float a2 = ${Kd};\n float a3 = ${Xd};\n float a4 = ${Yd};\n float a5 = ${Zd};\n\n float sign = sign(x);\n x = abs(x);\n float t = 1.0 / (1.0 + p * x);\n return sign * (1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x));\n`}),rL={kernelName:Kt,backendName:"webgl",kernelFunc:nL},sL=ND({opSnippet:"if (isnan(x)) return x;\n return exp(x);\n",packedOpSnippet:"\n vec4 result = exp(x);\n bvec4 isNaN = isnan(x);\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n",cpuKernelImpl:dF,dtype:"float32"}),aL={kernelName:Yt,backendName:"webgl",kernelFunc:sL};function iL(e){const{inputs:t,attrs:n,backend:r}=e,{dim:s}=n,{input:a}=t,i=a.shape.length,o=a.shape.slice();let l=s;return s<0&&(re(-(i+1)<=s,(()=>`Axis must be in the interval [${-(i+1)}, ${i}]`)),l=i+s+1),o.splice(l,0,1),MD({inputs:{x:a},backend:r,attrs:{shape:o}})}const oL={kernelName:Zt,backendName:"webgl",kernelFunc:iL},lL="return exp(x) - 1.0;",uL=ND({opSnippet:lL,packedOpSnippet:lL,cpuKernelImpl:fF}),cL={kernelName:Jt,backendName:"webgl",kernelFunc:uL};class hL{constructor(e,t,n){this.variableNames=["real","imag"];const r=t[1];this.outputShape=t;const s=n?`2.0 * ${Math.PI}`:`-2.0 * ${Math.PI}`,a=n?`${r}.0`:"1.0";let i;if("real"===e)i="return real * expR - imag * expI;";else{if("imag"!==e)throw new Error(`FFT component must be either "real" or "imag", got ${e}.`);i="return real * expI + imag * expR;"}this.userCode=`\n const float exponentMultiplier = ${s};\n\n float unaryOpComplex(float real, float expR, float imag, float expI) {\n ${i}\n }\n\n float mulMatDFT(int batch, int index) {\n float indexRatio = float(index) / float(${r});\n float exponentMultiplierTimesIndexRatio =\n exponentMultiplier * indexRatio;\n\n float result = 0.0;\n\n for (int i = 0; i < ${r}; i++) {\n // x = (-2|2 * PI / N) * index * i;\n float x = exponentMultiplierTimesIndexRatio * float(i);\n float expR = cos(x);\n float expI = sin(x);\n float real = getReal(batch, i);\n float imag = getImag(batch, i);\n\n result +=\n unaryOpComplex(real, expR, imag, expI) / ${a};\n }\n\n return result;\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n setOutput(mulMatDFT(coords[0], coords[1]));\n }\n `}}function pL(e,t,n){const r=n.texData.get(e.dataId),s=oe(e.shape),a=e.shape[e.shape.length-1],i=MD({inputs:{x:e},backend:n,attrs:{shape:[s/a,a]}}),o=i.shape,l=new hL("real",o,t),u=new hL("imag",o,t),c=[{dataId:r.complexTensorInfos.real.dataId,dtype:r.complexTensorInfos.real.dtype,shape:o},{dataId:r.complexTensorInfos.imag.dataId,dtype:r.complexTensorInfos.imag.dtype,shape:o}],h=n.runWebGLProgram(l,c,"float32"),p=n.runWebGLProgram(u,c,"float32"),d=gD({inputs:{real:h,imag:p},backend:n});n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(p);const f=MD({inputs:{x:d},backend:n,attrs:{shape:e.shape}});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(d),f}const dL={kernelName:Qt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{input:r}=t;return pL(r,!1,n)}};class fL{constructor(e,t){this.outputShape=[],this.customUniforms=[{name:"value",type:"float"}],this.variableNames=["x"],this.outputShape=e,this.userCode="\n void main() {\n // Input can be obtained from uniform value.\n setOutput(value);\n }\n "}}function mL(e){const{backend:t,attrs:n}=e,{shape:r,value:s}=n;let{dtype:a}=n;if(a=a||Ae(s),"string"===a){const e=we(a,oe(r));return e.fill(s),t.makeTensorInfo(r,a,e)}{const e=new fL(r,s),n=[[s]];return t.runWebGLProgram(e,[],a,n)}}const gL={kernelName:en,backendName:"webgl",kernelFunc:mL};class yL{constructor(e){this.variableNames=["Image"],this.outputShape=[];const t=e[2];this.outputShape=e,this.userCode=`\n void main() {\n ivec4 coords = getOutputCoords();\n int x = coords[2];\n\n int coordX = ${t} - x - 1;\n float outputValue;\n if(coordX >= 0 && coordX < ${t}) {\n outputValue = getImage(coords[0], coords[1], coordX, coords[3]);\n } else {\n outputValue = getImage(coords[0], coords[1], coords[2], coords[3]);\n }\n setOutput(outputValue);\n }\n `}}const bL={kernelName:tn,backendName:"webgl",kernelFunc:({inputs:e,backend:t})=>{const{image:n}=e,r=t,s=new yL(n.shape);return r.runWebGLProgram(s,[n],n.dtype)}},xL="return floor(x);",wL=ND({opSnippet:xL,packedOpSnippet:xL,cpuKernelImpl:mF}),vL={kernelName:nn,backendName:"webgl",kernelFunc:wL},kL=SD({opSnippet:"\n float s = sign(a) * sign(b);\n int ia = round(a);\n int ib = round(b);\n if (ib != 0) {\n // Windows (D3D) wants guaranteed non-zero int division at compile-time.\n return float(idiv(ia, ib, s));\n } else {\n return NAN;\n }\n",packedOpSnippet:"\n ivec4 ia = round(a);\n ivec4 ib = round(b);\n bvec4 cond = notEqual(ib, ivec4(0));\n ivec4 result = ivec4(0);\n vec4 s = sign(a) * sign(b);\n\n // Windows (D3D) wants guaranteed non-zero int division at compile-time.\n if (cond[0]) {\n result[0] = idiv(ia[0], ib[0], s[0]);\n }\n if (cond[1]) {\n result[1] = idiv(ia[1], ib[1], s[1]);\n }\n if (cond[2]) {\n result[2] = idiv(ia[2], ib[2], s[2]);\n }\n if (cond[3]) {\n result[3] = idiv(ia[3], ib[3], s[3]);\n }\n return vec4(result);\n",dtype:"int32"}),IL={kernelName:rn,backendName:"webgl",kernelFunc:kL};class NL{constructor(e){this.variableNames=["A"];const t=CM(),[n,r]=e;this.outputShape=e,this.userCode=`\n void main() {\n ivec3 coords = getOutputCoords();\n int texR = coords[0];\n int texC = coords[1];\n int depth = coords[2];\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${r}.0, ${n}.0);\n\n vec4 values = ${t.texture2D}(A, uv);\n float value;\n if (depth == 0) {\n value = values.r;\n } else if (depth == 1) {\n value = values.g;\n } else if (depth == 2) {\n value = values.b;\n } else if (depth == 3) {\n value = values.a;\n }\n\n setOutput(floor(value * 255.0 + 0.5));\n }\n `}}class SL{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;const t=CM(),[n,r]=e;this.outputShape=e,this.userCode=`\n void main() {\n ivec3 coords = getOutputCoords();\n int texR = coords[0];\n int texC = coords[1];\n int depth = coords[2];\n\n vec4 result = vec4(0.);\n\n for(int row=0; row<=1; row++) {\n for(int col=0; col<=1; col++) {\n texC = coords[1] + row;\n depth = coords[2] + col;\n\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${r}.0, ${n}.0);\n vec4 values = ${t.texture2D}(A, uv);\n float value;\n if (depth == 0) {\n value = values.r;\n } else if (depth == 1) {\n value = values.g;\n } else if (depth == 2) {\n value = values.b;\n } else if (depth == 3) {\n value = values.a;\n }\n\n result[row * 2 + col] = floor(value * 255.0 + 0.5);\n }\n }\n\n ${t.output} = result;\n }\n `}}const TL={kernelName:Zr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e;let{pixels:s}=t;const{numChannels:a}=r,i="undefined"!=typeof HTMLVideoElement&&s instanceof HTMLVideoElement,o="undefined"!=typeof HTMLImageElement&&s instanceof HTMLImageElement,[l,u]=i?[s.videoWidth,s.videoHeight]:[s.width,s.height],c=[u,l],h=[u,l,a];(o||i)&&(null==CL&&(CL=document.createElement("canvas").getContext("2d")),CL.canvas.width=l,CL.canvas.height=u,CL.drawImage(s,0,0,l,u),s=CL.canvas);const p=n.makeTensorInfo(c,"int32");n.texData.get(p.dataId).usage=JR.PIXELS,n.gpgpu.uploadPixelDataToTexture(n.getTexture(p.dataId),s);const d=He().getBool("WEBGL_PACK")?new SL(h):new NL(h),f=n.runWebGLProgram(d,[p],"int32");return n.disposeData(p.dataId),f}};let CL;const EL={kernelName:es,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dataFormat:c,dilations:h,dimRoundingMode:p,activation:d,leakyreluAlpha:f}=r,m=ou(c),g=Jl(s.shape,a.shape,l,h,u,p,!1,m);let y;const b=[];if(1!==g.filterHeight||1!==g.filterWidth||1!==g.dilationHeight||1!==g.dilationWidth||1!==g.strideHeight||1!==g.strideWidth||"SAME"!==g.padInfo.type&&"VALID"!==g.padInfo.type)if(He().getBool("WEBGL_CONV_IM2COL")&&1===s.shape[0])y=mO({x:s,filter:a,convInfo:g,backend:n,bias:i,activation:d,preluActivationWeights:o,leakyreluAlpha:f});else{const e=null!=i,t=null!=o,r="leakyrelu"===d,l=d?TD(d,!1):null,u=new hO(g,e,l,t,r),c=[s,a];if(i&&c.push(i),o&&c.push(o),r){const e=n.makeTensorInfo([],"float32",$s(f,"float32"));c.push(e),b.push(e)}y=n.runWebGLProgram(u,c,"float32")}else y=fO({x:s,filter:a,convInfo:g,backend:n,bias:i,activation:d,preluActivationWeights:o,leakyreluAlpha:f});const x=MD({inputs:{x:y},backend:n,attrs:{shape:g.outShape}});return b.push(y),b.forEach((e=>n.disposeIntermediateTensorInfo(e))),x}},$L={kernelName:ts,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dilations:c,dimRoundingMode:h,activation:p,leakyreluAlpha:d}=r,f=[];let m=c;null==m&&(m=[1,1]),re(iu(l,m),(()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${l} and dilations '${m}'`));const g=Jl(s.shape,a.shape,l,m,u,h,!0),y=He().getBool("WEBGL_PACK_DEPTHWISECONV")&&g.strideWidth<=2&&g.outChannels/g.inChannels==1,b=p?TD(p,y):null,x=[s,a],w=null!=i,v=null!=o,k="leakyrelu"===p;if(w&&x.push(i),v&&x.push(o),k){const e=n.makeTensorInfo([],"float32",$s(d,"float32"));x.push(e),f.push(e)}let I;I=y?new BO(g,w,b,v,k):new PO(g,w,b,v,k);const N=[[g.padInfo.top,g.padInfo.left],[g.strideHeight,g.strideWidth],[g.dilationHeight,g.dilationWidth],[g.inHeight,g.inWidth]],S=n.runWebGLProgram(I,x,"float32",N);return f.forEach((e=>n.disposeIntermediateTensorInfo(e))),S}};class AL{constructor(e,t,n){this.sliceDim=e,this.strides=t,this.variableNames=["x","indices"],this.outputShape=n;const r=UM(t.length),s=UM(n.length),a=this.sliceDim>1?"strides[j]":"strides";this.userCode=`\n ${r} strides = ${r}(${this.strides});\n void main() {\n ${s} coords = getOutputCoords();\n int flattenIndex = 0;\n for (int j = 0; j < ${this.sliceDim}; j++) {\n int index = round(getIndices(coords[0], j));\n flattenIndex += index * ${a};\n }\n setOutput(getX(flattenIndex, coords[1]));\n }\n `}}const RL={kernelName:on,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{params:r,indices:s}=t,a=s.shape,i=a[a.length-1],o=oe(r.shape),[l,u,c,h]=so(r,s),p=MD({inputs:{x:s},backend:n,attrs:{shape:[u,i]}}),d=MD({inputs:{x:r},backend:n,attrs:{shape:[oe(r.shape)/c,c]}});if(n.shouldExecuteOnCPU([r,s])||"string"===r.dtype){const e=n.readSync(s.dataId),t=n.bufferSync(r),a=gF(e,t,r.dtype,u,i,c,h,r.shape,o);return n.makeTensorInfo(l,r.dtype,a.values)}const f=new AL(i,h,[u,c]),m=n.runWebGLProgram(f,[d,p],d.dtype),g=MD({inputs:{x:m},backend:n,attrs:{shape:l}});return n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(m),g}};class ML{constructor(e,t){this.variableNames=["A","indices"],this.outputShape=t,this.rank=t.length;const n=UM(this.rank),r=function(e,t){const n=["resRC.x","resRC.y","resRC.z","resRC.w"],r=[];for(let t=0;t= 0) && (index < ${e[2]}) ? 1.0 : 0.0;\n setOutput(inBounds * getA(${r}));\n }\n `}}function FL(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,indices:a}=t,{axis:i,batchDims:o}=r,l=ye(i,s.shape)[0];if(He().get("DEBUG")){const e=n.readSync(a.dataId),t=s.shape[l];for(let n=0;n=0,(()=>`GatherV2: the index value ${r} is not in [0, ${t-1}]`))}}const u=$f(s,a,l,o),c=oe(a.shape),h=[],p=MD({inputs:{x:s},backend:n,attrs:{shape:[u.batchSize,u.outerSize,u.dimSize,u.sliceSize]}}),d=MD({inputs:{x:a},backend:n,attrs:{shape:[u.batchSize,c/u.batchSize]}});h.push(p),h.push(d);const f=[u.batchSize,u.outerSize,c/u.batchSize,u.sliceSize];if(n.shouldExecuteOnCPU([s,a])||"string"===s.dtype){const e=n.bufferSync(d),t=n.bufferSync(p),r=yF(t,e,f);return h.forEach((e=>n.disposeIntermediateTensorInfo(e))),n.makeTensorInfo(u.outputShape,r.dtype,r.values)}const m=new ML(p.shape,f),g=n.runWebGLProgram(m,[p,d],p.dtype);h.push(g);const y=MD({inputs:{x:g},backend:n,attrs:{shape:u.outputShape}});return h.forEach((e=>n.disposeIntermediateTensorInfo(e))),y}const DL={kernelName:an,backendName:"webgl",kernelFunc:FL},_L=SD({opSnippet:"return float(a > b);",packedOpSnippet:"\n return vec4(greaterThan(a, b));\n",cpuKernelImpl:bF,dtype:"bool"}),OL={kernelName:ln,backendName:"webgl",kernelFunc:_L},LL=SD({opSnippet:"return float(a >= b);",packedOpSnippet:"\n return vec4(greaterThanEqual(a, b));\n",dtype:"bool",cpuKernelImpl:xF}),zL={kernelName:un,backendName:"webgl",kernelFunc:LL},PL={kernelName:hn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{input:r}=t;return pL(r,!0,n)}},BL=ND({opSnippet:"return float(!isnan(x) && !isinf(x));",dtype:"bool"}),VL={kernelName:dn,backendName:"webgl",kernelFunc:BL},UL=ND({opSnippet:"return float(isinf(x));",dtype:"bool"}),WL={kernelName:fn,backendName:"webgl",kernelFunc:UL},GL=ND({opSnippet:"return float(isnan(x));",dtype:"bool"}),HL={kernelName:mn,backendName:"webgl",kernelFunc:GL},jL=SD({opSnippet:"return float(a < b);",packedOpSnippet:"\n return vec4(lessThan(a, b));\n",cpuKernelImpl:wF,dtype:"bool"}),qL={kernelName:yn,backendName:"webgl",kernelFunc:jL},KL=SD({opSnippet:"return float(a <= b);",packedOpSnippet:"\n return vec4(lessThanEqual(a, b));\n",cpuKernelImpl:vF,dtype:"bool"}),XL={kernelName:bn,backendName:"webgl",kernelFunc:KL},YL={kernelName:xn,backendName:"webgl",kernelFunc:function(e){const{backend:t,attrs:n}=e,{start:r,stop:s,num:a}=n,i=kF(r,s,a);return t.makeTensorInfo([i.length],"float32",i)}},ZL=ND({opSnippet:"if (isnan(x)) return x;\n return x < 0.0 ? 0./0. : log(x);\n",packedOpSnippet:"\n vec4 result = log(x);\n bvec4 isNaN = isnan(x);\n result.r = isNaN.r ? x.r : (x.r < 0.0 ? 0./0. : result.r);\n result.g = isNaN.g ? x.g : (x.g < 0.0 ? 0./0. : result.g);\n result.b = isNaN.b ? x.b : (x.b < 0.0 ? 0./0. : result.b);\n result.a = isNaN.a ? x.a : (x.a < 0.0 ? 0./0. : result.a);\n return result;\n",cpuKernelImpl:IF}),JL={kernelName:wn,backendName:"webgl",kernelFunc:ZL},QL=ND({opSnippet:"if (isnan(x)) return x;\n return log(1.0 + x);\n"}),ez={kernelName:vn,backendName:"webgl",kernelFunc:QL},tz=SD({opSnippet:"return float(a >= 1.0 && b >= 1.0);",packedOpSnippet:"\n return vec4(\n vec4(greaterThanEqual(a, vec4(1.0))) *\n vec4(greaterThanEqual(b, vec4(1.0))));\n",dtype:"bool"}),nz={kernelName:kn,backendName:"webgl",kernelFunc:tz},rz=ND({opSnippet:"return float(!(x >= 1.0));"}),sz={kernelName:In,backendName:"webgl",kernelFunc:rz},az=SD({opSnippet:"return float(a >= 1.0 || b >= 1.0);",packedOpSnippet:"\n return min(\n vec4(greaterThanEqual(a, vec4(1.0))) +\n vec4(greaterThanEqual(b, vec4(1.0))),\n vec4(1.0));\n",dtype:"bool"}),iz={kernelName:Nn,backendName:"webgl",kernelFunc:az};class oz{constructor(e,t,n,r,s){this.variableNames=["x"],this.outputShape=[];const a=t,i=e[3]-1;let o;this.outputShape=e;const l=`float(${n}) + float(${r}) * sum`;o=.5===s?`inversesqrt(${l})`:1===s?`1.0/(${l})`:`exp(log(${l}) * float(-${s}));`,this.userCode=`\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int r = coords[1];\n int c = coords[2];\n int d = coords[3];\n float x = getX(b, r, c, d);\n float sum = 0.0;\n for (int j = -${a}; j <= ${a}; j++) {\n int idx = d + j;\n if (idx >= 0 && idx <= ${i}) {\n float z = getX(b, r, c, idx);\n sum += z * z;\n }\n }\n float val = x * ${o};\n setOutput(val);\n }\n `}}class lz{constructor(e,t,n,r,s){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;const a=t,i=e[3]-1;let o;this.outputShape=e;const l=`float(${n}) + float(${r}) * sum`;o=.5===s?`inversesqrt(${l})`:1===s?`1.0/(${l})`:`exp(log(${l}) * float(-${s}));`,this.userCode=`\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords.x;\n int r = coords.y;\n int c = coords.z;\n int d = coords.w;\n\n bool hasNextCol = d < ${this.outputShape[3]};\n bool hasNextRow = c < ${this.outputShape[2]};\n\n vec4 sum = vec4(0.);\n vec4 xFragAtOutputCoords = getX(b, r, c, d);\n\n vec4 xAtOutputCoords = vec4(\n getChannel(xFragAtOutputCoords, vec2(c, d)),\n hasNextCol ?\n getChannel(xFragAtOutputCoords, vec2(c, d + 1)) : 0.0,\n hasNextRow ?\n getChannel(xFragAtOutputCoords , vec2(c + 1, d)) : 0.0,\n (hasNextRow && hasNextCol) ?\n getChannel(xFragAtOutputCoords, vec2(c + 1, d + 1)) : 0.0\n );\n\n int firstChannel = d - ${a};\n vec2 cache = vec2(0.);\n if(firstChannel >= 0){\n vec4 firstChannelFrag = getX(b, r, c, firstChannel);\n cache.x = getChannel(firstChannelFrag, vec2(c, firstChannel));\n if(hasNextRow){\n cache.y = getChannel(firstChannelFrag, vec2(c + 1, firstChannel));\n }\n }\n\n ivec2 depth = ivec2(d, d + 1);\n for (int j = - ${a}; j <= ${a}; j++) {\n ivec2 idx = depth + j;\n bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));\n bvec2 belowUpperBound = lessThanEqual(idx, ivec2(${i}));\n\n bool depthInRange = aboveLowerBound.x && belowUpperBound.x;\n bool depthPlusOneInRange = aboveLowerBound.y && belowUpperBound.y;\n\n if(depthInRange || depthPlusOneInRange){\n vec4 z = vec4(0.);\n vec4 xFragAtCurrentDepth;\n z.xz = cache.xy;\n if(depthPlusOneInRange && hasNextCol){\n xFragAtCurrentDepth = idx.y != d ?\n getX(b, r, c, idx.y) : xFragAtOutputCoords;\n z.y = getChannel(xFragAtCurrentDepth, vec2(c, idx.y));\n if(hasNextRow){\n z.w = getChannel(xFragAtCurrentDepth, vec2(c + 1, idx.y));\n }\n }\n cache.xy = z.yw;\n sum += z * z;\n }\n }\n vec4 result = xAtOutputCoords * ${o};\n setOutput(result);\n }\n `}}const uz={kernelName:Tn,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{depthRadius:a,bias:i,alpha:o,beta:l}=r,u=He().getBool("WEBGL_PACK_NORMALIZATION")?new lz(s.shape,a,i,o,l):new oz(s.shape,a,i,o,l);return n.runWebGLProgram(u,[s],s.dtype)}};class cz{constructor(e,t,n,r,s){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=e,this.depth=e[3],this.depthRadius=t,this.bias=n,this.alpha=r,this.beta=s,this.userCode=`\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int r = coords[1];\n int c = coords[2];\n\n float result = 0.0;\n for (int d = 0; d < ${this.depth}; ++d) {\n int depthBegin = int(max(0.0, float(d - ${t})));\n int depthEnd = int(min(float(${this.depth}),\n float(d + ${t} + 1)));\n\n const int MIN_DEPTH_BEGIN = 0;\n const int MAX_DEPTH_END = ${this.depth};\n\n float norm = 0.0;\n for (int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k) {\n if (k < depthBegin){\n continue;\n }\n else if (k >= depthBegin && k < depthEnd) {\n norm += getInputImage(b, r, c, k) * getInputImage(b, r, c, k);\n }\n else {\n break;\n }\n }\n\n norm = float(${r}) * norm + float(${n});\n\n for(int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k){\n if (k < depthBegin){\n continue;\n }\n else if (k >= depthBegin && k < depthEnd){\n float dyi = -2.0 * float(${r})\n * float(${s})\n * getInputImage(b ,r ,c, k) * getOutputImage(b, r, c, d)\n / norm;\n if (k == d) {\n dyi += pow(norm, -1.0 * ${s});\n }\n if (k == coords[3]) {\n dyi *= getDy(b, r, c, d);\n result += dyi;\n }\n }\n else {\n break;\n }\n }\n }\n setOutput(result);\n }\n `}}const hz={kernelName:Cn,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:r}=e,{x:s,y:a,dy:i}=t,{depthRadius:o,bias:l,alpha:u,beta:c}=r,h=new cz(s.shape,o,l,u,c);return n.runWebGLProgram(h,[s,a,i],s.dtype)}};function pz(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{reductionIndices:a,keepDims:i}=r,o=s.shape.length,l=ye(a,s.shape);let u=l;const c=Ac(u,o),h=null!=c,p=n.shouldExecuteOnCPU([s]);let d=s;if(h){if(p){const e=n.texData.get(d.dataId).values,t=new Array(o);for(let e=0;e 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n",cpuKernelImpl:SF}),mz={kernelName:$n,backendName:"webgl",kernelFunc:fz},gz={kernelName:An,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t;SM(s,"maxPool");const{filterSize:a,strides:i,pad:o,dimRoundingMode:l}=r;re(iu(i,1),(()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${i} and dilations '1'`));const u=Yl(s.shape,a,i,1,o,l);if(1===u.filterWidth&&1===u.filterHeight&&ue(u.inShape,u.outShape))return fD({inputs:{x:s},backend:n});const c=new I_(u,"max",!1);return n.runWebGLProgram(c,[s],s.dtype)}},yz={kernelName:Mn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{filterSize:a,strides:i,pad:o,dataFormat:l,dimRoundingMode:u}=r,c=Zl(s.shape,a,i,[1,1,1],o,u,l),h=new N_(c,"max",!1);return n.runWebGLProgram(h,[s],s.dtype)}};class bz{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;const t=e.strideHeight,n=e.strideWidth,r=e.dilationHeight,s=e.effectiveFilterHeight,a=e.effectiveFilterWidth,i=s-1-e.padInfo.top,o=a-1-e.padInfo.left,l=s*a-1;this.userCode=`\n const ivec2 pads = ivec2(${i}, ${o});\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n\n ivec2 dyRCCorner = coords.yz - pads;\n int dyRCorner = dyRCCorner.x;\n int dyCCorner = dyRCCorner.y;\n\n // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < ${s};\n wR += ${r}) {\n float dyR = float(dyRCorner + wR) / ${t}.0;\n\n if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < ${a}; wC++) {\n float dyC = float(dyCCorner + wC) / ${n}.0;\n\n if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(b, idyR, idyC, d);\n int maxPosValue = ${l} - int(getMaxPos(b, idyR, idyC, d));\n\n // Get the current value, check it against the value from the\n // position matrix.\n int curPosValue = wR * ${a} + wC;\n float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n dotProd += dyValue * mask;\n }\n }\n setOutput(dotProd);\n }\n `}}class xz{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;const t=e.strideDepth,n=e.strideHeight,r=e.strideWidth,s=e.dilationDepth,a=e.dilationHeight,i=e.dilationWidth,o=e.effectiveFilterDepth,l=e.effectiveFilterHeight,u=e.effectiveFilterWidth,c=o-1-e.padInfo.front,h=l-1-e.padInfo.top,p=u-1-e.padInfo.left,d=o*l*u-1;this.userCode=`\n const ivec3 pads = ivec3(${c}, ${h}, ${p});\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n int dyDCorner = dyCorner.x;\n int dyRCorner = dyCorner.y;\n int dyCCorner = dyCorner.z;\n\n // Convolve dy(?, ?, ?, ch) with pos mask(:, :, :, d) to get\n // dx(xD, xR, xC, ch).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n\n for (int wD = 0; wD < ${o};\n wD += ${s}) {\n float dyD = float(dyDCorner + wD) / ${t}.0;\n\n if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) {\n continue;\n }\n int idyD = int(dyD);\n\n for (int wR = 0; wR < ${l};\n wR += ${a}) {\n float dyR = float(dyRCorner + wR) / ${n}.0;\n\n if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||\n fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < ${u};\n wC += ${i}) {\n float dyC = float(dyCCorner + wC) / ${r}.0;\n\n if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(batch, idyD, idyR, idyC, ch);\n int maxPosValue = ${d} -\n int(getMaxPos(batch, idyD, idyR, idyC, ch));\n\n // Get the current value, check it against the value from the\n // position matrix.\n int curPosValue =\n wD * ${l} * ${u} +\n wR * ${u} + wC;\n float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n dotProd += dyValue * mask;\n }\n }\n }\n setOutput(dotProd);\n }\n `}}const wz={kernelName:Fn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a}=t,i=a,{filterSize:o,strides:l,pad:u,dimRoundingMode:c}=r,h=Zl(i.shape,o,l,[1,1,1],u,c),p=new N_(h,"max",!0),d=n.runWebGLProgram(p,[i],i.dtype),f=new xz(h),m=n.runWebGLProgram(f,[s,d],i.dtype);return n.disposeIntermediateTensorInfo(d),m}},vz={kernelName:Rn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a,output:i}=t,o=a;SM([a,i],"maxPoolGrad");const{filterSize:l,strides:u,pad:c,dimRoundingMode:h}=r,p=Yl(o.shape,l,u,1,c,h),d=new I_(p,"max",!0),f=n.runWebGLProgram(d,[o],o.dtype),m=new bz(p),g=n.runWebGLProgram(m,[s,f],o.dtype);return n.disposeIntermediateTensorInfo(f),g}},kz={kernelName:Dn,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:r}=e,{filterSize:s,strides:a,pad:i,includeBatchInIndex:o}=t,l=n;re(4===r.shape.length,(()=>`Error in maxPool: input must be rank 4 but got rank ${r.shape.length}.`));const u=[1,1];re(iu(a,u),(()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${u}'`));const c=Yl(r.shape,s,a,u,i),[h,p]=function(e,t,n,r){let s=new I_(n,"max",!1);const a=r.runWebGLProgram(s,[e],"float32");return s=new I_(n,"max",!0,!0,t),[a,r.runWebGLProgram(s,[e],"float32")]}(r,o,c,l);return[h,p]}},Iz={kernelName:_n,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:r}=e,{keepDims:s,axis:a}=t,i=n,o=r.shape.length,l=ye(a,r.shape);let u=l;const c=Ac(u,o),h=null!=c,p=i.shouldExecuteOnCPU([r]),d=[];let f=r;if(h){if(p){const e=i.texData.get(f.dataId).values,t=new Array(o);for(let e=0;e 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n",cpuKernelImpl:TF}),Tz={kernelName:Ln,backendName:"webgl",kernelFunc:Sz};class Cz{constructor(e,t,n){this.variableNames=["x"],this.outputShape=t.map(((t,n)=>t[0]+e[n]+t[1]));const r=e.length,s=UM(r),a=t.map((e=>e[0])).join(","),i=t.map(((t,n)=>t[0]+e[n])).join(","),o=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,r),l="reflect"===n?0:1;this.userCode=1!==r?`\n ${s} start = ${s}(${a});\n ${s} end = ${s}(${i});\n\n void main() {\n ${s} outC = getOutputCoords();\n for (int i = 0; i < ${r}; i++) {\n if (outC[i] < start[i]) {\n outC[i] = start[i] * 2 - outC[i] - ${l};\n } else if(outC[i] >= end[i]) {\n outC[i] = (end[i] - 1) * 2 - outC[i] + ${l};\n }\n }\n ${s} coords = outC - start;\n setOutput(getX(${o}));\n }\n `:`\n int start = ${a};\n int end = ${i};\n\n void main() {\n int outC = getOutputCoords();\n if (outC < start) {\n outC = start * 2 - outC - ${l};\n } else if(outC >= end) {\n outC = (end - 1) * 2 - outC + ${l};\n }\n setOutput(getX(outC - start));\n }\n `}}class Ez{constructor(e,t,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.map(((t,n)=>t[0]+e[n]+t[1]));const r=e.length,s=UM(r),a=t.map((e=>e[0])).join(","),i=t.map(((t,n)=>t[0]+e[n])).join(","),o=YF("rc",r),l=YF("source",r),u=`${o[r-1]} < ${this.outputShape[r-1]}`,c=1===r?"source":`vec2(${l.slice(-2).join()})`,h="reflect"===n?0:1;let p="";if(1===r){const e=`\n ${s} source = rc;\n if (source < start) {\n source = start * 2 - source - ${h};\n } else if (source >= end) {\n source = (end - 1) * 2 - source + ${h};\n }\n source -= start;\n `;p=`\n ${s} rc = outputLoc;\n ${e}\n result[0] = getChannel(getX(${l.join()}), ${c});\n ${o[r-1]} += 1;\n if(${u}) {\n ${e}\n result[1] = getChannel(getX(${l.join()}), ${c});\n }\n `}else{const e=`\n ${s} source = rc;\n ${s} lt = ${s}(lessThan(source, start));\n ${s} gte = ${s}(greaterThanEqual(source, end));\n ${s} orig = 1 - (lt + gte);\n source = orig * source +\n lt * (start * 2 - source - ${h}) +\n gte * ((end - 1) * 2 - source + ${h});\n source -= start;\n `;p=`\n ${s} rc = outputLoc;\n ${e}\n result[0] = getChannel(getX(${l.join()}), ${c});\n ${o[r-1]} += 1;\n if(${u}) {\n ${e}\n result[1] = getChannel(getX(${l.join()}), ${c});\n }\n rc = outputLoc;\n ${o[r-2]} += 1;\n if(${o[r-2]} < ${this.outputShape[r-2]}) {\n ${e}\n result[2] = getChannel(getX(${l.join()}), ${c});\n ${o[r-1]} += 1;\n if(${u}) {\n ${e}\n result[3] = getChannel(getX(${l.join()}), ${c});\n }\n }\n `}this.userCode=`\n const ${s} start = ${s}(${a});\n const ${s} end = ${s}(${i});\n\n void main() {\n ${s} outputLoc = getOutputCoords();\n vec4 result = vec4(0.);\n ${p}\n setOutput(result);\n }\n `}}const $z={kernelName:zn,backendName:"webgl",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:r}=e,{paddings:s,mode:a}=n,i=He().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Ez(r.shape,s,a):new Cz(r.shape,s,a);return t.runWebGLProgram(i,[r],r.dtype)}},Az=SD({opSnippet:"if (b == 0.0) return NAN;\n return mod(a, b);",packedOpSnippet:"\n vec4 result = mod(a, b);\n vec4 isNaN = vec4(equal(b, vec4(0.0)));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n"}),Rz={kernelName:Pn,backendName:"webgl",kernelFunc:Az};class Mz{constructor(e,t,n){this.variableNames=["probs"],this.customUniforms=[{name:"seed",type:"float"}],this.outputShape=[e,n],this.userCode=`\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n\n float r = random(seed);\n float cdf = 0.0;\n\n for (int i = 0; i < ${t-1}; i++) {\n cdf += getProbs(batch, i);\n\n if (r < cdf) {\n setOutput(float(i));\n return;\n }\n }\n\n // If no other event happened, last event happened.\n setOutput(float(${t-1}));\n }\n `}}const Fz=SD({opSnippet:"\nif (a == b) {\n return 1.0;\n};\nreturn a / b;",packedOpSnippet:"\n // vec4 one = vec4(equal(a, b));\n // return one + (vec4(1.0) - one) * a / b;\n vec4 result = a / b;\n if(a.x == b.x) {\n result.x = 1.;\n }\n if(a.y == b.y) {\n result.y = 1.;\n }\n if(a.z == b.z) {\n result.z = 1.;\n }\n if(a.w == b.w) {\n result.w = 1.;\n }\n\n return result;\n",checkOutOfBounds:!0}),Dz={kernelName:Gt,backendName:"webgl",kernelFunc:Fz},_z="return a - b;",Oz=SD({opSnippet:_z,packedOpSnippet:_z,supportsComplex:!0,cpuKernelImpl:GF}),Lz={kernelName:Pr,backendName:"webgl",kernelFunc:Oz};function zz(e){const{inputs:t,backend:n,attrs:r}=e,{logits:s}=t,{dim:a}=r,i=ye([a],s.shape),o=pz({inputs:{x:s},backend:n,attrs:{reductionIndices:i,keepDims:!1}}),l=Ec(o.shape,i),u=MD({inputs:{x:o},backend:n,attrs:{shape:l}}),c=Oz({inputs:{a:s,b:u},backend:n}),h=sL({inputs:{x:c},backend:n}),p=BD({inputs:{x:h},backend:n,attrs:{axis:i,keepDims:!1}}),d=MD({inputs:{x:p},backend:n,attrs:{shape:l}}),f=Fz({inputs:{a:h,b:d},backend:n});return n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(u),n.disposeIntermediateTensorInfo(c),n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(d),f}const Pz={kernelName:Cr,backendName:"webgl",kernelFunc:zz},Bz={kernelName:Bn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{logits:s}=t,{numSamples:a,seed:i,normalized:o}=r,l=o?s:zz({inputs:{logits:s},backend:n,attrs:{dim:s.shape.length-1}}),u=l.shape[0],c=l.shape[1],h=new Mz(u,c,a),p=[[i]],d=n.runWebGLProgram(h,[l],"int32",p);return o||n.disposeIntermediateTensorInfo(l),d}},Vz={kernelName:Un,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:r}=t;if(n.shouldExecuteOnCPU([r])){const e=n.texData.get(r.dataId),[t,s]=EF(e.values,r.shape,r.dtype);return n.makeTensorInfo(s,r.dtype,t)}let s;return s=He().getBool("WEBGL_PACK_UNARY_OPERATIONS")?new iD(r.shape,"\n vec4 result = -x;\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n"):new rD(r.shape,"if (isnan(x)) return x;\n return -x;\n"),n.runWebGLProgram(s,[r],r.dtype)}},Uz=Gp,Wz={kernelName:Gn,backendName:"webgl",kernelFunc:function(e){ns("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{inputs:t,backend:n,attrs:r}=e,{boxes:s,scores:a}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l}=r,u=n.readSync(s.dataId),c=n.readSync(a.dataId),{selectedIndices:h}=Uz(u,c,i,o,l);return n.makeTensorInfo([h.length],"int32",new Int32Array(h))}},Gz=Hp,Hz={kernelName:Hn,backendName:"webgl",kernelFunc:function(e){ns("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{inputs:t,backend:n,attrs:r}=e,{boxes:s,scores:a}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,padToMaxOutputSize:u}=r,c=n.readSync(s.dataId),h=n.readSync(a.dataId),{selectedIndices:p,validOutputs:d}=Gz(c,h,i,o,l,u);return[n.makeTensorInfo([p.length],"int32",new Int32Array(p)),n.makeTensorInfo([],"int32",new Int32Array([d]))]}},jz=jp,qz={kernelName:jn,backendName:"webgl",kernelFunc:function(e){ns("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{inputs:t,backend:n,attrs:r}=e,{boxes:s,scores:a}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,softNmsSigma:u}=r,c=n.readSync(s.dataId),h=n.readSync(a.dataId),p=i,d=o,f=l,m=u,{selectedIndices:g,selectedScores:y}=jz(c,h,p,d,f,m);return[n.makeTensorInfo([g.length],"int32",new Int32Array(g)),n.makeTensorInfo([y.length],"float32",new Float32Array(y))]}};class Kz{constructor(e,t,n,r){this.variableNames=["indices"],this.outputShape=[e,t],this.userCode=`\n void main() {\n ivec2 coords = getOutputCoords();\n int index = round(getIndices(coords.x));\n setOutput(mix(float(${r}), float(${n}),\n float(index == coords.y)));\n }\n `}}const Xz={kernelName:Kn,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:r}=e,{indices:s}=t,{depth:a,onValue:i,offValue:o}=r,l=oe(s.shape),u=new Kz(l,a,i,o),c=MD({inputs:{x:s},backend:n,attrs:{shape:[l]}}),h=n.runWebGLProgram(u,[c],s.dtype);n.disposeIntermediateTensorInfo(c);const p=MD({inputs:{x:h},backend:n,attrs:{shape:[...s.shape,a]}});return n.disposeIntermediateTensorInfo(h),p}};function Yz(e){const{inputs:t,backend:n}=e,{x:r}=t;if("complex64"===r.dtype){const e=H_({inputs:{input:r},backend:n}),t=Yz({inputs:{x:e},backend:n}),s=iO({inputs:{input:r},backend:n}),a=Yz({inputs:{x:s},backend:n}),i=gD({inputs:{real:t,imag:a},backend:n});return n.disposeIntermediateTensorInfo(e),n.disposeIntermediateTensorInfo(t),n.disposeIntermediateTensorInfo(s),n.disposeIntermediateTensorInfo(a),i}return mL({attrs:{shape:r.shape,dtype:r.dtype,value:"string"===r.dtype?"":0},backend:n})}const Zz={kernelName:Xr,backendName:"webgl",kernelFunc:Yz},Jz={kernelName:qn,backendName:"webgl",kernelFunc:function e(t){const{inputs:n,backend:r}=t,{x:s}=n;if("string"===s.dtype)throw new Error("onesLike is not supported under string dtype");if("complex64"===s.dtype){const t=H_({inputs:{input:s},backend:r}),n=e({inputs:{x:t},backend:r}),a=iO({inputs:{input:s},backend:r}),i=Yz({inputs:{x:a},backend:r}),o=gD({inputs:{real:n,imag:i},backend:r});return r.disposeIntermediateTensorInfo(t),r.disposeIntermediateTensorInfo(n),r.disposeIntermediateTensorInfo(a),r.disposeIntermediateTensorInfo(i),o}return mL({attrs:{shape:s.shape,dtype:s.dtype,value:1},backend:r})}},Qz={kernelName:Xn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{axis:s}=r;if(1===t.length)return iL({inputs:{input:t[0]},backend:n,attrs:{dim:s}});const a=t[0].shape,i=t[0].dtype;t.forEach((e=>{se(a,e.shape,"All tensors passed to stack must have matching shapes"),re(i===e.dtype,(()=>"All tensors passed to stack must have matching dtypes"))}));const o=[],l=uO({inputs:t.map((e=>{const t=iL({inputs:{input:e},backend:n,attrs:{dim:s}});return o.push(t),t})),backend:n,attrs:{axis:s}});return o.forEach((e=>n.disposeIntermediateTensorInfo(e))),l}};class eP{constructor(e,t,n){this.variableNames=["x"],this.customUniforms=[{name:"value",type:"float"}],this.outputShape=t.map(((t,n)=>t[0]+e[n]+t[1]));const r=e.length,s=UM(r),a=t.map((e=>e[0])).join(","),i=t.map(((t,n)=>t[0]+e[n])).join(","),o=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,r);this.userCode=1!==r?`\n ${s} start = ${s}(${a});\n ${s} end = ${s}(${i});\n\n void main() {\n ${s} outC = getOutputCoords();\n if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {\n setOutput(value);\n } else {\n ${s} coords = outC - start;\n setOutput(getX(${o}));\n }\n }\n `:`\n int start = ${a};\n int end = ${i};\n\n void main() {\n int outC = getOutputCoords();\n if (outC < start || outC >= end) {\n setOutput(value);\n } else {\n setOutput(getX(outC - start));\n }\n }\n `}}class tP{constructor(e,t,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"value",type:"float"}],this.outputShape=t.map(((t,n)=>t[0]+e[n]+t[1]));const r=e.length,s=UM(r),a=t.map((e=>e[0])).join(","),i=t.map(((t,n)=>t[0]+e[n])).join(","),o=YF("rc",r),l=YF("source",r),u=`${o[r-1]} < ${this.outputShape[r-1]}`,c=1===r?"source":`vec2(${l.slice(-2).join()})`,h=[`${s} rc = outputLoc;`,`${o[r-1]} += 1;\n if(${u}) {\n `,1===r?"":`}\n rc = outputLoc;\n ${o[r-2]} += 1;\n if(${o[r-2]} < ${this.outputShape[r-2]}) {`,1===r?"":` ${o[r-1]} += 1;\n if(${u}) {`],p=1===r?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))";let d="";for(let e=0,t=1===r?2:4;e{const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{paddings:a,constantValue:i}=r;if(0===oe(s.shape))return mL({backend:n,attrs:{shape:a.map(((e,t)=>e[0]+s.shape[t]+e[1])),value:i,dtype:s.dtype}});const o=He().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new tP(s.shape,a,i):new eP(s.shape,a,i),l=[[i]];return n.runWebGLProgram(o,[s],s.dtype,l)},rP={kernelName:Yn,backendName:"webgl",kernelFunc:nP},sP=SD({opSnippet:"\n if(a < 0.0 && floor(b) < b){\n return NAN;\n }\n if (b == 0.0) {\n return 1.0;\n }\n return (round(mod(b, 2.0)) != 1) ?\n pow(abs(a), b) : sign(a) * pow(abs(a), b);\n",packedOpSnippet:"\n // isModRound1 has 1 for components with round(mod(b, 2.0)) == 1, 0 otherwise.\n vec4 isModRound1 = vec4(equal(round(mod(b, 2.0)), ivec4(1)));\n vec4 multiplier = sign(a) * isModRound1 + (vec4(1.0) - isModRound1);\n vec4 result = multiplier * pow(abs(a), b);\n\n // Ensure that a^0 = 1, including 0^0 = 1 as this correspond to TF and JS\n bvec4 isExpZero = equal(b, vec4(0.0));\n result.r = isExpZero.r ? 1.0 : result.r;\n result.g = isExpZero.g ? 1.0 : result.g;\n result.b = isExpZero.b ? 1.0 : result.b;\n result.a = isExpZero.a ? 1.0 : result.a;\n\n vec4 isNaN = vec4(lessThan(a, vec4(0.0))) * vec4(lessThan(floor(b), b));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n"}),aP={kernelName:Jn,backendName:"webgl",kernelFunc:sP},iP={kernelName:er,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:i}=r,o=s.shape.length,l=[],u=ye(a,s.shape);let c=u;const h=Ac(c,o);let p,d=s;if(null!=h&&(d=UD({inputs:{x:s},backend:n,attrs:{perm:h}}),c=Mc(c.length,o),l.push(d)),$c("prod",c,o),n.shouldExecuteOnCPU([d])){const e=n.texData.get(d.dataId).values,{outVals:t,outShape:r,outDtype:s}=AF(d.shape,d.dtype,e,c);p=n.makeTensorInfo(r,s,t)}else{const[e,t]=Cc(d.shape,c),r=oe(t),a=MD({inputs:{x:d},backend:n,attrs:{shape:[-1,r]}}),i=OD(a,ra(s.dtype),"prod",n);p=MD({inputs:{x:i},backend:n,attrs:{shape:e}}),l.push(a),l.push(i)}if(i){l.push(p);const e=Ec(p.shape,u);p=MD({inputs:{x:p},backend:n,attrs:{shape:e}})}return l.forEach((e=>n.disposeIntermediateTensorInfo(e))),p}},oP=e=>{const{backend:t,attrs:n}=e,{start:r,stop:s,step:a,dtype:i}=n,o=RF(r,s,a,i);return t.makeTensorInfo([o.length],i,o)},lP={kernelName:tr,backendName:"webgl",kernelFunc:oP},uP=ND({opSnippet:"return 1.0 / x;"}),cP={kernelName:rr,backendName:"webgl",kernelFunc:uP},hP=ND({opSnippet:"if (isnan(x)) return x;\n return (x < 0.0) ? 0.0 : x;\n",packedOpSnippet:"\n vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n"}),pP={kernelName:sr,backendName:"webgl",kernelFunc:hP},dP=ND({opSnippet:"if (isnan(x)) return x;\n return (x < 0.0) ? 0.0 : min(6.0, x);\n",packedOpSnippet:"\n vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n"}),fP={kernelName:cr,backendName:"webgl",kernelFunc:dP};class mP{constructor(e,t,n,r,s){this.variableNames=["A"],this.outputShape=[];const[a,i,o,l]=e;this.outputShape=[a,t,n,l];const u=[r&&t>1?i-1:i,r&&n>1?o-1:o],c=[r&&t>1?t-1:t,r&&n>1?n-1:n];let h;h=s?"(vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC - vec2(0.5)":"vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n ${u[0]/c[0]},\n ${u[1]/c[1]});\n const vec2 inputShapeRC = vec2(${i}.0, ${o}.0);\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n ivec2 yRC = coords.yz;\n\n // Fractional source index.\n vec2 sourceFracIndexRC = ${h};\n\n // Compute the four integer indices.\n ivec2 sourceFloorRC = ivec2(max(sourceFracIndexRC, vec2(0.0)));\n ivec2 sourceCeilRC = ivec2(\n min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));\n\n float topLeft = getA(b, sourceFloorRC.x, sourceFloorRC.y, d);\n float bottomLeft = getA(b, sourceCeilRC.x, sourceFloorRC.y, d);\n float topRight = getA(b, sourceFloorRC.x, sourceCeilRC.y, d);\n float bottomRight = getA(b, sourceCeilRC.x, sourceCeilRC.y, d);\n\n vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC);\n\n float top = topLeft + (topRight - topLeft) * fracRC.y;\n float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;\n float newValue = top + (bottom - top) * fracRC.x;\n\n setOutput(newValue);\n }\n `}}class gP{constructor(e,t,n,r,s){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];const[a,i,o,l]=e;this.outputShape=[a,t,n,l];const u=[r&&t>1?i-1:i,r&&n>1?o-1:o],c=[r&&t>1?t-1:t,r&&n>1?n-1:n];let h;h=s?"(vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC - vec3(0.5)":"vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`\n const vec3 effectiveInputOverOutputRatioRC = vec3(\n ${u[0]/c[0]},\n ${u[1]/c[1]},\n ${u[1]/c[1]});\n const vec3 inputShapeRC = vec3(${i}.0, ${o}.0,\n ${o}.0);\n\n float getAValue(int b, int r, int c, int d) {\n return getChannel(getA(b, r, c, d), vec2(c, d));\n }\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n // Calculate values for next column in yRC.z.\n ivec3 yRC = coords.yzz + ivec3(0, 0, 1);\n\n // Fractional source index.\n vec3 sourceFracIndexRC = ${h};\n\n // Compute the four integer indices.\n ivec3 sourceFloorRC = ivec3(max(sourceFracIndexRC, vec3(0.0)));\n ivec3 sourceCeilRC = ivec3(\n min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));\n\n // Should we calculate next column and row elements in 2x2 packed cell.\n bool hasNextCol = d < ${l-1};\n bool hasNextRow = coords.z < ${n-1};\n\n // In parallel, construct four corners for all four components in\n // packed 2x2 cell.\n vec4 topLeft = vec4(\n getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d),\n hasNextCol ? getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d + 1) : 0.0);\n\n vec4 bottomLeft = vec4(\n getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d),\n hasNextCol ? getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d + 1) : 0.0);\n\n vec4 topRight = vec4(\n getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d),\n hasNextCol ? getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d + 1) : 0.0);\n\n vec4 bottomRight = vec4(\n getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d),\n hasNextCol ? getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d + 1) : 0.0);\n\n vec3 fracRC = sourceFracIndexRC - vec3(sourceFloorRC);\n\n vec4 top = mix(topLeft, topRight, fracRC.yyzz);\n vec4 bottom = mix(bottomLeft, bottomRight, fracRC.yyzz);\n vec4 newValue = mix(top, bottom, fracRC.x);\n\n setOutput(newValue);\n }\n `}}const yP={kernelName:lr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{images:s}=t,{alignCorners:a,halfPixelCenters:i,size:o}=r,[l,u]=o,c=He().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new gP(s.shape,l,u,a,i):new mP(s.shape,l,u,a,i);return n.runWebGLProgram(c,[s],"float32")}};class bP{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;const[,r,s]=t,[,a,i]=e,o=[n&&a>1?r-1:r,n&&i>1?s-1:s],l=[n&&a>1?a-1:a,n&&i>1?i-1:i],u=o[0]/l[0],c=o[1]/l[1],h=1/u,p=1/c,d=2*Math.ceil(h)+2,f=2*Math.ceil(p)+2;this.userCode=`\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n int r = coords[1];\n int c = coords[2];\n\n float accumulator = 0.0;\n\n const float heightScale = float(${u});\n const float widthScale = float(${c});\n\n const float invHeightScale = float(${h});\n const float invWidthScale = float(${p});\n\n const int winHeight = int(${d});\n const int winWidth = int(${f});\n\n // Compute bounds for where in dy we will look\n float startRLerp = floor(float(r) * invHeightScale);\n int startDyR = int(startRLerp - float(winHeight / 2));\n\n float startCLerp = floor(float(c) * invWidthScale);\n int startDyC = int(startCLerp - float(winWidth / 2));\n\n // Loop over dy\n for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {\n int dyR = dyROffset + startDyR;\n\n // Guard against the window exceeding the bounds of dy\n if (dyR < 0 || dyR >= ${a}) {\n continue;\n }\n\n for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {\n int dyC = dyCOffset + startDyC;\n\n // Guard against the window exceeding the bounds of dy\n if (dyC < 0 || dyC >= ${i}) {\n continue;\n }\n\n float dxR = float(dyR) * heightScale;\n int topDxRIndex = int(floor(dxR));\n int bottomDxRIndex = int(min(ceil(dxR), ${r-1}.0));\n float dxRLerp = dxR - float(topDxRIndex);\n float inverseDxRLerp = 1.0 - dxRLerp;\n\n float dxC = float(dyC) * widthScale;\n int leftDxCIndex = int(floor(dxC));\n int rightDxCIndex = int(min(ceil(dxC), ${s-1}.0));\n float dxCLerp = dxC - float(leftDxCIndex);\n float inverseDxCLerp = 1.0 - dxCLerp;\n\n if (r == topDxRIndex && c == leftDxCIndex) {\n // topLeft\n accumulator +=\n getDy(b, dyR, dyC, d) * inverseDxRLerp * inverseDxCLerp;\n }\n\n if (r == topDxRIndex && c == rightDxCIndex) {\n // topRight\n accumulator += getDy(b, dyR, dyC, d) * inverseDxRLerp * dxCLerp;\n }\n\n if (r == bottomDxRIndex && c == leftDxCIndex) {\n // bottomLeft\n accumulator += getDy(b, dyR, dyC, d) * dxRLerp * inverseDxCLerp;\n }\n\n if (r == bottomDxRIndex && c == rightDxCIndex) {\n // bottomRight\n accumulator += getDy(b, dyR, dyC, d) * dxRLerp * dxCLerp;\n }\n }\n }\n // End loop over dy\n\n setOutput(accumulator);\n }\n `}}const xP={kernelName:ur,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{images:s,dy:a}=t,{alignCorners:i}=r,o=new bP(a.shape,s.shape,i);return n.runWebGLProgram(o,[a],a.dtype)}};class wP{constructor(e,t,n,r,s){this.variableNames=["A"],this.outputShape=[];const[a,i,o,l]=e;this.outputShape=[a,t,n,l];const u=[r&&t>1?i-1:i,r&&n>1?o-1:o],c=[r&&t>1?t-1:t,r&&n>1?n-1:n],h=r?"0.5":"0.0";let p;p=s?"max((vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC, vec2(0.0))":"vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n ${u[0]/c[0]},\n ${u[1]/c[1]});\n const vec2 inputShapeRC = vec2(${i}.0, ${o}.0);\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n ivec2 yRC = coords.yz;\n\n // Fractional source index.\n vec2 sourceFracIndexRC = ${p};\n\n // Compute the coordinators of nearest neighbor point.\n ivec2 sourceNearestRC = ivec2(\n min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${h})));\n float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);\n\n setOutput(newValue);\n }\n `}}class vP{constructor(e,t,n,r,s){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];const[a,i,o,l]=e;this.outputShape=[a,t,n,l];const u=[r&&t>1?i-1:i,r&&n>1?o-1:o],c=[r&&t>1?t-1:t,r&&n>1?n-1:n],h=r?"0.5":"0.0";let p;p=s?"max((vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC, vec3(0.0))":"vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`\n const vec3 effectiveInputOverOutputRatioRC = vec3(\n ${u[0]/c[0]},\n ${u[1]/c[1]},\n ${u[1]/c[1]});\n const vec3 inputShapeRC = vec3(${i}.0, ${o}.0,\n ${o}.0);\n\n float getAValue(int b, int r, int c, int d) {\n return getChannel(getA(b, r, c, d), vec2(c, d));\n }\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n // Calculate values for next column in yRC.z.\n ivec3 yRC = coords.yzz + ivec3(0, 0, 1);\n\n // Fractional source index.\n vec3 sourceFracIndexRC = ${p};\n\n // Compute the coordinators of nearest neighbor point.\n ivec3 sourceNearestRC = ivec3(\n min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${h})));\n\n // Should we calculate next column and row elements in 2x2 packed cell.\n bool hasNextCol = d < ${l-1};\n bool hasNextRow = coords.z < ${n-1};\n\n vec4 newValue = vec4(\n getAValue(b, sourceNearestRC.x, sourceNearestRC.y, d),\n hasNextCol ? getAValue(b, sourceNearestRC.x, sourceNearestRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceNearestRC.x, sourceNearestRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceNearestRC.x, sourceNearestRC.z, d + 1) : 0.0);\n\n setOutput(newValue);\n }\n `}}const kP={kernelName:ir,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{images:s}=t,{alignCorners:a,halfPixelCenters:i,size:o}=r,[l,u]=o,c=He().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new vP(s.shape,l,u,a,i):new wP(s.shape,l,u,a,i);return n.runWebGLProgram(c,[s],s.dtype)}};class IP{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;const[,r,s]=t,[,a,i]=e,o=[n&&a>1?r-1:r,n&&i>1?s-1:s],l=[n&&a>1?a-1:a,n&&i>1?i-1:i],u=o[0]/l[0],c=o[1]/l[1],h=1/u,p=1/c,d=2*Math.ceil(h)+2,f=2*Math.ceil(p)+2;this.userCode=`\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n int r = coords[1];\n int c = coords[2];\n\n float accumulator = 0.0;\n\n const float heightScale = float(${u});\n const float widthScale = float(${c});\n\n const float invHeightScale = float(${h});\n const float invWidthScale = float(${p});\n\n const int winHeight = int(${d});\n const int winWidth = int(${f});\n\n // Compute bounds for where in dy we will look\n float startRLerp = floor(float(r) * invHeightScale);\n int startDyR = int(floor(startRLerp - float(winHeight / 2)));\n\n float startCLerp = floor(float(c) * invWidthScale);\n int startDyC = int(floor(startCLerp - float(winWidth / 2)));\n\n // Loop over dy\n for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {\n int dyR = dyROffset + startDyR;\n\n // Guard against the window exceeding the bounds of dy\n if (dyR < 0 || dyR >= ${a}) {\n continue;\n }\n\n for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {\n int dyC = dyCOffset + startDyC;\n\n // Guard against the window exceeding the bounds of dy\n if (dyC < 0 || dyC >= ${i}) {\n continue;\n }\n\n float sourceFracRow =\n float(${o[0]}) *\n (float(dyR) / float(${l[0]}));\n\n float sourceFracCol =\n float(${o[1]}) *\n (float(dyC) / float(${l[1]}));\n\n int sourceNearestRow = int(min(\n float(int(${r}) - 1),\n ${n} ? float(round(sourceFracRow)) :\n float(floor(sourceFracRow))));\n\n int sourceNearestCol = int(min(\n float(int(${s}) - 1),\n ${n} ? float(round(sourceFracCol)) :\n float(floor(sourceFracCol))));\n\n if (r == sourceNearestRow && c == sourceNearestCol) {\n accumulator += getDy(b, dyR, dyC, d);\n }\n }\n }\n // End loop over dy\n\n setOutput(accumulator);\n }\n `}}const NP={kernelName:or,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{images:s,dy:a}=t,{alignCorners:i}=r,o=new IP(a.shape,s.shape,i);return n.runWebGLProgram(o,[a],a.dtype)}};class SP{constructor(e,t){this.variableNames=["x"];const n=e.length;if(n>4)throw new Error(`WebGL backend: Reverse of rank-${n} tensor is not yet supported`);if(this.outputShape=e,1===n)return void(this.userCode=`\n void main() {\n int coord = getOutputCoords();\n setOutput(getX(${e[0]} - coord - 1));\n }\n `);const r=e.map(((n,r)=>(n=>-1!==t.indexOf(n)&&1!==e[n]?`${e[n]} - coords[${n}] - 1`:`coords[${n}]`)(r))).join(","),s=UM(n);this.userCode=`\n void main() {\n ${s} coords = getOutputCoords();\n setOutput(getX(${r}));\n }\n `}}class TP{constructor(e,t){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;const n=e.length;if(n>4)throw new Error(`WebGL backend: Reverse of rank-${n} tensor is not yet supported`);this.outputShape=e;const r=YF("rc",n),s=`${r[n-1]} + 1 < ${this.outputShape[n-1]}`,a=`${r[n-2]} + 1 < ${this.outputShape[n-2]}`,i=UM(n);function o(n){const r=e.map(((r,s)=>function(n,r){return-1!==t.indexOf(n)&&1!==e[n]?`${e[n]} - ${r[n]} - 1`:`${r[n]}`}(s,n)));return`getChannel(getX(${r.join(",")}), vec2(${r.slice(-2).join(",")}))`}this.userCode=1===n?`\n void main(){\n int rc = getOutputCoords();\n vec4 result = vec4(0.);\n result.r = getChannel(getX(${e[0]} - rc - 1),\n ${e[0]} - rc - 1);\n if(${s}){\n result.g = getChannel(getX(${e[0]} - (rc + 1) - 1),\n ${e[0]} - (rc + 1) - 1);\n }\n setOutput(result);\n }\n `:`\n void main() {\n ${i} rc = getOutputCoords();\n vec4 result = vec4(0.);\n result.r = ${function(e){return o(e)}(r.slice())};\n if(${s}){\n result.g = ${function(e){return e[n-1]="("+e[n-1]+" + 1)",o(e)}(r.slice())};\n }\n if(${a}) {\n result.b = ${function(e){return e[n-2]="("+e[n-2]+" + 1)",o(e)}(r.slice())};\n if(${s}) {\n result.a = ${function(e){return e[n-1]="("+e[n-1]+" + 1)",e[n-2]="("+e[n-2]+" + 1)",o(e)}(r.slice())};\n }\n }\n setOutput(result);\n }\n `}}const CP={kernelName:hr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{dims:a}=r,i=s.shape.length,o=ye(a,s.shape);if(0===i)return fD({inputs:{x:s},backend:n});const l=He().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new TP(s.shape,o):new SP(s.shape,o);return n.runWebGLProgram(l,[s],s.dtype)}};class EP{constructor(e,t){this.variableNames=["Image"],this.outputShape=[],this.customUniforms=[{name:"params",type:"vec4"}];const n=e[1],r=e[2];this.outputShape=e;let s="";s="number"==typeof t?`float outputValue = ${t.toFixed(2)};`:`\n vec3 fill = vec3(${t.join(",")});\n float outputValue = fill[coords[3]];`,this.userCode=`\n void main() {\n ivec4 coords = getOutputCoords();\n int x = coords[2];\n int y = coords[1];\n float coordXFloat = (float(x) - params[0]) * params[3] -\n (float(y) - params[1]) * params[2];\n float coordYFloat = (float(x) - params[0]) * params[2] +\n (float(y) - params[1]) * params[3];\n int coordX = int(round(coordXFloat + params[0]));\n int coordY = int(round(coordYFloat + params[1]));\n ${s}\n if(coordX >= 0 && coordX < ${r} && coordY >= 0 && coordY < ${n}) {\n outputValue = getImage(coords[0], coordY, coordX, coords[3]);\n }\n setOutput(outputValue);\n }\n `}}const $P={kernelName:Jr,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{image:r}=e,{radians:s,fillValue:a,center:i}=t,o=n,l=new EP(r.shape,a),[u,c]=zd(i,r.shape[1],r.shape[2]),h=[[u,c,Math.sin(s),Math.cos(s)]];return o.runWebGLProgram(l,[r],r.dtype,h)}},AP=ND({opSnippet:"\n // OpenGL ES does not support round function.\n // The algorithm is based on banker's rounding.\n float base = floor(x);\n if ((x - base) < 0.5) {\n return floor(x);\n } else if ((x - base) > 0.5) {\n return ceil(x);\n } else {\n if (mod(base, 2.0) == 0.0) {\n return base;\n } else {\n return base + 1.0;\n }\n }\n"}),RP={kernelName:pr,backendName:"webgl",kernelFunc:AP},MP=ND({opSnippet:"return inversesqrt(x);",cpuKernelImpl:MF}),FP={kernelName:dr,backendName:"webgl",kernelFunc:MP};class DP{constructor(e,t,n,r,s,a,i=!0){this.variableNames=["updates","indices","defaultValue"],this.outputShape=a;const o=UM(s.length),l=UM(a.length);let u="";1===n?u="i":2===n&&(u="i, j");const c=`getIndices(${u})`;let h="";1===r?h="i":2===r&&(h="i, coords[1]");const p=`getUpdates(${h})`,d=t>1?"strides[j]":"strides";this.userCode=`\n ${o} strides = ${o}(${s});\n\n void main() {\n ${l} coords = getOutputCoords();\n float sum = 0.0;\n bool found = false;\n for (int i = 0; i < ${e}; i++) {\n int flattenedIndex = 0;\n for (int j = 0; j < ${t}; j++) {\n int index = round(${c});\n flattenedIndex += index * ${d};\n }\n if (flattenedIndex == coords[0]) {\n sum += ${p};\n found = true;\n }\n }\n setOutput(mix(getDefaultValue(), sum, float(found)));\n }\n `}}const _P={kernelName:fr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{indices:s,updates:a}=t,{shape:i}=r,{sliceRank:o,numUpdates:l,sliceSize:u,strides:c,outputSize:h}=oo(0,s,i),p=[h/u,u];if(0===h)return n.makeTensorInfo(i,s.dtype);const d=MD({inputs:{x:s},backend:n,attrs:{shape:[l,o]}}),f=MD({inputs:{x:a},backend:n,attrs:{shape:[l,u]}}),m=n.makeTensorInfo([],"float32",new Float32Array([0])),g=new DP(l,o,d.shape.length,f.shape.length,c,p),y=n.runWebGLProgram(g,[f,d,m],f.dtype),b=MD({inputs:{x:y},backend:n,attrs:{shape:i}});return n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(y),n.disposeIntermediateTensorInfo(m),b}};class OP{constructor(e,t,n){let r,s;if(this.variableNames=["c","a","b"],this.outputShape=t,n>4)throw Error(`Where for rank ${n} is not yet supported`);if(1===n)s="resRC",r="resRC";else{const n=["resRC.x","resRC.y","resRC.z","resRC.w"],a=[],i=[];for(let r=0;r= 1.0) {\n setOutput(getA(${s}));\n } else {\n setOutput(getB(${s}));\n }\n }\n `}}const LP={kernelName:mr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{condition:r,t:s,e:a}=t,i=new OP(r.shape.length,s.shape,s.shape.length);return n.runWebGLProgram(i,[r,s,a],na(s.dtype,a.dtype))}},zP=ND({opSnippet:`\n // Stable and Attracting Fixed Point (0, 1) for Normalized Weights.\n // see: https://arxiv.org/abs/1706.02515\n float scaleAlpha = ${Gd};\n float scale = ${Hd};\n return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);\n`}),PP={kernelName:gr,backendName:"webgl",kernelFunc:zP},BP=ND({opSnippet:"if (isnan(x)) return x;\n return 1.0 / (1.0 + exp(-1.0 * x));\n",packedOpSnippet:"\n vec4 result = 1.0 / (1.0 + exp(-1.0 * x));\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n",cpuKernelImpl:FF}),VP={kernelName:vr,backendName:"webgl",kernelFunc:BP},UP=ND({opSnippet:"\n if (isnan(x)) { return 0.0; }\n return sign(x);\n"}),WP={kernelName:wr,backendName:"webgl",kernelFunc:UP},GP=ND({opSnippet:"if (isnan(x)) return x;\n return sin(x);\n"}),HP={kernelName:br,backendName:"webgl",kernelFunc:GP},jP=ND({opSnippet:"\n float e2x = exp(x);\n return (e2x - 1.0 / e2x) / 2.0;\n"}),qP={kernelName:xr,backendName:"webgl",kernelFunc:jP},KP=ND({opSnippet:"\n float epsilon = 1.1920928955078125e-7;\n float threshold = log(epsilon) + 2.0;\n\n bool too_large = x > -threshold;\n bool too_small = x < threshold;\n\n float result;\n float exp_x = exp(x);\n\n if (too_large){\n result = x;\n }\n else if (too_small){\n result = exp_x;\n }\n else{\n result = log(exp_x + 1.0);\n }\n return result;\n"}),XP={kernelName:kr,backendName:"webgl",kernelFunc:KP},YP={kernelName:Sr,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{blockShape:a,paddings:i}=r;re(s.shape.length<=4,(()=>"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet"));const o=a.reduce(((e,t)=>e*t)),l=[[0,0]];l.push(...i);for(let e=1+a.length;en.disposeIntermediateTensorInfo(e))),g}},ZP={kernelName:Er,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{indices:r,values:s,denseShape:a,defaultValue:i}=t;if(1!==a.shape.length)throw new Error(`Dense shape must be a vector, saw:\n ${a.shape}`);if(2!==r.shape.length)throw new Error(`Indices must be a matrix, saw:\n ${r.shape}`);if(1!==s.shape.length)throw new Error(`Values must be a vector, saw:\n ${s.shape}`);if(0!==i.shape.length)throw new Error(`Default value must be a scalar, saw:\n ${i.shape}`);const o=n.readSync(r.dataId),l=n.readSync(s.dataId),u=n.readSync(a.dataId),c=n.readSync(i.dataId)[0],[h,p,d,f,m]=OF(o,r.shape,r.dtype,l,s.dtype,u,c);return[n.makeTensorInfo(p,r.dtype,h),n.makeTensorInfo([p[0]],s.dtype,d),n.makeTensorInfo([f.length],"bool",new Uint8Array(f.map((e=>Number(e))))),n.makeTensorInfo([m.length],r.dtype,new Int32Array(m))]}},JP={kernelName:$r,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{inputIndices:r,inputShape:s,newShape:a}=t;if(2!==r.shape.length)throw new Error(`Input indices should be a matrix but received shape ${r.shape}`);if(1!==s.shape.length)throw new Error(`Input shape should be a vector but received shape ${s.shape}`);if(1!==a.shape.length)throw new Error(`Target shape should be a vector but received shape ${a.shape}`);const i=Array.from(n.readSync(s.dataId)),o=n.readSync(r.dataId),l=Array.from(n.readSync(a.dataId)),[u,c,h]=LF(o,r.shape,r.dtype,i,l);return[n.makeTensorInfo(c,r.dtype,u),n.makeTensorInfo([h.length],a.dtype,new Int32Array(h))]}},QP={kernelName:Ar,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{data:r,indices:s,segmentIds:a}=t;if(r.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(1!==s.shape.length)throw new Error(`Indices should be a vector but received shape\n ${s.shape}`);if(1!==a.shape.length)throw new Error(`Segment ids should be a vector but received shape\n ${a.shape}`);const i=n.readSync(r.dataId),o=n.readSync(s.dataId),l=n.readSync(a.dataId),[u,c]=zF(i,r.shape,r.dtype,o,l,!0);return n.makeTensorInfo(c,r.dtype,u)}},eB={kernelName:Rr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{data:r,indices:s,segmentIds:a}=t;if(r.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(1!==s.shape.length)throw new Error(`Indices should be a vector but received shape\n ${s.shape}`);if(1!==a.shape.length)throw new Error(`Segment ids should be a vector but received shape\n ${a.shape}`);const i=n.readSync(r.dataId),o=n.readSync(s.dataId),l=n.readSync(a.dataId),[u,c]=zF(i,r.shape,r.dtype,o,l);return n.makeTensorInfo(c,r.dtype,u)}},tB={kernelName:Mr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{sparseIndices:s,sparseValues:a,defaultValue:i}=t,{outputShape:o}=r,{sliceRank:l,numUpdates:u,strides:c,outputSize:h}=oo(0,s,o),p=new DP(u,l,s.shape.length,a.shape.length,c,[h,1],!1),d=n.runWebGLProgram(p,[a,s,i],a.dtype),f=MD({inputs:{x:d},backend:n,attrs:{shape:o}});return n.disposeIntermediateTensorInfo(d),f}},nB={kernelName:Tr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{numOrSizeSplits:a,axis:i}=r,o=ye(i,s.shape)[0],l=ff(s,a,o),u=s.shape.length,c=new Array(u).fill(0),h=s.shape.slice();return l.map((e=>{const t=[...h];t[o]=e;const r=z_({inputs:{x:s},backend:n,attrs:{begin:c,size:t}});return c[o]+=e,r}))}},rB="return sqrt(x);",sB=ND({opSnippet:rB,packedOpSnippet:rB,cpuKernelImpl:PF}),aB={kernelName:Ir,backendName:"webgl",kernelFunc:sB},iB=ND({opSnippet:"return x * x;"}),oB={kernelName:Dr,backendName:"webgl",kernelFunc:iB},lB="return (a - b) * (a - b);",uB=SD({opSnippet:lB,packedOpSnippet:lB}),cB={kernelName:Fr,backendName:"webgl",kernelFunc:uB},hB={kernelName:Yr,backendName:"webgl",kernelFunc:function({inputs:e,attrs:t,backend:n}){const{x:r}=e,s=`if (isnan(x)) return x;\n return x > 0.0 ? 1.0 : float(${t.alpha});\n `,a=new rD(r.shape,s);return n.runWebGLProgram(a,[r],r.dtype)}};class pB{constructor(e,t,n){this.variableNames=["x"],this.outputShape=n;const r=n.length,s=UM(n.length),a=UM(n.length);let i="";if(1===r)i="coords * strides + begin";else{let e=0;i=n.map(((t,r)=>(e++,1===n.length?`coords * strides[${r}] + begin[${r}]`:`coords[${e-1}] * strides[${r}] + begin[${r}]`))).join(",")}this.userCode=`\n ${s} begin = ${s}(${e});\n ${s} strides = ${s}(${t});\n\n void main() {\n ${a} coords = getOutputCoords();\n setOutput(getX(${i}));\n }\n `}}const dB={kernelName:_r,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{begin:a,end:i,strides:o,beginMask:l,endMask:u,ellipsisMask:c,newAxisMask:h,shrinkAxisMask:p}=r,{finalShapeSparse:d,finalShape:f,isIdentity:m,sliceDim0:g,isSimpleSlice:y,begin:b,end:x,strides:w}=No(s.shape,a,i,o,l,u,c,h,p);let v;if(m)v=MD({inputs:{x:s},backend:n,attrs:{shape:f}});else if(g||y){re(s.shape.length>=1,(()=>`Input must have rank at least 1, got: ${s.shape.length}`));const e=co(b,x,w),t=z_({inputs:{x:s},backend:n,attrs:{begin:b,size:e}});v=MD({inputs:{x:t},backend:n,attrs:{shape:f}}),n.disposeIntermediateTensorInfo(t)}else if(n.shouldExecuteOnCPU([s])){const e=n.readSync(s.dataId),t=Ni(s.shape,s.dtype,e),r=BF(d,t,w,b);v=n.makeTensorInfo(f,s.dtype,r.values)}else{const e=new pB(b,w,d);v=n.runWebGLProgram(e,[s],s.dtype)}const k=MD({inputs:{x:v},backend:n,attrs:{shape:f}});return n.disposeIntermediateTensorInfo(v),k}},fB={kernelName:Or,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{separator:s,nGramWidths:a,leftPad:i,rightPad:o,padWidth:l,preserveShortSequences:u}=r,{data:c,dataSplits:h}=t,p=n.readSync(c.dataId),d=n.readSync(h.dataId),[f,m]=VF(p,d,s,a,i,o,l,u);return[n.makeTensorInfo([f.length],"string",f),n.makeTensorInfo(h.shape,"int32",m)]}},mB={kernelName:Lr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{skipEmpty:s}=r,{input:a,delimiter:i}=t;if("string"!==a.dtype)throw new Error("Input must be of datatype string");if(1!==a.shape.length)throw new Error(`Input must be a vector, got shape: ${a.shape}`);if(0!==i.shape.length)throw new Error(`Delimiter must be a scalar, got shape: ${i.shape}`);const o=n.readSync(a.dataId),l=n.readSync(i.dataId)[0],[u,c,h]=UF(o,l,s),p=c.length;return[n.makeTensorInfo([p,2],"int32",u),n.makeTensorInfo([p],"string",c),n.makeTensorInfo([2],"int32",new Int32Array(h))]}},gB={kernelName:zr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{numBuckets:s}=r,{input:a}=t;if("string"!==a.dtype)throw new Error("Input must be of datatype string");if(s<=0)throw new Error("Number of buckets must be at least 1");const i=n.readSync(a.dataId),o=WF(i,s);return n.makeTensorInfo(a.shape,"int32",o)}},yB=ND({opSnippet:"return tan(x);"}),bB={kernelName:Br,backendName:"webgl",kernelFunc:yB},xB=ND({opSnippet:"\n float e2x = exp(-2.0 * abs(x));\n return sign(x) * (1.0 - e2x) / (1.0 + e2x);\n"}),wB={kernelName:Vr,backendName:"webgl",kernelFunc:xB};class vB{constructor(e,t){this.variableNames=["A"];const n=new Array(e.length);for(let r=0;r5)throw Error(`Tile for rank ${t} is not yet supported`);if(1===t)return`imod(resRC, ${e[0]})`;const n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],r=[];for(let t=0;t5){const e=n.readSync(s.dataId),t="string"===s.dtype?e.map((e=>Ds(e))):e,r=Ni(s.shape,s.dtype,t),i=HF(r,a);return n.makeTensorInfo(i.shape,i.dtype,i.values)}const i=new vB(s.shape,a);return n.runWebGLProgram(i,[s],s.dtype)}const IB={kernelName:Ur,backendName:"webgl",kernelFunc:kB};class NB{constructor(e){this.variableNames=["x","indices"],this.customUniforms=[{name:"n",type:"int"},{name:"firstPass",type:"int"},{name:"negativeInf",type:"float"},{name:"dir",type:"int"},{name:"inc",type:"int"}],this.outputShape=e,this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int elemIdx = coords[1];\n\n // We compare elements pair-wise within a group of size 2 * inc.\n // The comparing rule for each group alternates between ascending\n // and descending. Within each group, we compare each pair at\n // positions i and i+inc. To decide whether an element at position i\n // is x0 or x1, we mod it by 2 * inc, if the result is smaller than\n // inc, it is in the first half of the group, we denote it as x0,\n // otherwise we denote it as x1.\n // For example, as shown in the Bitonic top K paper referenced above,\n // Figure5(a) shows that element[1] is in the\n // second half of the group when group size is 2, but it is in the\n // first half of the group when group size is 4.\n\n bool isFirstInPair = imod(elemIdx, 2 * inc) < inc;\n int i = isFirstInPair ? elemIdx : elemIdx - inc;\n\n int i0 = firstPass == 1 ? i : int(getIndices(batch, i));\n int i1 = firstPass == 1 ? i + inc : int(getIndices(batch, i + inc));\n float x0 = i0 < n ? getX(batch, i0) : negativeInf;\n float x1 = i1 < n ? getX(batch, i1) : negativeInf;\n\n // Denotes which direction indices are in (ascending or descending).\n bool reverse = imod(elemIdx, 2 * dir) >= dir;\n bool isGreater = x0 > x1 || (x0 == x1 && i1 > i0);\n if (reverse == isGreater) { // Elements in opposite order of direction\n int iTemp = i0;\n i0 = i1;\n i1 = iTemp;\n }\n if (isFirstInPair) {\n setOutput(float(i0));\n } else {\n setOutput(float(i1));\n }\n }\n "}}class SB{constructor(e){this.variableNames=["x","indices"],this.customUniforms=[{name:"n",type:"int"},{name:"firstPass",type:"int"},{name:"k",type:"int"}],this.outputShape=e,this.userCode="\n void main() {\n // Takes max of indices (0, k), (1, k + 1), (2, k + 2) ...\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int elemIdx = coords[1];\n\n // The output size is half of the previous size.\n // If the previous sequence is | | | | _ _ _ _ | | | | _ _ _ _ (k=4),\n // we only need to output the indices at positions |, the indices at\n // positions _ can be thrown away, see Figure5(b) After Phase 2\n // (Merge phase) in the Bitonic Top K paper referenced above.\n // For example, the paper shows we only need to output the orange bars.\n // The output sequence should look like this | | | | | | | |.\n // Because the sequence is halved, to map the output index back\n // to the previous sequence to find the corresponding value,\n // we need to double the index. When we double the index,\n // we basically interpolate a position, so 2i looks like\n // | _ | _ | _ | _ | _ | _ | _. We move the | to the first k position\n // of each 2k positions by - elemIdx % k. E.g. for output at\n // index 4,5,6,7, we want to get the corresponding element at\n // original index 8,9,10,11, for output at index 8,9,10,11,\n // we want to get the corresponding element at original index\n // 16,17,18,19, so on and so forth.\n\n int i = elemIdx < k ? elemIdx : (elemIdx * 2 - imod(elemIdx, k));\n int i0 = firstPass == 1 ? i : int(getIndices(batch, i));\n int i1 = firstPass == 1 ? i + k : int(getIndices(batch, i + k));\n\n float x0 = getX(batch, i0);\n float x1 = i1 < n ? getX(batch, i1) : x0;\n\n setOutput(x0 >= x1 ? float(i0) : float(i1));\n }\n "}}function TB(e,t){null!==t&&e.disposeIntermediateTensorInfo(t)}function CB(e){let t=1;for(;tl){const e=n.readSync(s.dataId),[t,r]=jF(e,u,s.dtype,a,i);return[n.makeTensorInfo(t.shape,t.dtype,t.values),n.makeTensorInfo(r.shape,r.dtype,r.values)]}if(0===a)return u[u.length-1]=0,[n.makeTensorInfo(u,s.dtype,[]),n.makeTensorInfo(u,"int32",[])];if(1===c)return[s,mL({attrs:{shape:u,dtype:"int32",value:0},backend:n})];const h=n.texData.get(s.dataId),p=null!==h&&h.isPacked,d=p?n.unpackTensor(s):s,f=oe(u)/c,m=MD({inputs:{x:d},attrs:{shape:[f,c]},backend:n});p&&TB(n,d);const g=CB(a),y=CB(c);let b=null;const x=()=>null===b?[m,m]:[m,b],w=(e,t,r)=>{const s=x(),a=new NB(r),i=[[c],[null===b?1:0],[Number.NEGATIVE_INFINITY],[e],[t]],o=b;b=n.runWebGLProgram(a,s,"int32",i),TB(n,o)};for(let e=1;e=1;n/=2)w(t,n,[f,y])}for(let e=y;e>g;e/=2){const t=x(),r=new SB([f,e/2]),s=[[c],[null===b?1:0],[g]],a=b;b=n.runWebGLProgram(r,t,"int32",s),TB(n,a);const i=g/2,o=2*i;for(let e=i;e>=1;e/=2)w(o,e,b.shape)}let v=b;b=z_({inputs:{x:b},backend:n,attrs:{begin:0,size:[f,a]}}),TB(n,v);let k=FL({inputs:{x:m,indices:b},backend:n,attrs:{axis:1,batchDims:1}});TB(n,m);const I=u.slice(0,-1);I.push(a),v=b,b=MD({inputs:{x:b},attrs:{shape:I},backend:n}),TB(n,v);const N=k;return k=MD({inputs:{x:k},attrs:{shape:I},backend:n}),TB(n,N),[k,b]}};class $B{constructor(e,t,n,r,s,a){this.variableNames=["Image","Transforms"],this.outputShape=a;const i="nearest"===n?1:2;let o;switch(r){case"constant":o=1;break;case"reflect":o=2;break;case"wrap":o=3;break;case"nearest":o=4;break;default:o=1}this.userCode=`\n float mapCoord(float outCoord, float len) {\n float inCoord = outCoord;\n if(${o} == 2) {\n if (inCoord < 0.0) {\n if (len <= 1.0) {\n inCoord = 0.0;\n } else {\n float sz2 = 2.0 * len;\n if (inCoord < sz2) {\n inCoord = sz2 * float(int(float(-inCoord / sz2))) +\n inCoord;\n }\n inCoord = inCoord < -len ? inCoord + sz2 : -inCoord - 1.0;\n }\n } else if (inCoord > len - 1.0) {\n if (len <= 1.0) {\n inCoord = 0.0;\n } else {\n float sz2 = 2.0 * len;\n inCoord -= sz2 * float(int(float(inCoord / sz2)));\n if (inCoord >= len) {\n inCoord = sz2 - inCoord - 1.0;\n }\n }\n }\n return clamp(inCoord, 0.0, len - 1.0);\n } else if (${o} == 3) {\n if (inCoord < 0.0) {\n if (len <= 1.0) {\n inCoord = 0.0;\n } else {\n float sz = len - 1.0;\n inCoord += len * (float(int(float(-inCoord / sz))) + 1.0);\n }\n } else if (inCoord > len - 1.0) {\n if (len <= 1.0) {\n inCoord = 0.0;\n } else {\n float sz = len - 1.0;\n inCoord -= len * float(int(float(inCoord / sz)));\n }\n }\n return clamp(inCoord, 0.0, len - 1.0);\n } else if (${o} == 4) {\n return clamp(outCoord, 0.0, len - 1.0);\n } else {\n return outCoord;\n }\n }\n\n float readWithFillValue(int batch, int coordY, int coordX,\n int channel) {\n float outputValue;\n if (0 <= coordY && coordY < ${e} && 0 <= coordX && coordX < ${t}) {\n outputValue = getImage(batch, coordY, coordX, channel);\n } else {\n outputValue = float(${s});\n }\n return outputValue;\n }\n\n void main() {\n ivec4 coords = getOutputCoords();\n float outputValue;\n int batch = coords[0];\n int x = coords[2];\n int y = coords[1];\n int channel = coords[3];\n float xf = float(x);\n float yf = float(y);\n float a1 = getTransforms(batch, 0);\n float a2 = getTransforms(batch, 1);\n float a3 = getTransforms(batch, 2);\n float b1 = getTransforms(batch, 3);\n float b2 = getTransforms(batch, 4);\n float b3 = getTransforms(batch, 5);\n float c1 = getTransforms(batch, 6);\n float c2 = getTransforms(batch, 7);\n float projection = c1 * xf + c2 * yf + 1.0;\n if (projection == 0.0) {\n outputValue = float(${s});\n } else {\n float inX = (a1 * xf + a2 * yf + a3) / projection;\n float inY = (b1 * xf + b2 * yf + b3) / projection;\n float mapX = mapCoord(inX, float(${t}));\n float mapY = mapCoord(inY, float(${e}));\n\n if (${i} == 1) {\n int coordY = int(round(mapY));\n int coordX = int(round(mapX));\n outputValue = readWithFillValue(batch, coordY, coordX,\n channel);\n } else {\n float yFloor = floor(mapY);\n float xFloor = floor(mapX);\n float yCeil = yFloor + 1.0;\n float xCeil = xFloor + 1.0;\n float valueYFloor = (xCeil - mapX) *\n readWithFillValue(batch, int(yFloor), int(xFloor), channel) +\n (mapX - xFloor) *\n readWithFillValue(batch, int(yFloor), int(xCeil), channel);\n float valueYCeil = (xCeil - mapX) *\n readWithFillValue(batch, int(yCeil), int(xFloor), channel) +\n (mapX - xFloor) *\n readWithFillValue(batch, int(yCeil), int(xCeil), channel);\n outputValue = (yCeil - mapY) * valueYFloor +\n (mapY - yFloor) * valueYCeil;\n }\n }\n setOutput(outputValue);\n }\n `}}const AB={kernelName:Gr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{image:s,transforms:a}=t,{interpolation:i,fillMode:o,fillValue:l,outputShape:u}=r,[c,h,p,d]=s.shape,[f,m]=null!=u?u:[h,p],g=new $B(h,p,i,o,l,[c,f,m,d]);return n.runWebGLProgram(g,[s,a],"float32")}},RB={kernelName:jr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,attrs:n,backend:r}=e,{axis:s}=n,{x:a}=t;SM(a,"unique"),console.warn("WARNING: ","UI might be locked temporarily as data is being downloaded");const i=r.readSync(a.dataId),{outputValues:o,outputShape:l,indices:u}=KF(i,s,a.shape,a.dtype);return[r.makeTensorInfo(l,a.dtype,o),r.makeTensorInfo([u.length],"int32",u)]}},MB={kernelName:qr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{value:s}=t;let{axis:a}=r;a<0&&(a+=s.shape.length);const i=s,o=i.shape.length,l=s.shape[a],u=new Array(o-1);let c=0;for(let e=0;en.disposeIntermediateTensorInfo(e))),f}};class FB{constructor(e,t){this.variableNames=["x","segmentIds"];const n=e.windowSize,r=e.batchSize,s=e.inSize,a=e.numSegments,i=a*Math.ceil(s/n);this.outputShape=[r,i];const o=4*Math.floor(n/4),l=n%4,u="\n sumValue += dot(values, segFilter);\n ";let c="";s%n>0&&(c=`\n if (inIdx < 0 || inIdx >= ${s}) {\n return initializationValue;\n }\n `);let h="";s%n>0&&(h=`\n if (inIdx < 0 || inIdx >= ${s}) {\n return -1.0;\n }\n `),this.userCode=`\n const float initializationValue = 0.0;\n\n float getValue(int batch, int inIdx) {\n ${c}\n return getX(batch, inIdx);\n }\n\n float getSegmentIdAtIndex(int inIdx) {\n ${h}\n return getSegmentIds(inIdx);\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = int(floor(float(outIdx) / float(\n ${a})) * float(${n}));\n int currentSeg = int(mod(float(outIdx), float(${a})));\n\n float sumValue = 0.0;\n\n for (int i = 0; i < ${o}; i += 4) {\n int inIdx = inOffset + i;\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n getValue(batch, inIdx + 3)\n );\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 3)) == currentSeg ? 1 : 0\n );\n\n ${u}\n }\n\n int inIdx = inOffset + ${o};\n if (${1===l}) {\n vec4 values = vec4(\n getValue(batch, inIdx),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n int inIdxSeg = int(getSegmentIdAtIndex(inIdx));\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n 0,\n 0,\n 0\n );\n\n ${u}\n } else if (${2===l}) {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n initializationValue,\n initializationValue\n );\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n 0,\n 0\n );\n\n ${u}\n } else if (${3===l}) {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n initializationValue\n );\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,\n 0\n );\n\n ${u}\n }\n setOutput(sumValue);\n }\n `}}const DB=[HD,qD,XD,ZD,e_,r_,s_,a_,h_,p_,f_,g_,b_,w_,k_,S_,T_,$_,A_,R_,D_,B_,V_,U_,q_,Y_,Q_,yD,nO,cO,gO,vO,kO,IO,NO,SO,CO,$O,RO,_O,OO,zO,VO,GO,HO,qO,XO,YO,JO,QO,tL,rL,aL,oL,cL,dL,gL,bL,vL,IL,TL,EL,$L,RL,DL,OL,zL,mD,PL,oO,VL,WL,HL,wD,qL,XL,YL,JL,ez,nz,sz,iz,uz,hz,dz,mz,gz,yz,wz,vz,kz,Iz,Nz,Tz,$z,Rz,Bz,RD,Vz,Wz,Hz,qz,G_,Xz,Jz,Qz,rP,aP,ID,iP,lP,j_,Dz,cP,pP,fP,FD,yP,xP,kP,NP,CP,$P,RP,FP,_P,LP,PP,VP,WP,HP,qP,P_,Pz,XP,YP,ZP,JP,QP,eB,tB,nB,aB,oB,cB,hB,dB,fB,mB,gB,Lz,VD,bB,wB,IB,EB,AB,WD,RB,MB,{kernelName:Kr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,segmentIds:a}=t,{numSegments:i}=r,o=s.shape.length,l=[];let u=0;const c=Ac([u],o);let h=s;null!=c&&(h=UD({inputs:{x:s},backend:n,attrs:{perm:c}}),l.push(h),u=Mc(1,o)[0]);const p=Ef(h.shape,u,i),d=oe([h.shape[u]]),f=MD({inputs:{x:h},backend:n,attrs:{shape:[-1,d]}});l.push(f);const m=ra(s.dtype),g=(e,t,r,s,a)=>{const i=e.shape[0],o=e.shape[1],u=Cf(o,a),c=new FB({windowSize:u,inSize:o,batchSize:i,numSegments:a},t),h=n.compileAndRun(c,[e,r],s);if(l.push(h),h.shape[1]===a)return h;const p=oP({backend:n,attrs:{start:0,stop:a,step:1,dtype:"float32"}}),d=kB({inputs:{x:p},backend:n,attrs:{reps:[o/u]}});return l.push(p),l.push(d),g(h,t,d,s,a)},y=MD({inputs:{x:g(f,"unsortedSegmentSum",a,m,i)},backend:n,attrs:{shape:p}});let b=y;if(null!=c){l.push(y);const e=Rc(c);b=UD({inputs:{x:b},backend:n,attrs:{perm:e}})}return l.forEach((e=>n.disposeIntermediateTensorInfo(e))),b}},Zz];for(const e of DB)us(e);const _B={"tfjs-core":Bo,"tfjs-backend-cpu":"3.13.0","tfjs-backend-webgl":"3.13.0","tfjs-data":jS,"tfjs-layers":tx,"tfjs-converter":PN,tfjs:"3.13.0"}},8485:(e,t,n)=>{"use strict";n.d(t,{Z:()=>a});var r=n(3645),s=n.n(r)()((function(e){return e[1]}));s.push([e.id,".mindar-ui-overlay{display:flex;align-items:center;justify-content:center;position:absolute;left:0;right:0;top:0;bottom:0;background:rgba(0,0,0,0);z-index:2}.mindar-ui-overlay.hidden{display:none}.mindar-ui-loading .loader{border:16px solid #222;border-top:16px solid #fff;opacity:.8;border-radius:50%;width:120px;height:120px;animation:spin 2s linear infinite}@keyframes spin{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}.mindar-ui-compatibility .content{background:#000;color:#fff;opacity:.8;text-align:center;margin:20px;padding:20px;min-height:50vh}@media(min-aspect-ratio: 1/1){.mindar-ui-scanning .scanning{width:50vh;height:50vh}}@media(max-aspect-ratio: 1/1){.mindar-ui-scanning .scanning{width:80vw;height:80vw}}.mindar-ui-scanning .scanning .inner{position:relative;width:100%;height:100%;opacity:.8;background:linear-gradient(to right, white 10px, transparent 10px) 0 0,linear-gradient(to right, white 10px, transparent 10px) 0 100%,linear-gradient(to left, white 10px, transparent 10px) 100% 0,linear-gradient(to left, white 10px, transparent 10px) 100% 100%,linear-gradient(to bottom, white 10px, transparent 10px) 0 0,linear-gradient(to bottom, white 10px, transparent 10px) 100% 0,linear-gradient(to top, white 10px, transparent 10px) 0 100%,linear-gradient(to top, white 10px, transparent 10px) 100% 100%;background-repeat:no-repeat;background-size:40px 40px}.mindar-ui-scanning .scanning .inner .scanline{position:absolute;width:100%;height:10px;background:#fff;animation:move 2s linear infinite}@keyframes move{0%,100%{top:0%}50%{top:calc(100% - 10px)}}",""]);const a=s},3645:e=>{"use strict";e.exports=function(e){var t=[];return t.toString=function(){return this.map((function(t){var n=e(t);return t[2]?"@media ".concat(t[2]," {").concat(n,"}"):n})).join("")},t.i=function(e,n,r){"string"==typeof e&&(e=[[null,e,""]]);var s={};if(r)for(var a=0;a{"use strict";n.d(t,{Z:()=>r});const r='

Failed to launch :(

Looks like your device/browser is not compatible.



Please try the following recommended browsers:

For Android device - Chrome

For iOS device - Safari

'},9894:(e,t,n)=>{"use strict";n.d(t,{Z:()=>r});const r='
'},2810:(e,t,n)=>{"use strict";n.d(t,{Z:()=>r});const r='
'},3720:e=>{e.exports=n;var t=null;try{t=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch(e){}function n(e,t,n){this.low=0|e,this.high=0|t,this.unsigned=!!n}function r(e){return!0===(e&&e.__isLong__)}n.prototype.__isLong__,Object.defineProperty(n.prototype,"__isLong__",{value:!0}),n.isLong=r;var s={},a={};function i(e,t){var n,r,i;return t?(i=0<=(e>>>=0)&&e<256)&&(r=a[e])?r:(n=l(e,(0|e)<0?-1:0,!0),i&&(a[e]=n),n):(i=-128<=(e|=0)&&e<128)&&(r=s[e])?r:(n=l(e,e<0?-1:0,!1),i&&(s[e]=n),n)}function o(e,t){if(isNaN(e))return t?y:g;if(t){if(e<0)return y;if(e>=d)return k}else{if(e<=-f)return I;if(e+1>=f)return v}return e<0?o(-e,t).neg():l(e%p|0,e/p|0,t)}function l(e,t,r){return new n(e,t,r)}n.fromInt=i,n.fromNumber=o,n.fromBits=l;var u=Math.pow;function c(e,t,n){if(0===e.length)throw Error("empty string");if("NaN"===e||"Infinity"===e||"+Infinity"===e||"-Infinity"===e)return g;if("number"==typeof t?(n=t,t=!1):t=!!t,(n=n||10)<2||360)throw Error("interior hyphen");if(0===r)return c(e.substring(1),t,n).neg();for(var s=o(u(n,8)),a=g,i=0;i>>0:this.low},N.toNumber=function(){return this.unsigned?(this.high>>>0)*p+(this.low>>>0):this.high*p+(this.low>>>0)},N.toString=function(e){if((e=e||10)<2||36>>0).toString(e);if((a=l).isZero())return c+i;for(;c.length<6;)c="0"+c;i=""+c+i}},N.getHighBits=function(){return this.high},N.getHighBitsUnsigned=function(){return this.high>>>0},N.getLowBits=function(){return this.low},N.getLowBitsUnsigned=function(){return this.low>>>0},N.getNumBitsAbs=function(){if(this.isNegative())return this.eq(I)?64:this.neg().getNumBitsAbs();for(var e=0!=this.high?this.high:this.low,t=31;t>0&&0==(e&1<=0},N.isOdd=function(){return 1==(1&this.low)},N.isEven=function(){return 0==(1&this.low)},N.equals=function(e){return r(e)||(e=h(e)),(this.unsigned===e.unsigned||this.high>>>31!=1||e.high>>>31!=1)&&this.high===e.high&&this.low===e.low},N.eq=N.equals,N.notEquals=function(e){return!this.eq(e)},N.neq=N.notEquals,N.ne=N.notEquals,N.lessThan=function(e){return this.comp(e)<0},N.lt=N.lessThan,N.lessThanOrEqual=function(e){return this.comp(e)<=0},N.lte=N.lessThanOrEqual,N.le=N.lessThanOrEqual,N.greaterThan=function(e){return this.comp(e)>0},N.gt=N.greaterThan,N.greaterThanOrEqual=function(e){return this.comp(e)>=0},N.gte=N.greaterThanOrEqual,N.ge=N.greaterThanOrEqual,N.compare=function(e){if(r(e)||(e=h(e)),this.eq(e))return 0;var t=this.isNegative(),n=e.isNegative();return t&&!n?-1:!t&&n?1:this.unsigned?e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1:this.sub(e).isNegative()?-1:1},N.comp=N.compare,N.negate=function(){return!this.unsigned&&this.eq(I)?I:this.not().add(b)},N.neg=N.negate,N.add=function(e){r(e)||(e=h(e));var t=this.high>>>16,n=65535&this.high,s=this.low>>>16,a=65535&this.low,i=e.high>>>16,o=65535&e.high,u=e.low>>>16,c=0,p=0,d=0,f=0;return d+=(f+=a+(65535&e.low))>>>16,p+=(d+=s+u)>>>16,c+=(p+=n+o)>>>16,c+=t+i,l((d&=65535)<<16|(f&=65535),(c&=65535)<<16|(p&=65535),this.unsigned)},N.subtract=function(e){return r(e)||(e=h(e)),this.add(e.neg())},N.sub=N.subtract,N.multiply=function(e){if(this.isZero())return g;if(r(e)||(e=h(e)),t)return l(t.mul(this.low,this.high,e.low,e.high),t.get_high(),this.unsigned);if(e.isZero())return g;if(this.eq(I))return e.isOdd()?I:g;if(e.eq(I))return this.isOdd()?I:g;if(this.isNegative())return e.isNegative()?this.neg().mul(e.neg()):this.neg().mul(e).neg();if(e.isNegative())return this.mul(e.neg()).neg();if(this.lt(m)&&e.lt(m))return o(this.toNumber()*e.toNumber(),this.unsigned);var n=this.high>>>16,s=65535&this.high,a=this.low>>>16,i=65535&this.low,u=e.high>>>16,c=65535&e.high,p=e.low>>>16,d=65535&e.low,f=0,y=0,b=0,x=0;return b+=(x+=i*d)>>>16,y+=(b+=a*d)>>>16,b&=65535,y+=(b+=i*p)>>>16,f+=(y+=s*d)>>>16,y&=65535,f+=(y+=a*p)>>>16,y&=65535,f+=(y+=i*c)>>>16,f+=n*d+s*p+a*c+i*u,l((b&=65535)<<16|(x&=65535),(f&=65535)<<16|(y&=65535),this.unsigned)},N.mul=N.multiply,N.divide=function(e){if(r(e)||(e=h(e)),e.isZero())throw Error("division by zero");var n,s,a;if(t)return this.unsigned||-2147483648!==this.high||-1!==e.low||-1!==e.high?l((this.unsigned?t.div_u:t.div_s)(this.low,this.high,e.low,e.high),t.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?y:g;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return y;if(e.gt(this.shru(1)))return x;a=y}else{if(this.eq(I))return e.eq(b)||e.eq(w)?I:e.eq(I)?b:(n=this.shr(1).div(e).shl(1)).eq(g)?e.isNegative()?b:w:(s=this.sub(e.mul(n)),a=n.add(s.div(e)));if(e.eq(I))return this.unsigned?y:g;if(this.isNegative())return e.isNegative()?this.neg().div(e.neg()):this.neg().div(e).neg();if(e.isNegative())return this.div(e.neg()).neg();a=g}for(s=this;s.gte(e);){n=Math.max(1,Math.floor(s.toNumber()/e.toNumber()));for(var i=Math.ceil(Math.log(n)/Math.LN2),c=i<=48?1:u(2,i-48),p=o(n),d=p.mul(e);d.isNegative()||d.gt(s);)d=(p=o(n-=c,this.unsigned)).mul(e);p.isZero()&&(p=b),a=a.add(p),s=s.sub(d)}return a},N.div=N.divide,N.modulo=function(e){return r(e)||(e=h(e)),t?l((this.unsigned?t.rem_u:t.rem_s)(this.low,this.high,e.low,e.high),t.get_high(),this.unsigned):this.sub(this.div(e).mul(e))},N.mod=N.modulo,N.rem=N.modulo,N.not=function(){return l(~this.low,~this.high,this.unsigned)},N.and=function(e){return r(e)||(e=h(e)),l(this.low&e.low,this.high&e.high,this.unsigned)},N.or=function(e){return r(e)||(e=h(e)),l(this.low|e.low,this.high|e.high,this.unsigned)},N.xor=function(e){return r(e)||(e=h(e)),l(this.low^e.low,this.high^e.high,this.unsigned)},N.shiftLeft=function(e){return r(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?l(this.low<>>32-e,this.unsigned):l(0,this.low<>>e|this.high<<32-e,this.high>>e,this.unsigned):l(this.high>>e-32,this.high>=0?0:-1,this.unsigned)},N.shr=N.shiftRight,N.shiftRightUnsigned=function(e){if(r(e)&&(e=e.toInt()),0==(e&=63))return this;var t=this.high;return e<32?l(this.low>>>e|t<<32-e,t>>>e,this.unsigned):l(32===e?t:t>>>e-32,0,this.unsigned)},N.shru=N.shiftRightUnsigned,N.shr_u=N.shiftRightUnsigned,N.toSigned=function(){return this.unsigned?l(this.low,this.high,!1):this},N.toUnsigned=function(){return this.unsigned?this:l(this.low,this.high,!0)},N.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()},N.toBytesLE=function(){var e=this.high,t=this.low;return[255&t,t>>>8&255,t>>>16&255,t>>>24,255&e,e>>>8&255,e>>>16&255,e>>>24]},N.toBytesBE=function(){var e=this.high,t=this.low;return[e>>>24,e>>>16&255,e>>>8&255,255&e,t>>>24,t>>>16&255,t>>>8&255,255&t]},n.fromBytes=function(e,t,r){return r?n.fromBytesLE(e,t):n.fromBytesBE(e,t)},n.fromBytesLE=function(e,t){return new n(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)},n.fromBytesBE=function(e,t){return new n(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)}},6377:(e,t,n)=>{var r=n(4832),s=n(8652),a=n(801),i=n(2030),o=n(3618),l=n(9049),u=n(1971);u.alea=r,u.xor128=s,u.xorwow=a,u.xorshift7=i,u.xor4096=o,u.tychei=l,e.exports=u},4832:function(e,t,n){var r;!function(e,s,a){function i(e){var t,n=this,r=(t=4022871197,function(e){e=e.toString();for(var n=0;n>>0,t=(r*=t)>>>0,t+=4294967296*(r-=t)}return 2.3283064365386963e-10*(t>>>0)});n.next=function(){var e=2091639*n.s0+2.3283064365386963e-10*n.c;return n.s0=n.s1,n.s1=n.s2,n.s2=e-(n.c=0|e)},n.c=1,n.s0=r(" "),n.s1=r(" "),n.s2=r(" "),n.s0-=r(e),n.s0<0&&(n.s0+=1),n.s1-=r(e),n.s1<0&&(n.s1+=1),n.s2-=r(e),n.s2<0&&(n.s2+=1),r=null}function o(e,t){return t.c=e.c,t.s0=e.s0,t.s1=e.s1,t.s2=e.s2,t}function l(e,t){var n=new i(e),r=t&&t.state,s=n.next;return s.int32=function(){return 4294967296*n.next()|0},s.double=function(){return s()+11102230246251565e-32*(2097152*s()|0)},s.quick=s,r&&("object"==typeof r&&o(r,n),s.state=function(){return o(n,{})}),s}s&&s.exports?s.exports=l:n.amdD&&n.amdO?void 0===(r=function(){return l}.call(t,n,t,s))||(s.exports=r):this.alea=l}(0,e=n.nmd(e),n.amdD)},9049:function(e,t,n){var r;!function(e,s,a){function i(e){var t=this,n="";t.next=function(){var e=t.b,n=t.c,r=t.d,s=t.a;return e=e<<25^e>>>7^n,n=n-r|0,r=r<<24^r>>>8^s,s=s-e|0,t.b=e=e<<20^e>>>12^n,t.c=n=n-r|0,t.d=r<<16^n>>>16^s,t.a=s-e|0},t.a=0,t.b=0,t.c=-1640531527,t.d=1367130551,e===Math.floor(e)?(t.a=e/4294967296|0,t.b=0|e):n+=e;for(var r=0;r>>0)/4294967296};return s.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},s.int32=n.next,s.quick=s,r&&("object"==typeof r&&o(r,n),s.state=function(){return o(n,{})}),s}s&&s.exports?s.exports=l:n.amdD&&n.amdO?void 0===(r=function(){return l}.call(t,n,t,s))||(s.exports=r):this.tychei=l}(0,e=n.nmd(e),n.amdD)},8652:function(e,t,n){var r;!function(e,s,a){function i(e){var t=this,n="";t.x=0,t.y=0,t.z=0,t.w=0,t.next=function(){var e=t.x^t.x<<11;return t.x=t.y,t.y=t.z,t.z=t.w,t.w^=t.w>>>19^e^e>>>8},e===(0|e)?t.x=e:n+=e;for(var r=0;r>>0)/4294967296};return s.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},s.int32=n.next,s.quick=s,r&&("object"==typeof r&&o(r,n),s.state=function(){return o(n,{})}),s}s&&s.exports?s.exports=l:n.amdD&&n.amdO?void 0===(r=function(){return l}.call(t,n,t,s))||(s.exports=r):this.xor128=l}(0,e=n.nmd(e),n.amdD)},3618:function(e,t,n){var r;!function(e,s,a){function i(e){var t=this;t.next=function(){var e,n,r=t.w,s=t.X,a=t.i;return t.w=r=r+1640531527|0,n=s[a+34&127],e=s[a=a+1&127],n^=n<<13,e^=e<<17,n^=n>>>15,e^=e>>>12,n=s[a]=n^e,t.i=a,n+(r^r>>>16)|0},function(e,t){var n,r,s,a,i,o=[],l=128;for(t===(0|t)?(r=t,t=null):(t+="\0",r=0,l=Math.max(l,t.length)),s=0,a=-32;a>>15,r^=r<<4,r^=r>>>13,a>=0&&(i=i+1640531527|0,s=0==(n=o[127&a]^=r+i)?s+1:0);for(s>=128&&(o[127&(t&&t.length||0)]=-1),s=127,a=512;a>0;--a)r=o[s+34&127],n=o[s=s+1&127],r^=r<<13,n^=n<<17,r^=r>>>15,n^=n>>>12,o[s]=r^n;e.w=i,e.X=o,e.i=s}(t,e)}function o(e,t){return t.i=e.i,t.w=e.w,t.X=e.X.slice(),t}function l(e,t){null==e&&(e=+new Date);var n=new i(e),r=t&&t.state,s=function(){return(n.next()>>>0)/4294967296};return s.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},s.int32=n.next,s.quick=s,r&&(r.X&&o(r,n),s.state=function(){return o(n,{})}),s}s&&s.exports?s.exports=l:n.amdD&&n.amdO?void 0===(r=function(){return l}.call(t,n,t,s))||(s.exports=r):this.xor4096=l}(0,e=n.nmd(e),n.amdD)},2030:function(e,t,n){var r;!function(e,s,a){function i(e){var t=this;t.next=function(){var e,n,r=t.x,s=t.i;return e=r[s],n=(e^=e>>>7)^e<<24,n^=(e=r[s+1&7])^e>>>10,n^=(e=r[s+3&7])^e>>>3,n^=(e=r[s+4&7])^e<<7,e=r[s+7&7],n^=(e^=e<<13)^e<<9,r[s]=n,t.i=s+1&7,n},function(e,t){var n,r=[];if(t===(0|t))r[0]=t;else for(t=""+t,n=0;n0;--n)e.next()}(t,e)}function o(e,t){return t.x=e.x.slice(),t.i=e.i,t}function l(e,t){null==e&&(e=+new Date);var n=new i(e),r=t&&t.state,s=function(){return(n.next()>>>0)/4294967296};return s.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},s.int32=n.next,s.quick=s,r&&(r.x&&o(r,n),s.state=function(){return o(n,{})}),s}s&&s.exports?s.exports=l:n.amdD&&n.amdO?void 0===(r=function(){return l}.call(t,n,t,s))||(s.exports=r):this.xorshift7=l}(0,e=n.nmd(e),n.amdD)},801:function(e,t,n){var r;!function(e,s,a){function i(e){var t=this,n="";t.next=function(){var e=t.x^t.x>>>2;return t.x=t.y,t.y=t.z,t.z=t.w,t.w=t.v,(t.d=t.d+362437|0)+(t.v=t.v^t.v<<4^e^e<<1)|0},t.x=0,t.y=0,t.z=0,t.w=0,t.v=0,e===(0|e)?t.x=e:n+=e;for(var r=0;r>>4),t.next()}function o(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t.v=e.v,t.d=e.d,t}function l(e,t){var n=new i(e),r=t&&t.state,s=function(){return(n.next()>>>0)/4294967296};return s.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},s.int32=n.next,s.quick=s,r&&("object"==typeof r&&o(r,n),s.state=function(){return o(n,{})}),s}s&&s.exports?s.exports=l:n.amdD&&n.amdO?void 0===(r=function(){return l}.call(t,n,t,s))||(s.exports=r):this.xorwow=l}(0,e=n.nmd(e),n.amdD)},1971:(e,t,n)=>{var r;!function(s,a){var i,o=this,l=256,u=a.pow(l,6),c=a.pow(2,52),h=2*c,p=255;function d(e,t,n){var r=[],p=y(g((t=1==t?{entropy:!0}:t||{}).entropy?[e,b(s)]:null==e?function(){try{var e;return i&&(e=i.randomBytes)?e=e(l):(e=new Uint8Array(l),(o.crypto||o.msCrypto).getRandomValues(e)),b(e)}catch(e){var t=o.navigator,n=t&&t.plugins;return[+new Date,o,n,o.screen,b(s)]}}():e,3),r),d=new f(r),x=function(){for(var e=d.g(6),t=u,n=0;e=h;)e/=2,t/=2,n>>>=1;return(e+n)/t};return x.int32=function(){return 0|d.g(4)},x.quick=function(){return d.g(4)/4294967296},x.double=x,y(b(d.S),s),(t.pass||n||function(e,t,n,r){return r&&(r.S&&m(r,d),e.state=function(){return m(d,{})}),n?(a.random=e,t):e})(x,p,"global"in t?t.global:this==a,t.state)}function f(e){var t,n=e.length,r=this,s=0,a=r.i=r.j=0,i=r.S=[];for(n||(e=[n++]);s{"use strict";n.r(t),n.d(t,{default:()=>i});var r=n(3379),s=n.n(r),a=n(8485);s()(a.Z,{insert:"head",singleton:!1});const i=a.Z.locals||{}},3379:(e,t,n)=>{"use strict";var r,s=function(){var e={};return function(t){if(void 0===e[t]){var n=document.querySelector(t);if(window.HTMLIFrameElement&&n instanceof window.HTMLIFrameElement)try{n=n.contentDocument.head}catch(e){n=null}e[t]=n}return e[t]}}(),a=[];function i(e){for(var t=-1,n=0;n{e.exports=function(){return n(9855)('(()=>{var t={508:(t,e,r)=>{const{resize:a}=r(140);t.exports={buildImageList:t=>{const e=[];let r=100/Math.min(t.width,t.height);for(;;)if(e.push(r),r*=Math.pow(2,1/3),r>=.95){r=1;break}e.push(r),e.reverse();const i=[];for(let r=0;r{const e=Math.min(t.width,t.height),r=[],i=[];r.push(256/e),r.push(128/e);for(let e=0;e{const{Cumsum:a}=r(535),i=({image:t,cx:e,cy:r,sdThresh:a,imageDataCumsum:i,imageDataSqrCumsum:s})=>{if(e-6<0||e+6>=t.width)return null;if(r-6<0||r+6>=t.height)return null;let h=i.query(e-6,r-6,e+6,r+6);h/=169;let o=s.query(e-6,r-6,e+6,r+6);return o-=2*h*i.query(e-6,r-6,e+6,r+6),o+=169*h*h,o/169{const{image:e,cx:r,cy:a,vlen:i,tx:s,ty:h,imageDataCumsum:o,imageDataSqrCumsum:l}=t,{data:u,width:n,height:m}=e;if(r-6<0||r+6>=n)return null;if(a-6<0||a+6>=m)return null;let c=o.query(r-6,a-6,r+6,a+6),f=l.query(r-6,a-6,r+6,a+6),g=0,d=(a-6)*n+(r-6),p=(h-6)*n+(s-6),w=n-13;for(let t=0;t<13;t++){for(let t=0;t<13;t++)g+=u[d]*u[p],d+=1,p+=1;d+=w,p+=w}let M=o.query(s-6,h-6,s+6,h+6);M/=169,g-=M*c;let y=f-c*c/169;return 0==y?null:(y=Math.sqrt(y),1*g/(i*y))};t.exports={extract:t=>{const{data:e,width:r,height:h,scale:o}=t,l=[r*h];for(let t=0;t999&&(t=999),t<0&&(t=0),n[t]+=1,c+=1,l[a]=!0}}const f=.02*r*h;let g=999,d=0;for(;g>=0&&(d+=n[g],!(d>f));)g--;for(let t=0;tu&&(u=h,u>.95))break}if(u>.95)break}y[h]=u}return(t=>{let{image:e,featureMap:r,templateSize:a,searchSize:h,occSize:o,maxSimThresh:l,minSimThresh:u,sdThresh:n,imageDataCumsum:m,imageDataSqrCumsum:c}=t;const{data:f,width:g,height:d,scale:p}=e;o=Math.floor(Math.min(e.width,e.height)/10);const w=3*(2*a+1),M=Math.floor(g/w),y=Math.floor(d/w);let x=Math.floor(g/o)*Math.floor(d/o)+M*y;const q=[],C=new Float32Array(f.length);for(let t=0;th*h)continue;if(0===i&&0===a)continue;const o=s({image:e,vlen:p,cx:r+i,cy:f+a,tx:r,ty:f,imageDataCumsum:m,imageDataSqrCumsum:c});if(null!==o){if(oM&&(M=o,M>.99))break}}if(w.99)break}if(w.99)C[f*g+r]=1;else{q.push({x:r,y:f}),S+=1;for(let t=-o;t<=o;t++)for(let e=-o;e<=o;e++)f+t<0||f+t>=d||r+e<0||r+e>=g||(C[(f+t)*g+(r+e)]=1)}}return q})({image:t,featureMap:y,templateSize:6,searchSize:2,occSize:16,maxSimThresh:.9,minSimThresh:.2,sdThresh:8,imageDataCumsum:w,imageDataSqrCumsum:M})}}},535:t=>{t.exports={Cumsum:class{constructor(t,e,r){this.cumsum=[];for(let t=0;t0&&(i-=this.cumsum[e-1][r]),t>0&&(i-=this.cumsum[a][t-1]),t>0&&e>0&&(i+=this.cumsum[e-1][t-1]),i}}}},140:t=>{t.exports={downsampleBilinear:({image:t})=>{const{data:e,width:r,height:a}=t,i=Math.floor(r/2),s=Math.floor(a/2),h=new Float32Array(i*s),o=[0,1,r,r+1];for(let t=0;t{const{width:a,height:i,data:s}=t,h=2*t.width+(e?1:0),o=2*t.height+(r?1:0),l=new Float32Array(h*o);for(let t=0;t=a&&(u=a-1);for(let n=0;n=i&&(c=i-1);const f=(u-e)*(c-o)*s[m*a+r]+(u-e)*(o-m)*s[c*a+r]+(e-r)*(c-o)*s[m*a+u]+(e-r)*(o-m)*s[c*a+u];l[n*h+t]=f}}return{data:l,width:h,height:o}},resize:({image:t,ratio:e})=>{const r=Math.round(t.width*e),a=Math.round(t.height*e),i=new Uint8Array(r*a);for(let s=0;s=t.width&&(o=t.width-1);for(let l=0;l=t.height&&(u=t.height-1);let n=0,m=0;for(let e=h;e<=o;e++)for(let r=a;r<=u;r++)n+=1*t.data[r*t.width+e],m+=1;i[l*r+s]=Math.floor(n/m)}}return{data:i,width:r,height:a}}}}},e={};function r(a){if(e[a])return e[a].exports;var i=e[a]={exports:{}};return t[a](i,i.exports,r),i.exports}(()=>{const{extract:t}=r(589),{buildTrackingImageList:e}=r(508);onmessage=t=>{const{data:r}=t;if("compile"===r.type){const{targetImages:t}=r,i=50/t.length;let s=0;const h=[];for(let r=0;r{s+=u,postMessage({type:"progress",percent:s})}));h.push(n)}postMessage({type:"compileDone",list:h})}};const a=(e,r)=>{const a=[];for(let i=0;i{e.exports=function(){return n(9855)('(()=>{var t={331:(t,e,r)=>{"use strict";r.r(e),r.d(e,{AbstractMatrix:()=>v,CHO:()=>tt,CholeskyDecomposition:()=>tt,EVD:()=>K,EigenvalueDecomposition:()=>K,LU:()=>H,LuDecomposition:()=>H,Matrix:()=>k,MatrixColumnSelectionView:()=>T,MatrixColumnView:()=>I,MatrixFlipColumnView:()=>A,MatrixFlipRowView:()=>q,MatrixRowSelectionView:()=>P,MatrixRowView:()=>C,MatrixSelectionView:()=>V,MatrixSubView:()=>N,MatrixTransposeView:()=>j,NIPALS:()=>et,Nipals:()=>et,QR:()=>$,QrDecomposition:()=>$,SVD:()=>L,SingularValueDecomposition:()=>L,WrapperMatrix1D:()=>z,WrapperMatrix2D:()=>F,correlation:()=>J,covariance:()=>B,default:()=>k,determinant:()=>X,inverse:()=>O,linearDependencies:()=>Q,pseudoInverse:()=>W,solve:()=>U,wrap:()=>D});const s=Object.prototype.toString;function o(t){return s.call(t).endsWith("Array]")}const n=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!o(t))throw new TypeError("input must be an array");if(0===t.length)throw new TypeError("input must not be empty");var r=e.fromIndex,s=void 0===r?0:r,n=e.toIndex,i=void 0===n?t.length:n;if(s<0||s>=t.length||!Number.isInteger(s))throw new Error("fromIndex must be a positive integer smaller than length");if(i<=s||i>t.length||!Number.isInteger(i))throw new Error("toIndex must be an integer greater than fromIndex and at most equal to length");for(var h=t[s],l=s+1;lh&&(h=t[l]);return h},i=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!o(t))throw new TypeError("input must be an array");if(0===t.length)throw new TypeError("input must not be empty");var r=e.fromIndex,s=void 0===r?0:r,n=e.toIndex,i=void 0===n?t.length:n;if(s<0||s>=t.length||!Number.isInteger(s))throw new Error("fromIndex must be a positive integer smaller than length");if(i<=s||i>t.length||!Number.isInteger(i))throw new Error("toIndex must be an integer greater than fromIndex and at most equal to length");for(var h=t[s],l=s+1;l1&&void 0!==arguments[1]?arguments[1]:{};if(!o(t))throw new TypeError("input must be an array");if(0===t.length)throw new TypeError("input must not be empty");if(void 0!==r.output){if(!o(r.output))throw new TypeError("output option must be an array if specified");e=r.output}else e=new Array(t.length);var s=i(t),h=n(t);if(s===h)throw new RangeError("minimum and maximum input values are equal. Cannot rescale a constant array");var l=r.min,u=void 0===l?r.autoMinMax?s:0:l,a=r.max,c=void 0===a?r.autoMinMax?h:1:a;if(u>=c)throw new RangeError("min option must be smaller than max option");for(var f=(c-u)/(h-s),m=0;ms)throw new RangeError("Row index out of range")}function m(t,e,r){let s=r?t.columns:t.columns-1;if(e<0||e>s)throw new RangeError("Column index out of range")}function g(t,e){if(e.to1DArray&&(e=e.to1DArray()),e.length!==t.columns)throw new RangeError("vector size must be the same as the number of columns");return e}function w(t,e){if(e.to1DArray&&(e=e.to1DArray()),e.length!==t.rows)throw new RangeError("vector size must be the same as the number of rows");return e}function p(t,e,r){return{row:d(t,e),column:y(t,r)}}function d(t,e){if("object"!=typeof e)throw new TypeError("unexpected type for row indices");if(e.some((e=>e<0||e>=t.rows)))throw new RangeError("row indices are out of range");return Array.isArray(e)||(e=Array.from(e)),e}function y(t,e){if("object"!=typeof e)throw new TypeError("unexpected type for column indices");if(e.some((e=>e<0||e>=t.columns)))throw new RangeError("column indices are out of range");return Array.isArray(e)||(e=Array.from(e)),e}function M(t,e,r,s,o){if(5!==arguments.length)throw new RangeError("expected 4 arguments");if(x("startRow",e),x("endRow",r),x("startColumn",s),x("endColumn",o),e>r||s>o||e<0||e>=t.rows||r<0||r>=t.rows||s<0||s>=t.columns||o<0||o>=t.columns)throw new RangeError("Submatrix indices are out of range")}function b(t,e=0){let r=[];for(let s=0;s=o)throw new RangeError("min must be smaller than max");let i=o-s,h=new k(t,e);for(let r=0;rr?(o=!0,r=e):(s=!1,o=!0);t++}return s}isReducedEchelonForm(){let t=0,e=0,r=-1,s=!0,o=!1;for(;tr?(o=!0,r=e):(s=!1,o=!0);for(let r=e+1;rt.get(s,r)&&(s=o);if(0===t.get(s,r))r++;else{t.swapRows(e,s);let o=t.get(e,r);for(let s=r;s=0;)if(0===t.maxRow(s))s--;else{let o=0,n=!1;for(;ot&&(t=this.get(e,r));return t}maxIndex(){E(this);let t=this.get(0,0),e=[0,0];for(let r=0;rt&&(t=this.get(r,s),e[0]=r,e[1]=s);return e}min(){if(this.isEmpty())return NaN;let t=this.get(0,0);for(let e=0;ee&&(e=this.get(t,r));return e}maxRowIndex(t){f(this,t),E(this);let e=this.get(t,0),r=[t,0];for(let s=1;se&&(e=this.get(t,s),r[1]=s);return r}minRow(t){if(f(this,t),this.isEmpty())return NaN;let e=this.get(t,0);for(let r=1;re&&(e=this.get(r,t));return e}maxColumnIndex(t){m(this,t),E(this);let e=this.get(0,t),r=[0,t];for(let s=1;se&&(e=this.get(s,t),r[0]=s);return r}minColumn(t){if(m(this,t),this.isEmpty())return NaN;let e=this.get(0,t);for(let r=1;r=r)throw new RangeError("min must be smaller than max");let s=new k(this.rows,this.columns);for(let t=0;t0&&h(o,{min:e,max:r,output:o}),s.setRow(t,o)}return s}scaleColumns(t={}){if("object"!=typeof t)throw new TypeError("options must be an object");const{min:e=0,max:r=1}=t;if(!Number.isFinite(e))throw new TypeError("min must be a number");if(!Number.isFinite(r))throw new TypeError("max must be a number");if(e>=r)throw new RangeError("min must be smaller than max");let s=new k(this.rows,this.columns);for(let t=0;tr||e<0||e>=this.columns||r<0||r>=this.columns)throw new RangeError("Argument out of range");let s=new k(t.length,r-e+1);for(let o=0;o=this.rows)throw new RangeError(`Row index out of range: ${t[o]}`);s.set(o,n-e,this.get(t[o],n))}return s}subMatrixColumn(t,e,r){if(void 0===e&&(e=0),void 0===r&&(r=this.rows-1),e>r||e<0||e>=this.rows||r<0||r>=this.rows)throw new RangeError("Argument out of range");let s=new k(r-e+1,t.length);for(let o=0;o=this.columns)throw new RangeError(`Column index out of range: ${t[o]}`);s.set(n-e,o,this.get(n,t[o]))}return s}setSubMatrix(t,e,r){if((t=k.checkMatrix(t)).isEmpty())return this;M(this,e,e+t.rows-1,r,r+t.columns-1);for(let s=0;s=0){if(this.data=[],!(Number.isInteger(e)&&e>=0))throw new TypeError("nColumns must be a positive integer");for(let r=0;r>t);return this},t.prototype.signPropagatingRightShiftM=function(t){if(t=e.checkMatrix(t),this.rows!==t.rows||this.columns!==t.columns)throw new RangeError("Matrices dimensions must be equal");for(let e=0;e>t.get(e,r));return this},t.signPropagatingRightShift=function(t,r){return new e(t).signPropagatingRightShift(r)},t.prototype.rightShift=function(t){return"number"==typeof t?this.rightShiftS(t):this.rightShiftM(t)},t.prototype.rightShiftS=function(t){for(let e=0;e>>t);return this},t.prototype.rightShiftM=function(t){if(t=e.checkMatrix(t),this.rows!==t.rows||this.columns!==t.columns)throw new RangeError("Matrices dimensions must be equal");for(let e=0;e>>t.get(e,r));return this},t.rightShift=function(t,r){return new e(t).rightShift(r)},t.prototype.zeroFillRightShift=t.prototype.rightShift,t.prototype.zeroFillRightShiftS=t.prototype.rightShiftS,t.prototype.zeroFillRightShiftM=t.prototype.rightShiftM,t.zeroFillRightShift=t.rightShift,t.prototype.not=function(){for(let t=0;tMath.abs(l[o])&&(o=e);if(o!==r){for(s=0;s=0;o--){for(s=0;se?s.set(o,e,t.get(o,e)):o===e?s.set(o,e,1):s.set(o,e,0);return s}get upperTriangularMatrix(){let t=this.LU,e=t.rows,r=t.columns,s=new k(e,r);for(let o=0;oMath.abs(e)?(r=e/t,Math.abs(t)*Math.sqrt(1+r*r)):0!==e?(r=t/e,Math.abs(e)*Math.sqrt(1+r*r)):0}class ${constructor(t){let e,r,s,o,n=(t=F.checkMatrix(t)).clone(),i=t.rows,h=t.columns,l=new Float64Array(h);for(s=0;s=0;n--){for(o=0;o=0;r--){for(t=0;t=0;t--)if(0!==m[t]){for(let e=t+1;e=0;t--){if(t0;){let t,e;for(t=E-2;t>=-1&&-1!==t;t--){const e=Number.MIN_VALUE+R*Math.abs(m[t]+Math.abs(m[t+1]));if(Math.abs(p[t])<=e||Number.isNaN(p[t])){p[t]=0;break}}if(t===E-2)e=4;else{let r;for(r=E-1;r>=t&&r!==t;r--){let e=(r!==E?Math.abs(p[r]):0)+(r!==t+1?Math.abs(p[r-1]):0);if(Math.abs(m[r])<=R*e){m[r]=0;break}}r===t?e=3:r===E-1?e=1:(e=2,t=r)}switch(t++,e){case 1:{let e=p[E-2];p[E-2]=0;for(let r=E-2;r>=t;r--){let o=_(m[r],e),n=m[r]/o,i=e/o;if(m[r]=o,r!==t&&(e=-i*p[r-1],p[r-1]=n*p[r-1]),u)for(let t=0;t=m[t+1]);){let e=m[t];if(m[t]=m[t+1],m[t+1]=e,u&&te&&o.set(n,r,t.get(n,r)/this.s[r]);let n=this.U,i=n.rows,h=n.columns,l=new k(r,i);for(let t=0;tt&&e++;return e}get diagonal(){return Array.from(this.s)}get threshold(){return Number.EPSILON/2*Math.max(this.m,this.n)*this.s[0]}get leftSingularVectors(){return this.U}get rightSingularVectors(){return this.V}get diagonalMatrix(){return k.diag(this.s)}}function O(t,e=!1){return t=F.checkMatrix(t),e?new L(t).inverse():U(t,k.eye(t.rows))}function U(t,e,r=!1){return t=F.checkMatrix(t),e=F.checkMatrix(e),r?new L(t).solve(e):t.isSquare()?new H(t).solve(e):new $(t).solve(e)}function X(t){if((t=k.checkMatrix(t)).isSquare()){if(0===t.columns)return 1;let e,r,s,o;if(2===t.columns)return e=t.get(0,0),r=t.get(0,1),s=t.get(1,0),o=t.get(1,1),e*o-r*s;if(3===t.columns){let o,n,i;return o=new V(t,[1,2],[1,2]),n=new V(t,[1,2],[0,2]),i=new V(t,[1,2],[0,1]),e=t.get(0,0),r=t.get(0,1),s=t.get(0,2),e*X(o)-r*X(n)+s*X(i)}return new H(t).determinant}throw Error("determinant can only be calculated for a square matrix")}function Y(t,e){let r=[];for(let s=0;so)return new Array(e.rows+1).fill(0);{let t=e.addRow(r,[0]);for(let e=0;ee?n[t]=1/n[t]:n[t]=0;return o.mmul(k.diag(n).mmul(s.transpose()))}function B(t,e=t,r={}){t=new k(t);let s=!1;if("object"!=typeof e||k.isMatrix(e)||Array.isArray(e)?e=new k(e):(r=e,e=t,s=!0),t.rows!==e.rows)throw new TypeError("Both matrices must have the same number of rows");const{center:o=!0}=r;o&&(t=t.center("column"),s||(e=e.center("column")));const n=t.transpose().mmul(e);for(let e=0;e0;h--){for(c=0,i=0,u=0;u0&&(n=-n),e[h]=c*n,i-=o*n,r[h-1]=o-n,l=0;lu){b=0;do{for(b+=1,o=r[u],c=(r[u+1]-o)/(2*e[u]),f=_(c,1),c<0&&(f=-f),r[u]=e[u]/(c+f),r[u+1]=e[u]*(c+f),m=r[u+1],n=o-r[u],i=u+2;i=u;i--)for(p=w,w=g,M=y,o=g*e[i],n=g*c,f=_(c,e[i]),e[i+1]=y*f,y=e[i]/f,g=c/f,c=g*r[i]-y*o,r[i+1]=n+y*(g*o+y*r[i]),l=0;lv*E)}r[u]=r[u]+x,e[u]=0}for(i=0;i=u;h--)r[h]=e.get(h,u-1)/a,i+=r[h]*r[h];for(n=Math.sqrt(i),r[u]>0&&(n=-n),i-=r[u]*n,r[u]=r[u]-n,l=u;l=u;h--)o+=r[h]*e.get(h,l);for(o/=i,h=u;h<=c;h++)e.set(h,l,e.get(h,l)-o*r[h])}for(h=0;h<=c;h++){for(o=0,l=c;l>=u;l--)o+=r[l]*e.get(h,l);for(o/=i,l=u;l<=c;l++)e.set(h,l,e.get(h,l)-o*r[l])}r[u]=a*r[u],e.set(u,u-1,a*n)}}for(h=0;h=1;u--)if(0!==e.get(u,u-1)){for(h=u+1;h<=c;h++)r[h]=e.get(h,u-1);for(l=u;l<=c;l++){for(n=0,h=u;h<=c;h++)n+=r[h]*s.get(h,l);for(n=n/r[u]/e.get(u,u-1),h=u;h<=c;h++)s.set(h,l,s.get(h,l)+n*r[h])}}}(n,t,e,i),function(t,e,r,s,o){let n,i,h,l,u,a,c,f,m,g,w,p,d,y,M,b=t-1,x=t-1,E=Number.EPSILON,v=0,S=0,k=0,R=0,I=0,T=0,A=0,q=0;for(n=0;nx)&&(r[n]=o.get(n,n),e[n]=0),i=Math.max(n-1,0);i=0;){for(l=b;l>0&&(T=Math.abs(o.get(l-1,l-1))+Math.abs(o.get(l,l)),0===T&&(T=S),!(Math.abs(o.get(l,l-1))=0){for(A=k>=0?k+A:k-A,r[b-1]=f+A,r[b]=r[b-1],0!==A&&(r[b]=f-c/A),e[b-1]=0,e[b]=0,f=o.get(b,b-1),T=Math.abs(f)+Math.abs(A),k=f/T,R=A/T,I=Math.sqrt(k*k+R*R),k/=I,R/=I,i=b-1;i0)){for(T=Math.sqrt(T),m=l&&(A=o.get(u,u),I=f-A,T=m-A,k=(I*T-c)/o.get(u+1,u)+o.get(u,u+1),R=o.get(u+1,u+1)-A-I-T,I=o.get(u+2,u+1),T=Math.abs(k)+Math.abs(R)+Math.abs(I),k/=T,R/=T,I/=T,u!==l)&&!(Math.abs(o.get(u,u-1))*(Math.abs(R)+Math.abs(I))u+2&&o.set(n,n-3,0);for(h=u;h<=b-1&&(y=h!==b-1,h!==u&&(k=o.get(h,h-1),R=o.get(h+1,h-1),I=y?o.get(h+2,h-1):0,f=Math.abs(k)+Math.abs(R)+Math.abs(I),0!==f&&(k/=f,R/=f,I/=f)),0!==f);h++)if(T=Math.sqrt(k*k+R*R+I*I),k<0&&(T=-T),0!==T){for(h!==u?o.set(h,h-1,-T*f):l!==u&&o.set(h,h-1,-o.get(h,h-1)),k+=T,f=k/T,m=R/T,A=I/T,R/=k,I/=k,i=h;i=0;b--)if(k=r[b],R=e[b],0===R)for(l=b,o.set(b,b,1),n=b-1;n>=0;n--){for(c=o.get(n,n)-k,I=0,i=l;i<=b;i++)I+=o.get(n,i)*o.get(i,b);if(e[n]<0)A=c,T=I;else if(l=n,0===e[n]?o.set(n,b,0!==c?-I/c:-I/(E*S)):(f=o.get(n,n+1),m=o.get(n+1,n),R=(r[n]-k)*(r[n]-k)+e[n]*e[n],a=(f*T-A*I)/R,o.set(n,b,a),o.set(n+1,b,Math.abs(f)>Math.abs(A)?(-I-c*a)/f:(-T-m*a)/A)),a=Math.abs(o.get(n,b)),E*a*a>1)for(i=n;i<=b;i++)o.set(i,b,o.get(i,b)/a)}else if(R<0)for(l=b-1,Math.abs(o.get(b,b-1))>Math.abs(o.get(b-1,b))?(o.set(b-1,b-1,R/o.get(b,b-1)),o.set(b-1,b,-(o.get(b,b)-k)/o.get(b,b-1))):(M=Z(0,-o.get(b-1,b),o.get(b-1,b-1)-k,R),o.set(b-1,b-1,M[0]),o.set(b-1,b,M[1])),o.set(b,b-1,0),o.set(b,b,1),n=b-2;n>=0;n--){for(g=0,w=0,i=l;i<=b;i++)g+=o.get(n,i)*o.get(i,b-1),w+=o.get(n,i)*o.get(i,b);if(c=o.get(n,n)-k,e[n]<0)A=c,I=g,T=w;else if(l=n,0===e[n]?(M=Z(-g,-w,c,R),o.set(n,b-1,M[0]),o.set(n,b,M[1])):(f=o.get(n,n+1),m=o.get(n+1,n),p=(r[n]-k)*(r[n]-k)+e[n]*e[n]-R*R,d=2*(r[n]-k)*R,0===p&&0===d&&(p=E*S*(Math.abs(c)+Math.abs(R)+Math.abs(f)+Math.abs(m)+Math.abs(A))),M=Z(f*I-A*g+R*w,f*T-A*w-R*g,p,d),o.set(n,b-1,M[0]),o.set(n,b,M[1]),Math.abs(f)>Math.abs(A)+Math.abs(R)?(o.set(n+1,b-1,(-g-c*o.get(n,b-1)+R*o.get(n,b))/f),o.set(n+1,b,(-w-c*o.get(n,b)-R*o.get(n,b-1))/f)):(M=Z(-I-m*o.get(n,b-1),-T-m*o.get(n,b),A,R),o.set(n+1,b-1,M[0]),o.set(n+1,b,M[1]))),a=Math.max(Math.abs(o.get(n,b-1)),Math.abs(o.get(n,b))),E*a*a>1)for(i=n;i<=b;i++)o.set(i,b-1,o.get(i,b-1)/a),o.set(i,b,o.get(i,b)/a)}for(n=0;nx)for(i=n;i=0;i--)for(n=0;n<=x;n++){for(A=0,h=0;h<=Math.min(i,x);h++)A+=s.get(n,h)*o.get(h,i);s.set(n,i,A)}}}(n,l,h,i,t)}this.n=n,this.e=l,this.d=h,this.V=i}get realEigenvalues(){return Array.from(this.d)}get imaginaryEigenvalues(){return Array.from(this.e)}get eigenvectorMatrix(){return this.V}get diagonalMatrix(){let t,e,r=this.n,s=this.e,o=this.d,n=new k(r,r);for(t=0;t0?n.set(t,t+1,s[t]):s[t]<0&&n.set(t,t-1,s[t])}return n}}function Z(t,e,r,s){let o,n;return Math.abs(r)>Math.abs(s)?(o=s/r,n=r+o*s,[(t+o*e)/n,(e-o*t)/n]):(o=r/s,n=s+o*r,[(o*t+e)/n,(o*e-t)/n])}class tt{constructor(t){if(!(t=F.checkMatrix(t)).isSymmetric())throw new Error("Matrix is not symmetric");let e,r,s,o=t,n=o.rows,i=new k(n,n),h=!0;for(r=0;r0,i.set(r,r,Math.sqrt(Math.max(t,0))),s=r+1;s=0;n--)for(o=0;on;e++)u=t.transpose().mmul(i).div(i.transpose().mmul(i).get(0,0)),u=u.div(u.norm()),h=t.mmul(u).div(u.transpose().mmul(u).get(0,0)),e>0&&(c=h.clone().sub(a).pow(2).sum()),a=h.clone(),r?(l=r.transpose().mmul(h).div(h.transpose().mmul(h).get(0,0)),l=l.div(l.norm()),i=r.mmul(l).div(l.transpose().mmul(l).get(0,0))):i=h;if(r){let e=t.transpose().mmul(h).div(h.transpose().mmul(h).get(0,0));e=e.div(e.norm());let s=t.clone().sub(h.clone().mmul(e.transpose())),o=i.transpose().mmul(h).div(h.transpose().mmul(h).get(0,0)),n=r.clone().sub(h.clone().mulS(o.get(0,0)).mmul(l.transpose()));this.t=h,this.p=e.transpose(),this.w=u.transpose(),this.q=l,this.u=i,this.s=h.transpose().mmul(h),this.xResidual=s,this.yResidual=n,this.betas=o}else this.w=u.transpose(),this.s=h.transpose().mmul(h).sqrt(),this.t=s?h.clone().div(this.s.get(0,0)):h,this.xResidual=t.sub(h.mmul(u.transpose()))}}},842:(t,e,r)=>{"use strict";r.d(e,{Z:()=>s});class s{constructor(t=[],e=o){if(this.data=t,this.length=this.data.length,this.compare=e,this.length>0)for(let t=(this.length>>1)-1;t>=0;t--)this._down(t)}push(t){this.data.push(t),this.length++,this._up(this.length-1)}pop(){if(0===this.length)return;const t=this.data[0],e=this.data.pop();return this.length--,this.length>0&&(this.data[0]=e,this._down(0)),t}peek(){return this.data[0]}_up(t){const{data:e,compare:r}=this,s=e[t];for(;t>0;){const o=t-1>>1,n=e[o];if(r(s,n)>=0)break;e[t]=n,t=o}e[t]=s}_down(t){const{data:e,compare:r}=this,s=this.length>>1,o=e[t];for(;t=0)break;e[t]=n,t=s}e[t]=o}}function o(t,e){return te?1:0}},902:(t,e,r)=>{const{Matrix:s,inverse:o}=r(331),{solveHomography:n}=r(450);t.exports={estimate:({screenCoords:t,worldCoords:e,projectionTransform:r})=>{const i=n(e.map((t=>[t.x,t.y])),t.map((t=>[t.x,t.y]))),h=new s([[i[0],i[1],i[2]],[i[3],i[4],i[5]],[i[6],i[7],i[8]]]),l=new s(r),u=o(l).mmul(h).to1DArray(),a=Math.sqrt(u[0]*u[0]+u[3]*u[3]+u[6]*u[6]),c=Math.sqrt(u[1]*u[1]+u[4]*u[4]+u[7]*u[7]),f=(a+c)/2,m=[];m[0]=u[0]/a,m[3]=u[3]/a,m[6]=u[6]/a,m[1]=u[1]/c,m[4]=u[4]/c,m[7]=u[7]/c,m[2]=m[3]*m[7]-m[6]*m[4],m[5]=m[6]*m[1]-m[0]*m[7],m[8]=m[0]*m[4]-m[1]*m[3];const g=Math.sqrt(m[2]*m[2]+m[5]*m[5]+m[8]*m[8]);m[2]/=g,m[5]/=g,m[8]/=g;const w=[];return w[0]=u[2]/f,w[1]=u[5]/f,w[2]=u[8]/f,[[m[0],m[1],m[2],w[0]],[m[3],m[4],m[5],w[1]],[m[6],m[7],m[8],w[2]]]}}},421:(t,e,r)=>{const{estimate:s}=r(902),{refineEstimate:o}=r(269);t.exports={Estimator:class{constructor(t){this.projectionTransform=t}estimate({screenCoords:t,worldCoords:e}){return s({screenCoords:t,worldCoords:e,projectionTransform:this.projectionTransform})}refineEstimate({initialModelViewTransform:t,worldCoords:e,screenCoords:r}){return o({initialModelViewTransform:t,worldCoords:e,screenCoords:r,projectionTransform:this.projectionTransform})}}}},269:(t,e,r)=>{const{Matrix:s,inverse:o}=r(331),{normalizePoints:n,applyModelViewProjectionTransform:i,buildModelViewProjectionTransform:h,computeScreenCoordiate:l}=r(420);let u=[[],[],[]],a=[[],[]],c=[[],[],[]];const f=({initialModelViewTransform:t,projectionTransform:e,worldCoords:r,screenCoords:s,inlierProb:o})=>{const n=o<1;let i=t,u=0,a=0,c=new Array(r.length),f=new Array(r.length),p=new Array(r.length),d=new Array(r.length);for(let t=0;t<=10;t++){const y=h(e,i);for(let t=0;tt-e)),M=Math.max(4*f[t],16);for(let t=0;tM?a+=M/6:a+=M/6*(1-(1-f[t]/M)*(1-f[t]/M)*(1-f[t]/M))}else for(let t=0;t0&&a/u>.99)break;if(10===t)break;u=a;const b=[],x=[];for(let t=0;tM)continue;const s=w({modelViewProjectionTransform:y,modelViewTransform:i,projectionTransform:e,worldCoord:r[t]});if(n){const e=(1-c[t]/M)*(1-c[t]/M);for(let t=0;t<2;t++)for(let r=0;r<6;r++)s[t][r]*=e;b.push([p[t]*e]),b.push([d[t]*e])}else b.push([p[t]]),b.push([d[t]]);for(let t=0;t{let r,s,o,n=e[0]*e[0]+e[1]*e[1]+e[2]*e[2];n<1e-6?(r=1,s=0,o=0,n=0):(n=Math.sqrt(n),r=e[0]/n,s=e[1]/n,o=e[2]/n);const i=Math.cos(n),h=Math.sin(n),l=1-i;u[0][0]=r*r*l+i,u[0][1]=r*s*l-o*h,u[0][2]=r*o*l+s*h,u[0][3]=e[3],u[1][0]=s*r*l+o*h,u[1][1]=s*s*l+i,u[1][2]=s*o*l-r*h,u[1][3]=e[4],u[2][0]=o*r*l-s*h,u[2][1]=o*s*l+r*h,u[2][2]=o*o*l+i,u[2][3]=e[5];const a=[[],[],[]];for(let e=0;e<3;e++){for(let r=0;r<4;r++)a[e][r]=t[e][0]*u[0][r]+t[e][1]*u[1][r]+t[e][2]*u[2][r];a[e][3]+=t[e][3]}return a},g=({dU:t,J_U_S:e})=>{const r=new s(e),n=new s(t),i=r.transpose(),h=i.mmul(r),l=i.mmul(n);let u;try{u=o(h)}catch(t){return null}return u.mmul(l).to1DArray()},w=({modelViewProjectionTransform:t,modelViewTransform:e,projectionTransform:r,worldCoord:s})=>{const o=e,{x:n,y:h,z:l}=s,u=i(t,n,h,l),f=u.z*u.z;a[0][0]=r[0][0]*u.z/f,a[0][1]=r[0][1]*u.z/f,a[0][2]=(r[0][2]*u.z-r[2][2]*u.x)/f,a[1][0]=r[1][0]*u.z/f,a[1][1]=r[1][1]*u.z/f,a[1][2]=(r[1][2]*u.z-r[2][2]*u.y)/f,c[0][0]=o[0][2]*h,c[0][1]=-o[0][2]*n,c[0][2]=o[0][1]*n-o[0][0]*h,c[0][3]=o[0][0],c[0][4]=o[0][1],c[0][5]=o[0][2],c[1][0]=o[1][2]*h,c[1][1]=-o[1][2]*n,c[1][2]=o[1][1]*n-o[1][0]*h,c[1][3]=o[1][0],c[1][4]=o[1][1],c[1][5]=o[1][2],c[2][0]=o[2][2]*h,c[2][1]=-o[2][2]*n,c[2][2]=o[2][1]*n-o[2][0]*h,c[2][3]=o[2][0],c[2][4]=o[2][1],c[2][5]=o[2][2];const m=[[],[]];for(let t=0;t<2;t++)for(let e=0;e<6;e++){m[t][e]=0;for(let r=0;r<3;r++)m[t][e]+=a[t][r]*c[r][e]}return m};t.exports={refineEstimate:({initialModelViewTransform:t,projectionTransform:e,worldCoords:r,screenCoords:s})=>{let o=0,n=0;for(let t=0;t{const e=(t,e,r,s)=>({x:t[0][0]*e+t[0][1]*r+t[0][3],y:t[1][0]*e+t[1][1]*r+t[1][3],z:t[2][0]*e+t[2][1]*r+t[2][3]});t.exports={buildModelViewProjectionTransform:(t,e)=>[[t[0][0]*e[0][0]+t[0][2]*e[2][0],t[0][0]*e[0][1]+t[0][2]*e[2][1],t[0][0]*e[0][2]+t[0][2]*e[2][2],t[0][0]*e[0][3]+t[0][2]*e[2][3]],[t[1][1]*e[1][0]+t[1][2]*e[2][0],t[1][1]*e[1][1]+t[1][2]*e[2][1],t[1][1]*e[1][2]+t[1][2]*e[2][2],t[1][1]*e[1][3]+t[1][2]*e[2][3]],[e[2][0],e[2][1],e[2][2],e[2][3]]],applyModelViewProjectionTransform:e,computeScreenCoordiate:(t,r,s,o)=>{const{x:n,y:i,z:h}=e(t,r,s);return{x:n/h,y:i/h}}}},233:t=>{t.exports={compute:t=>{const{v1:e,v2:r}=t;let s=0;for(let t=0;t>>0;s+=(n=void 0,((n=((n=((n=((n=(o=i)-(o>>1&1431655765))>>2&858993459)+(858993459&n))>>4)+n&252645135)>>8)+n&16711935)>>16)+n&65535)}var o,n;return s}}},934:t=>{const e=({querypoint:t,keypoint:e,keycenterX:r,keycenterY:s,scaleOneOverLogK:o})=>{let n=t.angle-e.angle;n<=-Math.PI?n+=2*Math.PI:n>Math.PI&&(n-=2*Math.PI);const i=t.scale/e.scale,h=i*Math.cos(n),l=i*Math.sin(n),u=[h,-l,l,h],a=[u[0]*e.x+u[1]*e.y,u[2]*e.x+u[3]*e.y],c=t.x-a[0],f=t.y-a[1];return{x:u[0]*r+u[1]*s+c,y:u[2]*r+u[3]*s+f,angle:n,scale:Math.log(i)*o}};t.exports={computeHoughMatches:t=>{const{keywidth:r,keyheight:s,querywidth:o,queryheight:n,matches:i}=t,h=1.2*o,l=-h,u=1.2*n,a=-u,c=12,f=1/Math.log(10),m=Math.max(r,s),g=Math.floor(r/2),w=Math.floor(s/2),p=[];for(let t=0;tt-e));const d=.25*p[Math.floor(p.length/2)-(p.length%2==0?1:0)-1],y=Math.max(5,Math.ceil((h-l)/d)),M=Math.max(5,Math.ceil((u-a)/d)),b=y*M,x=b*c,E=[],v=[],S={};for(let t=0;t=h||n=u||p<=-Math.PI||p>Math.PI||m<-1||m>=1){E[t]=!1;continue}let d=y*(o-l)/(h-l),k=M*(n-a)/(u-a),R=c*(p+Math.PI)/(2*Math.PI),I=10*(m- -1)/2;v[t]={binX:d,binY:k,binAngle:R,binScale:I};let T=Math.floor(d-.5),A=Math.floor(k-.5),q=Math.floor(I-.5),C=(Math.floor(R-.5)+c)%c;if(T<0||T+1>=y||A<0||A+1>=M||q<0||q+1>=10)E[t]=!1;else{for(let t=0;t<2;t++){let e=T+t;for(let t=0;t<2;t++){let r=A+t;for(let t=0;t<2;t++){let s=(C+t)%c;for(let t=0;t<2;t++){const o=e+r*y+s*b+(q+t)*x;void 0===S[o]&&(S[o]=0),S[o]+=1}}}}E[t]=!0}}let k=0,R=-1;if(Object.keys(S).forEach((t=>{S[t]>k&&(k=S[t],R=t)})),k<3)return[];const I=Math.floor(R%x%b%y),T=Math.floor((R-I)%x%b/y),A=Math.floor((R-I-T*y)%x/b),q=Math.floor((R-I-T*y-A*b)/x),C=[];for(let t=0;t=1)continue;if(Math.abs(e.binY-(T+.5))>=1)continue;if(Math.abs(e.binScale-(q+.5))>=1)continue;const r=Math.abs(e.binAngle-(A+.5));Math.min(r,c-r)>=1||C.push(i[t])}return C}}},582:(t,e,r)=>{const{match:s}=r(492);t.exports={Matcher:class{constructor(t,e,r=!1){this.queryWidth=t,this.queryHeight=e,this.debugMode=r}matchDetection(t,e){let r={frames:[]},o=null;for(let n=0;n{const s=r(842).Z,{compute:o}=r(233),{computeHoughMatches:n}=r(934),{computeHomography:i}=r(838),{multiplyPointHomographyInhomogenous:h,matrixInverse33:l}=r(289),u=({node:t,keypoints:e,querypoint:r,queue:s,keypointIndexes:n,numPop:i})=>{if(t.leaf){for(let e=0;e0){const{node:t,d:o}=s.pop();u({node:t,keypoints:e,querypoint:r,queue:s,keypointIndexes:n,numPop:i+=1})}},a=t=>{const{H:e,matches:r,threshold:s}=t,o=s*s,n=[];for(let t=0;t{let m={};const g=[];for(let r=0;rt.d-e.d));u({node:h,keypoints:i,querypoint:n,queue:a,keypointIndexes:l,numPop:0});let c=-1,f=Number.MAX_SAFE_INTEGER,m=Number.MAX_SAFE_INTEGER;for(let t=0;t[t.keypoint.x,t.keypoint.y])),dstPoints:w.map((t=>[t.querypoint.x,t.querypoint.y])),keyframe:t});if(null===p)return{debugExtra:m};const d=a({H:p,matches:w,threshold:3});if(f&&(m.inlierMatches=d),d.length<6)return{debugExtra:m};const y=l(p,1e-5),M=[];for(let r=0;r100)continue;const r=o({v1:e.descriptors,v2:s.descriptors});r[t.keypoint.x,t.keypoint.y])),dstPoints:b.map((t=>[t.querypoint.x,t.querypoint.y])),keyframe:t});if(null===x)return{debugExtra:m};const E=a({H:x,matches:b,threshold:3});return f&&(m.inlierMatches2=E),{H:x,matches:E,debugExtra:m}}}},838:(t,e,r)=>{const{Matrix:s,inverse:o}=r(331),{createRandomizer:n}=r(48),{quadrilateralConvex:i,matrixInverse33:h,smallestTriangleArea:l,multiplyPointHomographyInhomogenous:u,checkThreePointsConsistent:a,checkFourPointsConsistent:c,determinant:f}=r(289),{solveHomography:m}=r(450),g=({H:t,testPoints:e,keyframe:r})=>{const s=h(t,1e-5);if(null===s)return!1;const o=[];for(let t=0;t{const e=1/t[8],r=[];for(let s=0;s<8;s++)r[s]=t[s]*e;return r[8]=1,r},p=({H:t,srcPoint:e,dstPoint:r,oneOverScale2:s})=>{const o=u(e,t),n=[o[0]-r[0],o[1]-r[1]];return Math.log(1+(n[0]*n[0]+n[1]*n[1])*s)},d=({H:t,testPoints:e})=>{const r=[];for(let s=0;s{const{srcPoints:e,dstPoints:r,keyframe:s,quickMode:o}=t,i=[[0,0],[s.width,0],[s.width,s.height],[0,s.height]];if(e.length<4)return null;const h=Math.min(10,e.length),l=n(),u=[];for(let t=0;t2;t+=x){x=Math.min(h,e.length-t);let s=t+x;for(let o=0;ot.cost-e.cost)),b.splice(-Math.floor((b.length+1)/2))}let E=null;for(let t=0;t{const e=(t,e,r)=>(e[0]-t[0])*(r[1]-t[1])-(e[1]-t[1])*(r[0]-t[0]),r=t=>{const e=t[4]*t[8]-t[5]*t[7],r=t[3]*t[8]-t[5]*t[6],s=t[3]*t[7]-t[4]*t[6];return t[0]*e-t[1]*r+t[2]*s},s=(t,e)=>[t[0]-e[0],t[1]-e[1]],o=(t,e)=>{const r=t[0]*e[1]-t[1]*e[0];return.5*Math.abs(r)};t.exports={matrixInverse33:(t,e)=>{const s=r(t);if(Math.abs(s)<=e)return null;const o=1/s;return[(t[4]*t[8]-t[5]*t[7])*o,(t[2]*t[7]-t[1]*t[8])*o,(t[1]*t[5]-t[2]*t[4])*o,(t[5]*t[6]-t[3]*t[8])*o,(t[0]*t[8]-t[2]*t[6])*o,(t[2]*t[3]-t[0]*t[5])*o,(t[3]*t[7]-t[4]*t[6])*o,(t[1]*t[6]-t[0]*t[7])*o,(t[0]*t[4]-t[1]*t[3])*o]},matrixMul33:(t,e)=>{const r=[];return r[0]=t[0]*e[0]+t[1]*e[3]+t[2]*e[6],r[1]=t[0]*e[1]+t[1]*e[4]+t[2]*e[7],r[2]=t[0]*e[2]+t[1]*e[5]+t[2]*e[8],r[3]=t[3]*e[0]+t[4]*e[3]+t[5]*e[6],r[4]=t[3]*e[1]+t[4]*e[4]+t[5]*e[7],r[5]=t[3]*e[2]+t[4]*e[5]+t[5]*e[8],r[6]=t[6]*e[0]+t[7]*e[3]+t[8]*e[6],r[7]=t[6]*e[1]+t[7]*e[4]+t[8]*e[7],r[8]=t[6]*e[2]+t[7]*e[5]+t[8]*e[8],r},quadrilateralConvex:(t,r,s,o)=>{const n=e(t,r,s)<=0;return e(r,s,o)<=0===n&&e(s,o,t)<=0===n&&e(o,t,r)<=0===n},smallestTriangleArea:(t,e,r,n)=>{const i=s(e,t),h=s(r,t),l=s(n,t),u=s(e,r),a=s(n,r),c=o(i,h),f=o(h,l),m=o(i,l),g=o(u,a);return Math.min(Math.min(Math.min(c,f),m),g)},multiplyPointHomographyInhomogenous:(t,e)=>{const r=e[6]*t[0]+e[7]*t[1]+e[8],s=[];return s[0]=(e[0]*t[0]+e[1]*t[1]+e[2])/r,s[1]=(e[3]*t[0]+e[4]*t[1]+e[5])/r,s},checkThreePointsConsistent:(t,r,s,o,n,i)=>e(t,r,s)>0==e(o,n,i)>0,checkFourPointsConsistent:(t,r,s,o,n,i,h,l)=>e(t,r,s)>0==e(n,i,h)>0&&e(r,s,o)>0==e(i,h,l)>0&&e(s,o,t)>0==e(h,l,n)>0&&e(o,t,r)>0==e(l,n,i)>0,determinant:r}},450:(t,e,r)=>{const{Matrix:s,inverse:o}=r(331),n=t=>{let e=0,r=0;for(let s=0;s{const{normPoints:r,param:i}=n(t),{normPoints:h,param:l}=n(e),u=h.length,a=[],c=[];for(let t=0;t{const s=r.s*r.meanX,o=r.s*r.meanY,n=[t[0]+s*t[6],t[1]+s*t[7],(t[0]+s*t[6])*-e.meanX+(t[1]+s*t[7])*-e.meanY+(t[2]+s)/e.s,t[3]+o*t[6],t[4]+o*t[7],(t[3]+o*t[6])*-e.meanX+(t[4]+o*t[7])*-e.meanY+(t[5]+o)/e.s,r.s*t[6],r.s*t[7],r.s*t[6]*-e.meanX+r.s*t[7]*-e.meanY+r.s/e.s];for(let t=0;t<9;t++)n[t]=n[t]/n[8];return n})(o(n).mmul(h).to1DArray(),i,l)}catch(t){return null}}}},48:t=>{t.exports={createRandomizer:()=>({seed:1234,arrayShuffle(t){const{arr:e,sampleSize:r}=t;for(let t=0;t>16&32767;r%=e.length;let s=e[t];e[t]=e[r],e[r]=s}},nextInt(t){this.seed=(214013*this.seed+2531011)%(1<<31);let e=this.seed>>16&32767;return e%=t,e}})}}},e={};function r(s){if(e[s])return e[s].exports;var o=e[s]={exports:{}};return t[s](o,o.exports,r),o.exports}r.d=(t,e)=>{for(var s in e)r.o(e,s)&&!r.o(t,s)&&Object.defineProperty(t,s,{enumerable:!0,get:e[s]})},r.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},(()=>{const{Matcher:t}=r(582),{Estimator:e}=r(421);let s=null,o=null,n=!1,i=null,h=null;onmessage=r=>{const{data:l}=r;if("setup"===l.type)s=l.projectionTransform,o=l.matchingDataList,n=l.debugMode,i=new t(l.inputWidth,l.inputHeight,n),h=new e(l.projectionTransform);else if("match"===l.type){const t=l.targetIndexes;let e=-1,r=null,s=null;for(let n=0;n{"use strict";var t=window.URL||window.webkitURL;e.exports=function(e,n){try{try{var r;try{(r=new(window.BlobBuilder||window.WebKitBlobBuilder||window.MozBlobBuilder||window.MSBlobBuilder)).append(e),r=r.getBlob()}catch(t){r=new Blob([e])}return new Worker(t.createObjectURL(r))}catch(t){return new Worker("data:application/javascript,"+encodeURIComponent(e))}}catch(e){if(!n)throw Error("Inline worker is not supported");return new Worker(n)}}},5217:(e,t,n)=>{const r=n(383),{Detector:s}=n(6416),{buildImageList:a,buildTrackingImageList:i}=n(7508),{build:o}=n(723),l=n(1113),u=n(4563),c=async(e,t)=>{const n=[];for(let r=0;r{const e=u.tensor(a.data,[a.data.length],"float32").reshape([a.height,a.width]),{featurePoints:s}=i.detect(e),l=s.filter((e=>e.maxima)),c=s.filter((e=>!e.maxima)),h=o({points:l}),p=o({points:c});n.push({maximaPoints:l,minimaPoints:c,maximaPointsCluster:h,minimaPointsCluster:p,width:a.width,height:a.height,scale:a.scale}),t(r)}))}return n};e.exports={Compiler:class{constructor(){this.data=null}compileImageTargets(e,t){return new Promise((async(n,s)=>{const o=[];for(let t=0;t{u+=s,t(u)}));this.data.push({targetImage:n,imageList:r,matchingData:i})}for(let e=0;e{const s=new r;s.onmessage=n=>{"progress"===n.data.type?t(50+n.data.percent):"compileDone"===n.data.type&&e(n.data.list)},s.postMessage({type:"compile",targetImages:o})}));for(let e=0;e{const r=n(4563),s=n(1077),{Tracker:a}=n(6417),{CropDetector:i}=n(7051),{Compiler:o}=n(5217),{InputLoader:l}=n(7325),{OneEuroFilter:u}=n(344);e.exports={Controller:class{constructor({inputWidth:e,inputHeight:t,onUpdate:n=null,debugMode:r=!1,maxTrack:a=1,warmupTolerance:o=null,missTolerance:u=null,filterMinCF:c=null,filterBeta:h=null}){this.inputWidth=e,this.inputHeight=t,this.maxTrack=a,this.filterMinCF=null===c?.001:c,this.filterBeta=null===h?1e3:h,this.warmupTolerance=null===o?5:o,this.missTolerance=null===u?5:u,this.cropDetector=new i(this.inputWidth,this.inputHeight,r),this.inputLoader=new l(this.inputWidth,this.inputHeight),this.markerDimensions=null,this.onUpdate=n,this.debugMode=r,this.processingVideo=!1,this.interestedTargetIndex=-1,this.trackingStates=[];const p=45*Math.PI/180,d=this.inputHeight/2/Math.tan(p/2);this.projectionTransform=[[d,0,this.inputWidth/2],[0,d,this.inputHeight/2],[0,0,1]],this.projectionMatrix=this._glProjectionMatrix({projectionTransform:this.projectionTransform,width:this.inputWidth,height:this.inputHeight,near:10,far:1e5}),this.worker=new s,this.workerMatchDone=null,this.workerTrackDone=null,this.worker.onmessage=e=>{"matchDone"===e.data.type&&null!==this.workerMatchDone&&this.workerMatchDone(e.data),"trackUpdateDone"===e.data.type&&null!==this.workerTrackDone&&this.workerTrackDone(e.data)}}showTFStats(){console.log(r.memory().numTensors),console.table(r.memory())}addImageTargets(e){return new Promise((async(t,n)=>{const r=await fetch(e),s=await r.arrayBuffer();t(this.addImageTargetsFromBuffer(s))}))}addImageTargetsFromBuffer(e){const t=(new o).importData(e),n=[],r=[],s=[];for(let e=0;e{for(;this.processingVideo;){const t=this.inputLoader.loadInput(e);if(this.trackingStates.reduce(((e,t)=>e+(t.isTracking?1:0)),0)this.warmupTolerance&&(n.showing=!0,n.trackingMatrix=null,n.filter.reset())),n.showing&&(n.isTracking?n.trackMiss=0:(n.trackCount=0,n.trackMiss+=1,n.trackMiss>this.missTolerance&&(n.showing=!1,n.trackingMatrix=null,this.onUpdate&&this.onUpdate({type:"updateMatrix",targetIndex:e,worldMatrix:null})))),n.showing){const t=this._glModelViewMatrix(n.currentModelViewTransform,e);n.trackingMatrix=n.filter.filter(Date.now(),t);const r=[];for(let e=0;e{this.workerMatchDone=e=>{n({targetIndex:e.targetIndex,modelViewTransform:e.modelViewTransform,debugExtra:e.debugExtra})},this.worker.postMessage({type:"match",featurePoints:e,targetIndexes:t})}))}_workerTrackUpdate(e,t){return new Promise((async(n,r)=>{this.workerTrackDone=e=>{n(e.modelViewTransform)};const{worldCoords:s,screenCoords:a}=t;this.worker.postMessage({type:"trackUpdate",modelViewTransform:e,worldCoords:s,screenCoords:a})}))}_glModelViewMatrix(e,t){const n=this.markerDimensions[t][1];return[e[0][0],-e[1][0],-e[2][0],0,-e[0][1],e[1][1],e[2][1],0,-e[0][2],e[1][2],e[2][2],0,e[0][1]*n+e[0][3],-(e[1][1]*n+e[1][3]),-(e[2][1]*n+e[2][3]),1]}_glProjectionMatrix({projectionTransform:e,width:t,height:n,near:r,far:s}){const a=[[2*e[0][0]/t,0,-(2*e[0][2]/t-1),0],[0,2*e[1][1]/n,-(2*e[1][2]/n-1),0],[0,0,-(s+r)/(s-r),-2*s*r/(s-r)],[0,0,-1,0]],i=[];for(let e=0;e<4;e++)for(let t=0;t<4;t++)i.push(a[t][e]);return i}}}},7051:(e,t,n)=>{n(4563);const{Detector:r}=n(6416),{buildModelViewProjectionTransform:s,computeScreenCoordiate:a}=n(7420);e.exports={CropDetector:class{constructor(e,t,n=!1){this.debugMode=n,this.width=e,this.height=t;let s=Math.min(e,t)/2,a=Math.pow(2,Math.round(Math.log(s)/Math.log(2)));this.cropSize=a,this.detector=new r(a,a,n),this.kernelCaches={},this.lastRandomIndex=4}detect(e){const t=Math.floor(this.height/2-this.cropSize/2),n=Math.floor(this.width/2-this.cropSize/2),r=this._detect(e,n,t);return this.debugMode&&(r.debugExtra.crop={startX:n,startY:t,cropSize:this.cropSize}),r}detectMoving(e){const t=this.lastRandomIndex%3,n=Math.floor(this.lastRandomIndex/3);let r=Math.floor(this.height/2-this.cropSize+n*this.cropSize/2),s=Math.floor(this.width/2-this.cropSize+t*this.cropSize/2);return s<0&&(s=0),r<0&&(r=0),s>=this.width-this.cropSize&&(s=this.width-this.cropSize-1),r>=this.height-this.cropSize&&(r=this.height-this.cropSize-1),this.lastRandomIndex=(this.lastRandomIndex+1)%9,this._detect(e,s,r)}_detect(e,t,n){const r=e.slice([n,t],[this.cropSize,this.cropSize]),{featurePoints:s,debugExtra:a}=this.detector.detect(r);return s.forEach((e=>{e.x+=t,e.y+=n})),this.debugMode&&(a.projectedImage=r.arraySync()),r.dispose(),{featurePoints:s,debugExtra:a}}}}},6416:(e,t,n)=>{const r=n(4563),{FREAKPOINTS:s}=n(2793),a=(s.length-1)*s.length/2;e.exports={Detector:class{constructor(e,t,n=!1){this.debugMode=n,this.width=e,this.height=t;let r=0;for(;e>=8&&t>=8&&(e/=2,t/=2,r++,5!==r););this.numOctaves=r,this.tensorCaches={},this.kernelCaches={}}detectImageData(e){const t=new Uint8ClampedArray(4*e.length);for(let n=0;ne.map((e=>e.arraySync())))),dogPyramidImages:r.map((e=>e?e.arraySync():null)),extremasResults:s.map((e=>e.arraySync())),extremaAngles:u.arraySync(),prunedExtremas:a,localizedExtremas:i.arraySync()}),n.forEach((e=>e.forEach((e=>e.dispose())))),r.forEach((e=>e&&e.dispose())),s.forEach((e=>e.dispose())),i.dispose(),o.dispose(),l.dispose(),u.dispose(),c.dispose(),h.dispose();const m=[];for(let e=0;e0,x:s,y:a,scale:i,angle:d[e],descriptors:t})}return{featurePoints:m,debugExtra:t}}_computeFreakDescriptors(e){if(!this.tensorCaches.computeFreakDescriptors){const t=[],n=[];for(let r=0;r= ${a}) {\n\t\tcontinue;\n\t }\n\n\t int p1 = int(getP(descIndex + i, 0));\n\t int p2 = int(getP(descIndex + i, 1));\n\n\t float v1 = getFreak(featureIndex, p1);\n\t float v2 = getFreak(featureIndex, p2);\n\n\t if (v1 < v2 + 0.01) {\n\t sum += int(pow(2.0, float(7 - i)));\n\t }\n\t }\n\t setOutput(float(sum));\n\t }\n\t`};this.kernelCaches.computeFreakDescriptors=[t]}return r.tidy((()=>{const[n]=this.kernelCaches.computeFreakDescriptors;return this._runWebGLProgram(n,[e,t],"int32")}))}_computeExtremaFreak(e,t,n){this.tensorCaches._computeExtremaFreak||r.tidy((()=>{const e=r.tensor(s);this.tensorCaches._computeExtremaFreak={freakPointsT:r.keep(e)}}));const{freakPointsT:a}=this.tensorCaches._computeExtremaFreak,i=[];for(let t=1;t{const[e]=this.kernelCaches._computeExtremaFreak;return this._compileAndRun(e,[...i,t,n,a])}))}_computeExtremaAngles(e){if(!this.kernelCaches.computeExtremaAngles){const t={variableNames:["histogram"],outputShape:[e.shape[0]],userCode:`\n\t void main() {\n\t int featureIndex = getOutputCoords();\n\n\t int maxIndex = 0;\n\t for (int i = 1; i < 36; i++) {\n\t if (getHistogram(featureIndex, i) > getHistogram(featureIndex, maxIndex)) {\n\t\tmaxIndex = i;\n\t }\n\t }\n\n\t int prev = imod(maxIndex - 1 + 36, 36);\n\t int next = imod(maxIndex + 1, 36);\n\n\t /**\n\t * Fit a quatratic to 3 points. The system of equations is:\n\t *\n\t * y0 = A*x0^2 + B*x0 + C\n\t * y1 = A*x1^2 + B*x1 + C\n\t * y2 = A*x2^2 + B*x2 + C\n\t *\n\t * This system of equations is solved for A,B,C.\n\t */\n\t float p10 = float(maxIndex - 1);\n\t float p11 = getHistogram(featureIndex, prev); \n\t float p20 = float(maxIndex);\n\t float p21 = getHistogram(featureIndex, maxIndex); \n\t float p30 = float(maxIndex + 1);\n\t float p31 = getHistogram(featureIndex, next); \n\n\t float d1 = (p30-p20)*(p30-p10);\n\t float d2 = (p10-p20)*(p30-p10);\n\t float d3 = p10-p20;\n\n\t // If any of the denominators are zero then, just use maxIndex.\n float fbin = float(maxIndex);\n\t if ( abs(d1) > 0.00001 && abs(d2) > 0.00001 && abs(d3) > 0.00001) {\n\t float a = p10*p10;\n\t float b = p20*p20;\n\n\t // Solve for the coefficients A,B,C\n\t float A = ((p31-p21)/d1)-((p11-p21)/d2);\n\t float B = ((p11-p21)+(A*(b-a)))/d3;\n\t float C = p11-(A*a)-(B*p10);\n\t fbin = -B / (2. * A);\n\t }\n\n\t float an = 2.0 *${Math.PI} * (fbin + 0.5) / 36. - ${Math.PI};\n\t setOutput(an);\n\t }\n\t`};this.kernelCaches.computeExtremaAngles=t}return r.tidy((()=>{const t=this.kernelCaches.computeExtremaAngles;return this._compileAndRun(t,[e])}))}_computeOrientationHistograms(e,t){const n=[];for(let e=1;e{const e=Math.ceil(4.5),t=[];for(let n=-e;n<=e;n++)for(let r=-e;r<=e;r++){const e=r*r+n*n;if(e<=20.25){const s=-.05555555555555555*e;let a=.0013888888*(720+s*(720+s*(360+s*(120+s*(30+s*(6+s))))));t.push([n,r,a])}}this.tensorCaches.orientationHistograms={radialPropertiesT:r.keep(r.tensor(t,[t.length,3]))}}));const{radialPropertiesT:s}=this.tensorCaches.orientationHistograms;if(!this.kernelCaches.computeOrientationHistograms){const n=[];for(let e=1;e{const[t,r]=this.kernelCaches.computeOrientationHistograms,a=this._compileAndRun(t,[...n,e,s]);return this._compileAndRun(r,[a])}))}_smoothHistograms(e){if(!this.kernelCaches.smoothHistograms){const t={variableNames:["histogram"],outputShape:[e.shape[0],36],userCode:"\n\t void main() {\n\t ivec2 coords = getOutputCoords();\n\n\t int featureIndex = coords[0];\n\t int binIndex = coords[1];\n\n\t int prevBin = imod(binIndex - 1 + 36, 36);\n\t int nextBin = imod(binIndex + 1, 36);\n\n float result = 0.274068619061197 * getHistogram(featureIndex, prevBin) + 0.451862761877606 * getHistogram(featureIndex, binIndex) + 0.274068619061197 * getHistogram(featureIndex, nextBin);\n\n\t setOutput(result);\n\t }\n\t"};this.kernelCaches.smoothHistograms=t}return r.tidy((()=>{const t=this.kernelCaches.smoothHistograms;for(let n=0;n<5;n++)e=this._compileAndRun(t,[e]);return e}))}_computeLocalization(e,t){if(!this.kernelCaches.computeLocalization){const n=[];let r="float getPixel(int octave, int y, int x) {";for(let e=1;e{const n=this.kernelCaches.computeLocalization[0],s=r.tensor(e,[e.length,e[0].length],"int32"),a=this._compileAndRun(n,[...t.slice(1),s]).arraySync(),i=[];for(let e=0;e{const{reductionKernels:r}=this.kernelCaches.applyPrune;for(let s=0;s=1&&m>t[f][g-1];)g-=1;if(g<5){for(let e=4;e>=g+1;e--)t[f][e]=t[f][e-1],n[f][e][0]=n[f][e-1][0],n[f][e][1]=n[f][e-1][1],n[f][e][2]=n[f][e-1][2],n[f][e][3]=n[f][e-1][3];t[f][g]=m,n[f][g][0]=a,n[f][g][1]=o,n[f][g][2]=c,n[f][g][3]=u}}}}));const s=[];for(let e=0;e<100;e++)for(let t=0;t<5;t++)s.push(n[e][t]);return s}_buildExtremas(e,t,n){const s=t.shape[0],a=t.shape[1],i="w"+a;if(this.kernelCaches.buildExtremas||(this.kernelCaches.buildExtremas={}),!this.kernelCaches.buildExtremas[i]){const e={variableNames:["image0","image1","image2"],outputShape:[s,a],userCode:`\n\t void main() {\n\t ivec2 coords = getOutputCoords();\n\n\t int y = coords[0];\n\t int x = coords[1];\n\n\t float value = getImage1(y, x);\n\n\t // Step 1: find local maxima/minima\n\t if (value * value < 9.) {\n\t setOutput(0.);\n\t return;\n\t }\n\t if (y < 7 || y > ${s-1-7}) {\n\t setOutput(0.);\n\t return;\n\t }\n\t if (x < 7 || x > ${a-1-7}) {\n\t setOutput(0.);\n\t return;\n\t }\n\n\t bool isMax = true;\n\t bool isMin = true;\n\t for (int dy = -1; dy <= 1; dy++) {\n\t for (int dx = -1; dx <= 1; dx++) {\n\t float value0 = getImage0(y+dy, x+dx);\n\t float value1 = getImage1(y+dy, x+dx);\n\t float value2 = getImage2(y+dy, x+dx);\n\n\t\tif (value < value0 || value < value1 || value < value2) {\n\t\t isMax = false;\n\t\t}\n\t\tif (value > value0 || value > value1 || value > value2) {\n\t\t isMin = false;\n\t\t}\n\t }\n\t }\n\n\t if (!isMax && !isMin) {\n\t setOutput(0.);\n\t return;\n\t }\n\n\t // compute edge score and reject based on threshold\n\t float dxx = getImage1(y, x+1) + getImage1(y, x-1) - 2. * getImage1(y, x);\n\t float dyy = getImage1(y+1, x) + getImage1(y-1, x) - 2. * getImage1(y, x);\n\t float dxy = 0.25 * (getImage1(y-1,x-1) + getImage1(y+1,x+1) - getImage1(y-1,x+1) - getImage1(y+1,x-1));\n\n\t float det = (dxx * dyy) - (dxy * dxy);\n\n\t if (abs(det) < 0.0001) { // determinant undefined. no solution\n\t setOutput(0.);\n\t return;\n\t }\n\n\t float edgeScore = (dxx + dyy) * (dxx + dyy) / det;\n\n\t if (abs(edgeScore) >= 6.25 ) {\n\t setOutput(0.);\n\t return;\n\t }\n\t setOutput(getImage1(y,x));\n\t }\n\t`};this.kernelCaches.buildExtremas[i]=e}return r.tidy((()=>{const r=this.kernelCaches.buildExtremas[i];return e=this._downsampleBilinear(e),n=this._upsampleBilinear(n,t),this._compileAndRun(r,[e,t,n])}))}_differenceImageBinomial(e,t){return r.tidy((()=>e.sub(t)))}_applyFilter(e){const t=e.shape[0],n=e.shape[1],s="w"+n;if(this.kernelCaches.applyFilter||(this.kernelCaches.applyFilter={}),!this.kernelCaches.applyFilter[s]){const e={variableNames:["p"],outputShape:[t,n],userCode:"\n\t void main() {\n\t ivec2 coords = getOutputCoords();\n\n\t float sum = getP(coords[0], coords[1]-2);\n\t sum += getP(coords[0], coords[1]-1) * 4.;\n\t sum += getP(coords[0], coords[1]) * 6.;\n\t sum += getP(coords[0], coords[1]+1) * 4.;\n\t sum += getP(coords[0], coords[1]+2);\n\t setOutput(sum);\n\t }\n\t"},r={variableNames:["p"],outputShape:[t,n],userCode:"\n\t void main() {\n\t ivec2 coords = getOutputCoords();\n\n\t float sum = getP(coords[0]-2, coords[1]);\n\t sum += getP(coords[0]-1, coords[1]) * 4.;\n\t sum += getP(coords[0], coords[1]) * 6.;\n\t sum += getP(coords[0]+1, coords[1]) * 4.;\n\t sum += getP(coords[0]+2, coords[1]);\n\t sum /= 256.;\n\t setOutput(sum);\n\t }\n\t"};this.kernelCaches.applyFilter[s]=[e,r]}return r.tidy((()=>{const[t,n]=this.kernelCaches.applyFilter[s],r=this._compileAndRun(t,[e]);return this._compileAndRun(n,[r])}))}_upsampleBilinear(e,t){e.shape[0];const n="w"+e.shape[1];if(this.kernelCaches.upsampleBilinear||(this.kernelCaches.upsampleBilinear={}),!this.kernelCaches.upsampleBilinear[n]){const e={variableNames:["p"],outputShape:[t.shape[0],t.shape[1]],userCode:"\n\t void main() {\n\t ivec2 coords = getOutputCoords();\n\t int j = coords[0];\n\t int i = coords[1];\n\n\t float sj = 0.5 * float(j) - 0.25; \n\t float si = 0.5 * float(i) - 0.25;\n\n\t float sj0 = floor(sj);\n\t float sj1 = ceil(sj);\n\t float si0 = floor(si);\n\t float si1 = ceil(si);\n\n\t int sj0I = int(sj0);\n\t int sj1I = int(sj1);\n\t int si0I = int(si0);\n\t int si1I = int(si1);\n\n\t float sum = 0.0;\n\t sum += getP(sj0I, si0I) * (si1 - si) * (sj1 - sj);\n\t sum += getP(sj1I, si0I) * (si1 - si) * (sj - sj0);\n\t sum += getP(sj0I, si1I) * (si - si0) * (sj1 - sj);\n\t sum += getP(sj1I, si1I) * (si - si0) * (sj - sj0);\n\t setOutput(sum);\n\t }\n\t"};this.kernelCaches.upsampleBilinear[n]=e}return r.tidy((()=>{const t=this.kernelCaches.upsampleBilinear[n];return this._compileAndRun(t,[e])}))}_downsampleBilinear(e){const t=e.shape[0],n=e.shape[1],s="w"+n;if(this.kernelCaches.downsampleBilinear||(this.kernelCaches.downsampleBilinear={}),!this.kernelCaches.downsampleBilinear[s]){const e={variableNames:["p"],outputShape:[Math.floor(t/2),Math.floor(n/2)],userCode:"\n\t void main() {\n\t ivec2 coords = getOutputCoords();\n\t int y = coords[0] * 2;\n\t int x = coords[1] * 2;\n\n\t float sum = getP(y, x) * 0.25;\n\t sum += getP(y+1,x) * 0.25; \n\t sum += getP(y, x+1) * 0.25; \n\t sum += getP(y+1,x+1) * 0.25;\n\t setOutput(sum);\n\t }\n\t"};this.kernelCaches.downsampleBilinear[s]=e}return r.tidy((()=>{const t=this.kernelCaches.downsampleBilinear[s];return this._compileAndRun(t,[e])}))}_compileAndRun(e,t){const n=r.backend().compileAndRun(e,t);return r.engine().makeTensorFromDataId(n.dataId,n.shape,n.dtype)}_runWebGLProgram(e,t,n){const s=r.backend().runWebGLProgram(e,t,n);return r.engine().makeTensorFromDataId(s.dataId,s.shape,s.dtype)}}}},2793:e=>{const t=[{sigma:.55,points:[[-1,0],[-.5,-.866025],[.5,-.866025],[1,-0],[.5,.866025],[-.5,.866025]]},{sigma:.475,points:[[0,.930969],[-.806243,.465485],[-.806243,-.465485],[-0,-.930969],[.806243,-.465485],[.806243,.465485]]},{sigma:.4,points:[[.847306,-0],[.423653,.733789],[-.423653,.733789],[-.847306,0],[-.423653,-.733789],[.423653,-.733789]]},{sigma:.325,points:[[-0,-.741094],[.641806,-.370547],[.641806,.370547],[0,.741094],[-.641806,.370547],[-.641806,-.370547]]},{sigma:.25,points:[[-.595502,0],[-.297751,-.51572],[.297751,-.51572],[.595502,-0],[.297751,.51572],[-.297751,.51572]]},{sigma:.175,points:[[0,.362783],[-.314179,.181391],[-.314179,-.181391],[-0,-.362783],[.314179,-.181391],[.314179,.181391]]},{sigma:.1,points:[[0,0]]}],n=[];for(let e=0;e{const t=(e,t,n,r)=>({x:e[0][0]*t+e[0][1]*n+e[0][3],y:e[1][0]*t+e[1][1]*n+e[1][3],z:e[2][0]*t+e[2][1]*n+e[2][3]});e.exports={buildModelViewProjectionTransform:(e,t)=>[[e[0][0]*t[0][0]+e[0][2]*t[2][0],e[0][0]*t[0][1]+e[0][2]*t[2][1],e[0][0]*t[0][2]+e[0][2]*t[2][2],e[0][0]*t[0][3]+e[0][2]*t[2][3]],[e[1][1]*t[1][0]+e[1][2]*t[2][0],e[1][1]*t[1][1]+e[1][2]*t[2][1],e[1][1]*t[1][2]+e[1][2]*t[2][2],e[1][1]*t[1][3]+e[1][2]*t[2][3]],[t[2][0],t[2][1],t[2][2],t[2][3]]],applyModelViewProjectionTransform:t,computeScreenCoordiate:(e,n,r,s)=>{const{x:a,y:i,z:o}=t(e,n,r);return{x:a/o,y:i/o}}}},7508:(e,t,n)=>{const{resize:r}=n(9140);e.exports={buildImageList:e=>{const t=[];let n=100/Math.min(e.width,e.height);for(;;)if(t.push(n),n*=Math.pow(2,1/3),n>=.95){n=1;break}t.push(n),t.reverse();const s=[];for(let n=0;n{const t=Math.min(e.width,e.height),n=[],s=[];n.push(256/t),n.push(128/t);for(let t=0;t{const{Controller:r}=n(7957),{Compiler:s}=n(5217),{UI:a}=n(2749),i={Controller:r,Compiler:s,UI:a};window.MINDAR||(window.MINDAR={}),window.MINDAR.IMAGE=i,e.exports=i},7325:(e,t,n)=>{const r=n(4563);e.exports={InputLoader:class{constructor(e,t){this.width=e,this.height=t,this.texShape=[t,e];const n=document.createElement("canvas").getContext("2d");n.canvas.width=e,n.canvas.height=t,this.context=n,this.program=this.buildProgram(e,t);const s=r.backend();this.tempPixelHandle=s.makeTensorInfo(this.texShape,"float32"),s.texData.get(this.tempPixelHandle.dataId).usage=2}_loadInput(e){return r.tidy((()=>{let t=r.browser.fromPixels(e);return t=t.mean(2),t}))}loadInput(e){this.context.drawImage(e,0,0,this.width,this.height);const t=r.backend();return t.gpgpu.uploadPixelDataToTexture(t.getTexture(this.tempPixelHandle.dataId),this.context.canvas),this._compileAndRun(this.program,[this.tempPixelHandle])}buildProgram(e,t){const n=2===r.env().getNumber("WEBGL_VERSION")?"texture":"texture2D";return{variableNames:["A"],outputShape:this.texShape,userCode:`\n\tvoid main() {\n\t ivec2 coords = getOutputCoords();\n\t int texR = coords[0];\n\t int texC = coords[1];\n\t vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${e}.0, ${t}.0);\n\n\t vec4 values = ${n}(A, uv);\n\t setOutput((0.299 * values.r + 0.587 * values.g + 0.114 * values.b) * 255.0);\n\t}\n `}}_compileAndRun(e,t){const n=r.backend().compileAndRun(e,t);return r.engine().makeTensorFromDataId(n.dataId,n.shape,n.dtype)}_runWebGLProgram(e,t,n){const s=r.backend().runWebGLProgram(e,t,n);return r.engine().makeTensorFromDataId(s.dataId,s.shape,s.dtype)}}}},2233:e=>{e.exports={compute:e=>{const{v1:t,v2:n}=e;let r=0;for(let e=0;e>>0;r+=(a=void 0,((a=((a=((a=((a=(s=i)-(s>>1&1431655765))>>2&858993459)+(858993459&a))>>4)+a&252645135)>>8)+a&16711935)>>16)+a&65535)}var s,a;return r}}},723:(e,t,n)=>{const{compute:r}=n(2233),{createRandomizer:s}=n(6048),a=e=>{const{points:t,pointIndexes:n,centerPointIndex:s,randomizer:i}=e;let o=!1;(n.length<=8||n.length<=16)&&(o=!0);const l={};if(!o){const e=(e=>{const{points:t,pointIndexes:n,randomizer:s}=e,a=[];for(let e=0;e{u.children.push(a({points:t,pointIndexes:l[e],centerPointIndex:e,randomizer:i}))})),u};e.exports={build:({points:e})=>{const t=[];for(let n=0;n{const r=n(4563),{buildModelViewProjectionTransform:s,computeScreenCoordiate:a}=n(7420);e.exports={Tracker:class{constructor(e,t,n,r,s,a=!1){this.markerDimensions=e,this.trackingDataList=t,this.projectionTransform=n,this.debugMode=a,this.trackingKeyframeList=[];for(let e=0;e.8&&e= (${i} - 6) || sy < 6 || sy >= (${a} - 6)) {\n\t setOutput(-2.);\n\t } \n\t else {\n\t float sumPoint = 0.;\n\t float sumPointSquare = 0.;\n\t float sumTemplate = 0.;\n\t float sumTemplateSquare = 0.;\n\t float sumPointTemplate = 0.;\n\n\t for (int templateOffsetY = 0; templateOffsetY < 13; templateOffsetY++) {\n\t\tfor (int templateOffsetX = 0; templateOffsetX < 13; templateOffsetX++) {\n\t\t int fx2 = sCenterX + templateOffsetX - 6;\n\t\t int fy2 = sCenterY + templateOffsetY - 6;\n\n\t\t int sx2 = sx + templateOffsetX - 6;\n\t\t int sy2 = sy + templateOffsetY - 6;\n\n\t\t int markerPixelIndex = fy2 * markerWidth + fx2;\n\t\t float markerPixel = getMarkerPixels(markerPixelIndex);\n\t\t float targetPixel = getTargetPixels(sy2, sx2);\n\n\t\t sumTemplate += markerPixel;\n\t\t sumTemplateSquare += markerPixel * markerPixel;\n\t\t sumPoint += targetPixel;\n\t\t sumPointSquare += targetPixel * targetPixel;\n\t\t sumPointTemplate += targetPixel * markerPixel;\n\t\t}\n\t }\n\n\t // Normalized cross-correlation\n\t // !important divide first avoid overflow (e.g. sumPoint / count * sumPoint)\n\t float count = float(13 * 13);\n\t float pointVariance = sqrt(sumPointSquare - sumPoint / count * sumPoint);\n\t float templateVariance = sqrt(sumTemplateSquare - sumTemplate / count * sumTemplate);\n\n\t if (pointVariance < 0.0000001) {\n\t\tsetOutput(-3.);\n\t } else if (templateVariance < 0.0000001) {\n\t\t//setOutput(sumTemplate);\n\t\tsetOutput(-4.);\n\t } else {\n\t\tsumPointTemplate -= sumPoint / count * sumTemplate;\n\t\tfloat sim = sumPointTemplate / pointVariance / templateVariance; \n\t\tsetOutput(sim);\n\t }\n\t }\n\t }\n\t`},t={variableNames:["featurePoints","markerProperties","maxIndex"],outputShape:[o,2],userCode:"\n\t void main() {\n\t ivec2 coords = getOutputCoords();\n\n\t float markerScale = getMarkerProperties(2);\n\n\t int featureIndex = coords[0];\n\n\t int maxIndex = int(getMaxIndex(featureIndex));\n\t int searchLocationIndex = maxIndex / 441;\n\t int searchOffsetIndex = imod(maxIndex, 441);\n\n\t if (coords[1] == 0) {\n\t int searchOffsetX = imod(searchOffsetIndex, 21) * 1;\n\t setOutput(getFeaturePoints(featureIndex, 0) + float(searchOffsetX - 10) / markerScale);\n\t }\n\t else if (coords[1] == 1) {\n\t int searchOffsetY = searchOffsetIndex / 21 * 1;\n\t setOutput(getFeaturePoints(featureIndex, 1) + float(searchOffsetY - 10) / markerScale);\n\t }\n\t }\n\t"},n={variableNames:["sims","maxIndex"],outputShape:[o],userCode:"\n\t void main() {\n\t int featureIndex = getOutputCoords();\n\t int maxIndex = int(getMaxIndex(featureIndex));\n\t setOutput(getSims(featureIndex, maxIndex));\n\t }\n\t"};this.kernelCaches.computeMatching=[e,t,n]}return r.tidy((()=>{const r=this.kernelCaches.computeMatching,a=this._compileAndRun(r[0],[e,t,n,s]),i=a.argMax(1);return{matchingPointsT:this._compileAndRun(r[1],[e,n,i]),simT:this._compileAndRun(r[2],[a,i])}}))}_computeProjection(e,t,n){const s=this.trackingKeyframeList[n].width,a=this.trackingKeyframeList[n].height,i=this.trackingKeyframeList[n].scale,o=s+"-"+a+"-"+i;if(this.kernelCaches.computeProjection||(this.kernelCaches.computeProjection={}),!this.kernelCaches.computeProjection[o]){const e={variableNames:["M","pixel"],outputShape:[a,s],userCode:`\n\t void main() {\n\t ivec2 coords = getOutputCoords();\n\n\t float m00 = getM(0, 0) * 1000.;\n\t float m01 = getM(0, 1) * 1000.;\n\t float m03 = getM(0, 3) * 1000.;\n\t float m10 = getM(1, 0) * 1000.;\n\t float m11 = getM(1, 1) * 1000.;\n\t float m13 = getM(1, 3) * 1000.;\n\t float m20 = getM(2, 0) * 1000.;\n\t float m21 = getM(2, 1) * 1000.;\n\t float m23 = getM(2, 3) * 1000.;\n\n\t float y = float(coords[0]) / float(${i});\n\t float x = float(coords[1]) / float(${i});\n\t float uz = (x * m20) + (y * m21) + m23;\n\t float oneOverUz = 1. / uz;\n\n\t float ux = (x * m00) + (y * m01) + m03;\n\t float uy = (x * m10) + (y * m11) + m13;\n\n\t ux = floor(ux * oneOverUz + 0.5);\n\t uy = floor(uy * oneOverUz + 0.5);\n\t setOutput(getPixel(int(uy), int(ux)));\n\t }\n\t`};this.kernelCaches.computeProjection[o]=e}return r.tidy((()=>{const n=this.kernelCaches.computeProjection[o];return this._compileAndRun(n,[e,t])}))}_buildAdjustedModelViewTransform(e){return r.tidy((()=>{let t=[];for(let n=0;n{const n=e.scale,s=[];for(let r=0;r{e.exports={downsampleBilinear:({image:e})=>{const{data:t,width:n,height:r}=e,s=Math.floor(n/2),a=Math.floor(r/2),i=new Float32Array(s*a),o=[0,1,n,n+1];for(let e=0;e{const{width:r,height:s,data:a}=e,i=2*e.width+(t?1:0),o=2*e.height+(n?1:0),l=new Float32Array(i*o);for(let e=0;e=r&&(u=r-1);for(let c=0;c=s&&(p=s-1);const d=(u-t)*(p-o)*a[h*r+n]+(u-t)*(o-h)*a[p*r+n]+(t-n)*(p-o)*a[h*r+u]+(t-n)*(o-h)*a[p*r+u];l[c*i+e]=d}}return{data:l,width:i,height:o}},resize:({image:e,ratio:t})=>{const n=Math.round(e.width*t),r=Math.round(e.height*t),s=new Uint8Array(n*r);for(let a=0;a=e.width&&(o=e.width-1);for(let l=0;l=e.height&&(u=e.height-1);let c=0,h=0;for(let t=i;t<=o;t++)for(let n=r;n<=u;n++)c+=1*e.data[n*e.width+t],h+=1;s[l*n+a]=Math.floor(c/h)}}return{data:s,width:n,height:r}}}},6048:e=>{e.exports={createRandomizer:()=>({seed:1234,arrayShuffle(e){const{arr:t,sampleSize:n}=e;for(let e=0;e>16&32767;n%=t.length;let r=t[e];t[e]=t[n],t[n]=r}},nextInt(e){this.seed=(214013*this.seed+2531011)%(1<<31);let t=this.seed>>16&32767;return t%=e,t}})}},344:e=>{const t=(e,t)=>{const n=2*Math.PI*t*e;return n/(n+1)},n=(e,t,n)=>e*t+(1-e)*n;e.exports={OneEuroFilter:class{constructor({minCutOff:e,beta:t}){this.minCutOff=e,this.beta=t,this.dCutOff=.001,this.xPrev=null,this.dxPrev=null,this.tPrev=null,this.initialized=!1}reset(){this.initialized=!1}filter(e,r){if(!this.initialized)return this.initialized=!0,this.xPrev=r,this.dxPrev=r.map((()=>0)),this.tPrev=e,r;const{xPrev:s,tPrev:a,dxPrev:i}=this,o=e-a,l=t(o,this.dCutOff),u=[],c=[],h=[];for(let e=0;e{n(4412);const r=n(9894).Z,s=n(7676).Z,a=n(2810).Z;e.exports={UI:class{constructor({uiLoading:e,uiScanning:t,uiError:n}){"yes"===e?this.loadingModal=this._loadHTML(r):"no"!==e&&(this.loadingModal=document.querySelector(e)),"yes"===n?this.compatibilityModal=this._loadHTML(s):"no"!==n&&(this.compatibilityModal=document.querySelector(n)),"yes"===t?this.scanningMask=this._loadHTML(a):"no"!==t&&(this.scanningMask=document.querySelector(t)),this.hideLoading(),this.hideCompatibility(),this.hideScanning()}showLoading(){this.loadingModal&&this.loadingModal.classList.remove("hidden")}hideLoading(){this.loadingModal&&this.loadingModal.classList.add("hidden")}showCompatibility(){this.compatibilityModal&&this.compatibilityModal.classList.remove("hidden")}hideCompatibility(){this.compatibilityModal&&this.compatibilityModal.classList.add("hidden")}showScanning(){this.scanningMask&&this.scanningMask.classList.remove("hidden")}hideScanning(){this.scanningMask&&this.scanningMask.classList.add("hidden")}_loadHTML(e){const t=document.createElement("template");t.innerHTML=e.trim();const n=t.content.firstChild;return document.getElementsByTagName("body")[0].appendChild(n),n}}}},3906:()=>{},2993:()=>{},8352:()=>{},4589:()=>{},1758:()=>{}},t={};function n(r){if(t[r])return t[r].exports;var s=t[r]={id:r,loaded:!1,exports:{}};return e[r].call(s.exports,s,s.exports,n),s.loaded=!0,s.exports}n.amdD=function(){throw new Error("define cannot be used indirect")},n.amdO={},n.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return n.d(t,{a:t}),t},n.d=(e,t)=>{for(var r in t)n.o(t,r)&&!n.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.nmd=e=>(e.paths=[],e.children||(e.children=[]),e),n.p="",n(5260)})();