From f73ea72c6cfd039c5acb2c9e6e27b5dbc7660e92 Mon Sep 17 00:00:00 2001 From: dilgenfritz Date: Mon, 1 Dec 2025 19:20:28 -0600 Subject: [PATCH] modified hero buttons --- hero-button-options.html | 450 ++ src/lib/webgazer.js | 14041 +++++++++++++++++++++++++++++++++++++ src/styles/styles.css | 48 +- 3 files changed, 14525 insertions(+), 14 deletions(-) create mode 100644 hero-button-options.html create mode 100644 src/lib/webgazer.js diff --git a/hero-button-options.html b/hero-button-options.html new file mode 100644 index 0000000..b3e20a5 --- /dev/null +++ b/hero-button-options.html @@ -0,0 +1,450 @@ + + + + + + Hero Button Design Options + + + +
+

🎨 Hero Button Design Options

+ +
+

Current Design (For Reference)

+
+ + + +
+
Angled corners with gradient border
+
+ +
+

Option 1: Neon Glow Cards

+
+ + + +
+
✨ Rounded corners with intense neon glow effect on hover. Modern and eye-catching.
+
+ +
+

Option 2: Hexagon Futuristic

+
+ + + +
+
🔷 Hexagonal shape with rotation effect. Very sci-fi and distinctive.
+
+ +
+

Option 3: Glass Morphism

+
+ + + +
+
🔮 Frosted glass effect with soft glow. Clean and premium feel.
+
+ +
+

Option 4: Cyberpunk Slant

+
+ + + +
+
âš¡ Skewed design with layered borders. Very cyberpunk aesthetic.
+
+ +
+

Option 5: Minimalist Border Animation

+
+ + + +
+
💫 Clean borders with shimmer effect on hover. Subtle and elegant.
+
+
+ + + + diff --git a/src/lib/webgazer.js b/src/lib/webgazer.js new file mode 100644 index 0000000..5f533b3 --- /dev/null +++ b/src/lib/webgazer.js @@ -0,0 +1,14041 @@ +/*! + * + * WebGazer.js: Democratizing Webcam Eye Tracking on the Browser + * Copyright (c) 2016, Brown WebGazer Team + * Licensed under GPLv3. Companies with a valuation of less than $1M can use WebGazer.js under LGPLv3. + * + */ +var webgazer;(()=>{var e={790:(e,t,n)=>{ +/*! + localForage -- Offline Storage, Improved + Version 1.7.3 + https://localforage.github.io/localForage + (c) 2013-2017 Mozilla, Apache License 2.0 +*/ +e.exports=function e(t,n,s){function r(i,o){if(!n[i]){if(!t[i]){if(a)return a(i,!0);var l=new Error("Cannot find module '"+i+"'");throw l.code="MODULE_NOT_FOUND",l}var u=n[i]={exports:{}};t[i][0].call(u.exports,(function(e){var n=t[i][1][e];return r(n||e)}),u,u.exports,e,t,n,s)}return n[i].exports}for(var a=void 0,i=0;i=43)}})).catch((function(){return!1}))}function k(e){return"boolean"==typeof m?u.resolve(m):v(e).then((function(e){return m=e}))}function I(e){var t=g[e.name],n={};n.promise=new u((function(e,t){n.resolve=e,n.reject=t})),t.deferredOperations.push(n),t.dbReady?t.dbReady=t.dbReady.then((function(){return n.promise})):t.dbReady=n.promise}function N(e){var t=g[e.name].deferredOperations.pop();if(t)return t.resolve(),t.promise}function S(e,t){var n=g[e.name].deferredOperations.pop();if(n)return n.reject(t),n.promise}function T(e,t){return new u((function(n,s){if(g[e.name]=g[e.name]||M(),e.db){if(!t)return n(e.db);I(e),e.db.close()}var r=[e.name];t&&r.push(e.version);var a=i.open.apply(i,r);t&&(a.onupgradeneeded=function(t){var n=a.result;try{n.createObjectStore(e.storeName),t.oldVersion<=1&&n.createObjectStore(f)}catch(n){if("ConstraintError"!==n.name)throw n;console.warn('The database "'+e.name+'" has been upgraded from version '+t.oldVersion+" to version "+t.newVersion+', but the storage "'+e.storeName+'" already exists.')}}),a.onerror=function(e){e.preventDefault(),s(a.error)},a.onsuccess=function(){n(a.result),N(e)}}))}function C(e){return T(e,!1)}function $(e){return T(e,!0)}function E(e,t){if(!e.db)return!0;var n=!e.db.objectStoreNames.contains(e.storeName),s=e.versione.db.version;if(s&&(e.version!==t&&console.warn('The database "'+e.name+"\" can't be downgraded from version "+e.db.version+" to version "+e.version+"."),e.version=e.db.version),r||n){if(n){var a=e.db.version+1;a>e.version&&(e.version=a)}return!0}return!1}function R(e){return new u((function(t,n){var s=new FileReader;s.onerror=n,s.onloadend=function(n){var s=btoa(n.target.result||"");t({__local_forage_encoded_blob:!0,data:s,type:e.type})},s.readAsBinaryString(e)}))}function A(e){return l([w(atob(e.data))],{type:e.type})}function F(e){return e&&e.__local_forage_encoded_blob}function _(e){var t=this,n=t._initReady().then((function(){var e=g[t._dbInfo.name];if(e&&e.dbReady)return e.dbReady}));return h(n,e,e),n}function D(e){I(e);for(var t=g[e.name],n=t.forages,s=0;s0&&(!e.db||"InvalidStateError"===r.name||"NotFoundError"===r.name))return u.resolve().then((function(){if(!e.db||"NotFoundError"===r.name&&!e.db.objectStoreNames.contains(e.storeName)&&e.version<=e.db.version)return e.db&&(e.version=e.db.version+1),$(e)})).then((function(){return D(e).then((function(){O(e,t,n,s-1)}))})).catch(n);n(r)}}function M(){return{forages:[],db:null,dbReady:null,deferredOperations:[]}}function L(e){var t=this,n={db:null};if(e)for(var s in e)n[s]=e[s];var r=g[n.name];r||(r=M(),g[n.name]=r),r.forages.push(t),t._initReady||(t._initReady=t.ready,t.ready=_);var a=[];function i(){return u.resolve()}for(var o=0;o>4,c[l++]=(15&s)<<4|r>>2,c[l++]=(3&r)<<6|63&a;return u}function fe(e){var t,n=new Uint8Array(e),s="";for(t=0;t>2],s+=X[(3&n[t])<<4|n[t+1]>>4],s+=X[(15&n[t+1])<<2|n[t+2]>>6],s+=X[63&n[t+2]];return n.length%3==2?s=s.substring(0,s.length-1)+"=":n.length%3==1&&(s=s.substring(0,s.length-2)+"=="),s}function me(e,t){var n="";if(e&&(n=pe.call(e)),e&&("[object ArrayBuffer]"===n||e.buffer&&"[object ArrayBuffer]"===pe.call(e.buffer))){var s,r=J;e instanceof ArrayBuffer?(s=e,r+=ee):(s=e.buffer,"[object Int8Array]"===n?r+=ne:"[object Uint8Array]"===n?r+=se:"[object Uint8ClampedArray]"===n?r+=re:"[object Int16Array]"===n?r+=ae:"[object Uint16Array]"===n?r+=oe:"[object Int32Array]"===n?r+=ie:"[object Uint32Array]"===n?r+=le:"[object Float32Array]"===n?r+=ue:"[object Float64Array]"===n?r+=ce:t(new Error("Failed to get type for BinaryArray"))),t(r+fe(s))}else if("[object Blob]"===n){var a=new FileReader;a.onload=function(){var n=Y+e.type+"~"+fe(this.result);t(J+te+n)},a.readAsArrayBuffer(e)}else try{t(JSON.stringify(e))}catch(n){console.error("Couldn't convert value into a JSON string: ",e),t(null,n)}}function ge(e){if(e.substring(0,Q)!==J)return JSON.parse(e);var t,n=e.substring(he),s=e.substring(Q,he);if(s===te&&Z.test(n)){var r=n.match(Z);t=r[1],n=n.substring(r[0].length)}var a=de(n);switch(s){case ee:return a;case te:return l([a],{type:t});case ne:return new Int8Array(a);case se:return new Uint8Array(a);case re:return new Uint8ClampedArray(a);case ae:return new Int16Array(a);case oe:return new Uint16Array(a);case ie:return new Int32Array(a);case le:return new Uint32Array(a);case ue:return new Float32Array(a);case ce:return new Float64Array(a);default:throw new Error("Unkown type: "+s)}}var ye={serialize:me,deserialize:ge,stringToBuffer:de,bufferToString:fe};function be(e,t,n,s){e.executeSql("CREATE TABLE IF NOT EXISTS "+t.storeName+" (id INTEGER PRIMARY KEY, key unique, value)",[],n,s)}function xe(e){var t=this,n={db:null};if(e)for(var s in e)n[s]="string"!=typeof e[s]?e[s].toString():e[s];var r=new u((function(e,s){try{n.db=openDatabase(n.name,String(n.version),n.description,n.size)}catch(e){return s(e)}n.db.transaction((function(r){be(r,n,(function(){t._dbInfo=n,e()}),(function(e,t){s(t)}))}),s)}));return n.serializer=ye,r}function we(e,t,n,s,r,a){e.executeSql(n,s,r,(function(e,i){i.code===i.SYNTAX_ERR?e.executeSql("SELECT name FROM sqlite_master WHERE type='table' AND name = ?",[t.storeName],(function(e,o){o.rows.length?a(e,i):be(e,t,(function(){e.executeSql(n,s,r,a)}),a)}),a):a(e,i)}),a)}function ve(e,t){var n=this;e=p(e);var s=new u((function(t,s){n.ready().then((function(){var r=n._dbInfo;r.db.transaction((function(n){we(n,r,"SELECT * FROM "+r.storeName+" WHERE key = ? LIMIT 1",[e],(function(e,n){var s=n.rows.length?n.rows.item(0).value:null;s&&(s=r.serializer.deserialize(s)),t(s)}),(function(e,t){s(t)}))}))})).catch(s)}));return c(s,t),s}function ke(e,t){var n=this,s=new u((function(t,s){n.ready().then((function(){var r=n._dbInfo;r.db.transaction((function(n){we(n,r,"SELECT * FROM "+r.storeName,[],(function(n,s){for(var a=s.rows,i=a.length,o=0;o0)return void a(Ie.apply(r,[e,o,n,s-1]));i(t)}}))}))})).catch(i)}));return c(a,n),a}function Ne(e,t,n){return Ie.apply(this,[e,t,n,1])}function Se(e,t){var n=this;e=p(e);var s=new u((function(t,s){n.ready().then((function(){var r=n._dbInfo;r.db.transaction((function(n){we(n,r,"DELETE FROM "+r.storeName+" WHERE key = ?",[e],(function(){t()}),(function(e,t){s(t)}))}))})).catch(s)}));return c(s,t),s}function Te(e){var t=this,n=new u((function(e,n){t.ready().then((function(){var s=t._dbInfo;s.db.transaction((function(t){we(t,s,"DELETE FROM "+s.storeName,[],(function(){e()}),(function(e,t){n(t)}))}))})).catch(n)}));return c(n,e),n}function Ce(e){var t=this,n=new u((function(e,n){t.ready().then((function(){var s=t._dbInfo;s.db.transaction((function(t){we(t,s,"SELECT COUNT(key) as c FROM "+s.storeName,[],(function(t,n){var s=n.rows.item(0).c;e(s)}),(function(e,t){n(t)}))}))})).catch(n)}));return c(n,e),n}function $e(e,t){var n=this,s=new u((function(t,s){n.ready().then((function(){var r=n._dbInfo;r.db.transaction((function(n){we(n,r,"SELECT key FROM "+r.storeName+" WHERE id = ? LIMIT 1",[e+1],(function(e,n){var s=n.rows.length?n.rows.item(0).key:null;t(s)}),(function(e,t){s(t)}))}))})).catch(s)}));return c(s,t),s}function Ee(e){var t=this,n=new u((function(e,n){t.ready().then((function(){var s=t._dbInfo;s.db.transaction((function(t){we(t,s,"SELECT key FROM "+s.storeName,[],(function(t,n){for(var s=[],r=0;r '__WebKitDatabaseInfoTable__'",[],(function(n,s){for(var r=[],a=0;a0}function Le(e){var t=this,n={};if(e)for(var s in e)n[s]=e[s];return n.keyPrefix=De(e,t._defaultConfig),Me()?(t._dbInfo=n,n.serializer=ye,u.resolve()):u.reject()}function ze(e){var t=this,n=t.ready().then((function(){for(var e=t._dbInfo.keyPrefix,n=localStorage.length-1;n>=0;n--){var s=localStorage.key(n);0===s.indexOf(e)&&localStorage.removeItem(s)}}));return c(n,e),n}function Pe(e,t){var n=this;e=p(e);var s=n.ready().then((function(){var t=n._dbInfo,s=localStorage.getItem(t.keyPrefix+e);return s&&(s=t.serializer.deserialize(s)),s}));return c(s,t),s}function Be(e,t){var n=this,s=n.ready().then((function(){for(var t=n._dbInfo,s=t.keyPrefix,r=s.length,a=localStorage.length,i=1,o=0;o=0;t--){var n=localStorage.key(t);0===n.indexOf(e)&&localStorage.removeItem(n)}})):u.reject("Invalid arguments"),c(s,t),s}var qe={_driver:"localStorageWrapper",_initStorage:Le,_support:_e(),iterate:Be,getItem:Pe,setItem:He,removeItem:Ge,clear:ze,length:Ue,key:We,keys:Ve,dropInstance:je},Ke=function(e,t){return e===t||"number"==typeof e&&"number"==typeof t&&isNaN(e)&&isNaN(t)},Xe=function(e,t){for(var n=e.length,s=0;s{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 s(e){return!0===(e&&e.__isLong__)}n.prototype.__isLong__,Object.defineProperty(n.prototype,"__isLong__",{value:!0}),n.isLong=s;var r={},a={};function i(e,t){var n,s,i;return t?(i=0<=(e>>>=0)&&e<256)&&(s=a[e])?s:(n=l(e,(0|e)<0?-1:0,!0),i&&(a[e]=n),n):(i=-128<=(e|=0)&&e<128)&&(s=r[e])?s:(n=l(e,e<0?-1:0,!1),i&&(r[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,s){return new n(e,t,s)}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===s)return c(e.substring(1),t,n).neg();for(var r=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&&!(e&1<=0},N.isOdd=function(){return!(1&~this.low)},N.isEven=function(){return!(1&this.low)},N.equals=function(e){return s(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(s(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){s(e)||(e=h(e));var t=this.high>>>16,n=65535&this.high,r=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+=r+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 s(e)||(e=h(e)),this.add(e.neg())},N.sub=N.subtract,N.multiply=function(e){if(this.isZero())return g;if(s(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,r=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+=r*d)>>>16,y&=65535,f+=(y+=a*p)>>>16,y&=65535,f+=(y+=i*c)>>>16,f+=n*d+r*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(s(e)||(e=h(e)),e.isZero())throw Error("division by zero");var n,r,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:(r=this.sub(e.mul(n)),a=n.add(r.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(r=this;r.gte(e);){n=Math.max(1,Math.floor(r.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(r);)d=(p=o(n-=c,this.unsigned)).mul(e);p.isZero()&&(p=b),a=a.add(p),r=r.sub(d)}return a},N.div=N.divide,N.modulo=function(e){return s(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 s(e)||(e=h(e)),l(this.low&e.low,this.high&e.high,this.unsigned)},N.or=function(e){return s(e)||(e=h(e)),l(this.low|e.low,this.high|e.high,this.unsigned)},N.xor=function(e){return s(e)||(e=h(e)),l(this.low^e.low,this.high^e.high,this.unsigned)},N.shiftLeft=function(e){return s(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(s(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,s){return s?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)}},312:function(e,t){var n,s,r;s=[e],n=function(e){"use strict";function t(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var n=Object.assign||function(e){for(var t=1;tMath.abs(n[a][i])&&(i=o);for(var l=a;l=a;h--)n[h][c]-=n[h][a]*n[a][c]/n[a][a]}for(var p=s-1;p>=0;p--){for(var d=0,f=p+1;f=0;v--)w+=v>1?y[v]+"x^"+v+" + ":1===v?y[v]+"x + ":y[v];return{string:w,points:x,predict:b,equation:[].concat(s(y)).reverse(),r2:o(a(e,x),t.precision)}}};function u(){var e=function(e,s){return n({_round:o},e,t({},s,(function(e,t){return l[s](e,n({},r,t))})))};return Object.keys(l).reduce(e,{})}e.exports=u()},void 0===(r="function"==typeof n?n.apply(t,s):n)||(e.exports=r)},391:(e,t,n)=>{var s=n(180),r=n(181),a=n(31),i=n(67),o=n(833),l=n(717),u=n(801);u.alea=s,u.xor128=r,u.xorwow=a,u.xorshift7=i,u.xor4096=o,u.tychei=l,e.exports=u},180:function(e,t,n){var s;!function(e,r){function a(e){var t=this,n=function(){var e=4022871197,t=function(t){t=String(t);for(var n=0;n>>0,e=(s*=e)>>>0,e+=4294967296*(s-=e)}return 2.3283064365386963e-10*(e>>>0)};return t}();t.next=function(){var e=2091639*t.s0+2.3283064365386963e-10*t.c;return t.s0=t.s1,t.s1=t.s2,t.s2=e-(t.c=0|e)},t.c=1,t.s0=n(" "),t.s1=n(" "),t.s2=n(" "),t.s0-=n(e),t.s0<0&&(t.s0+=1),t.s1-=n(e),t.s1<0&&(t.s1+=1),t.s2-=n(e),t.s2<0&&(t.s2+=1),n=null}function i(e,t){return t.c=e.c,t.s0=e.s0,t.s1=e.s1,t.s2=e.s2,t}function o(e,t){var n=new a(e),s=t&&t.state,r=n.next;return r.int32=function(){return 4294967296*n.next()|0},r.double=function(){return r()+11102230246251565e-32*(2097152*r()|0)},r.quick=r,s&&("object"==typeof s&&i(s,n),r.state=function(){return i(n,{})}),r}r&&r.exports?r.exports=o:n.amdD&&n.amdO?void 0===(s=function(){return o}.call(t,n,t,r))||(r.exports=s):this.alea=o}(0,e=n.nmd(e),n.amdD)},717:function(e,t,n){var s;!function(e,r){function a(e){var t=this,n="";t.next=function(){var e=t.b,n=t.c,s=t.d,r=t.a;return e=e<<25^e>>>7^n,n=n-s|0,s=s<<24^s>>>8^r,r=r-e|0,t.b=e=e<<20^e>>>12^n,t.c=n=n-s|0,t.d=s<<16^n>>>16^r,t.a=r-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 s=0;s>>0)/4294967296};return r.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},r.int32=n.next,r.quick=r,s&&("object"==typeof s&&i(s,n),r.state=function(){return i(n,{})}),r}r&&r.exports?r.exports=o:n.amdD&&n.amdO?void 0===(s=function(){return o}.call(t,n,t,r))||(r.exports=s):this.tychei=o}(0,e=n.nmd(e),n.amdD)},181:function(e,t,n){var s;!function(e,r){function a(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 s=0;s>>0)/4294967296};return r.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},r.int32=n.next,r.quick=r,s&&("object"==typeof s&&i(s,n),r.state=function(){return i(n,{})}),r}r&&r.exports?r.exports=o:n.amdD&&n.amdO?void 0===(s=function(){return o}.call(t,n,t,r))||(r.exports=s):this.xor128=o}(0,e=n.nmd(e),n.amdD)},833:function(e,t,n){var s;!function(e,r){function a(e){var t=this;t.next=function(){var e,n,s=t.w,r=t.X,a=t.i;return t.w=s=s+1640531527|0,n=r[a+34&127],e=r[a=a+1&127],n^=n<<13,e^=e<<17,n^=n>>>15,e^=e>>>12,n=r[a]=n^e,t.i=a,n+(s^s>>>16)|0},function(e,t){var n,s,r,a,i,o=[],l=128;for(t===(0|t)?(s=t,t=null):(t+="\0",s=0,l=Math.max(l,t.length)),r=0,a=-32;a>>15,s^=s<<4,s^=s>>>13,a>=0&&(i=i+1640531527|0,r=0==(n=o[127&a]^=s+i)?r+1:0);for(r>=128&&(o[127&(t&&t.length||0)]=-1),r=127,a=512;a>0;--a)s=o[r+34&127],n=o[r=r+1&127],s^=s<<13,n^=n<<17,s^=s>>>15,n^=n>>>12,o[r]=s^n;e.w=i,e.X=o,e.i=r}(t,e)}function i(e,t){return t.i=e.i,t.w=e.w,t.X=e.X.slice(),t}function o(e,t){null==e&&(e=+new Date);var n=new a(e),s=t&&t.state,r=function(){return(n.next()>>>0)/4294967296};return r.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},r.int32=n.next,r.quick=r,s&&(s.X&&i(s,n),r.state=function(){return i(n,{})}),r}r&&r.exports?r.exports=o:n.amdD&&n.amdO?void 0===(s=function(){return o}.call(t,n,t,r))||(r.exports=s):this.xor4096=o}(0,e=n.nmd(e),n.amdD)},67:function(e,t,n){var s;!function(e,r){function a(e){var t=this;t.next=function(){var e,n,s=t.x,r=t.i;return e=s[r],n=(e^=e>>>7)^e<<24,n^=(e=s[r+1&7])^e>>>10,n^=(e=s[r+3&7])^e>>>3,n^=(e=s[r+4&7])^e<<7,e=s[r+7&7],n^=(e^=e<<13)^e<<9,s[r]=n,t.i=r+1&7,n},function(e,t){var n,s=[];if(t===(0|t))s[0]=t;else for(t=""+t,n=0;n0;--n)e.next()}(t,e)}function i(e,t){return t.x=e.x.slice(),t.i=e.i,t}function o(e,t){null==e&&(e=+new Date);var n=new a(e),s=t&&t.state,r=function(){return(n.next()>>>0)/4294967296};return r.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},r.int32=n.next,r.quick=r,s&&(s.x&&i(s,n),r.state=function(){return i(n,{})}),r}r&&r.exports?r.exports=o:n.amdD&&n.amdO?void 0===(s=function(){return o}.call(t,n,t,r))||(r.exports=s):this.xorshift7=o}(0,e=n.nmd(e),n.amdD)},31:function(e,t,n){var s;!function(e,r){function a(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 s=0;s>>4),t.next()}function i(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 o(e,t){var n=new a(e),s=t&&t.state,r=function(){return(n.next()>>>0)/4294967296};return r.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},r.int32=n.next,r.quick=r,s&&("object"==typeof s&&i(s,n),r.state=function(){return i(n,{})}),r}r&&r.exports?r.exports=o:n.amdD&&n.amdO?void 0===(s=function(){return o}.call(t,n,t,r))||(r.exports=s):this.xorwow=o}(0,e=n.nmd(e),n.amdD)},801:function(e,t,n){var s;!function(r,a,i){var o,l=256,u=i.pow(l,6),c=i.pow(2,52),h=2*c,p=255;function d(e,t,n){var s=[],p=y(g((t=1==t?{entropy:!0}:t||{}).entropy?[e,b(a)]:null==e?function(){try{var e;return o&&(e=o.randomBytes)?e=e(l):(e=new Uint8Array(l),(r.crypto||r.msCrypto).getRandomValues(e)),b(e)}catch(e){var t=r.navigator,n=t&&t.plugins;return[+new Date,r,n,r.screen,b(a)]}}():e,3),s),d=new f(s),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),a),(t.pass||n||function(e,t,n,s){return s&&(s.S&&m(s,d),e.state=function(){return m(d,{})}),n?(i.random=e,t):e})(x,p,"global"in t?t.global:this==i,t.state)}function f(e){var t,n=e.length,s=this,r=0,a=s.i=s.j=0,i=s.S=[];for(n||(e=[n++]);r{window.requestAnimFrame=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(e,t){return window.setTimeout(e,1e3/60)},window.cancelRequestAnimFrame=window.cancelCancelRequestAnimationFrame||window.webkitCancelRequestAnimationFrame||window.mozCancelRequestAnimationFrame||window.oCancelRequestAnimationFrame||window.msCancelRequestAnimationFrame||window.clearTimeout},817:()=>{},590:()=>{},530:()=>{},108:()=>{},551:()=>{},234:()=>{}},t={};function n(s){var r=t[s];if(void 0!==r)return r.exports;var a=t[s]={id:s,loaded:!1,exports:{}};return e[s].call(a.exports,a,a.exports,n),a.loaded=!0,a.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 s in t)n.o(t,s)&&!n.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:t[s]})},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);var s={};(()=>{"use strict";n.d(s,{default:()=>zB});var e={};n.r(e),n.d(e,{browserFiles:()=>si,browserHTTPRequest:()=>pi,concatenateArrayBuffers:()=>ra,copyModel:()=>Ga,decodeWeights:()=>ea,encodeWeights:()=>Qr,fromMemory:()=>gi,fromMemorySync:()=>yi,getLoadHandlers:()=>ga,getModelArtifactsForJSON:()=>la,getModelArtifactsForJSONSync:()=>oa,getModelArtifactsInfoForJSON:()=>ua,getSaveHandlers:()=>ma,getWeightSpecs:()=>ca,http:()=>hi,isHTTPScheme:()=>ui,listModels:()=>Va,loadWeights:()=>ii,moveModel:()=>Ha,registerLoadRouter:()=>fa,registerSaveRouter:()=>da,removeModel:()=>Ua,weightsLoaderFactory:()=>oi,withSaveHandler:()=>bi,withSaveHandlerSync:()=>xi});var t={};n.r(t),n.d(t,{assertParamsValid:()=>Ei,computeFlatOffset:()=>Vi,computeOutShape:()=>Ai,getNormalizedAxes:()=>Oi,isSliceContinous:()=>Wi,maskToAxes:()=>Ri,parseSliceParams:()=>Ui,sliceInfo:()=>Gi,startForAxis:()=>Pi,startIndicesWithElidedDims:()=>Mi,stopForAxis:()=>Bi,stopIndicesWithElidedDims:()=>Li,stridesForAxis:()=>zi,stridesWithElidedDims:()=>Fi});var r={};n.r(r),n.d(r,{conv2d:()=>kh,depthwiseConv2d:()=>Sh,matMul:()=>Th});var a={};n.r(a),n.d(a,{collectGatherOpShapeInfo:()=>Ud,computeOutShape:()=>Vd,segOpComputeOptimalWindowSize:()=>Wd});var i={};n.r(i),n.d(i,{ERF_A1:()=>ad,ERF_A2:()=>id,ERF_A3:()=>od,ERF_A4:()=>ld,ERF_A5:()=>ud,ERF_P:()=>rd,PARALLELIZE_THRESHOLD:()=>qp,RowPartitionType:()=>Vp,SELU_SCALE:()=>sd,SELU_SCALEALPHA:()=>nd,applyActivation:()=>wh,assertAndGetBroadcastShape:()=>ki,assertAxesAreInnerMostDims:()=>Dl,assertParamsConsistent:()=>Bp,assignToTypedArray:()=>md,axesAreInnerMostDims:()=>Rl,calculateShapes:()=>uh,checkEinsumDimSizes:()=>Nd,checkPadOnDimRoundingMode:()=>Fo,combineLocations:()=>Al,combineRaggedTensorToTensorShapes:()=>Up,complexWithEvenIndex:()=>pd,complexWithOddIndex:()=>dd,computeConv2DInfo:()=>ko,computeConv3DInfo:()=>Io,computeDefaultPad:()=>No,computeDilation2DInfo:()=>xo,computeOptimalWindowSize:()=>Kp,computeOutAndReduceShapes:()=>Fl,computeOutShape:()=>Wp,computePool2DInfo:()=>wo,computePool3DInfo:()=>vo,convertConv2DDataFormat:()=>Ao,decodeEinsumEquation:()=>kd,eitherStridesOrDilationsAreOne:()=>Ro,expandShapeToKeepDim:()=>_l,exponent:()=>yd,exponents:()=>gd,fromStringArrayToUint8:()=>Hd,fromUint8ToStringArray:()=>Gd,getAxesPermutation:()=>Ol,getBroadcastDims:()=>wi,getComplexWithIndex:()=>fd,getEinsumComputePath:()=>Sd,getEinsumPermutation:()=>Id,getFusedBiasGradient:()=>xh,getFusedDyActivation:()=>bh,getImageCenter:()=>Xp,getInnerMostAxes:()=>Ll,getPermuted:()=>Zp,getRaggedRank:()=>Hp,getReductionAxes:()=>vi,getReshaped:()=>Yp,getReshapedPermuted:()=>Jp,getRowPartitionTypesHelper:()=>Gp,getSliceBeginCoords:()=>Qp,getSliceSize:()=>ed,getSparseFillEmptyRowsIndicesDenseShapeMismatch:()=>Ed,getSparseFillEmptyRowsNegativeIndexErrorMessage:()=>Rd,getSparseFillEmptyRowsOutOfRangeIndexErrorMessage:()=>Ad,getSparseReshapeEmptyTensorZeroOutputDimErrorMessage:()=>Dd,getSparseReshapeInputOutputMismatchErrorMessage:()=>Md,getSparseReshapeInputOutputMultipleErrorMessage:()=>Od,getSparseReshapeMultipleNegativeOneOutputDimErrorMessage:()=>Fd,getSparseReshapeNegativeOutputDimErrorMessage:()=>_d,getSparseSegmentReductionIndicesOutOfRangeErrorMessage:()=>Bd,getSparseSegmentReductionNegativeSegmentIdsErrorMessage:()=>Ld,getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage:()=>zd,getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage:()=>Pd,getUndoAxesPermutation:()=>Ml,isIdentityPermutation:()=>Td,log:()=>Rs,mergeRealAndImagArrays:()=>cd,prepareAndValidate:()=>td,prepareSplitSize:()=>$d,segment_util:()=>a,shouldFuse:()=>vh,slice_util:()=>t,splitRealAndImagArrays:()=>hd,tupleValuesAreOne:()=>Eo,upcastType:()=>Sr,validateDefaultValueShape:()=>jp,validateInput:()=>lh,validateUpdateShape:()=>oh,warn:()=>Es});var o={};n.r(o),n.d(o,{json:()=>kv});var l={};n.r(l),n.d(l,{json:()=>Iv});var u={};n.r(u),n.d(u,{json:()=>Nv});var c={};n.r(c),n.d(c,{json:()=>Sv});var h={};n.r(h),n.d(h,{json:()=>Tv});var p={};n.r(p),n.d(p,{json:()=>Cv});var d={};n.r(d),n.d(d,{json:()=>$v});var f={};n.r(f),n.d(f,{json:()=>Ev});var m={};n.r(m),n.d(m,{json:()=>Rv});var g={};n.r(g),n.d(g,{json:()=>Av});var y={};n.r(y),n.d(y,{json:()=>Fv});var b={};n.r(b),n.d(b,{json:()=>_v});var x={};n.r(x),n.d(x,{json:()=>Dv});var w={};n.r(w),n.d(w,{json:()=>Ov});var v={};n.r(v),n.d(v,{json:()=>Mv});var k={};n.r(k),n.d(k,{json:()=>Lv});var I={};n.r(I),n.d(I,{json:()=>zv});var N={};n.r(N),n.d(N,{json:()=>Pv});var S={};n.r(S),n.d(S,{json:()=>Bv});var T={};n.r(T),n.d(T,{OP_SCOPE_SUFFIX:()=>jr,abs:()=>ro,acos:()=>ao,acosh:()=>io,add:()=>oo,addN:()=>lo,all:()=>uo,any:()=>co,argMax:()=>ho,argMin:()=>po,asin:()=>fo,asinh:()=>mo,atan:()=>go,atan2:()=>yo,atanh:()=>bo,avgPool:()=>Do,avgPool3d:()=>Oo,basicLSTMCell:()=>Vo,batchNorm:()=>Go,batchNorm2d:()=>Ho,batchNorm3d:()=>jo,batchNorm4d:()=>qo,batchToSpaceND:()=>Uo,bincount:()=>Ko,booleanMaskAsync:()=>rh,broadcastArgs:()=>Xo,broadcastTo:()=>Yo,buffer:()=>Ya,cast:()=>Za,ceil:()=>Zo,clipByValue:()=>Qo,clone:()=>Ja,complex:()=>Kr,concat:()=>Mo,concat1d:()=>el,concat2d:()=>tl,concat3d:()=>nl,concat4d:()=>sl,conv1d:()=>al,conv2d:()=>rl,conv2dTranspose:()=>ol,conv3d:()=>ll,conv3dTranspose:()=>cl,cos:()=>hl,cosh:()=>pl,cosineWindow:()=>mh,cumprod:()=>dl,cumsum:()=>fl,denseBincount:()=>ml,depthToSpace:()=>gl,depthwiseConv2d:()=>yl,diag:()=>bl,dilation2d:()=>xl,div:()=>vl,divNoNan:()=>Sl,dot:()=>Tl,dropout:()=>dh,einsum:()=>Cl,elu:()=>$l,enclosingPowerOfTwo:()=>fh,equal:()=>kl,erf:()=>El,euclideanNorm:()=>jl,exp:()=>ql,expandDims:()=>Kl,expm1:()=>Xl,eye:()=>Zl,fft:()=>_c,fill:()=>Jo,floor:()=>Jl,floorDiv:()=>wl,fused:()=>r,gather:()=>Ql,gatherND:()=>ph,greater:()=>eu,greaterEqual:()=>tu,ifft:()=>Dc,imag:()=>nu,image:()=>Np,inTopKAsync:()=>gh,irfft:()=>Oc,isFinite:()=>su,isInf:()=>ru,isNaN:()=>au,leakyRelu:()=>iu,less:()=>ou,lessEqual:()=>lu,linalg:()=>Sp,linspace:()=>uu,localResponseNormalization:()=>cu,log:()=>hu,log1p:()=>pu,logSigmoid:()=>mu,logSoftmax:()=>yu,logSumExp:()=>bu,logicalAnd:()=>xu,logicalNot:()=>wu,logicalOr:()=>vu,logicalXor:()=>ku,losses:()=>Tp,lowerBound:()=>Su,matMul:()=>Lo,max:()=>zl,maxPool:()=>Tu,maxPool3d:()=>Cu,maxPoolWithArgmax:()=>$u,maximum:()=>Eu,mean:()=>Ru,meshgrid:()=>_u,min:()=>Pl,minimum:()=>Du,mirrorPad:()=>Ou,mod:()=>Mu,moments:()=>Lu,movingAverage:()=>ih,mul:()=>zo,multiRNNCell:()=>zu,multinomial:()=>Pu,neg:()=>du,norm:()=>Hl,notEqual:()=>Bu,oneHot:()=>Wu,ones:()=>Fu,onesLike:()=>Vu,op:()=>qr,outerProduct:()=>Uu,pad:()=>Gu,pad1d:()=>Hu,pad2d:()=>ju,pad3d:()=>qu,pad4d:()=>Ku,pool:()=>Yu,pow:()=>Bl,prelu:()=>Zu,print:()=>Qa,prod:()=>Ju,raggedGather:()=>Qu,raggedTensorToTensor:()=>ec,rand:()=>tc,randomGamma:()=>ic,randomNormal:()=>oc,randomStandardNormal:()=>lc,randomUniform:()=>uc,range:()=>cc,real:()=>hc,reciprocal:()=>pc,relu:()=>dc,relu6:()=>fc,reshape:()=>_o,reverse:()=>mc,reverse1d:()=>gc,reverse2d:()=>yc,reverse3d:()=>bc,reverse4d:()=>xc,rfft:()=>Lc,round:()=>wc,rsqrt:()=>vc,scalar:()=>no,scatterND:()=>ch,searchSorted:()=>Nu,selu:()=>kc,separableConv2d:()=>Ic,setdiff1dAsync:()=>Nc,sigmoid:()=>Po,sign:()=>Sc,signal:()=>Ip,sin:()=>Tc,sinh:()=>Cc,slice:()=>Bo,slice1d:()=>$c,slice2d:()=>Ec,slice3d:()=>Rc,slice4d:()=>Ac,softmax:()=>Fc,softplus:()=>fu,spaceToBatchND:()=>Xu,sparse:()=>Cp,sparseToDense:()=>hh,spectral:()=>kp,split:()=>Mc,sqrt:()=>Wl,square:()=>Vl,squaredDifference:()=>zc,squeeze:()=>Pc,stack:()=>Bc,step:()=>Wc,stridedSlice:()=>Vc,string:()=>$p,sub:()=>gu,sum:()=>Ul,tan:()=>Uc,tanh:()=>Wo,tensor:()=>Yr,tensor1d:()=>Gc,tensor2d:()=>Hc,tensor3d:()=>Ii,tensor4d:()=>jc,tensor5d:()=>qc,tensor6d:()=>Kc,tile:()=>Yl,topk:()=>Xc,transpose:()=>ah,truncatedNormal:()=>Yc,unique:()=>Zc,unsortedSegmentSum:()=>Jc,unstack:()=>Qc,upperBound:()=>eh,variable:()=>th,where:()=>Il,whereAsync:()=>sh,zeros:()=>Au,zerosLike:()=>Nl});var C={};n.r(C),n.d(C,{mx:()=>PI,XI:()=>AN,Nk:()=>FN,ct:()=>DI,YG:()=>ON,hH:()=>WN,z3:()=>NS,sG:()=>OS,uM:()=>BS,vS:()=>sT,qB:()=>hT,GG:()=>dT,lg:()=>bT,rq:()=>mT,cu:()=>AT,WR:()=>$T,GE:()=>DT,px:()=>MT,jC:()=>ZT,He:()=>eC,hE:()=>cC,BF:()=>gS,Dk:()=>wC,cl:()=>$C,_B:()=>WC,ub:()=>jC,Ku:()=>JC,qy:()=>e$,Zy:()=>p$,bu:()=>m$,zv:()=>SI,dH:()=>KI,HS:()=>CN,yH:()=>O$,l3:()=>L$,z9:()=>P$,x6:()=>G$,eW:()=>Q$,GK:()=>nE,SP:()=>aE,f6:()=>oE,dl:()=>jS,Dw:()=>pE,xT:()=>gE,_X:()=>tN,wz:()=>IE});class ${constructor(e,t){this.backend=e,this.dataMover=t,this.data=new WeakMap,this.dataIdsCount=0}get(e){return this.data.has(e)||this.dataMover.moveData(this.backend,e),this.data.get(e)}set(e,t){this.dataIdsCount++,this.data.set(e,t)}has(e){return this.data.has(e)}delete(e){return this.dataIdsCount--,this.data.delete(e)}numDataIds(){return this.dataIdsCount}}class E{refCount(e){return R("refCount")}incRef(e){return R("incRef")}timerAvailable(){return!0}time(e){return R("time")}read(e){return R("read")}readSync(e){return R("readSync")}readToGPU(e,t){return R("readToGPU")}numDataIds(){return R("numDataIds")}disposeData(e,t){return R("disposeData")}write(e,t,n){return R("write")}move(e,t,n,s,r){return R("move")}memory(){return R("memory")}floatPrecision(){return R("floatPrecision")}epsilon(){return 32===this.floatPrecision()?1e-7:1e-4}dispose(){return R("dispose")}}function R(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`)} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function A(e){let t=e.length,n=0;for(;t>0;)n=Math.random()*t|0,t--,D(e,t,n)}function F(e,t,n){return Math.max(e,Math.min(t,n))}function _(e){return e%2==0?e:e+1}function D(e,t,n){const s=e[t];e[t]=e[n],e[n]=s}function O(e,t){if(!e)throw new Error("string"==typeof t?t:t())}function M(e,t,n=""){O(B(e,t),(()=>n+` Shapes ${e} and ${t} must match`))}function L(e){O(null!=e,(()=>"The input to the tensor constructor must be a non-null value."))}function z(e,t=[],n=!1){if(null==t&&(t=[]),Array.isArray(e)||Z(e)&&!n)for(let s=0;s0,n,s=setTimeout){return new Promise(((r,a)=>{let i=0;const o=()=>{if(e())return void r();i++;const l=t(i);null!=n&&i>=n?a():s(o,l)};o()}))}function H(e,t){let n=1,s=-1;for(let t=0;t=0)n*=e[t];else if(-1===e[t]){if(-1!==s)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${s} and dim ${t}`);s=t}else if(e[t]<0)throw Error(`Shapes can not be < 0. Found ${e[t]} at dim ${t}`);if(-1===s){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 r=e.slice();return r[s]=t/n,r}function j(e,t){const n=t.length;return O((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}`)),O(e.every((e=>W(e))),(()=>`All values in axis param must be integers but got axis ${e}`)),e.map((e=>e<0?n+e:e))}function q(e,t){const n=[],s=[],r=null!=t&&Array.isArray(t)&&0===t.length,a=null==t||r?null:j(t,e).sort();let i=0;for(let t=0;tt)&&1===e[t]&&(n.push(e[t]),s.push(t)),a[i]<=t&&i++}1!==e[t]&&(n.push(e[t]),s.push(t))}return{newShape:n,keptDims:s}}function K(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 X(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 Y(e,t){return"complex64"!==t&&(("float32"!==t||"complex64"===e)&&(("int32"!==t||"float32"===e||"complex64"===e)&&("bool"!==t||"bool"!==e)))}function Z(e){return e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray}function J(e){if("float32"===e||"int32"===e)return 4;if("complex64"===e)return 8;if("bool"===e)return 1;throw new Error(`Unknown dtype ${e}`)}function Q(e){return"string"==typeof e||e instanceof String}function ee(e){return"number"==typeof e}function te(e){return Array.isArray(e)?te(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray?"int32":ee(e)?"float32":Q(e)?"string":"boolean"==typeof e?"bool":"float32"}function ne(e){return!!(e&&e.constructor&&e.call&&e.apply)}function se(e,t){for(let n=t;n=0;--s)n[s]=n[s+1]*e[s+1];return n}function ae(e,t,n,s=!1){const r=new Array;if(1===t.length){const a=t[0]*(s?2:1);for(let t=0;te*t))*(s?2:1);for(let t=0;te*t))*(n?2:1);if(0===s)return[];if(s!==t.length)throw new Error(`[${e}] does not match the input size ${t.length}${n?" for a complex tensor":""}.`);return ae(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 ie(e,new Float32Array(n));if("int32"===t)return ie(e,new Int32Array(n));if("bool"===t)return ie(e,new Uint8Array(n));throw new Error(`Unknown data type ${t}`)}function ce(e){e.forEach((t=>{O(Number.isInteger(t)&&t>=0,(()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`))}))}function he(e,t,n){if(0===t)return 0;if(1===t)return e[0];let s=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 ye(){return xe}let be,xe=null;function we(){if(null==be){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}be=e}return be}function ve(e,t){const n=function(){const e=we();return null==e._tfGlobals&&(e._tfGlobals=new Map),e._tfGlobals}();if(n.has(e))return n.get(e);{const s=t();return n.set(e,s),n.get(e)}}const ke="Abs",Ie="Acos",Ne="Acosh",Se="Add",Te="AddN",Ce="All",$e="Any",Ee="ArgMax",Re="ArgMin",Ae="Asin",Fe="Asinh",_e="Atan",De="Atanh",Oe="Atan2",Me="AvgPool",Le="AvgPoolGrad",ze="AvgPool3D",Pe="AvgPool3DGrad",Be="BatchMatMul",We="BatchToSpaceND",Ve="Bincount",Ue="BroadcastArgs",Ge="Cast",He="Ceil",je="ClipByValue",qe="Complex",Ke="ComplexAbs",Xe="Concat",Ye="Conv2D",Ze="Conv2DBackpropFilter",Je="Conv2DBackpropInput",Qe="Conv3D",et="Conv3DBackpropFilterV2",tt="Conv3DBackpropInputV2",nt="Cos",st="Cosh",rt="Cumprod",at="Cumsum",it="CropAndResize",ot="DenseBincount",lt="DepthToSpace",ut="DepthwiseConv2dNative",ct="DepthwiseConv2dNativeBackpropFilter",ht="DepthwiseConv2dNativeBackpropInput",pt="Diag",dt="Dilation2D",ft="Dilation2DBackpropInput",mt="Dilation2DBackpropFilter",gt="RealDiv",yt="Einsum",bt="Elu",xt="EluGrad",wt="Erf",vt="Equal",kt="Exp",It="ExpandDims",Nt="Expm1",St="FFT",Tt="Fill",Ct="FlipLeftRight",$t="Floor",Et="FloorDiv",Rt="FusedBatchNorm",At="GatherV2",Ft="GatherNd",_t="Greater",Dt="GreaterEqual",Ot="Identity",Mt="IFFT",Lt="Imag",zt="IsFinite",Pt="IsInf",Bt="IsNan",Wt="LeakyRelu",Vt="Less",Ut="LessEqual",Gt="LinSpace",Ht="Log",jt="Log1p",qt="LogicalAnd",Kt="LogicalNot",Xt="LogicalOr",Yt="LRN",Zt="LRNGrad",Jt="Max",Qt="Maximum",en="MaxPool",tn="MaxPoolGrad",nn="MaxPool3D",sn="MaxPool3DGrad",rn="MaxPoolWithArgmax",an="Mean",on="Min",ln="Minimum",un="MirrorPad",cn="Mod",hn="Multinomial",pn="Multiply",dn="Neg",fn="NotEqual",mn="NonMaxSuppressionV3",gn="NonMaxSuppressionV4",yn="NonMaxSuppressionV5",bn="OnesLike",xn="OneHot",wn="Pack",vn="PadV2",kn="Pow",In="Prelu",Nn="Prod",Sn="RaggedGather",Tn="RaggedTensorToTensor",Cn="Range",$n="Real",En="Reciprocal",Rn="Relu",An="Reshape",Fn="ResizeNearestNeighbor",_n="ResizeNearestNeighborGrad",Dn="ResizeBilinear",On="ResizeBilinearGrad",Mn="Relu6",Ln="Reverse",zn="Round",Pn="Rsqrt",Bn="ScatterNd",Wn="SearchSorted",Vn="Select",Un="Selu",Gn="Slice",Hn="Sin",jn="Sinh",qn="Sign",Kn="Sigmoid",Xn="Softplus",Yn="Sqrt",Zn="Sum",Jn="SpaceToBatchND",Qn="SplitV",es="Softmax",ts="SparseFillEmptyRows",ns="SparseReshape",ss="SparseSegmentMean",rs="SparseSegmentSum",as="SparseToDense",is="SquaredDifference",os="Square",ls="StridedSlice",us="StringNGrams",cs="StringSplit",hs="StringToHashBucketFast",ps="Sub",ds="Tan",fs="Tanh",ms="Tile",gs="TopK",ys="Transform",bs="Transpose",xs="Unique",ws="Unpack",vs="UnsortedSegmentSum",ks="ZerosLike",Is="Step",Ns="FromPixels",Ss="RotateWithOffset",Ts="_FusedMatMul",Cs="FusedConv2D",$s="FusedDepthwiseConv2D"; +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function Es(...e){ye().getBool("IS_TEST")||ye().getBool("PROD")||console.warn(...e)}function Rs(...e){ye().getBool("IS_TEST")||ye().getBool("PROD")||console.log(...e)} +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +const As=ve("kernelRegistry",(()=>new Map)),Fs=ve("gradRegistry",(()=>new Map));function _s(e,t){const n=zs(e,t);return As.get(n)}function Ds(e){return Fs.get(e)}function Os(e){const t=As.entries(),n=[];for(;;){const{done:s,value:r}=t.next();if(s)break;const[a,i]=r,[o]=a.split("_");o===e&&n.push(i)}return n}function Ms(e){const{kernelName:t,backendName:n}=e,s=zs(t,n);As.has(s)&&Es(`The kernel '${t}' for backend '${n}' is already registered`),As.set(s,e)}function Ls(e){const{kernelName:t}=e;Fs.has(t)&&ye().getBool("DEBUG")&&Es(`Overriding the gradient for '${t}'`),Fs.set(t,e)}function zs(e,t){return`${t}_${e}`}var Ps=n(570); +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +const Bs=n.n(Ps)()||Ps;function Ws(e){return Bs.fromString(e,!0,16)}const Vs=Ws("c3a5c85c97cb3127"),Us=Ws("b492b66fbe98f273"),Gs=Ws("9ae16a3b2f90404f");function Hs(e){return e.xor(e.shru(47))}function js(e,t,n){const s=e.slice(t,t+n);return Bs.fromBytes(Array.from(s),!0,!0)}function qs(e,t){return js(e,t,8)}function Ks(e,t){return js(e,t,4)}function Xs(e,t){return 0===t?e:e.shru(t).or(e.shl(64-t))}function Ys(e,t,n=Ws("9ddfea08eb382d69")){let s=e.xor(t).mul(n);s=s.xor(s.shru(47));let r=t.xor(s).mul(n);return r=r.xor(r.shru(47)),r=r.mul(n),r}function Zs(e,t,n,s){return function(e,t,n,s,r,a){r=r.add(e),a=Xs(a.add(r).add(s),21);const i=r;return r=(r=r.add(t)).add(n),a=a.add(Xs(r,44)),[r.add(s),a.add(i)]}(qs(e,t),qs(e,t+8),qs(e,t+16),qs(e,t+24),n,s)}function Js(e,t=e.length){const n=Bs.fromNumber(81,!0);if(t<=32)return t<=16?function(e,t=e.length){if(t>=8){const n=Gs.add(2*t),s=qs(e,0).add(Gs),r=qs(e,t-8);return Ys(Xs(r,37).mul(n).add(s),Xs(s,25).add(r).mul(n),n)}if(t>=4){const n=Gs.add(2*t);return Ys(Ks(e,0).shl(3).add(t),Ks(e,t-4),n)}if(t>0){const n=e[0]+(e[t>>1]<<8),s=t+(e[t-1]<<2);return Hs(Gs.mul(n).xor(Vs.mul(s))).mul(Gs)}return Gs}(e,t):function(e,t=e.length){const n=Gs.add(2*t),s=qs(e,0).mul(Us),r=qs(e,8),a=qs(e,t-8).mul(n),i=qs(e,t-16).mul(Gs);return Ys(Xs(s.add(r),43).add(Xs(a,30)).add(i),s.add(Xs(r.add(Gs),18)).add(a),n)}(e,t);if(t<=64)return function(e,t=e.length){const n=Gs.add(2*t),s=qs(e,0).mul(Gs),r=qs(e,8),a=qs(e,t-8).mul(n),i=qs(e,t-16).mul(Gs),o=Xs(s.add(r),43).add(Xs(a,30)).add(i),l=Ys(o,s.add(Xs(r.add(Gs),18)).add(a),n),u=qs(e,16).mul(n),c=qs(e,24),h=o.add(qs(e,t-32)).mul(n),p=l.add(qs(e,t-24)).mul(n);return Ys(Xs(u.add(c),43).add(Xs(h,30)).add(p),u.add(Xs(c.add(s),18)).add(h),n)}(e,t);let s=n,r=n.mul(Us).add(113),a=Hs(r.mul(Gs).add(113)).mul(Gs),i=[Bs.UZERO,Bs.UZERO],o=[Bs.UZERO,Bs.UZERO];s=s.mul(Gs).add(qs(e,0));let l=0;const u=64*(t-1>>6),c=u+(t-1&63)-63;do{s=Xs(s.add(r).add(i[0]).add(qs(e,l+8)),37).mul(Us),r=Xs(r.add(i[1]).add(qs(e,l+48)),42).mul(Us),s=s.xor(o[1]),r=r.add(i[0]).add(qs(e,l+40)),a=Xs(a.add(o[0]),33).mul(Us),i=Zs(e,l,i[1].mul(Us),s.add(o[0])),o=Zs(e,l+32,a.add(o[1]),r.add(qs(e,l+16))),[a,s]=[s,a],l+=64}while(l!==u);const h=Us.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]),s=Xs(s.add(r).add(i[0]).add(qs(e,l+8)),37).mul(h),r=Xs(r.add(i[1]).add(qs(e,l+48)),42).mul(h),s=s.xor(o[1].mul(9)),r=r.add(i[0].mul(9).add(qs(e,l+40))),a=Xs(a.add(o[0]),33).mul(h),i=Zs(e,l,i[1].mul(h),s.add(o[0])),o=Zs(e,l+32,a.add(o[1]),r.add(qs(e,l+16))),[a,s]=[s,a],Ys(Ys(i[0],o[0],h).add(Hs(r).mul(Vs)).add(a),Ys(i[1],o[1],h).add(s),h)} +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function Qs(e,t){return"string"===t?nr(e):er([e],t)}function er(e,t){if("string"===t)throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=z(e)),ye().getBool("DEBUG")&&function(e,t){for(let n=0;n{s=n()};let a;const i=tr();if(this.backendTimer.timerAvailable())a=this.backendTimer.time(r);else{r();for(const e of s)e.dataSync();a=Promise.resolve({kernelMs:tr()-i})}if(ye().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let t=0;t{ar(t,n.dtype,e)}))}return{kernelName:e,outputs:s,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:s,inputs:r,extraInfo:a}=e;n.forEach((e=>{Promise.all([e.data(),s,a]).then((n=>{this.logger.logKernelProfile(t,e,n[0],n[1],r,n[2])}))}))}}function ar(e,t,n){if("float32"!==t)return!1;for(let t=0;t0?s:""} `}}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 or(e,t,n,s){const r=re(t),a=function(e,t,n,s){const r=P(t),a=s[s.length-1],i=new Array(a).fill(0),o=t.length,l="complex64"===n?hr(e):e;if(o>1)for(let e=0;e" "+e)).join("\n")),l.join("\n")}function lr(e,t,n){let s;return s=Array.isArray(e)?`${parseFloat(e[0].toFixed(7))} + ${parseFloat(e[1].toFixed(7))}j`:Q(e)?`'${e}'`:"bool"===n?ur(e):parseFloat(e.toFixed(7)).toString(),U(s,t)}function ur(e){return 0===e?"false":"true"}function cr(e,t,n,s,r,a=!0){const i="complex64"===n?2:1,o=t[0],l=t.length;if(0===l){if("complex64"===n){return[lr(hr(e)[0],0,n)]}return"bool"===n?[ur(e[0])]:[e[0].toString()]}if(1===l){if(o>20){const t=3*i;let s=Array.from(e.slice(0,t)),a=Array.from(e.slice((o-3)*i,o*i));return"complex64"===n&&(s=hr(s),a=hr(a)),["["+s.map(((e,t)=>lr(e,r[t],n))).join(", ")+", ..., "+a.map(((e,t)=>lr(e,r[o-3+t],n))).join(", ")+"]"]}return["["+("complex64"===n?hr(e):Array.from(e)).map(((e,t)=>lr(e,r[t],n))).join(", ")+"]"]}const u=t.slice(1),c=s.slice(1),h=s[0]*i,p=[];if(o>20){for(let t=0;t<3;t++){const s=t*h,a=s+h;p.push(...cr(e.slice(s,a),u,n,c,r,!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||X(t,this.size),this.strides=re(e)}set(e,...t){0===t.length&&(t=[0]),O(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;tsr(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(),dr().readToGPU(this.dataId,e)}dataSync(){this.throwIfDisposed();const e=dr().readSync(this.dataId);if("string"===this.dtype)try{return e.map((e=>sr(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 dr().read(this.dataId);return"string"===this.dtype?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(dr().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return fr.print(this,e)}clone(){return this.throwIfDisposed(),fr.clone(this)}toString(e=!1){return or(this.dataSync(),this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),fr.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),dr().makeVariable(this,e,t,n)}}function yr(){return ve("Tensor",(()=>gr))}Object.defineProperty(gr,Symbol.hasInstance,{value:e=>!!e&&null!=e.data&&null!=e.dataSync&&null!=e.throwIfDisposed}),yr();class br extends gr{constructor(e,t,n,s){super(e.shape,e.dtype,e.dataId,s),this.trainable=t,this.name=n}assign(e){if(e.dtype!==this.dtype)throw new Error(`dtype of the new value (${e.dtype}) and previous value (${this.dtype}) must match`);if(!B(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);dr().disposeTensor(this),this.dataId=e.dataId,dr().incRef(this,null)}dispose(){dr().disposeVariable(this),this.isDisposedInternal=!0}} +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +var xr,wr,vr,kr,Ir;Object.defineProperty(br,Symbol.hasInstance,{value:e=>e instanceof gr&&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"}(xr||(xr={})),function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"}(wr||(wr={})),function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"}(vr||(vr={})),function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"}(kr||(kr={})),function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"}(Ir||(Ir={}));const Nr={float32:kr,int32:wr,bool:vr,complex64:Ir};function Sr(e,t){if("string"===e||"string"===t){if("string"===e&&"string"===t)return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return Nr[e][t]}function Tr(e){return Sr(e,"int32")} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function Cr(e,t){if(e.dtype===t.dtype)return[e,t];const n=Sr(e.dtype,t.dtype);return[e.cast(n),t.cast(n)]}function $r(e,t){return t.some((t=>t.id===e.id))}function Er(e){const t=[];return Rr(e,t,new Set),t}function Rr(e,t,n){if(null==e)return;if(e instanceof gr)return void t.push(e);if(s=e,!Array.isArray(s)&&"object"!=typeof s)return;var s;const r=e;for(const e in r){const s=r[e];n.has(s)||(n.add(s),Rr(s,t,n))}} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function Ar(e){return null!=e.kernelName}class Fr{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 _r{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new Fr}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){Os(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 E||"function"!=typeof n.then)return this.registry[e]=n,{success:!0,asyncInit:!1};{const t=++this.pendingBackendInitId,s=n.then((n=>!(t(tthis.registryFactory[t].priority-this.registryFactory[e].priority))}initializeBackendsAndReturnBest(){const e=this.getSortedBackends();for(let t=0;tthis.startScope(s)),(()=>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 _r.nextTensorId++}nextVariableId(){return _r.nextVariableId++}clone(e){const t=Or.runKernel(Ot,{x:e}),n={x:e};return this.addTapeNode(this.state.activeScope.name,n,[t],(e=>({x:()=>{const t={x:e},n={dtype:"float32"};return Or.runKernel(Ge,t,n)}})),[],{}),t}runKernel(e,t,n){null==this.backendName&&this.backend;if(!(null!=_s(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 s=this.backend.numDataIds();let r=0;n.forEach((e=>{r+="complex64"===e.dtype?3:1}));const a=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],i=s-t-r-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 s=this.isTapeOn(),r=this.state.numBytes,a=this.state.numTensors;let i,o;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0),null==this.backendName&&this.backend;const l=Ar(e)?e.kernelName:null!=this.state.activeScope?this.state.activeScope.name:"";if(Ar(e)){const{kernelName:t,inputs:r,attrs:a}=e;null==this.backendName&&this.backend;const l=_s(t,this.backendName);O(null!=l,(()=>`Cannot find registered kernel '${t}' for backend '${this.backendName}'`)),i=()=>{const e=this.backend.numDataIds();o=l.kernelFunc({inputs:r,attrs:a,backend:this.backend});const i=Array.isArray(o)?o:[o];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(t,e,i);const u=i.map((e=>null!=e.rank?e:this.makeTensorFromTensorInfo(e)));if(s){const e=this.getTensorsForGradient(t,r,u);n=this.saveTensorsForBackwardMode(e)}return u}}else{const{forwardFunc:t}=e,r=e=>{s&&(n=e.map((e=>this.keep(this.clone(e)))))};i=()=>{const e=this.backend.numDataIds();o=this.tidy((()=>t(this.backend,r)));const n=Array.isArray(o)?o:[o];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(l,e,n),n}}const{inputs:u,attrs:c}=e,h=Ar(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()})),s&&this.addTapeNode(l,u,t,h,n,c),this.state.profiling&&this.state.activeProfile.kernels.push({name:l,bytesAdded:this.state.numBytes-r,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){const t=e.map((e=>this.keep(this.clone(e))));return t}getTensorsForGradient(e,t,n){const s=Ds(e);if(null!=s){const e=s.inputsToSave||[],r=s.outputsToSave||[];let a;s.saveAllInputs?(O(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)=>r[t]));return a.concat(i)}return[]}makeTensor(e,t,n,s){if(null==e)throw new Error("Values passed to engine.makeTensor() are null");n=n||"float32",s=s||this.backend;let r=e;"string"===n&&Q(e[0])&&(r=e.map((e=>nr(e))));const a=s.write(r,t,n),i=new gr(t,n,a,this.nextTensorId());if(this.trackTensor(i,s),"string"===n){const e=this.state.tensorInfo.get(a),t=function(e){if(null==e)return 0;let t=0;return e.forEach((e=>t+=e.length)),t}(r);this.state.numBytes+=t-e.bytes,e.bytes=t}return i}makeTensorFromDataId(e,t,n,s){const r={dataId:e,shape:t,dtype:n=n||"float32"};return this.makeTensorFromTensorInfo(r,s)}makeTensorFromTensorInfo(e,t){const{dataId:n,shape:s,dtype:r}=e,a=new gr(s,r,n,this.nextTensorId());return this.trackTensor(a,t),a}makeVariable(e,t=!0,n,s){n=n||this.nextVariableId().toString(),null!=s&&s!==e.dtype&&(e=e.cast(s));const r=new br(e,t,n,this.nextTensorId());if(null!=this.state.registeredVariables[r.name])throw new Error(`Variable with name ${r.name} was already registered`);return this.state.registeredVariables[r.name]=r,this.incRef(r,this.backend),r}trackTensor(e,t){this.state.numTensors++,"string"===e.dtype&&this.state.numStringTensors++;let n=0;"complex64"!==e.dtype&&"string"!==e.dtype&&(n=e.size*J(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 br||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*J(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,s,r,a){const i={id:this.state.nextTapeNodeId++,kernelName:e,inputs:t,outputs:n,saved:r},o=Ds(e);null!=o&&(s=o.gradFunc),null!=s&&(i.gradient=e=>(e=e.map(((e,t)=>{if(null==e){const e=n[t],s=le(e.size,e.dtype);return this.makeTensor(s,e.shape,e.dtype)}return e})),s(e.length>1?e:e[0],r,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=Er(e),n=new Set(t.map((e=>e.id)));for(let e=0;e{e.kept||e.scopeId!==s.id||this.track(e)}))}gradients(e,t,n,s=!1){if(O(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 r=this.scopedRun((()=>this.startTape()),(()=>this.endTape()),(()=>this.tidy("forward",e)));O(r instanceof gr,(()=>"The result y returned by f() must be a tensor."));const a= +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n){const s={},r={};for(let e=0;es[e.id]=!0)),o=!0,r[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],s=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[r.id]=null==n?function(e){const t=oe(P(e),"float32");return Or.makeTensor(t,e,"float32")}(r.shape):n,function(e,t,n,s){for(let r=t.length-1;r>=0;r--){const a=t[r],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 r=n((()=>o[t]()));if("float32"!==r.dtype)throw new Error(`Error in gradient for op ${a.kernelName}. The gradient of input ${t} must have 'float32' dtype, but has '${r.dtype}'`);const i=a.inputs[t];if(!B(r.shape,i.shape))throw new Error(`Error in gradient for op ${a.kernelName}. The gradient of input '${t}' has shape '${r.shape}', which does not match the shape of the input '${i.shape}'`);if(null==e[i.id])e[i.id]=r;else{const t=e[i.id];e[i.id]=s(t,r),t.dispose()}}}}(e,a,(e=>this.tidy(e)),Mr);const s=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:r,grads:s}}))}customGrad(e){return O(ne(e),(()=>"The f passed in customGrad(f) must be a function.")),(...t)=>{let n;O(t.every((e=>e instanceof gr)),(()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors"));const s={};t.forEach(((e,t)=>{s[t]=e}));return this.runKernelFunc({forwardFunc:(s,r)=>(n=e(...t,r),O(n.value instanceof gr,(()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor")),O(ne(n.gradFunc),(()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function.")),n.value),backwardsFunc:(e,s)=>{const r=n.gradFunc(e,s),a=Array.isArray(r)?r:[r];O(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(...).")),O(a.every((e=>e instanceof gr)),(()=>"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:s})}}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=tr(),n=await this.backend.time(e);return n.wallMs=tr()-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 Fr;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 Dr(){const e=we();if(null==e._tfengine){const t=new me(e);e._tfengine=new _r(t)}var t;return t=e._tfengine.ENV,xe=t,dr=()=>e._tfengine,e._tfengine}_r.nextTensorId=0,_r.nextVariableId=0;const Or=Dr();function Mr(e,t){const n={a:e,b:t};return Or.runKernel(Se,n)}let Lr;function zr(e){if(void 0!==Lr)return Lr;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 Pr(){return"undefined"!=typeof window&&null!=window.document||"undefined"!=typeof WorkerGlobalScope} +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +const Br=ye(); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function Wr(e,t){let n=e;if(Z(e))return"string"===t?[]:[e.length];if(!Array.isArray(e))return[];const s=[];for(;Array.isArray(n)||Z(n)&&"string"!==t;)s.push(n.length),n=n[0];return Array.isArray(e)&&ye().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&Vr(e,s,[]),s}function Vr(e,t,n){if(n=n||[],!Array.isArray(e)&&!Z(e))return void O(0===t.length,(()=>`Element arr[${n.join("][")}] is a primitive, but should be an array/TypedArray of ${t[0]} elements`));O(t.length>0,(()=>`Element arr[${n.join("][")}] should be a primitive, but is an array of ${e.length} elements`)),O(e.length===t[0],(()=>`Element arr[${n.join("][")}] should have ${t[0]} elements, but has ${e.length} elements`));const s=t.slice(1);for(let t=0;t=0&&(r=s),Ur(s,r,t,n),null==e||!Z(e)&&!Array.isArray(e)&&"number"!=typeof e&&"boolean"!=typeof e&&"string"!=typeof e){const s=null==e?"null":e.constructor.name;throw new Error(`Argument '${t}' passed to '${n}' must be a Tensor or TensorLike, but got '${s}'`)}const a=Wr(e,r);Z(e)||Array.isArray(e)||(e=[e]);const i="string"!==r?er(e,r):z(e,[],!0);return Or.makeTensor(i,a,r)}function Hr(e,t,n,s="numeric"){if(!Array.isArray(e))throw new Error(`Argument ${t} passed to ${n} must be a \`Tensor[]\` or \`TensorLike[]\``);return e.map(((e,r)=>Gr(e,`${t}[${r}]`,n,s)))}Br.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.")})),Br.registerFlag("IS_BROWSER",(()=>Pr())),Br.registerFlag("IS_NODE",(()=>"undefined"!=typeof process&&void 0!==process.versions&&void 0!==process.versions.node)),Br.registerFlag("IS_CHROME",(()=>"undefined"!=typeof navigator&&null!=navigator&&null!=navigator.userAgent&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor))),Br.registerFlag("PROD",(()=>!1)),Br.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",(()=>Br.getBool("DEBUG"))),Br.registerFlag("DEPRECATION_WARNINGS_ENABLED",(()=>!0)),Br.registerFlag("IS_TEST",(()=>!1)),Br.registerFlag("CHECK_COMPUTATION_FOR_ERRORS",(()=>!0)),Br.registerFlag("WRAP_TO_IMAGEBITMAP",(()=>!1)),Br.registerFlag("ENGINE_COMPILE_ONLY",(()=>!1)),Br.registerFlag("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU",(()=>!1)),Br.registerFlag("USE_SETTIMEOUTCUSTOM",(()=>!1)); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +const jr="__op";function qr(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 s=e[n];n.endsWith("_")&&(n=n.substring(0,n.length-1)),n+=jr;const r=(...e)=>{Or.startScope(n);try{const t=s(...e);return de(t)&&console.error("Cannot return a Promise inside of tidy."),Or.endScope(t),t}catch(e){throw Or.endScope(null),e}};return Object.defineProperty(r,"name",{value:n,configurable:!0}),r}const Kr=qr({complex_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t){const n=Gr(e,"real","complex"),s=Gr(t,"imag","complex");M(n.shape,s.shape,`real and imag shapes, ${n.shape} and ${s.shape}, must match in call to tf.complex().`);const r={real:n,imag:s};return Or.runKernel(qe,r)}}); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function Xr(e,t,n,s){if(null==s&&(s=te(e)),"complex64"===s)throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!Z(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){ce(t);const e=P(t),s=P(n);O(e===s,(()=>`Based on the provided shape, [${t}], the tensor should have ${e} values but has ${s}`));for(let e=0;e`Error creating a new Tensor. Inferred shape (${n}) does not match the provided shape (${t}). `))}}return Z(e)||Array.isArray(e)||(e=[e]),t=t||n,e="string"!==s?er(e,s):z(e,[],!0),Or.makeTensor(e,t,s)} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function Yr(e,t,n){return Xr(e,t,Wr(e,n),n)} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +const Zr={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8},Jr=4;async function Qr(e,t){const n=[],s=[],r=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)+Jr*t.length,s=new Uint8Array(n);let r=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 s=new Uint8Array(t);let r=0;return n.forEach((e=>{s.set(new Uint8Array(e.buffer),r),r+=e.byteLength})),s.buffer}const na="undefined"!=typeof Buffer&&("undefined"==typeof Blob||"undefined"==typeof atob||"undefined"==typeof btoa);function sa(e){return na?Buffer.byteLength(e):new Blob([e]).size}function ra(e){if(1===e.length)return e[0];let t=0;e.forEach((e=>{t+=e.byteLength}));const n=new Uint8Array(t);let s=0;return e.forEach((e=>{n.set(new Uint8Array(e),s),s+=e.byteLength})),n.buffer}function aa(e){for(e=e.trim();e.endsWith("/");)e=e.slice(0,e.length-1);const t=e.split("/");return t[t.length-1]}function ia(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}function oa(e,t,n){const s={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy};if(null!=e.trainingConfig&&(s.trainingConfig=e.trainingConfig),null!=e.weightsManifest){if(!t)throw new Error("modelJSON has weightsManifest but weightSpecs is null");if(!n)throw new Error("modelJSON has weightsManifest but weightData is null");s.weightSpecs=t,s.weightData=n}return null!=e.signature&&(s.signature=e.signature),null!=e.userDefinedMetadata&&(s.userDefinedMetadata=e.userDefinedMetadata),null!=e.modelInitializer&&(s.modelInitializer=e.modelInitializer),s}async function la(e,t){let n,s;return null!=e.weightsManifest&&([n,s]=await t(e.weightsManifest)),oa(e,n,s)}function ua(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:sa(JSON.stringify(e.modelTopology)),weightSpecsBytes:null==e.weightSpecs?0:sa(JSON.stringify(e.weightSpecs)),weightDataBytes:null==e.weightData?0:e.weightData.byteLength}}function ca(e){const t=[];for(const n of e)t.push(...n.weights);return t}function ha(){const e=function(){const e=e=>{let t=e<<13,n=0;for(;!(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 s=>{const r=new ArrayBuffer(4*s.length),a=new Uint32Array(r);for(let r=0;r>10]+(1023&i)]+t[i>>10];a[r]=o}return new Float32Array(r)}} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class pa{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return null==pa.instance&&(pa.instance=new pa),pa.instance}static registerSaveRouter(e){pa.getInstance().saveRouters.push(e)}static registerLoadRouter(e){pa.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return pa.getHandlers(e,"save")}static getLoadHandlers(e,t){return pa.getHandlers(e,"load",t)}static getHandlers(e,t,n){const s=[];return("load"===t?pa.getInstance().loadRouters:pa.getInstance().saveRouters).forEach((t=>{const r=t(e,n);null!==r&&s.push(r)})),s}}const da=e=>pa.registerSaveRouter(e),fa=e=>pa.registerLoadRouter(e),ma=e=>pa.getSaveHandlers(e),ga=(e,t)=>pa.getLoadHandlers(e,t),ya="tensorflowjs",ba="models_store",xa="model_info_store";function wa(){if(!ye().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 va(e){const t=e.result;t.createObjectStore(ba,{keyPath:"modelPath"}),t.createObjectStore(xa,{keyPath:"modelPath"})}class ka{constructor(e){if(this.indexedDB=wa(),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 s=this.indexedDB.open(ya,1);s.onupgradeneeded=()=>va(s),s.onsuccess=()=>{const r=s.result;if(null==t){const t=r.transaction(ba,"readonly"),s=t.objectStore(ba).get(this.modelPath);s.onsuccess=()=>{if(null==s.result)return r.close(),n(new Error(`Cannot find model with path '${this.modelPath}' in IndexedDB.`));e(s.result.modelArtifacts)},s.onerror=e=>(r.close(),n(s.error)),t.oncomplete=()=>r.close()}else{const s=ua(t),a=r.transaction(xa,"readwrite");let i=a.objectStore(xa);const o=i.put({modelPath:this.modelPath,modelArtifactsInfo:s});let l;o.onsuccess=()=>{l=r.transaction(ba,"readwrite");const o=l.objectStore(ba).put({modelPath:this.modelPath,modelArtifacts:t,modelArtifactsInfo:s});o.onsuccess=()=>e({modelArtifactsInfo:s}),o.onerror=e=>{i=a.objectStore(xa);const t=i.delete(this.modelPath);t.onsuccess=()=>(r.close(),n(o.error)),t.onerror=e=>(r.close(),n(o.error))}},o.onerror=e=>(r.close(),n(o.error)),a.oncomplete=()=>{null==l?r.close():l.oncomplete=()=>r.close()}}},s.onerror=e=>n(s.error)}))}}ka.URL_SCHEME="indexeddb://";const Ia=e=>{return ye().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(ka.URL_SCHEME)?(t=e.slice(ka.URL_SCHEME.length),new ka(t)):null;var t};pa.registerSaveRouter(Ia),pa.registerLoadRouter(Ia);class Na{constructor(){this.indexedDB=wa()}async listModels(){return new Promise(((e,t)=>{const n=this.indexedDB.open(ya,1);n.onupgradeneeded=()=>va(n),n.onsuccess=()=>{const s=n.result,r=s.transaction(xa,"readonly"),a=r.objectStore(xa).getAll();a.onsuccess=()=>{const t={};for(const e of a.result)t[e.modelPath]=e.modelArtifactsInfo;e(t)},a.onerror=e=>(s.close(),t(a.error)),r.oncomplete=()=>s.close()},n.onerror=e=>t(n.error)}))}async removeModel(e){var t;return e=(t=e).startsWith(ka.URL_SCHEME)?t.slice(ka.URL_SCHEME.length):t,new Promise(((t,n)=>{const s=this.indexedDB.open(ya,1);s.onupgradeneeded=()=>va(s),s.onsuccess=()=>{const r=s.result,a=r.transaction(xa,"readwrite"),i=a.objectStore(xa),o=i.get(e);let l;o.onsuccess=()=>{if(null==o.result)return r.close(),n(new Error(`Cannot find model with path '${e}' in IndexedDB.`));{const s=i.delete(e),a=()=>{l=r.transaction(ba,"readwrite");const s=l.objectStore(ba).delete(e);s.onsuccess=()=>t(o.result.modelArtifactsInfo),s.onerror=e=>n(o.error)};s.onsuccess=a,s.onerror=e=>(a(),r.close(),n(o.error))}},o.onerror=e=>(r.close(),n(o.error)),a.oncomplete=()=>{null==l?r.close():l.oncomplete=()=>r.close()}},s.onerror=e=>n(s.error)}))}} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +const Sa="/",Ta="tensorflowjs_models",Ca="info",$a="model_topology",Ea="weight_specs",Ra="weight_data",Aa="model_metadata";function Fa(e){return{info:[Ta,e,Ca].join(Sa),topology:[Ta,e,$a].join(Sa),weightSpecs:[Ta,e,Ea].join(Sa),weightData:[Ta,e,Ra].join(Sa),modelMetadata:[Ta,e,Aa].join(Sa)}}function _a(e){for(const t of Object.values(e))window.localStorage.removeItem(t)}function Da(e){const t=e.split(Sa);if(t.length<3)throw new Error(`Invalid key format: ${e}`);return t.slice(1,t.length-1).join(Sa)}class Oa{constructor(e){if(!ye().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=Fa(this.modelPath)}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");{const t=JSON.stringify(e.modelTopology),n=JSON.stringify(e.weightSpecs),s=ua(e);try{this.LS.setItem(this.keys.info,JSON.stringify(s)),this.LS.setItem(this.keys.topology,t),this.LS.setItem(this.keys.weightSpecs,n),this.LS.setItem(this.keys.weightData,function(e){if(na)return Buffer.from(e).toString("base64");const t=new Uint8Array(e);let n="";for(let e=0,s=t.length;e{return ye().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(Oa.URL_SCHEME)?(t=e.slice(Oa.URL_SCHEME.length),new Oa(t)):null;var t};pa.registerSaveRouter(Ma),pa.registerLoadRouter(Ma);class La{constructor(){O(ye().getBool("IS_BROWSER"),(()=>"Current environment is not a web browser")),O("undefined"==typeof window||void 0!==window.localStorage,(()=>"Current browser does not appear to support localStorage")),this.LS=window.localStorage}async listModels(){const e={},t=Ta+Sa,n=Sa+Ca;for(let s=0;s"scheme must not be undefined or null.")),e.endsWith(za)&&(e=e.slice(0,e.indexOf(za))),O(e.length>0,(()=>"scheme must not be an empty string."));const n=Pa.getInstance();O(null==n.managers[e],(()=>`A model store manager is already registered for scheme '${e}'.`)),n.managers[e]=t}static getManager(e){const t=Pa.getInstance().managers[e];if(null==t)throw new Error(`Cannot find model manager for scheme '${e}'`);return t}static getSchemes(){return Object.keys(Pa.getInstance().managers)}}function Ba(e){if(-1===e.indexOf(za))throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${Pa.getSchemes().join(",")}`);return{scheme:e.split(za)[0],path:e.split(za)[1]}}async function Wa(e,t,n=!1){O(e!==t,(()=>`Old path and new path are the same: '${e}'`));const s=pa.getLoadHandlers(e);O(s.length>0,(()=>`Copying failed because no load handler is found for source URL ${e}.`)),O(s.length<2,(()=>`Copying failed because more than one (${s.length}) load handlers for source URL ${e}.`));const r=s[0],a=pa.getSaveHandlers(t);O(a.length>0,(()=>`Copying failed because no save handler is found for destination URL ${t}.`)),O(a.length<2,(()=>`Copying failed because more than one (${s.length}) save handlers for destination URL ${t}.`));const i=a[0],o=Ba(e).scheme,l=Ba(e).path,u=o===Ba(e).scheme,c=await r.load();n&&u&&await Pa.getManager(o).removeModel(l);const h=await i.save(c);return n&&!u&&await Pa.getManager(o).removeModel(l),h.modelArtifactsInfo}async function Va(){const e=Pa.getSchemes(),t={};for(const n of e){const e=await Pa.getManager(n).listModels();for(const s in e){t[n+za+s]=e[s]}}return t}async function Ua(e){const t=Ba(e);return Pa.getManager(t.scheme).removeModel(t.path)}async function Ga(e,t){return Wa(e,t,!1)}async function Ha(e,t){return Wa(e,t,!0)} +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class ja{constructor(){this.messageName="setTimeoutCustom",this.functionRefs=[],this.handledMessageCount=0,this.hasEventListener=!1}fetch(e,t){return fetch(e,t)}now(){return performance.now()}encode(e,t){if("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)}setTimeoutCustom(e,t){window&&ye().getBool("USE_SETTIMEOUTCUSTOM")?(this.functionRefs.push(e),setTimeout((()=>{window.postMessage({name:this.messageName,index:this.functionRefs.length-1},"*")}),t),this.hasEventListener||(this.hasEventListener=!0,window.addEventListener("message",(e=>{if(e.source===window&&e.data.name===this.messageName){e.stopPropagation();(0,this.functionRefs[e.data.index])(),this.handledMessageCount++,this.handledMessageCount===this.functionRefs.length&&(this.functionRefs=[],this.handledMessageCount=0)}}),!0))):setTimeout(e,t)}}if(ye().get("IS_BROWSER")){ye().setPlatform("browser",new ja);try{Pa.registerManager(Oa.URL_SCHEME,new La)}catch(e){}try{Pa.registerManager(ka.URL_SCHEME,new Na)}catch(e){}} +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +const qa=()=>n(817);let Ka;class Xa{constructor(){this.util=n(590),this.textEncoder=new this.util.TextEncoder}fetch(e,t){return null!=ye().global.fetch?ye().global.fetch(e,t):(null==Ka&&(Ka=qa()),Ka(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)}} +/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function Ya(e,t="float32",n){return t=t||"float32",ce(e),new pr(e,t,n)}ye().get("IS_NODE")&&!ye().get("IS_BROWSER")&&ye().setPlatform("node",new Xa);const Za=qr({cast_: +/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t){const n=Gr(e,"x","cast");if(!function(e){return"bool"===e||"complex64"===e||"float32"===e||"int32"===e||"string"===e}(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 s={x:n},r={dtype:t};return Or.runKernel(Ge,s,r)}});const Ja=qr({clone_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const t={x:Gr(e,"x","clone","string_or_numeric")};return Or.runKernel(Ot,t)}}); +/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function Qa(e,t=!1){console.log(e.toString(t))} +/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +Dr();fr={buffer:Ya,cast:Za,clone:Ja,print:Qa};function ei(e){return new Promise((e=>setTimeout(e))).then(e)}class ti{constructor(e){if(!ye().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(ti.URL_SCHEME)&&(e=e.slice(ti.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=ia(e,[{paths:["./"+this.weightDataFileName],weights:e.weightSpecs}]),s=window.URL.createObjectURL(new Blob([JSON.stringify(n)],{type:"application/json"})),r=null==this.modelJsonAnchor?document.createElement("a"):this.modelJsonAnchor;if(r.download=this.modelJsonFileName,r.href=s,await ei((()=>r.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:ua(e)}}}}ti.URL_SCHEME="downloads://";class ni{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 s=JSON.parse(n.target.result),r=s.modelTopology;if(null==r)return void t(new Error(`modelTopology field is missing from file ${this.jsonFile.name}`));if(null==s.weightsManifest)return void t(new Error(`weightManifest field is missing from file ${this.jsonFile.name}`));if(0===this.weightsFiles.length)return void e({modelTopology:r});const a=la(s,(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 s of e)t.push(...s.weights),n.push(...s.paths);const s=this.checkManifestAndWeightFiles(e),r=n.map((e=>this.loadWeightsFile(e,s[e])));return Promise.all(r).then((e=>[t,ra(e)]))}loadWeightsFile(e,t){return new Promise(((n,s)=>{const r=new FileReader;r.onload=e=>{const t=e.target.result;n(t)},r.onerror=t=>s(`Failed to weights data from file of path '${e}'.`),r.readAsArrayBuffer(t)}))}checkManifestAndWeightFiles(e){const t=[],n=this.weightsFiles.map((e=>aa(e.name))),s={};for(const r of e)r.paths.forEach((e=>{const r=aa(e);if(-1!==t.indexOf(r))throw new Error(`Duplicate file basename found in weights manifest: '${r}'`);if(t.push(r),-1===n.indexOf(r))throw new Error(`Weight file with basename '${r}' is not provided.`);s[e]=this.weightsFiles[n.indexOf(r)]}));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 s}}function si(e){return new ni(e)} +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function ri(e,t,n,s){!function(e){O(null!=e&&Array.isArray(e)&&e.length>0,(()=>"promises must be a none empty array"))}(e),function(e,t){O(e>=0&&e<=1,(()=>`Progress fraction must be in range [0, 1], but got startFraction ${e}`)),O(t>=0&&t<=1,(()=>`Progress fraction must be in range [0, 1], but got endFraction ${t}`)),O(t>=e,(()=>`startFraction must be no more than endFraction, but got startFraction ${e} and endFraction ${t}`))}(n=null==n?0:n,s=null==s?1:s);let r=0;return Promise.all(e.map((a=>(a.then((a=>{const i=n+ ++r/e.length*(s-n);return t(i),a})),a))))} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +async function ai(e,t){null==t&&(t={});const n=null==t.fetchFunc?ye().platform.fetch:t.fetchFunc,s=e.map((e=>n(e,t.requestInit,{isBinary:!0}))),r=(null==t.onProgress?await Promise.all(s):await ri(s,t.onProgress,0,.5)).map((e=>e.arrayBuffer()));return null==t.onProgress?await Promise.all(r):await ri(r,t.onProgress,.5,1)}async function ii(e,t="",n,s){return oi((e=>ai(e,{requestInit:s})))(e,t,n)}function oi(e){return async(t,n="",s)=>{const r=t.map((()=>!1)),a={},i=null!=s?s.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=Zr[l]*P(e.shape),c=()=>{r[t]=!0,null==a[t]&&(a[t]=[]),a[t].push({manifestEntry:e,groupOffset:n,sizeBytes:u})};null!=s?s.forEach(((t,n)=>{t===e.name&&(c(),i[n]=!0)})):c(),o.push(e.name),n+=u}))})),!i.every((e=>e))){const e=s.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=r.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 s=0;for(let e=0;e{const t=ea(r.slice(e.groupOffset,e.groupOffset+e.sizeBytes),[e.manifestEntry]);for(const e in t)h[e]=t[e]})),p+=n})),h}}pa.registerSaveRouter((e=>ye().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(ti.URL_SCHEME)?function(e="model"){return new ti(e)}(e.slice(ti.URL_SCHEME.length)):null));class li{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?(O("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=ye().platform.fetch,O(null!=e&&e.length>0,(()=>"URL path for http must not be null, undefined or empty.")),Array.isArray(e)&&O(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=ia(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 s=await this.fetch(this.path,t);if(s.ok)return{modelArtifactsInfo:ua(e),responses:[s]};throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${s.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,s=t.weightsManifest;if(null==n&&null==s)throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`);return la(t,(e=>this.loadWeights(e)))}async loadWeights(e){const t=Array.isArray(this.path)?this.path[1]:this.path,[n,s]=function(e){const t=e.lastIndexOf("/"),n=e.lastIndexOf("?"),s=e.substring(0,t),r=n>t?e.substring(n):"";return[s+"/",r]}(t),r=this.weightPathPrefix||n,a=ca(e),i=[],o=[];for(const t of e)for(const e of t.paths)null!=this.weightUrlConverter?o.push(this.weightUrlConverter(e)):i.push(r+e+s);this.weightUrlConverter&&i.push(...await Promise.all(o));return[a,ra(await ai(i,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress}))]}}function ui(e){return null!=e.match(li.URL_SCHEME_REGEX)}li.URL_SCHEME_REGEX=/^https?:\/\//;const ci=(e,t)=>{if("undefined"==typeof fetch&&(null==t||null==t.fetchFunc))return null;{let n=!0;if(n=Array.isArray(e)?e.every((e=>ui(e))):ui(e),n)return hi(e,t)}return null};function hi(e,t){return new li(e,t)}function pi(e,t){return hi(e,t)}pa.registerSaveRouter(ci),pa.registerLoadRouter(ci); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class di{constructor(e){this.modelArtifacts=e}load(){return this.modelArtifacts}}class fi{constructor(e){this.saveHandler=e}save(e){return this.saveHandler(e)}}class mi{constructor(e){e.load&&(this.load=()=>Promise.resolve(e.load())),e.save&&(this.save=t=>Promise.resolve(e.save(t)))}}function gi(e,t,n,s){return new mi(yi(...arguments))}function yi(e,t,n,s){if(1===arguments.length){return null!=e.modelTopology||null!=e.weightSpecs?new di(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 di({modelTopology:e}))}return console.warn("Please call tf.io.fromMemory() with only one argument. The argument should be of type ModelArtifacts. The multi-argument signature of tf.io.fromMemory() has been deprecated and will be removed in a future release."),new di({modelTopology:e,weightSpecs:t,weightData:n,trainingConfig:s})}function bi(e){return new fi(e)}function xi(e){return new fi(e)} +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function wi(e,t){const n=e.length,s=[];for(let r=0;r1&&1===i&&s.unshift(a)}return s}function vi(e,t){const n=[];for(let s=0;s1)&&n.unshift(a)}return n}function ki(e,t){const n=[],s=Math.max(e.length,t.length);for(let r=0;r4)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,s=!1,r=!1,a=!1,i=!1,o=!1;if(e.data instanceof Uint8Array)n=!0;else if("undefined"!=typeof ImageData&&e instanceof ImageData)s=!0;else if("undefined"!=typeof HTMLVideoElement&&e instanceof HTMLVideoElement)r=!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(null!=_s(Ns,Or.backendName)){const n={pixels:e},s={numChannels:t};return Or.runKernel(Ns,n,s)}const[l,u]=r?[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(s||n)c=e.data;else if(a||r||o){if(null==Ni)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.");Ni=new OffscreenCanvas(1,1).getContext("2d")}else Ni=document.createElement("canvas").getContext("2d",{willReadFrequently:!0});Ni.canvas.width=l,Ni.canvas.height=u,Ni.drawImage(e,0,0,l,u),c=Ni.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;n`Error in slice${s}D: Length of begin ${t} must match the rank of the array (${s}).`)),O(s===n.length,(()=>`Error in slice${s}D: Length of size ${n} must match the rank of the array (${s}).`));for(let r=0;r`Error in slice${s}D: begin[${r}] + size[${r}] (${t[r]+n[r]}) would overflow input.shape[${r}] (${e.shape[r]})`))}function Ri(e){const t=[];let n=0;for(;e>0;)1&e&&t.push(n),e/=2,n++;return t}function Ai(e,t,n){const s=[];for(let r=0;r0){const l=t[0],u=n+1;c=Mi(i,l,u,s,e),h=Li(o,l,u,r,e),p=Fi(a,l,u,e)}else for(let t=0;t-1)a[r]=0;else{const i=_i(t,n,r);let o=s[i];e&1<-1)a[r]=Number.MAX_SAFE_INTEGER;else{const i=_i(t,n,r);let o=s[i];e&1<0?Number.MIN_SAFE_INTEGER:Number.MAX_SAFE_INTEGER);const l=s[r];return i<0&&(i+=l),i=F(0,i,l-1),i}function Bi(e,t,n,s,r,a){let i=t[r];const o=n[r]||1;(e&1<0?Number.MAX_SAFE_INTEGER:Number.MIN_SAFE_INTEGER);const l=s[r];return i<0&&(i+=l),i=o>0?F(0,i,l):F(-1,i,l-1),i}function Wi(e,t,n){let s=n.length;for(let e=0;e1){s=e;break}for(let r=s+1;r0||n[r]!==e[r])return!1;return!0}function Vi(e,t){let n=e.length>0?e[e.length-1]:1;for(let s=0;s{O(-1!==e,(()=>"slice() does not support negative begin indexing."))})),a=null==n?new Array(r).fill(-1):"number"==typeof n?[n,...new Array(r-1).fill(-1)]:n.lengtht>=0?t:(O(-1===t,(()=>`Negative size values should be exactly -1 but got ${t} for the slice() size at index ${n}.`)),e.shape[n]-s[n]))),[s,a]}function Gi(e,t,n,s,r,a,i,o,l){let u;if(null==s?(u=new Array(t.length),u.fill(1)):u=s,null!=i&&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:r,endMask:a,ellipsisMask:i,newAxisMask:o,shrinkAxisMask:l};for(let e=0;e0?0:-1,p.strides[t]>0?s:s-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<=s)throw Error(`slice index ${p.begin[t]} of dimension ${t} out of bounds.`)}else p.begin[t]=Hi(p.begin[t],0,p.strides[t],s,r,a),p.end[t]=Hi(p.end[t],1,p.strides[t],s,r,a);const e=1===p.strides[t]&&0===p.begin[t]&&p.end[t]===s;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&&s>=0&&(o=p.strides[t]<0?-s:s,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]):t===Ci&&y.push(1)}return{finalShapeSparse:y.filter(((e,t)=>p.finalShapeGatherIndices[t]!==Ci)),finalShape:y,isIdentity:d,sliceDim0:f,isSimpleSlice:m,begin:p.begin,end:p.end,strides:p.strides}}function Hi(e,t,n,s,r,a){if(r[t])return n>0?a[t]:a[t+1&1];{const t=e<0?s+e:e;return ta[1]?a[1]:t}} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class ji{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}}class qi{constructor(){this.classNameMap={}}static getMap(){return null==qi.instance&&(qi.instance=new qi),qi.instance}static register(e){qi.getMap().classNameMap[e.className]=[e,e.fromConfig]}}function Ki(e){O(null!=e.className,(()=>"Class being registered does not have the static className property defined.")),O("string"==typeof e.className,(()=>"className is required to be a string, but got type "+typeof e.className)),O(e.className.length>0,(()=>"Class being registered has an empty-string as its className, which is disallowed.")),qi.register(e)}function Xi(){return Or}function Yi(){return Or.memory()}function Zi(e,t){return Or.tidy(e,t)}function Ji(e){Er(e).forEach((e=>e.dispose()))}function Qi(e){return Or.keep(e)}function eo(e,t,n=1){return Or.registerBackend(e,t,n)}function to(e){return Or.customGrad(e)} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function no(e,t){if((Z(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&&Z(e)&&!(e instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return Xr(e,[],[],t)}mr=function(e){ye().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(e+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}; +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class so extends ji{minimize(e,t=!1,n){const{value:s,grads:r}=this.computeGradients(e,n);if(null!=n){const e=n.map((e=>({name:e.name,tensor:r[e.name]})));this.applyGradients(e)}else this.applyGradients(r);return Ji(r),t?s:(s.dispose(),null)}get iterations(){return null==this.iterations_&&(this.iterations_=0),this.iterations_}incrementIterations(){this.iterations_=this.iterations+1}computeGradients(e,t){return function(e,t){O(ne(e),(()=>"The f passed in variableGrads(f) must be a function")),O(null==t||Array.isArray(t)&&t.every((e=>e instanceof br)),(()=>"The varList passed in variableGrads(f, varList) must be an array of variables"));const n=null!=t;if(!n){t=[];for(const e in Or.registeredVariables)t.push(Or.registeredVariables[e])}const s=n?t.filter((e=>!e.trainable)):null,r=t.length;t=t.filter((e=>e.trainable)),O(t.length>0,(()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${r} variables is trainable.`));const{value:a,grads:i}=Or.gradients(e,t,null,!0);O(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().")),O(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!=s&&s.forEach((e=>o[e.name]=null)),{value:a,grads:o}}(e,t)}dispose(){null!=this.iterations_&&Ji(this.iterations_)}async saveIterations(){return null==this.iterations_&&(this.iterations_=0),{name:"iter",tensor:no(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(so,Symbol.hasInstance,{value:e=>null!=e.minimize&&null!=e.computeGradients&&null!=e.applyGradients});const ro=qr({abs_: +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const t=Gr(e,"x","abs");if("complex64"===t.dtype){const e={x:t};return Or.runKernel(Ke,e)}{const e={x:t};return Or.runKernel(ke,e)}}});const ao=qr({acos_: +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const t={x:Gr(e,"x","acos")};return Or.runKernel(Ie,t)}});const io=qr({acosh_: +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const t={x:Gr(e,"x","acosh")};return Or.runKernel(Ne,t)}});const oo=qr({add_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t){let n=Gr(e,"a","add"),s=Gr(t,"b","add");[n,s]=Cr(n,s);const r={a:n,b:s};return Or.runKernel(Se,r)}});const lo=qr({addN_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){O(Array.isArray(e),(()=>"The argument passed to tf.addN() must be a list of tensors")),O(e.length>=1,(()=>`Must pass at least one tensor to tf.addN(), but got ${e.length}`));const t=e.map(((e,t)=>Gr(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(!B(e.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")}));const s=t;return Or.runKernel(Te,s)}});const uo=qr({all_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t=null,n=!1){const s={x:Gr(e,"x","all","bool")},r={axis:t,keepDims:n};return Or.runKernel(Ce,s,r)}});const co=qr({any_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t=null,n=!1){const s={x:Gr(e,"x","any","bool")},r={axis:t,keepDims:n};return Or.runKernel($e,s,r)}});const ho=qr({argMax_: +/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t=0){const n={x:Gr(e,"x","argMax")},s={axis:t};return Or.runKernel(Ee,n,s)}});const po=qr({argMin_: +/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t=0){const n={x:Gr(e,"x","argMin")},s={axis:t};return Or.runKernel(Re,n,s)}});const fo=qr({asin_: +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const t={x:Gr(e,"x","asin")};return Or.runKernel(Ae,t)}});const mo=qr({asinh_: +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const t={x:Gr(e,"x","asinh")};return Or.runKernel(Fe,t)}});const go=qr({atan_: +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const t={x:Gr(e,"x","atan")};return Or.runKernel(_e,t)}});const yo=qr({atan2_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t){let n=Gr(e,"a","atan2"),s=Gr(t,"b","atan2");[n,s]=Cr(n,s);const r={a:n,b:s};return Or.runKernel(Oe,r)}});const bo=qr({atanh_: +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const t={x:Gr(e,"x","atanh")};return Or.runKernel(De,t)}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function xo(e,t,n,s,r="NHWC",a){return ko(e,[...t,e[3]],n,a,s,null,null,Ao(r))}function wo(e,t,n,s,r,a,i="channelsLast"){const[o,l]=So(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 ko(e,u,n,s,r,a,!1,i)}function vo(e,t,n,s,r,a,i="NDHWC"){const[o,l,u]=To(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 Io(e,c,n,s,r,!1,h,a)}function ko(e,t,n,s,r,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]=So(n),[y,b]=So(s),x=Co(p,y),w=Co(d,b),{padInfo:v,outHeight:k,outWidth:I}=function(e,t,n,s,r,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 r=function(e,t,n,s,r){null==s&&(s=No(e,t,n));const a=e[0],i=e[1],o=$o((a-t+2*s)/n+1,r),l=$o((i-t+2*s)/n+1,r);return[o,l]}([t,n],a,s,e,o);c=r[0],h=r[1]}else if("same"===e){c=Math.ceil(t/s),h=Math.ceil(n/r);const e=Math.max(0,(c-1)*s+a-t),o=Math.max(0,(h-1)*r+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)/s),h=Math.ceil((n-i+1)/r);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=$o((t-a+p+d)/s+1,o),h=$o((n-i+f+m)/r+1,o)}}return{padInfo:u,outHeight:c,outWidth:h}}(r,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 Io(e,t,n,s,r,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]=To(n),[w,v,k]=To(s),I=Co(d,w),N=Co(f,v),S=Co(m,k),{padInfo:T,outDepth:C,outHeight:$,outWidth:E}=function(e,t,n,s,r,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,s,r,a){null==r&&(r=No(e,t,s));const i=e[0],o=e[1],l=e[2],u=$o((i-t+2*r)/s+1,a),c=$o((o-t+2*r)/s+1,a),h=$o((l-t+2*r)/s+1,a);return[u,c,h,n]}([t,n,s,1],o,1,r,e,c);p=a[0],d=a[1],f=a[2]}else if("same"===e){p=Math.ceil(t/r),d=Math.ceil(n/a),f=Math.ceil(s/i);const e=(p-1)*r+o-t,c=(d-1)*a+l-n,m=(f-1)*i+u-s,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)/r),d=Math.ceil((n-l+1)/a),f=Math.ceil((s-u+1)/i)}return{padInfo:h,outDepth:p,outHeight:d,outWidth:f}}(r,u,c,h,y,b,x,I,N,S,o),R=a?g*p:g;let A;return"channelsFirst"===i?A=[l,R,C,$,E]:"channelsLast"===i&&(A=[l,C,$,E,R]),{batchSize:l,dataFormat:i,inDepth:u,inHeight:c,inWidth:h,inChannels:p,outDepth:C,outHeight:$,outWidth:E,outChannels:R,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:A,filterShape:t}}function No(e,t,n,s=1){const r=Co(t,s);return Math.floor((e[0]*(n-1)-n+r)/2)}function So(e){return"number"==typeof e?[e,e,e]:2===e.length?[e[0],e[1],1]:e}function To(e){return"number"==typeof e?[e,e,e]:e}function Co(e,t){return t<=1?e:e+(e-1)*(t-1)}function $o(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 Eo(e){const[t,n,s]=So(e);return 1===t&&1===n&&1===s}function Ro(e,t){return Eo(e)||Eo(t)}function Ao(e){if("NHWC"===e)return"channelsLast";if("NCHW"===e)return"channelsFirst";throw new Error(`Unknown dataFormat ${e}`)}function Fo(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)O(W(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=>{O(W(t),(()=>`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${t}.`))}))}))}}}const _o=qr({reshape_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t){const n={x:Gr(e,"x","reshape","string_or_numeric")},s={shape:t};return Or.runKernel(An,n,s)}});const Do=qr({avgPool_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n,s,r){const a=Gr(e,"x","avgPool","float32");O(Ro(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=_o(a,[1,a.shape[0],a.shape[1],a.shape[2]])),O(4===i.rank,(()=>`Error in avgPool: x must be rank 4 but got rank ${i.rank}.`)),Fo("avgPool",s,r);const l={x:i},u={filterSize:t,strides:n,pad:s,dimRoundingMode:r};let c=Or.runKernel(Me,l,u);return c=Za(c,a.dtype),o?_o(c,[c.shape[1],c.shape[2],c.shape[3]]):c}});const Oo=qr({avgPool3d_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n,s,r,a="NDHWC"){const i=Gr(e,"x","avgPool3d","float32");let o=i,l=!1;4===i.rank&&(l=!0,o=_o(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),O(5===o.rank,(()=>`Error in avgPool3d: x must be rank 5 but got rank ${o.rank}.`)),O("NDHWC"===a,(()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${a}`)),Fo("avgPool3d",s,r);const u={x:o},c={filterSize:t,strides:n,pad:s,dimRoundingMode:r,dataFormat:a};let h=Or.runKernel(ze,u,c);return h=Za(h,o.dtype),l?_o(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}});const Mo=qr({concat_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t=0){O(e.length>=1,(()=>"Pass at least one tensor to concat"));const n=Hr(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 Ja(n[0]);const s=n,r={axis:t};return Or.runKernel(Xe,s,r)}});const Lo=qr({matMul_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n=!1,s=!1){let r=Gr(e,"a","matMul"),a=Gr(t,"b","matMul");[r,a]=Cr(r,a);const i={a:r,b:a},o={transposeA:n,transposeB:s};return Or.runKernel(Be,i,o)}});const zo=qr({mul_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t){let n=Gr(e,"a","mul"),s=Gr(t,"b","mul");[n,s]=Cr(n,s);const r={a:n,b:s};return Or.runKernel(pn,r)}});const Po=qr({sigmoid_: +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const t={x:Gr(e,"x","sigmoid","float32")};return Or.runKernel(Kn,t)}});const Bo=qr({slice_: +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n){const s=Gr(e,"x","slice","string_or_numeric");if(0===s.rank)throw new Error("Slicing scalar is not possible");const r={x:s},a={begin:t,size:n};return Or.runKernel(Gn,r,a)}});const Wo=qr({tanh_: +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const t={x:Gr(e,"x","tanh","float32")};return Or.runKernel(fs,t)}});const Vo=qr({basicLSTMCell_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n,s,r,a){const i=Gr(e,"forgetBias","basicLSTMCell"),o=Gr(t,"lstmKernel","basicLSTMCell"),l=Gr(n,"lstmBias","basicLSTMCell"),u=Gr(s,"data","basicLSTMCell"),c=Gr(r,"c","basicLSTMCell"),h=Gr(a,"h","basicLSTMCell"),p=Mo([u,h],1),d=Lo(p,o),f=oo(d,l),m=f.shape[0],g=f.shape[1]/4,y=[m,g],b=Bo(f,[0,0],y),x=Bo(f,[0,g],y),w=Bo(f,[0,2*g],y),v=Bo(f,[0,3*g],y),k=oo(zo(Po(b),Wo(x)),zo(c,Po(oo(i,w))));return[k,zo(Wo(k),Po(v))]}});const Uo=qr({batchToSpaceND_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n){const s=Gr(e,"x","batchToSpaceND"),r=t.reduce(((e,t)=>e*t));O(s.rank>=1+t.length,(()=>`input rank is ${s.rank} but should be > than blockShape.length ${t.length}`)),O(n.length===t.length,(()=>`crops.length is ${n.length} but should be equal to blockShape.length ${t.length}`)),O(s.shape[0]%r==0,(()=>`input tensor batch is ${s.shape[0]} but is not divisible by the product of the elements of blockShape ${t.join(" * ")} === ${r}`));const a={x:s},i={blockShape:t,crops:n};return Or.runKernel(We,a,i)}});const Go=qr({batchNorm_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n,s,r,a){null==a&&(a=.001);const i=Gr(e,"x","batchNorm"),o=Gr(t,"mean","batchNorm"),l=Gr(n,"variance","batchNorm");let u,c;null!=r&&(u=Gr(r,"scale","batchNorm")),null!=s&&(c=Gr(s,"offset","batchNorm")),O(o.rank===l.rank,(()=>"Batch normalization gradient requires mean and variance to have equal ranks.")),O(null==c||o.rank===c.rank,(()=>"Batch normalization gradient requires mean and offset to have equal ranks.")),O(null==u||o.rank===u.rank,(()=>"Batch normalization gradient requires mean and scale to have equal ranks."));const h=function(e){let t;return t=0===e.rank||1===e.rank?_o(e,[1,1,1,e.size]):2===e.rank?_o(e,[1,1,e.shape[0],e.shape[1]]):3===e.rank?_o(e,[1,e.shape[0],e.shape[1],e.shape[2]]):e,t}(i),p={x:h,scale:u,offset:c,mean:o,variance:l},d={varianceEpsilon:a},f=Or.runKernel(Rt,p,d);return _o(f,i.shape)}});const Ho=qr({batchNorm2d_:function(e,t,n,s,r,a){const i=Gr(e,"x","batchNorm"),o=Gr(t,"mean","batchNorm"),l=Gr(n,"variance","batchNorm");let u,c;return null!=r&&(u=Gr(r,"scale","batchNorm")),null!=s&&(c=Gr(s,"offset","batchNorm")),O(2===i.rank,(()=>`Error in batchNorm2D: x must be rank 2 but got rank ${i.rank}.`)),O(2===o.rank||1===o.rank,(()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${o.rank}.`)),O(2===l.rank||1===l.rank,(()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${l.rank}.`)),null!=u&&O(2===u.rank||1===u.rank,(()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${u.rank}.`)),null!=c&&O(2===c.rank||1===c.rank,(()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${c.rank}.`)),Go(i,o,l,c,u,a)}});const jo=qr({batchNorm3d_:function(e,t,n,s,r,a){const i=Gr(e,"x","batchNorm"),o=Gr(t,"mean","batchNorm"),l=Gr(n,"variance","batchNorm");let u,c;return null!=r&&(u=Gr(r,"scale","batchNorm")),null!=s&&(c=Gr(s,"offset","batchNorm")),O(3===i.rank,(()=>`Error in batchNorm3D: x must be rank 3 but got rank ${i.rank}.`)),O(3===o.rank||1===o.rank,(()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${o.rank}.`)),O(3===l.rank||1===l.rank,(()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${l.rank}.`)),null!=u&&O(3===u.rank||1===u.rank,(()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${u.rank}.`)),null!=c&&O(3===c.rank||1===c.rank,(()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${c.rank}.`)),Go(i,o,l,c,u,a)}});const qo=qr({batchNorm4d_:function(e,t,n,s,r,a){const i=Gr(e,"x","batchNorm"),o=Gr(t,"mean","batchNorm"),l=Gr(n,"variance","batchNorm");let u,c;return null!=r&&(u=Gr(r,"scale","batchNorm")),null!=s&&(c=Gr(s,"offset","batchNorm")),O(4===i.rank,(()=>`Error in batchNorm4D: x must be rank 4 but got rank ${i.rank}.`)),O(4===o.rank||1===o.rank,(()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${o.rank}.`)),O(4===l.rank||1===l.rank,(()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${l.rank}.`)),null!=u&&O(4===u.rank||1===u.rank,(()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${u.rank}.`)),null!=c&&O(4===c.rank||1===c.rank,(()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${c.rank}.`)),Go(i,o,l,c,u,a)}});const Ko=qr({bincount_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n){const s=Gr(e,"x","bincount"),r=Gr(t,"weights","bincount");O("int32"===s.dtype,(()=>`Error in bincount: input dtype must be int32, but got ${s.dtype}`)),O(n>=0,(()=>`size must be non-negative, but got ${n}.`)),O(r.size===s.size||0===r.size,(()=>`Error in bincount: weights must have the same size as input or0-length, but got input shape: ${s.shape}, weights shape: ${r.shape}.`));const a={x:s,weights:r},i={size:n};return Or.runKernel(Ve,a,i)}});const Xo=qr({broadcastArgs_: +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t){const n=Gr(e,"s0","broadcastArgs","int32"),s=Gr(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!==s.rank)throw new Error(`broadcastArgs(): second input must be a vector (rank=1). Has rank ${s.rank}`);const r={s0:n,s1:s};return Or.runKernel(Ue,r)}});const Yo=qr({broadcastTo_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t){let n=Gr(e,"broadcastTo","x");const s=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(r[e]===t[e])a[e]=1;else if(1!==n.shape[e])throw new Error(`broadcastTo(): [${s}] cannot be broadcast to [${t}].`);if(0===a.map(((e,t)=>e>1?t:-1)).filter((e=>e>=0)).length)return Ja(n);const i={x:n},o={reps:a};return Or.runKernel(ms,i,o)}});const Zo=qr({ceil_: +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const t={x:Gr(e,"x","ceil","float32")};return Or.runKernel(He,t)}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function Jo(e,t,n){const s={shape:e,value:t,dtype:n};return Or.runKernel(Tt,{},s)}const Qo=qr({clipByValue_: +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n){const s=Gr(e,"x","clipByValue");if(O(t<=n,(()=>`Error in clip: min (${t}) must be less than or equal to max (${n}).`)),t===n)return Jo(s.shape,t,s.dtype);const r={x:s},a={clipValueMin:t,clipValueMax:n};return Or.runKernel(je,r,a)}});const el=qr({concat1d_:function(e){return Mo(e,0)}});const tl=qr({concat2d_:function(e,t){return Mo(e,t)}});const nl=qr({concat3d_:function(e,t){return Mo(e,t)}});const sl=qr({concat4d_:function(e,t){return Mo(e,t)}});const rl=qr({conv2d_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n,s,r="NHWC",a=[1,1],i){const o=Gr(e,"x","conv2d","float32"),l=Gr(t,"filter","conv2d","float32");let u=o,c=!1;3===o.rank&&(c=!0,u=_o(o,[1,o.shape[0],o.shape[1],o.shape[2]])),O(4===u.rank,(()=>`Error in conv2d: input must be rank 4, but got rank ${u.rank}.`)),O(4===l.rank,(()=>`Error in conv2d: filter must be rank 4, but got rank ${l.rank}.`)),Fo("conv2d",s,i);const h="NHWC"===r?u.shape[3]:u.shape[1];O(h===l.shape[2],(()=>`Error in conv2d: depth of input (${h}) must match input depth for filter ${l.shape[2]}.`)),O(Ro(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:s,dataFormat:r,dilations:a,dimRoundingMode:i},f=Or.runKernel(Ye,p,d);return c?_o(f,[f.shape[1],f.shape[2],f.shape[3]]):f}});const al=qr({conv1d_:function(e,t,n,s,r="NWC",a=1,i){const o=Gr(e,"x","conv1d"),l=Gr(t,"filter","conv1d");let u=o,c=!1;2===o.rank&&(c=!0,u=_o(o,[1,o.shape[0],o.shape[1]])),O(3===u.rank,(()=>`Error in conv1d: input must be rank 3, but got rank ${u.rank}.`)),O(3===l.rank,(()=>`Error in conv1d: filter must be rank 3, but got rank ${l.rank}.`)),Fo("conv1d",s,i),O(u.shape[2]===l.shape[1],(()=>`Error in conv1d: depth of input (${u.shape[2]}) must match input depth for filter ${l.shape[1]}.`)),O(Ro(n,a),(()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${n} and dilation '${a}'`)),O("NWC"===r,(()=>`Error in conv1d: got dataFormat of ${r} but only NWC is currently supported.`));const h=_o(l,[1,l.shape[0],l.shape[1],l.shape[2]]),p=_o(u,[u.shape[0],1,u.shape[1],u.shape[2]]),d=rl(p,h,[1,n],s,"NHWC",[1,a],i);return _o(d,c?[d.shape[2],d.shape[3]]:[d.shape[0],d.shape[2],d.shape[3]])}});const il=qr({conv2DBackpropInput_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n,s,r,a="NHWC",i){O(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=_o(t,[1,t.shape[0],t.shape[1],t.shape[2]]),o=[1,e[0],e[1],e[2]]),O(4===o.length,(()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${o.length}.`)),O(4===l.rank,(()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${l.rank}`)),O(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];O(c===n.shape[2],(()=>`Error in conv2dDerInput: depth of input (${c}) must match input depth for filter ${n.shape[2]}.`)),O(h===n.shape[3],(()=>`Error in conv2dDerInput: depth of output (${h}) must match output depth for filter ${n.shape[3]}.`)),Fo("conv2dDerInput",r,i);const p={dy:l,filter:n},d={strides:s,pad:r,dataFormat:a,dimRoundingMode:i,inputShape:o},f=Or.runKernel(Je,p,d);return u?_o(f,[f.shape[1],f.shape[2],f.shape[3]]):f}});const ol=qr({conv2dTranspose_:function(e,t,n,s,r,a){const i=Gr(e,"x","conv2dTranspose"),o=Gr(t,"filter","conv2dTranspose");return il(n,i,o,s,r,"NHWC",a)}});const ll=qr({conv3d_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n,s,r="NDHWC",a=[1,1,1]){const i=Gr(e,"x","conv3d"),o=Gr(t,"filter","conv3d");let l=i,u=!1;4===i.rank&&(u=!0,l=_o(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),O(5===l.rank,(()=>`Error in conv3d: input must be rank 5, but got rank ${l.rank}.`)),O(5===o.rank,(()=>`Error in conv3d: filter must be rank 5, but got rank ${o.rank}.`)),O(l.shape[4]===o.shape[3],(()=>`Error in conv3d: depth of input (${l.shape[4]}) must match input depth for filter ${o.shape[3]}.`)),O(Ro(n,a),(()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`)),O("NDHWC"===r,(()=>`Error in conv3d: got dataFormat of ${r} but only NDHWC is currently supported.`));const c={x:l,filter:o},h={strides:n,pad:s,dataFormat:r,dilations:a},p=Or.runKernel(Qe,c,h);return u?_o(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}});const ul=qr({conv3DBackpropInput_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n,s,r){O(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=_o(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];O(5===a.length,(()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${a.length}.`)),O(5===i.rank,(()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${i.rank}`)),O(5===n.rank,(()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${n.rank}`)),O(l===n.shape[3],(()=>`Error in conv3dDerInput: depth of input (${l}) must match input depth for filter ${n.shape[3]}.`)),O(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:r,strides:s,inputShape:a},p=Or.runKernel(tt,c,h);return o?_o(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}});const cl=qr({conv3dTranspose_:function(e,t,n,s,r){const a=Gr(e,"x","conv3dTranspose"),i=Gr(t,"filter","conv3dTranspose");return ul(n,a,i,s,r)}});const hl=qr({cos_: +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const t={x:Gr(e,"x","cos","float32")};return Or.runKernel(nt,t)}});const pl=qr({cosh_: +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const t={x:Gr(e,"x","cosh","float32")};return Or.runKernel(st,t)}});const dl=qr({cumprod_: +/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the 'License'); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an 'AS IS' BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t=0,n=!1,s=!1){const r={x:Gr(e,"x","cumprod")},a={axis:t,exclusive:n,reverse:s};return Or.runKernel(rt,r,a)}});const fl=qr({cumsum_: +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t=0,n=!1,s=!1){const r={x:Gr(e,"x","cumsum")},a={axis:t,exclusive:n,reverse:s};return Or.runKernel(at,r,a)}});const ml=qr({denseBincount_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n,s=!1){const r=Gr(e,"x","denseBincount"),a=Gr(t,"weights","denseBincount");O("int32"===r.dtype,(()=>`Error in denseBincount: input dtype must be int32, but got ${r.dtype}`)),O(r.rank<=2,(()=>`Error in denseBincount: input must be at most rank 2, but got rank ${r.rank}.`)),O(n>=0,(()=>`size must be non-negative, but got ${n}.`)),O(a.size===r.size||0===a.size,(()=>`Error in denseBincount: weights must have the same shape as x or 0-length, but got x shape: ${r.shape}, weights shape: ${a.shape}.`));const i={x:r,weights:a},o={size:n,binaryOutput:s};return Or.runKernel(ot,i,o)}});const gl=qr({depthToSpace_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n="NHWC"){const s=Gr(e,"x","depthToSpace","float32"),r="NHWC"===n?s.shape[1]:s.shape[2],a="NHWC"===n?s.shape[2]:s.shape[3],i="NHWC"===n?s.shape[3]:s.shape[1];O(t>1,(()=>`blockSize should be > 1 for depthToSpace, but was: ${t}`)),O(r*t>=0,(()=>`Negative dimension size caused by overflow when multiplying\n ${r} and ${t} for depthToSpace with input shape\n ${s.shape}`)),O(a*t>=0,(()=>`Negative dimension size caused by overflow when multiplying\n ${a} and ${t} for depthToSpace with input shape\n ${s.shape}`)),O(i%(t*t)==0,(()=>`Dimension size must be evenly divisible by ${t*t} but is ${i} for depthToSpace with input shape ${s.shape}`));const o={x:s},l={blockSize:t,dataFormat:n};return Or.runKernel(lt,o,l)}});const yl=qr({depthwiseConv2d_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n,s,r="NHWC",a=[1,1],i){const o=Gr(e,"x","depthwiseConv2d","float32"),l=Gr(t,"filter","depthwiseConv2d","float32");let u=o,c=!1;3===o.rank&&(c=!0,u=_o(o,[1,o.shape[0],o.shape[1],o.shape[2]])),O(4===u.rank,(()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${u.rank}.`)),O(4===l.rank,(()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${l.rank}.`));const h="NHWC"===r?u.shape[3]:u.shape[1];O(h===l.shape[2],(()=>`Error in depthwiseConv2d: number of input channels (${h}) must match the inChannels dimension in filter ${l.shape[2]}.`)),Fo("depthwiseConv2d",s,i);const p={x:u,filter:l},d={strides:n,pad:s,dataFormat:r,dilations:a,dimRoundingMode:i},f=Or.runKernel(ut,p,d);return c?_o(f,[f.shape[1],f.shape[2],f.shape[3]]):f}});const bl=qr({diag_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const t={x:Gr(e,"x","diag")};return Or.runKernel(pt,t)}});const xl=qr({dilation2d_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n,s,r=[1,1],a="NHWC"){const i=Gr(e,"x","dilation2d"),o=Gr(t,"filter","dilation2d");O(3===i.rank||4===i.rank,(()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${i.rank}.`)),O(3===o.rank,(()=>`Error in dilation2d: filter must be rank 3, but got rank ${o.rank}.`)),O("NHWC"===a,(()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${a}`));let l=i,u=!1;3===i.rank&&(l=_o(i,[1,i.shape[0],i.shape[1],i.shape[2]]),u=!0);const c={x:l,filter:o},h={strides:n,pad:s,dilations:r},p=Or.runKernel(dt,c,h);return u?_o(p,[p.shape[1],p.shape[2],p.shape[3]]):p}});const wl=qr({floorDiv_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t){let n=Gr(e,"a","floorDiv"),s=Gr(t,"b","floorDiv");[n,s]=Cr(n,s);const r={a:n,b:s};return Or.runKernel(Et,r)}});const vl=qr({div_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t){let n=Gr(e,"a","div"),s=Gr(t,"b","div");if([n,s]=Cr(n,s),"int32"===n.dtype&&"int32"===s.dtype)return wl(n,s);const r={a:n,b:s};return Or.runKernel(gt,r,{})}});const kl=qr({equal_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t){let n=Gr(e,"a","equal","string_or_numeric"),s=Gr(t,"b","equal","string_or_numeric");[n,s]=Cr(n,s),ki(n.shape,s.shape);const r={a:n,b:s};return Or.runKernel(vt,r)}});const Il=qr({where_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n){const s=Gr(t,"a","where"),r=Gr(n,"b","where"),a=Gr(e,"condition","where","bool"),i=ki(ki(a.shape,s.shape),r.shape),o={condition:Yo(a,i),t:Yo(s,i),e:Yo(r,i)};return Or.runKernel(Vn,o)}});const Nl=qr({zerosLike_: +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const t={x:Gr(e,"x","zerosLike")};return Or.runKernel(ks,t)}});const Sl=qr({divNoNan_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t){let n=Gr(e,"a","div"),s=Gr(t,"b","div");[n,s]=Cr(n,s);const r=vl(n,s),a=Nl(r),i=kl(s,a);return Il(i,a,r)}});const Tl=qr({dot_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t){const n=Gr(e,"t1","dot"),s=Gr(t,"t2","dot");O(!(1!==n.rank&&2!==n.rank||1!==s.rank&&2!==s.rank),(()=>`Error in dot: inputs must all be rank 1 or 2, but got ranks ${n.rank} and ${s.rank}.`));const r=1===n.rank?n.size:n.shape[1],a=1===s.rank?s.size:s.shape[0];if(O(r===a,(()=>`Error in dot: inner dimensions of inputs must match, but got ${r} and ${a}.`)),1===n.rank&&1===s.rank){const e=_o(n,[1,-1]),t=_o(s,[-1,1]),r=Lo(e,t);return _o(r,[])}if(1===n.rank&&2===s.rank){const e=_o(n,[1,-1]),t=_o(s,[s.shape[0],s.shape[1]]),r=Lo(e,t);return _o(r,[r.size])}if(2===n.rank&&1===s.rank){const e=_o(s,[-1,1]),t=Lo(n,e);return _o(t,[t.size])}{const e=_o(s,[s.shape[0],s.shape[1]]);return Lo(n,e)}}});const Cl=qr({einsum_: +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,...t){const n=t.map(((e,t)=>Gr(e,`tensors${t}`,"einsum"))),s={equation:e};return Or.runKernel(yt,n,s)}});const $l=qr({elu_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const t={x:Gr(e,"x","elu","float32")};return Or.runKernel(bt,t)}});const El=qr({erf_: +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){let t=Gr(e,"x","erf");O("int32"===t.dtype||"float32"===t.dtype,(()=>"Input dtype must be `int32` or `float32`.")),"int32"===t.dtype&&(t=Za(t,"float32"));const n={x:t};return Or.runKernel(wt,n)}}); +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function Rl(e,t){for(let n=0;ne[t]))]}function _l(e,t){return Al(e,t.map((e=>1)),t)}function Dl(e,t,n){O(Rl(t,n),(()=>`${e} supports only inner-most axes for now. Got axes ${t} and rank-${n} input.`))}function Ol(e,t){if(Rl(e,t))return null;const n=[];for(let s=0;sn.push(e))),n}function Ml(e){return e.map(((e,t)=>[t,e])).sort(((e,t)=>e[1]-t[1])).map((e=>e[0]))}function Ll(e,t){const n=[];for(let s=t-e;s"Axis must be <= rank of the tensor"));const s={input:n},r={dim:t};return Or.runKernel(It,s,r)}});const Xl=qr({expm1_: +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const t={x:Gr(e,"x","expm1")};return Or.runKernel(Nt,t)}});const Yl=qr({tile_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t){const n=Gr(e,"x","tile","string_or_numeric");O(n.rank===t.length,(()=>`Error in transpose: rank of input ${n.rank} must match length of reps ${t}.`));const s={x:n},r={reps:t};return Or.runKernel(ms,s,r)}});const Zl=qr({eye_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n,s="float32"){null==t&&(t=e);const r=Ya([e,t],s),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}.`)),O(W(t),(()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`));let i=a,o=!1;3===a.rank&&(o=!0,i=_o(a,[1,a.shape[0],a.shape[1],a.shape[2]]));const l={x:i},u={depthRadius:t,bias:n,alpha:s,beta:r},c=Or.runKernel(Yt,l,u);return o?_o(c,[c.shape[1],c.shape[2],c.shape[3]]):c}});const hu=qr({log_: +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const t={x:Gr(e,"x","log","float32")};return Or.runKernel(Ht,t)}});const pu=qr({log1p_: +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const t={x:Gr(e,"x","log1p")};return Or.runKernel(jt,t)}});const du=qr({neg_: +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const t={x:Gr(e,"x","neg")};return Or.runKernel(dn,t)}});const fu=qr({softplus_: +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const t={x:Gr(e,"x","softplus")};return Or.runKernel(Xn,t)}});const mu=qr({logSigmoid_: +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const t=Gr(e,"x","logSigmoid"),n=to((e=>({value:du(fu(du(e))),gradFunc:t=>zo(t,Po(du(e)))})));return n(t)}});const gu=qr({sub_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t){let n=Gr(e,"a","sub"),s=Gr(t,"b","sub");[n,s]=Cr(n,s);const r={a:n,b:s};return Or.runKernel(ps,r)}});const yu=qr({logSoftmax_: +/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t=-1){const n=Gr(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}`);const s=to(((e,n)=>{const s=zl(e,t,!0),r=gu(e,s),a=gu(Za(r,"float32"),hu(Ul(ql(r),t,!0)));n([a]);return{value:a,gradFunc:(e,n)=>{const[s]=n,r=ql(s);return gu(e,zo(Ul(e,t,!0),r))}}}));return s(n)}});const bu=qr({logSumExp_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t=null,n=!1){const s=Gr(e,"x","logSumExp"),r=j(t,s.shape),a=zl(s,r,!0),i=gu(s,a),o=ql(i),l=Ul(o,r),u=hu(l),c=oo(_o(a,u.shape),u);if(n){const e=_l(c.shape,r);return _o(c,e)}return c}});const xu=qr({logicalAnd_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t){const n=Gr(e,"a","logicalAnd","bool"),s=Gr(t,"b","logicalAnd","bool");ki(n.shape,s.shape);const r={a:n,b:s};return Or.runKernel(qt,r)}});const wu=qr({logicalNot_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const t={x:Gr(e,"x","logicalNot","bool")};return Or.runKernel(Kt,t)}});const vu=qr({logicalOr_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t){const n=Gr(e,"a","logicalOr","bool"),s=Gr(t,"b","logicalOr","bool");ki(n.shape,s.shape);const r={a:n,b:s};return Or.runKernel(Xt,r)}});const ku=qr({logicalXor_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t){const n=Gr(e,"a","logicalXor","bool"),s=Gr(t,"b","logicalXor","bool");return ki(n.shape,s.shape),xu(vu(e,t),wu(xu(e,t)))}}),Iu=2147483648;const Nu=qr({searchSorted_:function(e,t,n="left"){const s=Gr(e,"sortedSequence","searchSorted"),r=Gr(t,"values","searchSorted"),a=s.shape[s.shape.length-1],i=r.shape[r.shape.length-1],o=_o(s,[-1,a]),l=_o(r,[-1,i]);if(o.rank<2)throw new Error("Sorted input argument must be at least 2-dimensional");if(o.shape[0]!==l.shape[0])throw new Error("Leading dimension of 'sortedSequence' and 'values' must match.");if(P(l.shape)>=Iu)throw new Error("values tensor size must less than 2147483648");if(o.shape[1]>=Iu)throw new Error(`trailing dim_size must less than 2147483648 for int32 output type, was ${o.shape[1]}`);const u={sortedSequence:o,values:l},c={side:n};return Or.runKernel(Wn,u,c)}}); +/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function Su(e,t){return Nu(e,t,"left")}const Tu=qr({maxPool_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n,s,r){const a=Gr(e,"x","maxPool");let i=a,o=!1;3===a.rank&&(o=!0,i=_o(a,[1,a.shape[0],a.shape[1],a.shape[2]])),O(4===i.rank,(()=>`Error in maxPool: input must be rank 4 but got rank ${i.rank}.`)),O(Ro(n,1),(()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${n} and dilations '1'`)),Fo("maxPool",s,r);const l={x:i},u={filterSize:t,strides:n,pad:s,dimRoundingMode:r},c=Or.runKernel(en,l,u);return o?_o(c,[c.shape[1],c.shape[2],c.shape[3]]):c}});const Cu=qr({maxPool3d_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t=[1,1,1],n,s,r,a="NDHWC"){const i=Gr(e,"x","maxPool3d");let o=i,l=!1;4===i.rank&&(l=!0,o=_o(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),O(5===o.rank,(()=>`Error in maxPool3d: x must be rank 5 but got rank ${o.rank}.`)),O("NDHWC"===a,(()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${a}`)),Fo("maxPool3d",s,r);const u={x:o},c={filterSize:t,strides:n,pad:s,dimRoundingMode:r,dataFormat:a},h=Or.runKernel(nn,u,c);return l?_o(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}});const $u=qr({maxPoolWithArgmax_: +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n,s,r=!1){const a={x:Gr(e,"x","maxPoolWithArgmax")},i={filterSize:t,strides:n,pad:s,includeBatchInIndex:r},o=Or.runKernel(rn,a,i);return{result:o[0],indexes:o[1]}}});const Eu=qr({maximum_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t){let n=Gr(e,"a","maximum"),s=Gr(t,"b","maximum");[n,s]=Cr(n,s),"bool"===n.dtype&&(n=Za(n,"int32"),s=Za(s,"int32")),ki(n.shape,s.shape);const r={a:n,b:s};return Or.runKernel(Qt,r)}});const Ru=qr({mean_: +/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t=null,n=!1){const s={x:Gr(e,"x","mean")},r={axis:t,keepDims:n};return Or.runKernel(an,s,r)}}); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function Au(e,t="float32"){if("complex64"===t){const t=Au(e,"float32"),n=Au(e,"float32");return Kr(t,n)}const n=le(P(e),t);return Or.makeTensor(n,e,t)} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function Fu(e,t="float32"){if("complex64"===t){const t=Fu(e,"float32"),n=Au(e,"float32");return Kr(t,n)}const n=oe(P(e),t);return Or.makeTensor(n,e,t)} +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function _u(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 s=Gr(e,"x","meshgrid",e instanceof gr?e.dtype:"float32");if(void 0===t)return[s];let r=Gr(t,"y","meshgrid",t instanceof gr?t.dtype:"float32");const a=P(s.shape),i=P(r.shape);return"xy"===n?(s=_o(s,[1,-1]),r=_o(r,[-1,1]),[Lo(Fu([i,1],s.dtype),s),Lo(r,Fu([1,a],r.dtype))]):(s=_o(s,[-1,1]),r=_o(r,[1,-1]),[Lo(s,Fu([1,i],s.dtype)),Lo(Fu([a,1],r.dtype),r)])}const Du=qr({minimum_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t){let n=Gr(e,"a","minimum"),s=Gr(t,"b","minimum");[n,s]=Cr(n,s),"bool"===n.dtype&&(n=Za(n,"int32"),s=Za(s,"int32")),ki(n.shape,s.shape);const r={a:n,b:s};return Or.runKernel(ln,r)}});const Ou=qr({mirrorPad_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n){O("reflect"===n||"symmetric"===n,(()=>`Invalid mode. Mode must be either reflect or symmetric. Got ${n}.`));const s=Gr(e,"x","mirrorPad");if(0===s.rank)throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");O(t.length===s.rank,(()=>`Padding doesn't match input. Must be ${s.rank}. Got ${t.length}.`));const r="reflect"===n?1:0;for(let e=0;e"Invalid number of paddings. Must be length of 2 each.")),O(t[e][0]>=0&&t[e][0]<=s.shape[e]-r&&t[e][1]>=0&&t[e][1]<=s.shape[e]-r,(()=>`Padding in dimension ${e} cannot be greater than or equal to ${s.shape[e]-r} or less than 0 for input of shape ${s.shape}`));const a={paddings:t,mode:n},i={x:s};return Or.runKernel(un,i,a)}});const Mu=qr({mod_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t){let n=Gr(e,"a","mod"),s=Gr(t,"b","mod");[n,s]=Cr(n,s);const r={a:n,b:s};return Or.runKernel(cn,r)}});const Lu=qr({moments_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t=null,n=!1){const s=j(t,(e=Gr(e,"x","moments")).shape),r=Ru(e,s,n);let a=r.shape;n||(a=_l(r.shape,s));const i=Vl(gu(Za(e,"float32"),_o(r,a)));return{mean:r,variance:Ru(i,s,n)}}});const zu=qr({multiRNNCell_:function(e,t,n,s){const r=Gr(t,"data","multiRNNCell"),a=Hr(n,"c","multiRNNCell"),i=Hr(s,"h","multiRNNCell");let o=r;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?_o(r,[1,-1]):r},l={numSamples:t,seed:n,normalized:s},u=Or.runKernel(hn,o,l);return 1===i?_o(u,[u.size]):u}});const Bu=qr({notEqual_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t){let n=Gr(e,"a","notEqual","string_or_numeric"),s=Gr(t,"b","notEqual","string_or_numeric");[n,s]=Cr(n,s),ki(n.shape,s.shape);const r={a:n,b:s};return Or.runKernel(fn,r)}});const Wu=qr({oneHot_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n=1,s=0,r="int32"){if(t<2)throw new Error(`Error in oneHot: depth must be >=2, but it is ${t}`);const a={indices:Gr(e,"indices","oneHot","int32")},i={dtype:r,depth:t,onValue:n,offValue:s};return Or.runKernel(xn,a,i)}});const Vu=qr({onesLike_: +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const t={x:Gr(e,"x","onesLike")};return Or.runKernel(bn,t)}});const Uu=qr({outerProduct_:function(e,t){const n=Gr(e,"v1","outerProduct"),s=Gr(t,"v2","outerProduct");O(1===n.rank&&1===s.rank,(()=>`Error in outerProduct: inputs must be rank 1, but got ranks ${n.rank} and ${s.rank}.`));const r=_o(n,[-1,1]),a=_o(s,[1,-1]);return Lo(r,a)}});const Gu=qr({pad_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n=0){const s=Gr(e,"x","pad");if(0===s.rank)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");const r={paddings:t,constantValue:n},a={x:s};return Or.runKernel(vn,a,r)}});const Hu=qr({pad1d_:function(e,t,n=0){return O(2===t.length,(()=>"Invalid number of paddings. Must be length of 2.")),Gu(e,[t],n)}});const ju=qr({pad2d_:function(e,t,n=0){return O(2===t.length&&2===t[0].length&&2===t[1].length,(()=>"Invalid number of paddings. Must be length of 2 each.")),Gu(e,t,n)}});const qu=qr({pad3d_:function(e,t,n=0){return O(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.")),Gu(e,t,n)}});const Ku=qr({pad4d_:function(e,t,n=0){return O(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.")),Gu(e,t,n)}});const Xu=qr({spaceToBatchND_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n){const s=Gr(e,"x","spaceToBatchND");O(s.rank>=1+t.length,(()=>`input rank ${s.rank} should be > than [blockShape] ${t.length}`)),O(n.length===t.length,(()=>`paddings.shape[0] ${n.length} must be equal to [blockShape] ${t.length}`)),O(s.shape.reduce(((e,s,r)=>r>0&&r<=t.length?e&&(s+n[r-1][0]+n[r-1][1])%t[r-1]==0:e),!0),(()=>`input spatial dimensions ${s.shape.slice(1)} with paddings ${n.toString()} must be divisible by blockShapes ${t.toString()}`));const r={x:s},a={blockShape:t,paddings:n};return Or.runKernel(Jn,r,a)}});const Yu=qr({pool_: +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n,s,r,a,i){null==r&&(r=[1,1]),null==a&&(a=1),0===s&&(s="valid");const o=Gr(e,"x","maxPool");let l=o,u=!1;3===o.rank&&(u=!0,l=_o(o,[1,o.shape[0],o.shape[1],o.shape[2]])),O(Ro(a,r),(()=>`Error in pool: Either strides or dilations must be 1. Got strides ${a} and dilations '${r}'`));const c=wo(l.shape,t,a,r,s),h=[c.dilationHeight,c.dilationWidth];let p;p="same"===s?function(e,t){const n=e.map(((e,n)=>e+(e-1)*(t[n]-1))),s=n.map((e=>e-1)),r=s.map((e=>Math.floor(e/2))),a=s.map(((e,t)=>e-r[t]));return s.map(((e,t)=>[r[t],a[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 s=n.map((e=>e[0])),r=n.map((e=>e[1])),a=e.concat(s,r),i=t.map(((e,t)=>(e-a[t]%e)%e)),o=r.map(((e,t)=>e+i[t])),l=t.map(((e,t)=>[s[t],o[t]])),u=t.map(((e,t)=>[0,i[t]]));return[l,u]}([c.inHeight,c.inWidth],h,p),g=d?s:"valid",y=d?l:Xu(l,h,f),b=("avg"===n?()=>Do(y,t,a,g,i):()=>Tu(y,t,a,g,i))(),x=d?b:Uo(b,h,m);return u?_o(x,[x.shape[1],x.shape[2],x.shape[3]]):x}});const Zu=qr({prelu_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t){const n={x:Gr(e,"x","prelu"),alpha:Gr(t,"alpha","prelu")};return Or.runKernel(In,n)}});const Ju=qr({prod_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t=null,n=!1){let s=Gr(e,"x","prod");"bool"===s.dtype&&(s=Za(s,"int32"));const r={x:s},a={axis:t,keepDims:n};return Or.runKernel(Nn,r,a)}});const Qu=qr({raggedGather_: +/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n,s){const r={paramsNestedSplits:e.map(((e,t)=>Gr(e,`tensors${t}`,"raggedGather","int32"))),paramsDenseValues:Gr(t,"paramsDenseValues","raggedGather"),indices:Gr(n,"indices","raggedGather","int32")},a={outputRaggedRank:s},i=Or.runKernel(Sn,r,a);return{outputNestedSplits:i.slice(0,i.length-1),outputDenseValues:i[i.length-1]}}});const ec=qr({raggedTensorToTensor_: +/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n,s,r){const a=Gr(e,"shape","raggedTensorToTensor","int32"),i=Gr(t,"values","raggedTensorToTensor"),o={shape:a,values:i,defaultValue:Gr(n,"defaultValue","raggedTensorToTensor",i.dtype),rowPartitionTensors:s.map(((e,t)=>Gr(e,`tensors${t}`,"raggedTensorToTensor","int32")))},l={rowPartitionTypes:r};return Or.runKernel(Tn,o,l)}});const tc=qr({rand_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n){const s=P(e);let r=null;if(null==n||"float32"===n)r=new Float32Array(s);else if("int32"===n)r=new Int32Array(s);else{if("bool"!==n)throw new Error(`Unknown data type ${n}`);r=new Uint8Array(s)}for(let e=0;e=1||0===a);const i=Math.sqrt(-2*Math.log(a)/a);e=this.mean+this.stdDev*s*i,t=this.mean+this.stdDev*r*i,this.truncated&&!this.isValidTruncated(e)||(n=!0)}return this.truncated&&!this.isValidTruncated(t)||(this.nextVal=this.convertValue(t)),this.convertValue(e)}convertValue(e){return null==this.dtype||"float32"===this.dtype?e:Math.round(e)}isValidTruncated(e){return e<=this.upper&&e>=this.lower}}class rc{constructor(e,t,n,s){this.alpha=e,this.beta=1/t,this.dtype=n;const r=s||Math.random();this.randu=nc.alea(r.toString()),this.randn=new sc(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,s,r,a;for(;;){do{s=this.randn.nextValue(),a=1+this.c*s}while(a<=0);if(a*=a*a,e=s*s,t=1-.331*e*e,n=.5*e+this.d*(1-a+Math.log(a)),r=this.randu(),rnull==this.dtype||"float32"===this.dtype,this.min=e,this.range=t-e,this.dtype=n,null==s&&(s=Math.random()),"number"==typeof s&&(s=s.toString()),!this.canReturnFloat()&&this.range<=1)throw new Error(`The difference between ${e} - ${t} <= 1 and dtype is not float`);this.random=nc.alea(s)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}}const ic=qr({randomGamma_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n=1,s="float32",r){if(null==n&&(n=1),null==s&&(s="float32"),"float32"!==s&&"int32"!==s)throw new Error(`Unsupported data type ${s}`);const a=new rc(t,n,s,r),i=Ya(e,s);for(let e=0;e`Error in reverse1D: x must be rank 1 but got rank ${t.rank}.`)),mc(t,0)}});const yc=qr({reverse2d_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t){const n=Gr(e,"x","reverse");return O(2===n.rank,(()=>`Error in reverse2D: x must be rank 2 but got rank ${n.rank}.`)),mc(n,t)}});const bc=qr({reverse3d_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t){const n=Gr(e,"x","reverse");return O(3===n.rank,(()=>`Error in reverse3D: x must be rank 3 but got rank ${n.rank}.`)),mc(n,t)}});const xc=qr({reverse4d_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t){const n=Gr(e,"x","reverse");return O(4===n.rank,(()=>`Error in reverse4D: x must be rank 4 but got rank ${n.rank}.`)),mc(n,t)}});const wc=qr({round_: +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const t={x:Gr(e,"x","round")};return Or.runKernel(zn,t)}});const vc=qr({rsqrt_: +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const t={x:Gr(e,"x","rsqrt","float32")};return Or.runKernel(Pn,t)}});const kc=qr({selu_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const t={x:Gr(e,"x","selu")};return Or.runKernel(Un,t)}});const Ic=qr({separableConv2d_:function(e,t,n,s,r,a=[1,1],i="NHWC"){const o=Gr(e,"x","separableConv2d"),l=Gr(t,"depthwiseFilter","separableConv2d"),u=Gr(n,"pointwiseFilter","separableConv2d");let c=o,h=!1;if(3===o.rank&&(h=!0,c=_o(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");O(4===c.rank,(()=>`Error in separableConv2d: input must be rank 4, but got rank ${c.rank}.`)),O(4===l.rank,(()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${l.rank}.`)),O(4===u.rank,(()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${l.rank}.`)),O(1===u.shape[0],(()=>`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${u.shape[0]}.`)),O(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];O(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=yl(c,l,s,r,i,a),m=rl(f,u,1,"valid",i);return h?_o(m,[m.shape[1],m.shape[2],m.shape[3]]):m}});const Nc= +/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +async function(e,t){const n=Gr(e,"x","setdiff1d"),s=Gr(t,"y","setdiff1d");O(n.dtype===s.dtype,(()=>`x and y should have the same dtype, but got x (${n.dtype}) and y (${s.dtype}).`)),O(1===n.rank,(()=>`x should be 1D tensor, but got x (${n.shape}).`)),O(1===s.rank,(()=>`y should be 1D tensor, but got y (${s.shape}).`));const r=await n.data(),a=await s.data(),i=new Set(a);let o=0;for(let e=0;e`slice1d expects a rank-1 tensor, but got a rank-${s.rank} tensor`)),Bo(s,[t],[n])}});const Ec=qr({slice2d_: +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n){const s=Gr(e,"x","slice2d");return O(2===s.rank,(()=>`slice2d expects a rank-2 tensor, but got a rank-${s.rank} tensor`)),Bo(s,t,n)}});const Rc=qr({slice3d_: +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n){const s=Gr(e,"x","slice3d");return O(3===s.rank,(()=>`slice3d expects a rank-3 tensor, but got a rank-${s.rank} tensor`)),Bo(s,t,n)}});const Ac=qr({slice4d_: +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n){const s=Gr(e,"x","slice4d");return O(4===s.rank,(()=>`slice4d expects a rank-4 tensor, but got a rank-${s.rank} tensor`)),Bo(s,t,n)}});const Fc=qr({softmax_: +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t=-1){const n=Gr(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 s={logits:n},r={dim:t};return Or.runKernel(es,s,r)}});const _c=qr({fft_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){O("complex64"===e.dtype,(()=>`The dtype for tf.spectral.fft() must be complex64 but got ${e.dtype}.`));const t={input:e};return Or.runKernel(St,t)}});const Dc=qr({ifft_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){O("complex64"===e.dtype,(()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${e.dtype}.`));const t={input:e};return Or.runKernel(Mt,t)}});const Oc=qr({irfft_: +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const t=e.shape[e.shape.length-1],n=e.size/t;let s;if(t<=2){const r=_o(e,[n,t]);s=Dc(r)}else{const r=[n,2*(t-1)],a=_o(hc(e),[n,t]),i=_o(nu(e),[n,t]),o=mc(Bo(a,[0,1],[n,t-2]),1),l=zo(mc(Bo(i,[0,1],[n,t-2]),1),no(-1)),u=Mo([a,o],1),c=Mo([i,l],1),h=_o(Kr(u,c),[r[0],r[1]]);s=Dc(h)}if(s=hc(s),3===e.rank&&0!==e.shape[0]){const t=s,n=e.shape[0];s=_o(s,[n,s.shape[0]/n,s.shape[1]]),t.dispose()}return s}});const Mc=qr({split_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n=0){const s={x:Gr(e,"x","split")},r={numOrSizeSplits:t,axis:n};return Or.runKernel(Qn,s,r)}});const Lc=qr({rfft_: +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t){O("float32"===e.dtype,(()=>`The dtype for rfft() must be real value but got ${e.dtype}`));let n=e.shape[e.shape.length-1];const s=e.size/n;let r;if(null!=t&&t0)),a=e.shape.map((e=>e));a[e.shape.length-1]=t,r=Bo(e,s,a),n=t}else if(null!=t&&t>n){const s=e.shape.map((e=>e));s[e.shape.length-1]=t-n,r=Mo([e,Au(s)],e.shape.length-1),n=t}else r=e;const a=Nl(r),i=_o(Kr(r,a),[s,n]),o=_c(i),l=Math.floor(n/2)+1,u=hc(o),c=nu(o),h=Mc(u,[l,n-l],u.shape.length-1),p=Mc(c,[l,n-l],c.shape.length-1),d=r.shape.slice();return d[r.shape.length-1]=l,_o(Kr(h[0],p[0]),d)}});const zc=qr({squaredDifference_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t){let n=Gr(e,"a","squaredDifference"),s=Gr(t,"b","squaredDifference");[n,s]=Cr(n,s),ki(n.shape,s.shape);const r={a:n,b:s};return Or.runKernel(is,r,{})}});const Pc=qr({squeeze_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t){const n=Gr(e,"x","squeeze","string_or_numeric");return _o(n,q(n.shape,t).newShape)}});const Bc=qr({stack_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t=0){const n=Hr(e,"tensors","stack","string_or_numeric");O(n.length>=1,(()=>"Pass at least one tensor to tf.stack")),n.length>0&&O(t<=n[0].rank,(()=>"Axis must be <= rank of the tensor"));const s=n,r={axis:t};return Or.runKernel(wn,s,r)}});const Wc=qr({step_: +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t=0){const n={x:Gr(e,"x","step")},s={alpha:t};return Or.runKernel(Is,n,s)}});const Vc=qr({stridedSlice_: +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n,s,r=0,a=0,i=0,o=0,l=0){const u={x:Gr(e,"x","stridedSlice","string_or_numeric")},c={begin:t,end:n,strides:s,beginMask:r,endMask:a,ellipsisMask:i,newAxisMask:o,shrinkAxisMask:l};return Or.runKernel(ls,u,c)}});const Uc=qr({tan_: +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const t={x:Gr(e,"x","tan","float32")};return Or.runKernel(ds,t)}}); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function Gc(e,t){L(e);const n=Wr(e,t);if(1!==n.length)throw new Error("tensor1d() requires values to be a flat/TypedArray");return Xr(e,null,n,t)} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function Hc(e,t,n){if(L(e),null!=t&&2!==t.length)throw new Error("tensor2d() requires shape to have two numbers");const s=Wr(e,n);if(2!==s.length&&1!==s.length)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(1===s.length&&null==t)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return Xr(e,t,s,n)} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function jc(e,t,n){if(L(e),null!=t&&4!==t.length)throw new Error("tensor4d() requires shape to have four numbers");const s=Wr(e,n);if(4!==s.length&&1!==s.length)throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");if(1===s.length&&null==t)throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");return Xr(e,t,s,n)} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function qc(e,t,n){if(L(e),null!=t&&5!==t.length)throw new Error("tensor5d() requires shape to have five numbers");const s=Wr(e,n);if(5!==s.length&&1!==s.length)throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray");if(1===s.length&&null==t)throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");return Xr(e,t,s,n)} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function Kc(e,t,n){if(L(e),null!=t&&6!==t.length)throw new Error("tensor6d() requires shape to have six numbers");const s=Wr(e,n);if(6!==s.length&&1!==s.length)throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray");if(1===s.length&&null==t)throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");return Xr(e,t=t||s,s,n)}const Xc=qr({topk_: +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t=1,n=!0){const s=Gr(e,"x","topk");if(0===s.rank)throw new Error("topk() expects the input to be of rank 1 or higher");const r=s.shape[s.shape.length-1];if(t<0)throw new Error(`'k' passed to topk() must be >= 0 but got ${t}`);if(t>r)throw new Error(`'k' passed to topk() must be <= the last dimension (${r}) but got ${t}`);const a={x:s},i={k:t,sorted:n},[o,l]=Or.runKernel(gs,a,i);return{values:o,indices:l}}});const Yc=qr({truncatedNormal_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t=0,n=1,s,r){if(null!=s&&"bool"===s)throw new Error("Unsupported data type $ { dtype }");const a=new sc(t,n,s,!0,r),i=Ya(e,s);for(let e=0;e0,(()=>"The input tensor must be at least 1D"));const s={x:n},r={axis:t},[a,i]=Or.runKernel(xs,s,r);return{values:a,indices:i}}});const Jc=qr({unsortedSegmentSum_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n){const s=Gr(e,"x","unsortedSegmentSum"),r=Gr(t,"segmentIds","unsortedSegmentSum","int32");O(W(n),(()=>"numSegments must be of dtype int"));const a={x:s,segmentIds:r},i={numSegments:n};return Or.runKernel(vs,a,i)}});const Qc=qr({unstack_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t=0){const n=Gr(e,"x","unstack","string_or_numeric");O(t>=-n.shape.length&&t`Axis = ${t} is not in [-${n.shape.length}, ${n.shape.length})`));const s={value:n},r={axis:t};return Or.runKernel(ws,s,r)}}); +/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function eh(e,t){return Nu(e,t,"right")} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function th(e,t=!0,n,s){return Or.makeVariable(e,t,n,s)} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function nh(e,t){const n=[];for(let e=0;e0,(()=>"mask cannot be scalar")),M(o.slice(a,a+i),r.shape,"mask's shape must match the first K dimensions of tensor's shape,");let l=1;for(let e=a;et)).reverse()),O(s.rank===t.length,(()=>`Error in transpose: rank of input ${s.rank} must match length of perm ${t}.`)),t.forEach((e=>{O(e>=0&&e"All entries in 'perm' must be between 0 and "+(s.rank-1)+` but got ${t}`))})),s.rank<=1)return s.clone();const r={x:s},a={perm:t};return"complex64"===s.dtype?Zi((()=>{let e=hc(s),t=nu(s);return e=Or.runKernel(bs,{x:e},a),t=Or.runKernel(bs,{x:t},a),n&&(t=du(t)),Kr(e,t)})):Or.runKernel(bs,r,a)}});const ih=qr({movingAverage_: +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n,s,r=!0){const a=Gr(e,"v","movingAverage"),i=Gr(t,"x","movingAverage"),o=Gr(n,"decay","movingAverage");var l,u;u=i,O((l=a).dtype===u.dtype,(()=>`The dtypes of the first(${l.dtype}) and second(${u.dtype}) input must match`)),O(B(a.shape,i.shape),(()=>"Shape mismatch in v and x"));const c=no(1),h=gu(c,o);let p=zo(gu(i,a),h);if(r){O(null!=s,(()=>"When using zeroDebias: true, step is required."));const e=Gr(s,"step","movingAverage");p=vl(p,gu(c,Bl(o,e)))}return oo(a,p)}});function oh(e,t,n){const s=t.rank>1?t.shape[t.rank-1]:1,r=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: ${s}, and batchDim: ${r}.`;if(n.rank1?t.shape[s-1]:1,a=n.length;let i=1;for(let e=r;e2)throw new Error(`sparseIndices should be a scalar, vector, or matrix, but got shape ${e.shape}.`);const r=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!==r))throw new Error(`sparseValues has incorrect shape ${t.shape}, should be [] or [${r}]`);if(t.dtype!==s.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}(r,a,n,i);const o={sparseIndices:r,sparseValues:a,defaultValue:i},l={outputShape:n};return Or.runKernel(as,o,l)}});const ph=qr({gatherND_: +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t){const n=Gr(t,"indices","gatherND","int32"),s={params:Gr(e,"x","gatherND","string_or_numeric"),indices:n};return Or.runKernel(Ft,s)}});const dh=qr({dropout_: +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n,s){const r=Gr(e,"x","dropout");if(O("float32"===r.dtype,(()=>`x has to be a floating point tensor since it's going to be scaled, but got a ${r.dtype} tensor instead.`)),O(t>=0&&t<1,(()=>`rate must be a float in the range [0, 1), but got ${t}.`)),0===t)return e instanceof gr?r.clone():r;const a= +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t){if(null==t)return e.shape.slice();if(B(e.shape,t))return t;if(e.shape.length===t.length){const n=[];for(let s=0;s1,(()=>`inTopK() expects the predictions to be of rank 2 or higher, but got ${s.rank}`)),O(s.rank-1===r.rank,(()=>`predictions rank should be 1 larger than targets rank, but got predictions rank ${s.rank} and targets rank ${r.rank}`)),M(s.shape.slice(0,s.shape.length-1),r.shape,"predictions's shape should be align with the targets' shape, except the last dimension.");const a=s.shape[s.shape.length-1];O(n>0&&n<=a,(()=>`'k' passed to inTopK() must be > 0 && <= the predictions last dimension (${a}), but got ${n}`));const i=await s.data(),o=await r.data(),[l,u]=[i.length/a,a],c=K("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}.`)),O(4===l.rank,(()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${l.shape}.`)),O(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];O(u===n[2],(()=>`Error in conv2dDerFilter: depth of input ${u}) must match input depth in filter (${n[2]}.`)),O(c===n[3],(()=>`Error in conv2dDerFilter: depth of dy (${c}) must match output depth for filter (${n[3]}).`)),Fo("conv2dDerFilter",r,i);const h={x:o,dy:l},p={strides:s,pad:r,dataFormat:a,dimRoundingMode:i,filterShape:n};return Or.runKernel(Ze,h,p)}}); +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function bh(e,t,n){if(null==n||"linear"===n)return e;if("relu"===n)return zo(e,Wc(t));throw new Error(`Cannot compute gradient for fused activation ${n}.`)}function xh(e,t){let n=t;const s=vi(e.shape,t.shape);return s.length>0&&(n=Ul(n,s)),_o(n,e.shape)}function wh(e,t,n,s){if("linear"===t)return e;if("relu"===t)return dc(e);if("elu"===t)return $l(e);if("relu6"===t)return fc(e);if("prelu"===t)return Zu(e,n);if("leakyrelu"===t)return iu(e,s);if("sigmoid"===t)return Po(e);throw new Error(`Unknown fused activation ${t}.`)}const vh=(e,t)=>!(e>0)||"linear"===t;const kh=qr({fusedConv2d_: +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function({x:e,filter:t,strides:n,pad:s,dataFormat:r="NHWC",dilations:a=[1,1],dimRoundingMode:i,bias:o,activation:l="linear",preluActivationWeights:u,leakyreluAlpha:c}){if(l=l||"linear",!1===vh(Or.state.gradientDepth,l)){O("NHWC"===r,(()=>`Error in fused conv2d: got dataFormat of ${r} but only NHWC is currently supported for the case of gradient depth is 0 and the activation is not linear.`));let h=rl(e,t,n,s,r,a,i);return null!=o&&(h=oo(h,o)),wh(h,l,u,c)}const h=Gr(e,"x","conv2d","float32"),p=Gr(t,"filter","conv2d","float32");let d=h,f=!1;3===h.rank&&(f=!0,d=_o(h,[1,h.shape[0],h.shape[1],h.shape[2]])),O(4===d.rank,(()=>`Error in fused conv2d: input must be rank 4, but got rank ${d.rank}.`)),O(4===p.rank,(()=>`Error in fused conv2d: filter must be rank 4, but got rank ${p.rank}.`)),Fo("fused conv2d",s,i);const m="NHWC"===r?d.shape[3]:d.shape[1];O(p.shape[2]===m,(()=>`Error in conv2d: depth of input (${m}) must match input depth for filter ${p.shape[2]}.`)),O(Ro(n,a),(()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`));const g=ko(d.shape,p.shape,n,a,s,i);let y,b;if(null!=o&&(y=Gr(o,"bias","fused conv2d"),[y]=Cr(y,h),"NHWC"===r?ki(g.outShape,y.shape):(O(y.shape.length<=1,(()=>`Error in fused conv2d: only supports scalar or 1-D Tensor bias for NCHW format but got the bias of rank-${y.shape.length}.`)),O(0===y.shape.length||y.shape[0]===g.outChannels||1===y.shape[0],(()=>`Error in fused conv2d: bias shape (${y.shape}) is not compatible with the number of output channels (${g.outChannels})`)))),null!=u){const e=u.shape;if(O(e.length<=1||3===e.length,(()=>`Error in fused conv2d: only supports scalar, 1-D Tensor or 3-D Tensor PReLU activation weights but got a tensor of rank-${e.length}.`)),1===e.length)O(1===e[0]||e[0]===g.outChannels,(()=>`Error in fused conv2d: PReLU activation weights (${e}) is not compatible with the number of output channels (${g.outChannels}).`));else if(3===e.length)try{ki(e,g.outShape)}catch(t){const n=`Error in fused conv2d: PReLU activation weights (${e}) is not compatible with the output shape of the conv2d (${g.outShape}).`;throw Error(n)}b=Gr(u,"prelu weights","fused conv2d")}const x=(e,t)=>{O("NHWC"===r,(()=>`Error in gradient of fused conv2D: got dataFormat of ${r} but only NHWC is currently supported.`));const[i,o,u,c]=t,h=bh(e,u,l);O(Eo(a),(()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${a}'`));const p=[il(o.shape,h,i,n,s),yh(o,h,i.shape,n,s)];if(null!=c){const e=xh(c,h);p.push(e)}return p},w={x:d,filter:p,bias:y,preluActivationWeights:b},v={strides:n,pad:s,dataFormat:r,dilations:a,dimRoundingMode:i,activation:l,leakyreluAlpha:c};if(null==o){const e=to(((e,t,n)=>{let s=Or.runKernel(Cs,w,v);return n([t,e,s]),f&&(s=_o(s,[s.shape[1],s.shape[2],s.shape[3]])),{value:s,gradFunc:x}}));return e(d,p)}{const e=to(((e,t,n,s)=>{let r=Or.runKernel(Cs,w,v);return s([t,e,r,n]),f&&(r=_o(r,[r.shape[1],r.shape[2],r.shape[3]])),{value:r,gradFunc:x}}));return e(d,p,y)}}});const Ih=qr({depthwiseConv2dNativeBackpropFilter_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n,s,r,a=[1,1],i){let o=e;3===e.rank&&(o=_o(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;3===l.rank&&(l=_o(t,[1,t.shape[0],t.shape[1],t.shape[2]]));const u={x:o,dy:l},c={strides:s,pad:r,dimRoundingMode:i,dilations:a,filterShape:n};return Or.runKernel(ct,u,c)}});const Nh=qr({depthwiseConv2dNativeBackpropInput_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n,s,r,a=[1,1],i){let o=t,l=!1;3===t.rank&&(l=!0,o=_o(t,[1,t.shape[0],t.shape[1],t.shape[2]]));const u={dy:o,filter:n},c={strides:s,pad:r,dimRoundingMode:i,dilations:a,inputShape:e},h=Or.runKernel(ht,u,c);return l?_o(h,[h.shape[1],h.shape[2],h.shape[3]]):h}});const Sh=qr({fusedDepthwiseConv2d_: +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function({x:e,filter:t,strides:n,pad:s,dataFormat:r="NHWC",dilations:a=[1,1],dimRoundingMode:i,bias:o,activation:l="linear",preluActivationWeights:u,leakyreluAlpha:c}){if(!1===vh(Or.state.gradientDepth,l)){let h=yl(e,t,n,s,r,a,i);return null!=o&&(h=oo(h,o)),wh(h,l,u,c)}const h=Gr(e,"x","depthwiseConv2d","float32"),p=Gr(t,"filter","depthwiseConv2d","float32");let d=h,f=!1;3===h.rank&&(f=!0,d=_o(h,[1,h.shape[0],h.shape[1],h.shape[2]])),O(4===d.rank,(()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${d.rank}.`)),O(4===p.rank,(()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${p.rank}.`)),O(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]),O(Ro(n,a),(()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`)),Fo("fused depthwiseConv2d",s,i);const m=ko(d.shape,p.shape,n,a,s,i,!0);let g,y;null!=o&&(g=Gr(o,"bias","fused conv2d"),[g]=Cr(g,h),ki(m.outShape,g.shape)),null!=u&&(y=Gr(u,"prelu weights","fused depthwiseConv2d"));const b=(e,t)=>{O(Eo(a),(()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${a}'`));const[r,o,u,c]=t,h=bh(e,u,l),p=Nh(o.shape,h,r,n,s,a,i),d=Ih(o,h,r.shape,n,s,a,i);if(null!=c){return[p,d,xh(g,h)]}return[p,d]},x={x:d,filter:p,bias:g,preluActivationWeights:y},w={strides:n,pad:s,dataFormat:r,dilations:a,dimRoundingMode:i,activation:l,leakyreluAlpha:c};if(null==o){const e=to(((e,t,n)=>{let s=Or.runKernel($s,x,w);return n([t,e,s]),f&&(s=_o(s,[s.shape[1],s.shape[2],s.shape[3]])),{value:s,gradFunc:b}}));return e(d,p)}{const e=to(((e,t,n,s)=>{let r=Or.runKernel($s,x,w);return s([t,e,r,n]),f&&(r=_o(r,[r.shape[1],r.shape[2],r.shape[3]])),{value:r,gradFunc:b}}));return e(d,p,g)}}});const Th=qr({fusedMatMul_: +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function({a:e,b:t,transposeA:n=!1,transposeB:s=!1,bias:r,activation:a="linear",preluActivationWeights:i,leakyreluAlpha:o=.2}){if(!1===vh(Or.state.gradientDepth,a)){let l=Lo(e,t,n,s);return null!=r&&(l=oo(l,r)),wh(l,a,i,o)}let l=Gr(e,"a","fused matMul"),u=Gr(t,"b","fused matMul");[l,u]=Cr(l,u);const c=n?l.shape[l.rank-2]:l.shape[l.rank-1],h=s?u.shape[u.rank-1]:u.shape[u.rank-2],p=n?l.shape[l.rank-1]:l.shape[l.rank-2],d=s?u.shape[u.rank-2]:u.shape[u.rank-1],f=l.shape.slice(0,-2),m=u.shape.slice(0,-2),g=P(f),y=P(m);O(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=${s} must match.`));const b=ki(l.shape.slice(0,-2),u.shape.slice(0,-2)).concat([p,d]),x=_o(l,n?[g,c,p]:[g,p,c]),w=_o(u,s?[y,d,h]:[y,h,d]);let v,k;null!=r&&(v=Gr(r,"bias","fused matMul"),[v]=Cr(v,l),ki(b,v.shape)),null!=i&&(k=Gr(i,"prelu weights","fused matMul"));const I=(e,t)=>{const[i,o,l,u]=t,c=bh(_o(e,l.shape),l,a);let h,p;if(n||s?!n&&s?(h=Lo(c,o,!1,!1),p=Lo(c,i,!0,!1)):n&&!s?(h=Lo(o,c,!1,!0),p=Lo(i,c,!1,!1)):(h=Lo(o,c,!0,!0),p=Lo(c,i,!0,!0)):(h=Lo(c,o,!1,!0),p=Lo(i,c,!0,!1)),null!=r){return[h,p,xh(u,c)]}return[h,p]},N={a:x,b:w,bias:v,preluActivationWeights:k},S={transposeA:n,transposeB:s,activation:a,leakyreluAlpha:o};if(null==r){const e=to(((e,t,n)=>{const s=Or.runKernel(Ts,N,S);return n([e,t,s]),{value:_o(s,b),gradFunc:I}}));return e(x,w)}{const e=to(((e,t,n,s)=>{const r=Or.runKernel(Ts,N,S);return s([e,t,r,n]),{value:_o(r,b),gradFunc:I}}));return e(x,w,v)}}});const Ch=qr({hammingWindow_: +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){return mh(e,.54,.46)}});const $h=qr({hannWindow_: +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){return mh(e,.5,.5)}});const Eh=qr({frame_: +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n,s=!1,r=0){let a=0;const i=[];for(;a+t<=e.size;)i.push(Bo(e,a,t)),a+=n;if(s)for(;a`Error in cropAndResize: image must be rank 4,but got rank ${i.rank}.`)),O(2===o.rank&&4===o.shape[1],(()=>`Error in cropAndResize: boxes must be have size [${u},4] but had shape ${o.shape}.`)),O(1===l.rank&&l.shape[0]===u,(()=>`Error in cropAndResize: boxInd must be have size [${u}] but had shape ${o.shape}.`)),O(2===s.length,(()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${s.length}.`)),O(s[0]>=1&&s[1]>=1,(()=>`cropSize must be atleast [1,1], but was ${s}`)),O("bilinear"===r||"nearest"===r,(()=>`method must be bilinear or nearest, but was ${r}`));const c={image:i,boxes:o,boxInd:l},h={method:r,extrapolationValue:a,cropSize:s};return Or.runKernel(it,c,h)}});const Fh=qr({flipLeftRight_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const t=Gr(e,"image","flipLeftRight","float32");O(4===t.rank,(()=>`Error in flipLeftRight: image must be rank 4,but got rank ${t.rank}.`));const n={image:t};return Or.runKernel(Ct,n,{})}});const _h=qr({grayscaleToRGB_: +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const t=Gr(e,"image","grayscaleToRGB"),n=t.rank-1,s=t.shape[n];O(t.rank>=2,(()=>`Error in grayscaleToRGB: images must be at least rank 2, but got rank ${t.rank}.`)),O(1===s,(()=>`Error in grayscaleToRGB: last dimension of a grayscale image should be size 1, but got size ${s}.`));const r=new Array(t.rank);return r.fill(1,0,n),r[n]=3,Yl(t,r)}});const Dh=qr({rotateWithOffset_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n=0,s=.5){const r=Gr(e,"image","rotateWithOffset","float32");O(4===r.rank,(()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${r.rank}.`));const a={image:r},i={radians:t,fillValue:n,center:s};return Or.runKernel(Ss,a,i)}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function Oh(e,t,n,s,r,a){null==s&&(s=.5),null==r&&(r=Number.NEGATIVE_INFINITY),null==a&&(a=0);const i=e.shape[0];return n=Math.min(n,i),O(0<=s&&s<=1,(()=>`iouThreshold must be in [0, 1], but was '${s}'`)),O(2===e.rank,(()=>`boxes must be a 2D tensor, but was of rank '${e.rank}'`)),O(4===e.shape[1],(()=>`boxes must have 4 columns, but 2nd dimension was ${e.shape[1]}`)),O(1===t.rank,(()=>"scores must be a 1D tensor")),O(t.shape[0]===i,(()=>`scores has incompatible shape with boxes. Expected ${i}, but was ${t.shape[0]}`)),O(0<=a&&a<=1,(()=>`softNmsSigma must be in [0, 1], but was '${a}'`)),{maxOutputSize:n,iouThreshold:s,scoreThreshold:r,softNmsSigma:a}}const Mh=qr({nonMaxSuppression_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY){const a=Gr(e,"boxes","nonMaxSuppression","float32"),i=Gr(t,"scores","nonMaxSuppression","float32"),o=Oh(a,i,n,s,r),l={maxOutputSize:n=o.maxOutputSize,iouThreshold:s=o.iouThreshold,scoreThreshold:r=o.scoreThreshold};return Or.runKernel(mn,{boxes:a,scores:i},l)}}); +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function Lh(e,t,n){const s=function(e,t,n){return function(e,t,n){let s=0,r=e.length,a=0,i=!1;for(;s>>1);const o=n(t,e[a]);o>0?s=a+1:(r=a,i=!o)}return i?s:-s-1}(e,t,n||zh)}(e,t,n),r=s<0?-(s+1):s;e.splice(r,0,t)}function zh(e,t){return e>t?1:er&&u.push({score:t[e],boxIndex:e,suppressBeginIndex:0});u.sort(Hh);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=Uh(e,a,h[n]);if(i>=s){o=!0;break}if(t.score=t.score*Gh(s,c,i),t.score<=r)break}t.suppressBeginIndex=h.length,o||(t.score===n?(h.push(a),p.push(t.score)):t.score>r&&Lh(u,t,Hh))}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 Uh(e,t,n){const s=e.subarray(4*t,4*t+4),r=e.subarray(4*n,4*n+4),a=Math.min(s[0],s[2]),i=Math.min(s[1],s[3]),o=Math.max(s[0],s[2]),l=Math.max(s[1],s[3]),u=Math.min(r[0],r[2]),c=Math.min(r[1],r[3]),h=Math.max(r[0],r[2]),p=Math.max(r[1],r[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 Gh(e,t,n){const s=Math.exp(t*n*n);return n<=e?s:0}function Hh(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex}const jh= +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +async function(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY){const a=Gr(e,"boxes","nonMaxSuppressionAsync"),i=Gr(t,"scores","nonMaxSuppressionAsync"),o=Oh(a,i,n,s,r);n=o.maxOutputSize,s=o.iouThreshold,r=o.scoreThreshold;const l=await Promise.all([a.data(),i.data()]),u=l[0],c=l[1],{selectedIndices:h}=Ph(u,c,n,s,r);return a!==e&&a.dispose(),i!==t&&i.dispose(),Gc(h,"int32")};const qh=qr({nonMaxSuppressionWithScore_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY,a=0){const i=Gr(e,"boxes","nonMaxSuppression"),o=Gr(t,"scores","nonMaxSuppression"),l=Oh(i,o,n,s,r,a),u={boxes:i,scores:o},c={maxOutputSize:n=l.maxOutputSize,iouThreshold:s=l.iouThreshold,scoreThreshold:r=l.scoreThreshold,softNmsSigma:a=l.softNmsSigma},h=Or.runKernel(yn,u,c);return{selectedIndices:h[0],selectedScores:h[1]}}});const Kh= +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +async function(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY,a=0){const i=Gr(e,"boxes","nonMaxSuppressionAsync"),o=Gr(t,"scores","nonMaxSuppressionAsync"),l=Oh(i,o,n,s,r,a);n=l.maxOutputSize,s=l.iouThreshold,r=l.scoreThreshold,a=l.softNmsSigma;const u=await Promise.all([i.data(),o.data()]),c=u[0],h=u[1],{selectedIndices:p,selectedScores:d}=Wh(c,h,n,s,r,a);return i!==e&&i.dispose(),o!==t&&o.dispose(),{selectedIndices:Gc(p,"int32"),selectedScores:Gc(d)}};const Xh=qr({nonMaxSuppressionPadded_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY,a=!1){const i=Gr(e,"boxes","nonMaxSuppression"),o=Gr(t,"scores","nonMaxSuppression"),l=Oh(i,o,n,s,r,null),u={boxes:i,scores:o},c={maxOutputSize:l.maxOutputSize,iouThreshold:l.iouThreshold,scoreThreshold:l.scoreThreshold,padToMaxOutputSize:a},h=Or.runKernel(gn,u,c);return{selectedIndices:h[0],validOutputs:h[1]}}});const Yh= +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +async function(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY,a=!1){const i=Gr(e,"boxes","nonMaxSuppressionAsync"),o=Gr(t,"scores","nonMaxSuppressionAsync"),l=Oh(i,o,n,s,r,null),u=l.maxOutputSize,c=l.iouThreshold,h=l.scoreThreshold,[p,d]=await Promise.all([i.data(),o.data()]),{selectedIndices:f,validOutputs:m}=Bh(p,d,u,c,h,a);return i!==e&&i.dispose(),o!==t&&o.dispose(),{selectedIndices:Gc(f,"int32"),validOutputs:no(m,"int32")}};const Zh=qr({resizeBilinear_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n=!1,s=!1){const r=Gr(e,"images","resizeBilinear");O(3===r.rank||4===r.rank,(()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${r.rank}.`)),O(2===t.length,(()=>`Error in resizeBilinear: new shape must 2D, but got shape ${t}.`)),O(!1===s||!1===n,(()=>"Error in resizeBilinear: If halfPixelCenters is true, alignCorners must be false."));let a=r,i=!1;3===r.rank&&(i=!0,a=_o(r,[1,r.shape[0],r.shape[1],r.shape[2]]));const[]=t,o={images:a},l={alignCorners:n,halfPixelCenters:s,size:t},u=Or.runKernel(Dn,o,l);return i?_o(u,[u.shape[1],u.shape[2],u.shape[3]]):u}});const Jh=qr({resizeNearestNeighbor_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n=!1,s=!1){const r=Gr(e,"images","resizeNearestNeighbor");O(3===r.rank||4===r.rank,(()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${r.rank}.`)),O(2===t.length,(()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${t}.`)),O("float32"===r.dtype||"int32"===r.dtype,(()=>"`images` must have `int32` or `float32` as dtype")),O(!1===s||!1===n,(()=>"Error in resizeNearestNeighbor: If halfPixelCenters is true, alignCorners must be false."));let a=r,i=!1;3===r.rank&&(i=!0,a=_o(r,[1,r.shape[0],r.shape[1],r.shape[2]]));const[]=t,o={images:a},l={alignCorners:n,halfPixelCenters:s,size:t},u=Or.runKernel(Fn,o,l);return i?_o(u,[u.shape[1],u.shape[2],u.shape[3]]):u}});const Qh=qr({threshold_: +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t="binary",n=!1,s=.5){const r=Gr(e,"image","threshold"),a=r.shape[0]*r.shape[1];let i,o,l,u,c=zo(Gc([s]),255);if(O(3===r.rank,(()=>`Error in threshold: image must be rank 3,but got rank ${r.rank}.`)),O(3===r.shape[2]||1===r.shape[2],(()=>`Error in threshold: image color channel must be equal to 3 or 1but got ${r.shape[2]}.`)),O("int32"===r.dtype||"float32"===r.dtype,(()=>`Error in dtype: image dtype must be int32 or float32,but got dtype ${r.dtype}.`)),O("otsu"===t||"binary"===t,(()=>`Method must be binary or otsu, but was ${t}`)),3===r.shape[2]){[i,o,l]=Mc(r,[1,1,1],-1);const e=zo(i,.2989),t=zo(o,.587),n=zo(l,.114);u=oo(oo(e,t),n)}else u=e;if("otsu"===t){c=function(e,t){let n,s,r,a,i,o,l=Gc([-1]),u=Gc([0]),c=Gc([0]);for(let h=0;h`Error in transform: image must be rank 4,but got rank ${i.rank}.`)),O(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")),O(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:s,fillValue:r,outputShape:a};return Or.runKernel(ys,l,u)}});const tp=qr({bandPart_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n){O(t%1==0,(()=>`bandPart(): numLower must be an integer, got ${t}.`)),O(n%1==0,(()=>`bandPart(): numUpper must be an integer, got ${n}.`));const s=Gr(e,"a","bandPart");O(s.rank>=2,(()=>`bandPart(): Rank must be at least 2, got ${s.rank}.`));const r=s.shape,[a,i]=s.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=_o(cc(0,a,1,"int32"),[-1,1]),l=cc(0,i,1,"int32"),u=gu(o,l),c=xu(lu(u,no(+t,"int32")),tu(u,no(-n,"int32"))),h=Au([a,i],s.dtype);return _o(Bc(Qc(_o(s,[-1,a,i])).map((e=>Il(c,e,h)))),r)}});const np=qr({gramSchmidt_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){let t;if(Array.isArray(e)){t=!1,O(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=Mc(e,e.shape[0],0).map((e=>Pc(e,[0])));O(e.length<=e[0].shape[0],(()=>`Gram-Schmidt: Number of vectors (${e.length}) exceeds number of dimensions (${e[0].shape[0]}).`));const n=[],s=e;for(let t=0;t{let e=s[t];if(t>0)for(let s=0;s{O(2===e.shape.length,(()=>`qr2d() requires a 2D Tensor, but got a ${e.shape.length}D Tensor.`));const n=e.shape[0],s=e.shape[1];let r=Zl(n),a=Ja(e);const i=Hc([[1]],[1,1]);let o=Ja(i);const l=n>=s?s:n;for(let e=0;e{const t=Bo(a,[e,e],[n-e,1]),l=Hl(t),u=Bo(a,[e,e],[1,1]),c=Il(eu(u,0),Hc([[-1]]),Hc([[1]])),h=gu(u,zo(c,l)),p=vl(t,h);o=1===p.shape[0]?Ja(i):Mo([i,Bo(p,[1,0],[p.shape[0]-1,p.shape[1]])],0);const d=du(vl(Lo(c,h),l)),f=Bo(a,[e,0],[n-e,s]),m=zo(d,o),g=ah(o);if(0===e)a=gu(f,Lo(m,Lo(g,f)));else{const t=gu(f,Lo(m,Lo(g,f)));a=Mo([Bo(a,[0,0],[e,s]),t],0)}const y=ah(m),b=Bo(r,[0,e],[n,r.shape[1]-e]);if(0===e)r=gu(b,Lo(Lo(b,o),y));else{const t=gu(b,Lo(Lo(b,o),y));r=Mo([Bo(r,[0,0],[n,e]),t],1)}return[o,a,r]})),Ji([t,l,u])}return!t&&n>s&&(r=Bo(r,[0,0],[n,s]),a=Bo(a,[0,0],[s,s])),[r,a]}))}const rp=qr({qr_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t=!1){if(O(e.rank>=2,(()=>`qr() requires input tensor to have a rank >= 2, but got rank ${e.rank}`)),2===e.rank)return sp(e,t);{const n=e.shape.slice(0,e.shape.length-2).reduce(((e,t)=>e*t)),s=Qc(_o(e,[n,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),r=[],a=[];s.forEach((e=>{const[n,s]=sp(e,t);r.push(n),a.push(s)}));return[_o(Bc(r,0),e.shape),_o(Bc(a,0),e.shape)]}}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +var ap;!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"}(ap||(ap={}));const ip=qr({computeWeightedLoss_:function(e,t,n=ap.SUM_BY_NONZERO_WEIGHTS){const s=Gr(e,"losses","computeWeightedLoss");let r=null;null!=t&&(r=Gr(t,"weights","computeWeightedLoss"));const a=null==r?s:zo(s,r);if(n===ap.NONE)return a;if(n===ap.SUM)return Ul(a);if(n===ap.MEAN){if(null==r)return Ru(a);{const e=s.size/r.size,t=vl(Ul(a),Ul(r));return e>1?vl(t,no(e)):t}}if(n===ap.SUM_BY_NONZERO_WEIGHTS){if(null==r)return vl(Ul(a),no(s.size));{const e=zo(r,Fu(s.shape)),t=Za(Ul(Bu(e,no(0))),"float32");return vl(Ul(a),t)}}throw Error(`Unknown reduction: ${n}`)}});const op=qr({absoluteDifference_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n,s=ap.SUM_BY_NONZERO_WEIGHTS){const r=Gr(e,"labels","absoluteDifference"),a=Gr(t,"predictions","absoluteDifference");let i=null;null!=n&&(i=Gr(n,"weights","absoluteDifference")),M(r.shape,a.shape,"Error in absoluteDifference: ");const o=ro(gu(r,a));return ip(o,i,s)}});const lp=qr({cosineDistance_:function(e,t,n,s,r=ap.SUM_BY_NONZERO_WEIGHTS){const a=Gr(e,"labels","cosineDistance"),i=Gr(t,"predictions","cosineDistance");let o=null;null!=s&&(o=Gr(s,"weights","cosineDistance")),M(a.shape,i.shape,"Error in cosineDistance: ");const l=no(1),u=gu(l,Ul(zo(a,i),n,!0));return ip(u,o,r)}});const up=qr({hingeLoss_:function(e,t,n,s=ap.SUM_BY_NONZERO_WEIGHTS){let r=Gr(e,"labels","hingeLoss");const a=Gr(t,"predictions","hingeLoss");let i=null;null!=n&&(i=Gr(n,"weights","hingeLoss")),M(r.shape,a.shape,"Error in hingeLoss: ");const o=no(1);r=gu(zo(no(2),r),o);const l=dc(gu(o,zo(r,a)));return ip(l,i,s)}});const cp=qr({huberLoss_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n,s=1,r=ap.SUM_BY_NONZERO_WEIGHTS){const a=Gr(e,"labels","huberLoss"),i=Gr(t,"predictions","huberLoss");let o=null;null!=n&&(o=Gr(n,"weights","huberLoss")),M(a.shape,i.shape,"Error in huberLoss: ");const l=no(s),u=ro(gu(i,a)),c=Du(u,l),h=gu(u,c),p=oo(zo(no(.5),Vl(c)),zo(l,h));return ip(p,o,r)}});const hp=qr({logLoss_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n,s=1e-7,r=ap.SUM_BY_NONZERO_WEIGHTS){const a=Gr(e,"labels","logLoss"),i=Gr(t,"predictions","logLoss");let o=null;null!=n&&(o=Gr(n,"weights","logLoss")),M(a.shape,i.shape,"Error in logLoss: ");const l=no(1),u=no(s),c=du(zo(a,hu(oo(i,u)))),h=zo(gu(l,a),hu(oo(gu(l,i),u))),p=gu(c,h);return ip(p,o,r)}});const pp=qr({meanSquaredError_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n,s=ap.SUM_BY_NONZERO_WEIGHTS){const r=Gr(e,"labels","meanSquaredError"),a=Gr(t,"predictions","meanSquaredError");let i=null;null!=n&&(i=Gr(n,"weights","meanSquaredError")),M(r.shape,a.shape,"Error in meanSquaredError: ");const o=zc(r,a);return ip(o,i,s)}});const dp=qr({sigmoidCrossEntropy_:function(e,t,n,s=0,r=ap.SUM_BY_NONZERO_WEIGHTS){let a=Gr(e,"multiClassLabels","sigmoidCrossEntropy");const i=Gr(t,"logits","sigmoidCrossEntropy");let o=null;if(null!=n&&(o=Gr(n,"weights","sigmoidCrossEntropy")),M(a.shape,i.shape,"Error in sigmoidCrossEntropy: "),s>0){const e=no(s),t=no(1),n=no(.5);a=oo(zo(a,gu(t,e)),zo(n,e))}const l= +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t){const n=Gr(e,"labels","sigmoidCrossEntropyWithLogits"),s=Gr(t,"logits","sigmoidCrossEntropyWithLogits");M(n.shape,s.shape,"Error in sigmoidCrossEntropyWithLogits: ");const r=dc(s),a=zo(s,n),i=pu(ql(du(ro(s))));return oo(gu(r,a),i)}(a,i);return ip(l,o,r)}});const fp=qr({softmaxCrossEntropy_:function(e,t,n,s=0,r=ap.SUM_BY_NONZERO_WEIGHTS){let a=Gr(e,"onehotLabels","softmaxCrossEntropy");const i=Gr(t,"logits","softmaxCrossEntropy");let o=null;if(null!=n&&(o=Gr(n,"weights","softmaxCrossEntropy")),M(a.shape,i.shape,"Error in softmaxCrossEntropy: "),s>0){const e=no(s),t=no(1),n=no(a.shape[1]);a=oo(zo(a,gu(t,e)),vl(e,n))}const l= +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +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}`);const s=to(((e,t,s)=>{const r=bu(t,[n],!0),a=gu(Za(t,"float32"),r);s([e,a]);const i=du(zo(a,e));return{value:Ul(i,[n]),gradFunc:(e,t)=>{const[s,r]=t,a=_l(e.shape,[n]);return[zo(_o(e,a),gu(Za(s,"float32"),ql(r))),zo(_o(e,a),gu(ql(r),Za(s,"float32")))]}}}));return s(e,t)}(a,i);return ip(l,o,r)}});const mp=qr({sparseFillEmptyRows_: +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n,s){const r=Gr(e,"indices","sparseFillEmptyRows","int32"),a=Gr(t,"values","sparseFillEmptyRows"),i=Gr(n,"denseShape","sparseFillEmptyRows","int32"),o=Gr(s,"defaultValue","sparseFillEmptyRows",a.dtype);if(2!==r.rank)throw new Error(`Indices should be Tensor2D but received shape\n ${r.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:r,values:a,denseShape:i,defaultValue:o},u=Or.runKernel(ts,l);return{outputIndices:u[0],outputValues:u[1],emptyRowIndicator:u[2],reverseIndexMap:u[3]}}});const gp=qr({sparseReshape_: +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n){const s=Gr(e,"inputIndices","sparseReshape","int32"),r=Gr(t,"inputShape","sparseReshape","int32"),a=Gr(n,"newShape","sparseReshape","int32");if(2!==s.rank)throw new Error(`Input indices should be Tensor2D but received shape\n ${s.shape}`);if(1!==r.rank)throw new Error(`Input shape should be Tensor1D but received shape ${r.shape}`);if(1!==a.rank)throw new Error(`New shape should be Tensor1D but received shape ${a.shape}`);const i={inputIndices:s,inputShape:r,newShape:a},o=Or.runKernel(ns,i);return{outputIndices:o[0],outputShape:o[1]}}});const yp=qr({sparseSegmentMean_: +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n){const s=Gr(e,"data","sparseSegmentMean"),r=Gr(t,"indices","sparseSegmentMean","int32"),a=Gr(n,"segmentIds","sparseSegmentMean","int32");if(s.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(1!==r.rank)throw new Error(`Indices should be Tensor1D but received shape\n ${r.shape}`);if(1!==a.rank)throw new Error(`Segment ids should be Tensor1D but received shape\n ${a.shape}`);const i={data:s,indices:r,segmentIds:a};return Or.runKernel(ss,i)}});const bp=qr({sparseSegmentSum_: +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n){const s=Gr(e,"data","sparseSegmentSum"),r=Gr(t,"indices","sparseSegmentSum","int32"),a=Gr(n,"segmentIds","sparseSegmentSum","int32");if(s.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(1!==r.rank)throw new Error(`Indices should be Tensor1D but received shape\n ${r.shape}`);if(1!==a.rank)throw new Error(`Segment ids should be Tensor1D but received shape\n ${a.shape}`);const i={data:s,indices:r,segmentIds:a};return Or.runKernel(rs,i)}});const xp=qr({stringNGrams_: +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n,s,r,a,i,o){const l=Gr(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=Gr(t,"dataSplits","stringNGrams");if("int32"!==u.dtype)throw new Error("Data splits must be of datatype int32");const c={separator:n,nGramWidths:s,leftPad:r,rightPad:a,padWidth:i,preserveShortSequences:o},h={data:l,dataSplits:u},p=Or.runKernel(us,h,c);return{nGrams:p[0],nGramsSplits:p[1]}}});const wp=qr({stringSplit_: +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n=!0){const s=Gr(e,"input","stringSplit","string"),r=Gr(t,"delimiter","stringSplit","string");if(1!==s.rank)throw new Error(`Input should be Tensor1D but received shape ${s.shape}`);if(0!==r.rank)throw new Error(`Delimiter should be a scalar but received shape ${r.shape}`);const a={skipEmpty:n},i={input:s,delimiter:r},o=Or.runKernel(cs,i,a);return{indices:o[0],values:o[1],shape:o[2]}}});const vp=qr({stringToHashBucketFast_: +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t){const n=Gr(e,"input","stringToHashBucketFast","string"),s={numBuckets:t};if(t<=0)throw new Error("Number of buckets must be at least 1");const r={input:n};return Or.runKernel(hs,r,s)}}),kp={fft:_c,ifft:Dc,rfft:Lc,irfft:Oc},Ip={hammingWindow:Ch,hannWindow:$h,frame:Eh,stft:Rh},Np={flipLeftRight:Fh,grayscaleToRGB:_h,resizeNearestNeighbor:Jh,resizeBilinear:Zh,rotateWithOffset:Dh,cropAndResize:Ah,nonMaxSuppression:Mh,nonMaxSuppressionAsync:jh,nonMaxSuppressionWithScore:qh,nonMaxSuppressionWithScoreAsync:Kh,nonMaxSuppressionPadded:Xh,nonMaxSuppressionPaddedAsync:Yh,threshold:Qh,transform:ep},Sp={bandPart:tp,gramSchmidt:np,qr:rp},Tp={absoluteDifference:op,computeWeightedLoss:ip,cosineDistance:lp,hingeLoss:up,huberLoss:cp,logLoss:hp,meanSquaredError:pp,sigmoidCrossEntropy:dp,softmaxCrossEntropy:fp},Cp={sparseFillEmptyRows:mp,sparseReshape:gp,sparseSegmentMean:yp,sparseSegmentSum:bp},$p={stringNGrams:xp,stringSplit:wp,stringToHashBucketFast:vp}; +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class Ep extends so{constructor(e,t,n=null){super(),this.learningRate=e,this.rho=t,this.epsilon=n,this.accumulatedGrads=[],this.accumulatedUpdates=[],null==n&&(this.epsilon=Or.backend.epsilon())}applyGradients(e){(Array.isArray(e)?e.map((e=>e.name)):Object.keys(e)).forEach(((t,n)=>{const s=Or.registeredVariables[t],r=!1;null==this.accumulatedGrads[n]&&(this.accumulatedGrads[n]={originalName:`${t}/accum_grad`,variable:Zi((()=>Nl(s).variable(r)))}),null==this.accumulatedUpdates[n]&&(this.accumulatedUpdates[n]={originalName:`${t}/accum_var`,variable:Zi((()=>Nl(s).variable(r)))});const a=Array.isArray(e)?e[n].tensor:e[t];if(null==a)return;const i=this.accumulatedGrads[n].variable,o=this.accumulatedUpdates[n].variable;Zi((()=>{const e=oo(zo(i,this.rho),zo(Vl(a),1-this.rho)),t=zo(vl(Wl(oo(o,this.epsilon)),Wl(oo(i,this.epsilon))),a),n=oo(zo(o,this.rho),zo(Vl(t),1-this.rho));i.assign(e),o.assign(n);const r=oo(zo(t,-this.learningRate),s);s.assign(r)}))})),this.incrementIterations()}dispose(){null!=this.accumulatedUpdates&&(Ji(this.accumulatedGrads.map((e=>e.variable))),Ji(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,n=!1;this.accumulatedGrads=e.slice(0,t).map((e=>({originalName:e.name,variable:e.tensor.variable(n)}))),this.accumulatedUpdates=e.slice(t,2*t).map((e=>({originalName:e.name,variable:e.tensor.variable(n)})))}getConfig(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.rho,t.epsilon)}}Ep.className="Adadelta",Ki(Ep); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class Rp extends so{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 s=Or.registeredVariables[t];if(null==this.accumulatedGrads[n]){const e=!1;this.accumulatedGrads[n]={originalName:`${t}/accumulator`,variable:Zi((()=>Jo(s.shape,this.initialAccumulatorValue).variable(e)))}}const r=Array.isArray(e)?e[n].tensor:e[t];if(null==r)return;const a=this.accumulatedGrads[n].variable;Zi((()=>{const e=oo(a,Vl(r));a.assign(e);const t=oo(zo(vl(r,Wl(oo(e,Or.backend.epsilon()))),-this.learningRate),s);s.assign(t)}))})),this.incrementIterations()}dispose(){null!=this.accumulatedGrads&&Ji(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(false)})))}getConfig(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}}static fromConfig(e,t){return new e(t.learningRate,t.initialAccumulatorValue)}}Rp.className="Adagrad",Ki(Rp); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class Ap extends so{constructor(e,t,n,s=null){super(),this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=s,this.accumulatedFirstMoment=[],this.accumulatedSecondMoment=[],Zi((()=>{this.accBeta1=no(t).variable(),this.accBeta2=no(n).variable()})),null==s&&(this.epsilon=Or.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map((e=>e.name)):Object.keys(e);Zi((()=>{const n=gu(1,this.accBeta1),s=gu(1,this.accBeta2);t.forEach(((t,r)=>{const a=Or.registeredVariables[t],i=!1;null==this.accumulatedFirstMoment[r]&&(this.accumulatedFirstMoment[r]={originalName:`${t}/m`,variable:Zi((()=>Nl(a).variable(i)))}),null==this.accumulatedSecondMoment[r]&&(this.accumulatedSecondMoment[r]={originalName:`${t}/v`,variable:Zi((()=>Nl(a).variable(i)))});const o=Array.isArray(e)?e[r].tensor:e[t];if(null==o)return;const l=this.accumulatedFirstMoment[r].variable,u=this.accumulatedSecondMoment[r].variable,c=oo(zo(l,this.beta1),zo(o,1-this.beta1)),h=oo(zo(u,this.beta2),zo(Vl(o),1-this.beta2)),p=vl(c,n),d=vl(h,s);l.assign(c),u.assign(h);const f=oo(zo(vl(p,oo(Wl(d),this.epsilon)),-this.learningRate),a);a.assign(f)})),this.accBeta1.assign(zo(this.accBeta1,this.beta1)),this.accBeta2.assign(zo(this.accBeta2,this.beta2))})),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.accBeta2.dispose(),null!=this.accumulatedFirstMoment&&Ji(this.accumulatedFirstMoment.map((e=>e.variable))),null!=this.accumulatedSecondMoment&&Ji(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),Zi((()=>{this.accBeta1.assign(Bl(this.beta1,this.iterations_+1)),this.accBeta2.assign(Bl(this.beta2,this.iterations_+1))}));const t=e.length/2,n=!1;this.accumulatedFirstMoment=e.slice(0,t).map((e=>({originalName:e.name,variable:e.tensor.variable(n)}))),this.accumulatedSecondMoment=e.slice(t,2*t).map((e=>({originalName:e.name,variable:e.tensor.variable(n)})))}getConfig(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon)}}Ap.className="Adam",Ki(Ap); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class Fp extends so{constructor(e,t,n,s=null,r=0){super(),this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=s,this.decay=r,this.accumulatedFirstMoment=[],this.accumulatedWeightedInfNorm=[],Zi((()=>{this.iteration=no(0).variable(),this.accBeta1=no(t).variable()})),null==s&&(this.epsilon=Or.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map((e=>e.name)):Object.keys(e);Zi((()=>{const n=gu(1,this.accBeta1),s=vl(-this.learningRate,oo(zo(this.iteration,this.decay),1));t.forEach(((t,r)=>{const a=Or.registeredVariables[t],i=!1;null==this.accumulatedFirstMoment[r]&&(this.accumulatedFirstMoment[r]={originalName:`${t}/m`,variable:Nl(a).variable(i)}),null==this.accumulatedWeightedInfNorm[r]&&(this.accumulatedWeightedInfNorm[r]={originalName:`${t}/v`,variable:Nl(a).variable(i)});const o=Array.isArray(e)?e[r].tensor:e[t];if(null==o)return;const l=this.accumulatedFirstMoment[r].variable,u=this.accumulatedWeightedInfNorm[r].variable,c=oo(zo(l,this.beta1),zo(o,1-this.beta1)),h=zo(u,this.beta2),p=ro(o),d=Eu(h,p);l.assign(c),u.assign(d);const f=oo(zo(vl(s,n),vl(c,oo(d,this.epsilon))),a);a.assign(f)})),this.iteration.assign(oo(this.iteration,1)),this.accBeta1.assign(zo(this.accBeta1,this.beta1))})),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.iteration.dispose(),null!=this.accumulatedFirstMoment&&Ji(this.accumulatedFirstMoment.map((e=>e.variable))),null!=this.accumulatedWeightedInfNorm&&Ji(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)}}Fp.className="Adamax",Ki(Fp); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class _p extends so{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 s=Array.isArray(e)?e[n].tensor:e[t];if(null==s)return;const r=Or.registeredVariables[t];Zi((()=>{const e=oo(zo(this.c,s),r);r.assign(e)}))})),this.incrementIterations()}setLearningRate(e){this.learningRate=e,null!=this.c&&this.c.dispose(),this.c=Qi(no(-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)}}_p.className="SGD",Ki(_p); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class Dp extends _p{constructor(e,t,n=!1){super(e),this.learningRate=e,this.momentum=t,this.useNesterov=n,this.accumulations=[],this.m=no(this.momentum)}applyGradients(e){(Array.isArray(e)?e.map((e=>e.name)):Object.keys(e)).forEach(((t,n)=>{const s=Or.registeredVariables[t];if(null==this.accumulations[n]){const e=!1;this.accumulations[n]={originalName:`${t}/momentum`,variable:Zi((()=>Nl(s).variable(e)))}}const r=this.accumulations[n].variable,a=Array.isArray(e)?e[n].tensor:e[t];null!=a&&Zi((()=>{let e;const t=oo(zo(this.m,r),a);e=this.useNesterov?oo(zo(this.c,oo(a,zo(t,this.m))),s):oo(zo(this.c,t),s),r.assign(t),s.assign(e)}))})),this.incrementIterations()}dispose(){this.m.dispose(),null!=this.accumulations&&Ji(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(false)})))}getConfig(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}}static fromConfig(e,t){return new e(t.learningRate,t.momentum,t.useNesterov)}}Dp.className="Momentum",Ki(Dp); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class Op extends so{constructor(e,t=.9,n=0,s=null,r=!1){if(super(),this.learningRate=e,this.decay=t,this.momentum=n,this.epsilon=s,this.accumulatedMeanSquares=[],this.accumulatedMoments=[],this.accumulatedMeanGrads=[],this.centered=r,null==s&&(this.epsilon=Or.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 s=Or.registeredVariables[t],r=!1;null==this.accumulatedMeanSquares[n]&&(this.accumulatedMeanSquares[n]={originalName:`${t}/rms`,variable:Zi((()=>Nl(s).variable(r)))}),null==this.accumulatedMoments[n]&&(this.accumulatedMoments[n]={originalName:`${t}/momentum`,variable:Zi((()=>Nl(s).variable(r)))}),null==this.accumulatedMeanGrads[n]&&this.centered&&(this.accumulatedMeanGrads[n]={originalName:`${t}/mg`,variable:Zi((()=>Nl(s).variable(r)))});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;Zi((()=>{const e=oo(zo(i,this.decay),zo(Vl(a),1-this.decay));if(this.centered){const t=this.accumulatedMeanGrads[n].variable,r=oo(zo(t,this.decay),zo(a,1-this.decay)),l=vl(zo(a,this.learningRate),Wl(gu(e,oo(Vl(r),this.epsilon)))),u=oo(zo(o,this.momentum),l);i.assign(e),t.assign(r),o.assign(u);const c=gu(s,u);s.assign(c)}else{const e=oo(zo(i,this.decay),zo(Vl(a),1-this.decay)),t=oo(zo(o,this.momentum),vl(zo(a,this.learningRate),Wl(oo(e,this.epsilon))));i.assign(e),o.assign(t);const n=gu(s,t);s.assign(n)}}))})),this.incrementIterations()}dispose(){null!=this.accumulatedMeanSquares&&Ji(this.accumulatedMeanSquares.map((e=>e.variable))),null!=this.accumulatedMeanGrads&&this.centered&&Ji(this.accumulatedMeanGrads.map((e=>e.variable))),null!=this.accumulatedMoments&&Ji(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)}}Op.className="RMSProp",Ki(Op); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class Mp{static sgd(e){return new _p(e)}static momentum(e,t,n=!1){return new Dp(e,t,n)}static rmsprop(e,t=.9,n=0,s=null,r=!1){return new Op(e,t,n,s,r)}static adam(e=.001,t=.9,n=.999,s=null){return new Ap(e,t,n,s)}static adadelta(e=.001,t=.95,n=null){return new Ep(e,t,n)}static adamax(e=.002,t=.9,n=.999,s=null,r=0){return new Fp(e,t,n,s,r)}static adagrad(e,t=.1){return new Rp(e,t)}}const Lp={sgd:Mp.sgd,momentum:Mp.momentum,adadelta:Mp.adadelta,adagrad:Mp.adagrad,rmsprop:Mp.rmsprop,adamax:Mp.adamax,adam:Mp.adam},zp="undefined"!=typeof requestAnimationFrame?requestAnimationFrame:"undefined"!=typeof setImmediate?setImmediate:e=>e();function Pp(){return new Promise((e=>zp((()=>e()))))} +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function Bp(e,t){const n=e[0].length;e.forEach(((e,t)=>{O(e.length===n,(()=>`Error in concat${n}D: rank of tensors[${t}] must be the same as the rank of the rest (${n})`))})),O(t>=0&&t`Error in concat${n}D: axis must be between 0 and ${n-1}.`));const s=e[0];e.forEach(((e,r)=>{for(let a=0;a`Error in concat${n}D: Shape of tensors[${r}] (${e}) does not match the shape of the rest (${s}) along the non-concatenated axis ${r}.`))}))}function Wp(e,t){const n=e[0].slice();for(let s=1;s=0)if(o>=0){if(o!==a)throw new Error(`rt input.shape and shape=${t} are incompatible: rt input.shape[${r+e}] = ${a} but shape[${r+e}] = ${o}`)}else s[i]=a}return s}function Gp(e){const t={FIRST_DIM_SIZE:Vp.FIRST_DIM_SIZE,VALUE_ROWIDS:Vp.VALUE_ROWIDS,ROW_LENGTHS:Vp.ROW_LENGTHS,ROW_SPLITS:Vp.ROW_SPLITS,ROW_LIMITS:Vp.ROW_LIMITS,ROW_STARTS:Vp.ROW_STARTS},n=[];for(const s of e){if(!(s in t))break;n.push(t[s])}return n}function Hp(e){return 0===e.length?0:e[0]===Vp.FIRST_DIM_SIZE?e.length-1:e.length}function jp(e,t){if(null==e||null==t)return;const n=e.length,s=t.length;if(n>=s)throw new Error(`defaultValue.shape=${e} and ragged tensor flatValues.shape=${t}, are incompatible: defaultValue.rank = ${n} must be less than ragged tensor input flatValues.rank = ${s})`);for(let r=0;r=0&&s>=0&&1!==n&&n!==s)throw new Error(`defaultValue.shape=${e}, and ragged tensor input flatValues.shape=${t} are incompatible: defaultValue.shape[${r-e.length}] = ${n} but ragged tensor input.flatValues.shape[${r-e.length}] = ${s}`)}}!function(e){e[e.FIRST_DIM_SIZE=0]="FIRST_DIM_SIZE",e[e.VALUE_ROWIDS=1]="VALUE_ROWIDS",e[e.ROW_LENGTHS=2]="ROW_LENGTHS",e[e.ROW_SPLITS=3]="ROW_SPLITS",e[e.ROW_LIMITS=4]="ROW_LIMITS",e[e.ROW_STARTS=5]="ROW_STARTS"}(Vp||(Vp={})); +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +const qp=30;function Kp(e){return e<=qp?e:se(e,Math.floor(Math.sqrt(e)))} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function Xp(e,t,n){return[n*("number"==typeof e?e:e[0]),t*("number"==typeof e?e:e[1])]} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function Yp(e,t,n,s=!0){let r=[];if(s)r=r.concat(t.slice(0)),r.push(e[0]/n),r=r.concat(e.slice(1));else{r=r.concat(e[0]);const n=t.length;for(let s=0;s=2*t+1||s%2==1?r.push(s):n.push(s);s.push(...n),s.push(0),s.push(...r)}return s}function Jp(e,t,n,s=!0){const r=[];s?r.push(e[0]/n):r.push(e[0]*n);for(let n=1;nn)throw new Error(`index innermost dimension length must be <= tensor rank; saw: ${t.shape[s-1]} vs. ${n}`);if(0===P(e.shape))throw new Error(`Requested more than 0 entries, but input is empty. Input shape: ${e.shape}.`);const r=t.shape,a=r[r.length-1];let i=1;for(let e=0;ee/u)),1].slice(0,a);return[l,i,u,c]} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +const nd=1.7580993408473768,sd=1.0507009873554805,rd=.3275911,ad=.254829592,id=-.284496736,od=1.421413741,ld=-1.453152027,ud=1.061405429; +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function cd(e,t){if(e.length!==t.length)throw new Error(`Cannot merge real and imag arrays of different lengths. real:${e.length}, imag: ${t.length}.`);const n=new Float32Array(2*e.length);for(let s=0;s/g,wd=",",vd="...";function kd(e,t){const n=((e=e.replace(/\s/g,"")).length-e.replace(xd,"").length)/bd.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 ("${bd}").`);const[s,r]=e.split(bd);O(-1===s.indexOf(vd),(()=>`The ellipsis notation ("${vd}") is not supported yet.`));const a=s.split(wd),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:s}}function Nd(e,t,n){const s=new Array(e);for(let e=0;e`Expected dimension ${s[t[e][n]]} at axis ${n} of input shaped ${JSON.stringify(r)}, but got dimension ${r[n]}`))}}function Sd(e,t){const n=e,s=[];let r=0;0===e.length&&n.push(-1),r=e.length+1;for(let e=0;ee===t))}function Cd(e,t){const n=[];for(let s=0;s"Number of splits must evenly divide the axis.")),s=new Array(t).fill(e.shape[n]/t);else{const r=t.reduce(((e,t)=>(-1===t&&(e+=1),e)),0);O(r<=1,(()=>"There should be only one negative value in split array."));const a=t.indexOf(-1);if(-1!==a){const s=t.reduce(((e,t)=>t>0?e+t:e));t[a]=e.shape[n]-s}O(e.shape[n]===t.reduce(((e,t)=>e+t)),(()=>"The sum of sizes must match the size of the axis dimension.")),s=t}return s} +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function Ed(e){return`Received SparseTensor with denseShape[0] = 0 but\n indices.shape[0] = ${e}`}function Rd(e,t){return`indices(${e}, 0) is invalid: ${t} < 0`}function Ad(e,t,n){return`indices(${e}, 0) is invalid: ${t} >= ${n}`} +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function Fd(e,t){return`only one output dimension may be -1, not both ${e} and ${t}`}function _d(e,t){return`size ${e} must be non-negative, not ${t}`}function Dd(){return"reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero"}function Od(e,t){return`Input to reshape is a SparseTensor with ${P(e)}\n dense values, but the requested shape requires a multiple of ${P(t)}. inputShape=${e} outputShape= ${t}`}function Md(e,t){return`Input to reshape is a tensor with ${P(e)} dense values, but the requested shape has ${P(t)}. inputShape=${e} outputShape=${t}`} +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function Ld(){return"segment ids must be >= 0"}function zd(){return"segment ids are not increasing"}function Pd(e,t){return`Segment id ${e} out of range [0, ${t}), possibly because segmentIds input is not sorted.`}function Bd(e,t,n){return`Bad: indices[${e}] == ${t} out of range [0, ${n})`} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function Wd(e,t){let n,s=!1;for(e<=qp?(n=e,s=!0):n=se(e,Math.floor(Math.sqrt(e)));!s;)n>t||n===e?s=!0:n=se(e,n+1);return n}function Vd(e,t,n){const s=[],r=e.length;for(let a=0;ar))throw new Error(`Expect batchDims in the range of [-${r}, ${r}], but got ${s}`);if(s<0&&(s+=r),s>a)throw new Error(`batchDims (${s}) must be less than rank(x) (\n ${a}).`);if(nsr(e)))}catch(e){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${e}`)}}function Hd(e){return e.map((e=>nr(e)))} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +const jd={kernelName:ke,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>zo(e,Wc(Za(n,"float32"),-1))}}},qd={kernelName:Ie,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const t=Vl(Za(n,"float32")),s=Wl(gu(no(1),t));return du(vl(e,s))}}}},Kd={kernelName:Ne,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const t=Wl(gu(Vl(Za(n,"float32")),1));return vl(e,t)}}}},Xd={kernelName:Se,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,r=ki(n.shape,s.shape);return{a:()=>{let t=e;const s=vi(n.shape,r);return s.length>0&&(t=Ul(t,s)),_o(t,n.shape)},b:()=>{let t=e;const n=vi(s.shape,r);return n.length>0&&(t=Ul(t,n)),_o(t,s.shape)}}}},Yd={kernelName:Te,saveAllInputs:!0,gradFunc:(e,t)=>{const n={};return t.forEach(((t,s)=>{n[s]=()=>e.clone()})),n}},Zd={kernelName:Ee,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Nl(n)}}},Jd={kernelName:Re,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Nl(n)}}},Qd={kernelName:Ae,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>vl(e,Wl(gu(no(1),Vl(Za(n,"float32")))))}}},ef={kernelName:Fe,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const t=Wl(oo(no(1),Vl(Za(n,"float32"))));return vl(e,t)}}}},tf={kernelName:Oe,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,r=ki(n.shape,s.shape);return{a:()=>{const t=oo(Vl(n),Vl(s));let a=zo(e,vl(s,t));const i=vi(n.shape,r);return i.length>0&&(a=Ul(a,i)),_o(a,n.shape)},b:()=>{const t=oo(Vl(n),Vl(s));let a=du(zo(e,vl(n,t)));const i=vi(s.shape,r);return i.length>0&&(a=Ul(a,i)),_o(a,s.shape)}}}},nf={kernelName:_e,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>vl(e,oo(Vl(Za(n,"float32")),1))}}},sf={kernelName:De,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>vl(e,gu(no(1),Vl(Za(n,"float32"))))}}};const rf=qr({avgPool3dGrad_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n,s,r,a){const i=Gr(e,"dy","avgPool3dGrad"),o=Gr(t,"input","avgPool3dGrad");let l=i,u=o,c=!1;4===o.rank&&(c=!0,l=_o(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]]),u=_o(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),O(5===l.rank,(()=>`Error in avgPool3dGrad: dy must be rank 5 but got rank ${l.rank}.`)),O(5===u.rank,(()=>`Error in avgPool3dGrad: input must be rank 5 but got rank ${u.rank}.`)),Fo("avgPool3dGrad",r,a);const h={dy:l,input:u},p={filterSize:n,strides:s,pad:r,dimRoundingMode:a},d=Or.runKernel(Pe,h,p);return c?_o(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}}),af={kernelName:ze,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{filterSize:r,strides:a,pad:i,dimRoundingMode:o}=n;return{x:()=>rf(e,s,r,a,i,o)}}};const of=qr({avgPoolGrad_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n,s,r){const a=Gr(e,"dy","avgPoolGrad"),i=Gr(t,"input","avgPoolGrad");O(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=_o(i,[1,i.shape[0],i.shape[1],i.shape[2]]),l=_o(a,[1,a.shape[0],a.shape[1],a.shape[2]])),O(4===l.rank,(()=>`Error in avgPoolGrad: dy must be rank 4 but got rank ${l.rank}.`)),O(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:s,pad:r},p=Or.runKernel(Le,c,h);return u?_o(p,[p.shape[1],p.shape[2],p.shape[3]]):p}}),lf={kernelName:Me,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{filterSize:r,strides:a,pad:i}=n;return{x:()=>of(e,s,r,a,i)}}},uf={kernelName:Be,inputsToSave:["a","b"],gradFunc:(e,t,n)=>{const[s,r]=t,{transposeA:a,transposeB:i}=n;return a||i?!a&&i?{a:()=>Lo(e,r,!1,!1),b:()=>Lo(e,s,!0,!1)}:a&&!i?{a:()=>Lo(r,e,!1,!0),b:()=>Lo(s,e,!1,!1)}:{a:()=>Lo(r,e,!0,!0),b:()=>Lo(e,s,!0,!0)}:{a:()=>Lo(e,r,!1,!0),b:()=>Lo(s,e,!0,!1)}}},cf={kernelName:We,gradFunc:(e,t,n)=>{const{blockShape:s,crops:r}=n;return{x:()=>Xu(e,s,r)}}},hf={kernelName:"BroadcastTo",gradFunc:(e,t,n)=>{const s=n,r=s.inputShape,a=s.shape,i=Array.from(a);for(let e=r.length-1;e>=0;e--)if(r[e]===a[e])i[e]=1;else if(1!==r[e])throw new Error(`broadcastTo(): [${r}] cannot be broadcast to [${a}].`);const o=[];for(let e=0;e1&&o.push(e);return{x:()=>Ul(e,o,!0)}}},pf={kernelName:Ge,gradFunc:e=>({x:()=>e.clone()})},df={kernelName:He,gradFunc:e=>({x:()=>Nl(e)})},ff={kernelName:je,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{clipValueMin:r,clipValueMax:a}=n;return{x:()=>Il(xu(tu(s,r),lu(s,a)),e,Nl(e))}}},mf={kernelName:Ke,inputsToSave:["x"],gradFunc:jd.gradFunc},gf={kernelName:Xe,saveAllInputs:!0,gradFunc:(e,t,n)=>{const s=t.map((e=>e.shape)),{axis:r}=n,a=j(r,t[0].shape)[0],i=s.map((e=>e[a]));return Mc(e,i,a).map((e=>()=>e))}},yf={kernelName:Ye,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const[s,r]=t,{dilations:a,strides:i,pad:o,dataFormat:l}=n;return O(Eo(a),(()=>`Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${a}'`)),{x:()=>il(s.shape,e,r,i,o,l),filter:()=>yh(s,e,r.shape,i,o,l)}}},bf={kernelName:Je,inputsToSave:["dy","filter"],gradFunc:(e,t,n)=>{const[s,r]=t,{strides:a,pad:i,dataFormat:o,dimRoundingMode:l}=n;return{dy:()=>rl(e,r,a,i,o,1,l),filter:()=>yh(e,s,r.shape,a,i,o,l)}}};const xf=qr({conv3DBackpropFilter_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n,s,r){let a=e;4===e.rank&&(a=_o(e,[1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]]));let i=t;4===i.rank&&(i=_o(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]])),O(5===a.rank,(()=>`Error in conv3dDerFilter: input must be rank 5, but got shape ${a.shape}.`)),O(5===i.rank,(()=>`Error in conv3dDerFilter: dy must be rank 5, but got shape ${i.shape}.`)),O(5===n.length,(()=>`Error in conv3dDerFilter: filterShape must be length 5, but got ${n}.`)),O(a.shape[4]===n[3],(()=>`Error in conv3dDerFilter: depth of input ${a.shape[4]}) must match input depth in filter (${n[3]}.`)),O(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:s,pad:r,filterShape:n};return Or.runKernel(et,o,l)}}),wf={kernelName:Qe,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const{dilations:s,strides:r,pad:a}=n;O(Eo(s),(()=>`Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`));const[i,o]=t;return{x:()=>ul(i.shape,e,o,r,a),filter:()=>xf(i,e,o.shape,r,a)}}},vf={kernelName:nt,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>zo(du(Tc(Za(n,"float32"))),e)}}},kf={kernelName:st,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>zo(Cc(Za(n,"float32")),e)}}},If={kernelName:at,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{axis:r,exclusive:a,reverse:i}=n;return{x:()=>{const t=Ol([r],s.rank);let n=fl(e,r,a,!i);return null!=t&&(n=ah(n,t)),n}}}},Nf={kernelName:ut,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const{dilations:s,strides:r,pad:a,dimRoundingMode:i}=n,o=null==s?[1,1]:s;O(Eo(o),(()=>`Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations '${o}'`));const[l,u]=t;return O(4===l.rank,(()=>`Error in gradient of depthwiseConv2dNative: input must be rank 4, but got rank ${l.rank}.`)),O(4===u.rank,(()=>`Error in gradient of depthwiseConv2dNative: filter must be rank 4, but got rank ${u.rank}.`)),O(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]}.`)),O(Ro(r,o),(()=>`Error in gradient of depthwiseConv2d: Either strides or dilations must be 1. Got strides ${r} and dilations '${o}'.`)),Fo("depthwiseConv2d",a,i),{x:()=>Nh(l.shape,e,u,r,a,o,i),filter:()=>Ih(l,e,u.shape,r,a,o,i)}}},Sf={kernelName:dt,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const[s,r]=t,a={x:s,filter:r,dy:e},i={x:s,filter:r,dy:e};return{x:()=>Or.runKernel(ft,a,n),filter:()=>Or.runKernel(mt,i,n)}}},Tf={kernelName:bt,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t,s={dy:e,y:n};return{x:()=>Or.runKernel(xt,s)}}},Cf={kernelName:wt,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t,s=zo(ql(du(Vl(n))),2/Math.sqrt(Math.PI));return{x:()=>zo(e,s)}}},$f={kernelName:kt,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>zo(e,n)}}},Ef={kernelName:It,inputsToSave:["input"],gradFunc:(e,t)=>{const[n]=t;return{input:()=>_o(e,n.shape)}}},Rf={kernelName:Nt,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>zo(e,ql(n))}}},Af={kernelName:$t,gradFunc:e=>({x:()=>Nl(e)})},Ff={kernelName:Et,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,r=ki(n.shape,s.shape);return{a:()=>{const t=vl(e,Za(s,"float32")),a=vi(n.shape,r);return a.length>0?_o(Ul(t,a),n.shape):t},b:()=>{let t=zo(e,Za(n,"float32"));const a=vi(s.shape,r);a.length>0&&(t=_o(Ul(t,a),s.shape));const i=Vl(s);return du(vl(t,Za(i,"float32")))}}}},_f={kernelName:Rt,inputsToSave:["x","mean","variance","scale"],gradFunc:(e,t,n)=>{const{varianceEpsilon:s}=n,[r,a,i,o]=t,l=null==o?no(1):o,u=vi(a.shape,r.shape),c=[];if(1===a.rank){for(let e=0;e1===a.rank?_o(zo(zo(e,Yl(_o(d,[1,1,1,a.shape[0]]),c)),l),r.shape):_o(zo(zo(e,d),l),r.shape),mean:()=>{let e=zo(zo(d,no(-1)),p);return 1===a.rank&&(e=Ul(e,u)),_o(e,a.shape)},variance:()=>{let e=zo(zo(f,h),p);return 1===a.rank&&(e=Ul(e,u)),_o(e,a.shape)},scale:()=>{const t=zo(h,d);let n=zo(e,t);return 1===a.rank&&(n=Ul(n,u)),_o(n,a.shape)},offset:()=>{let t=e;return 1===a.rank&&(t=Ul(t,u)),_o(t,a.shape)}}}},Df={kernelName:At,inputsToSave:["x","indices"],gradFunc:(e,t,n)=>{const[s,r]=t,{axis:a}=n,i=j(a,s.shape)[0];return{x:()=>{const t=s.shape,n=r.size,o=t.slice(0,i),l=o.length,u=t.slice(a,t.length).slice(1),c=u.length,h=Of(0,l),p=Of(l+1,l+1+c),d=Mf([o,[n],u]),f=_o(e,d),m=_o(r,[n]),g=Mf([[l],h,p]),y=ah(f,g);let b=Jc(y,m,s.shape[i]);const x=Ml(g);return b=ah(b,x),b},indices:()=>r}}};function Of(e,t){const n=[];for(let s=e;s{const[n,s]=t;return{a:()=>Nl(n),b:()=>Nl(s)}}},zf={kernelName:Ot,gradFunc:e=>({x:()=>Za(e,"float32")})},Pf={kernelName:zt,gradFunc:e=>({x:()=>Nl(e)})},Bf={kernelName:Pt,gradFunc:e=>({x:()=>Nl(e)})},Wf={kernelName:Bt,gradFunc:e=>({x:()=>Nl(e)})},Vf={kernelName:Wt,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{alpha:r}=n,a=eu(s,0);return{x:()=>Il(a,e,zo(e,r))}}},Uf={kernelName:jt,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>vl(e,oo(n,1))}}},Gf={kernelName:Ht,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>vl(e,Za(n,"float32"))}}},Hf={kernelName:"LogSoftmax",inputsToSave:[],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[s]=t,{axis:r}=n;return{logits:()=>{const t=ql(s);return gu(e,zo(Ul(e,r,!0),t))}}}};const jf=qr({localResponseNormalizationBackprop_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n,s=5,r=1,a=1,i=.5){const o={x:e,y:t,dy:n},l={depthRadius:s,bias:r,alpha:a,beta:i};return Or.runKernel(Zt,o,l)}}),qf={kernelName:Yt,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[s,r]=t,{depthRadius:a,bias:i,alpha:o,beta:l}=n;return{x:()=>jf(s,r,e,a,i,o,l)}}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function Kf(e,t,n,s){return t.rankzo(e,Za(kl(n,t),e.dtype))}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +const Xf={kernelName:Jt,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const s=n,{reductionIndices:r}=s,a=t[0],i=Kf(e,t[1],a,j(r,a.shape));return{x:()=>i.x()}}},Yf={kernelName:Qt,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t;return{a:()=>zo(e,Za(tu(n,s),"float32")),b:()=>zo(e,Za(ou(n,s),"float32"))}}};const Zf=qr({maxPool3dGrad_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n,s,r,a,i){const o=Gr(e,"dy","maxPool3dGrad"),l=Gr(t,"input","maxPool3dGrad"),u=Gr(n,"output","maxPool3dGrad");let c=o,h=l,p=u,d=!1;4===l.rank&&(d=!0,c=_o(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]]),h=_o(l,[1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]]),p=_o(u,[1,u.shape[0],u.shape[1],u.shape[2],u.shape[3]])),O(5===c.rank,(()=>`Error in maxPool3dGrad: dy must be rank 5 but got rank ${c.rank}.`)),O(5===h.rank,(()=>`Error in maxPool3dGrad: input must be rank 5 but got rank ${h.rank}.`)),O(5===p.rank,(()=>`Error in maxPool3dGrad: output must be rank 5 but got rank ${p.rank}.`)),Fo("maxPool3dGrad",a,i);const f={dy:c,input:h,output:p},m={filterSize:s,strides:r,pad:a,dimRoundingMode:i},g=Or.runKernel(sn,f,m);return d?_o(g,[g.shape[1],g.shape[2],g.shape[3],g.shape[4]]):g}}),Jf={kernelName:nn,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[s,r]=t,{filterSize:a,strides:i,pad:o,dimRoundingMode:l}=n;return{x:()=>Zf(e,s,r,a,i,o,l)}}};const Qf=qr({maxPoolGrad_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n,s,r,a,i){const o=Gr(e,"dy","maxPoolGrad"),l=Gr(t,"input","maxPoolGrad"),u=Gr(n,"output","maxPoolGrad");O(l.rank===o.rank,(()=>`Rank of input (${l.rank}) does not match rank of dy (${o.rank})`)),O(4===o.rank,(()=>`Error in maxPoolGrad: dy must be rank 4 but got rank ${o.rank}.`)),O(4===l.rank,(()=>`Error in maxPoolGrad: input must be rank 4 but got rank ${l.rank}.`)),Fo("maxPoolGrad",a,i);const c={dy:o,input:l,output:u},h={filterSize:s,strides:r,pad:a,dimRoundingMode:i};return Or.runKernel(tn,c,h)}}),em={kernelName:en,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[s,r]=t,{filterSize:a,strides:i,pad:o}=n;return{x:()=>Qf(e,s,r,a,i,o)}}},tm={kernelName:an,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{axis:r}=n,a=j(r,s.shape),i=P(Fl(s.shape,a)[1]);return{x:()=>{const t=s.shape.slice();a.forEach((e=>{t[e]=1}));const n=_o(e,t);return vl(zo(n,Fu(s.shape,"float32")),i)}}}},nm={kernelName:on,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const s=n,{axis:r}=s,[a,i]=t,o=Kf(e,i,a,j(r,a.shape));return{x:()=>o.x()}}},sm={kernelName:un,inputsToSave:["x"],gradFunc:(e,t,n)=>{const s=t[0],{paddings:r}=n,a=r.map((e=>e[0]));return{x:()=>Bo(e,a,s.shape)}}},rm={kernelName:wn,saveAllInputs:!0,gradFunc:(e,t,n)=>{const{axis:s}=n;return Qc(e,s).map((e=>()=>e))}},am={kernelName:vn,inputsToSave:["x"],gradFunc:(e,t,n)=>{const s=t[0],{paddings:r}=n,a=r.map((e=>e[0]));return{x:()=>Bo(e,a,s.shape)}}},im={kernelName:kn,inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:(e,t)=>{const[n,s,r]=t,a=n,i=s,o=ki(a.shape,i.shape);return{a:()=>{const t=Za(i,"float32");let n=zo(e,zo(t,Bl(a,gu(t,no(1)))));const s=vi(a.shape,o);return s.length>0&&(n=Ul(n,s)),_o(n,a.shape)},b:()=>{const t=eu(a,0),n=Il(t,hu(a),Nl(a));let s=zo(e,zo(r,n));const l=vi(i.shape,o);return l.length>0&&(s=Ul(s,l)),_o(s,i.shape)}}}},om={kernelName:In,inputsToSave:["x","alpha"],gradFunc:(e,t)=>{const[n,s]=t,r=eu(n,0);return{x:()=>Il(r,e,zo(e,s)),alpha:()=>{let t=Il(r,Nl(e),zo(e,n));const a=vi(s.shape,e.shape);return a.length>0&&(t=Ul(t,a)),_o(t,s.shape)}}}};function lm(e,t,n){const s=e.shape.length,r=s-n.length,a=Ol(n,s);let i=e;null!=a&&(i=ah(e,a));const o=i.shape.slice(),l=o.splice(s-n.length,n.length).reduce(((e,t)=>e*t),1);o.push(l);let u= +/** + * @license + * Copyright 2022 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n){const s=e.shape.slice();s[n]=1;const r=_o(t,s),a=dl(e,n,!0,!1),i=dl(e,n,!0,!0),o=zo(a,i);return zo(r,o)}(i.reshape(o),t,r);if(u=u.reshape(i.shape),null!=a){const e=Ml(a);u=ah(u,e)}return u}const um={kernelName:Nn,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{axis:r}=n;let a=[];return a=null==r?s.shape.map(((e,t)=>t)):"number"==typeof r?[r]:r,{x:()=>lm(s,e,a)}}},cm={kernelName:En,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>vl(e,du(Vl(n)))}}},hm={kernelName:Mn,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t,s=zo(lu(n,6),Wc(n));return{x:()=>zo(e,Za(s,"float32"))}}},pm={kernelName:Rn,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>zo(e,Za(Wc(n),"float32"))}}},dm={kernelName:An,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>_o(e,n.shape)}}},fm={kernelName:Pn,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>du(vl(e,zo(Bl(n,1.5),2)))}}},mm={kernelName:Un,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const t=eu(n,no(0)),s=no(nd),r=no(sd),a=zo(e,r),i=zo(zo(e,s),ql(Za(n,"float32")));return Il(t,a,i)}}}},gm={kernelName:Hn,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>zo(hl(Za(n,"float32")),e)}}},ym={kernelName:jn,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>zo(pl(Za(n,"float32")),e)}}},bm={kernelName:Gn,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{begin:r,size:a}=n,i=s.shape,[o,l]=Ui(s,r,a),u=[];for(let t=0;tGu(e,u)}}},xm={kernelName:Xn,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>zo(e,Po(n))}}},wm={kernelName:Jn,gradFunc:(e,t,n)=>{const{blockShape:s,paddings:r}=n;return{x:()=>Uo(e,s,r)}}},vm={kernelName:Qn,gradFunc:(e,t,n)=>{const{axis:s}=n;return{x:()=>Mo(e,s)}}},km={kernelName:Yn,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>vl(e,zo(Wl(Za(n,"float32")),2))}}},Im={kernelName:os,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>zo(e,zo(Za(n,"float32"),2))}}},Nm={kernelName:Zn,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,r=s.shape.slice(),{axis:a}=n;j(a,s.shape).forEach((e=>{r[e]=1}));const i=_o(e,r),o=zo(i,Fu(s.shape,"float32"));return{x:()=>o}}},Sm={kernelName:ds,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>vl(e,Vl(hl(n)))}}},Tm={kernelName:ms,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{reps:r}=n;return{x:()=>{let t=Nl(s);if(1===s.rank)for(let n=0;n{const[n]=t;return{x:()=>function(e,t){const n=Eu(t,Nl(t)),s=Ql(e,n);let r=tu(t,no(0,"int32"));const a=s.rank-r.rank;for(let e=0;e{const[n,s]=t,r=ki(n.shape,s.shape);return{a:()=>{const t=vl(e,Za(s,"float32")),a=vi(n.shape,r);return a.length>0?_o(Ul(t,a),n.shape):t},b:()=>{let t=zo(e,Za(n,"float32"));const a=vi(s.shape,r);a.length>0&&(t=_o(Ul(t,a),s.shape));const i=Vl(s);return du(vl(t,Za(i,"float32")))}}}},Tf,Cf,$f,Ef,Rf,Ff,Af,_f,Df,Lf,zf,Pf,Bf,Wf,Vf,Uf,Gf,Hf,qf,Xf,Xf,Yf,Jf,em,tm,nm,{kernelName:ln,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t;return{a:()=>zo(e,Za(lu(n,s),"float32")),b:()=>zo(e,Za(eu(n,s),"float32"))}}},sm,{kernelName:cn,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,r=ki(n.shape,s.shape);return{a:()=>{const t=vi(n.shape,r);return t.length>0?_o(Ul(e,t),n.shape):e},b:()=>{const t=zo(e,du(Jl(vl(n,s)))),a=vi(s.shape,r);return a.length>0?_o(Ul(t,a),s.shape):t}}}},{kernelName:pn,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,r=ki(n.shape,s.shape);return{a:()=>{const t=zo(e,Za(s,"float32")),a=vi(n.shape,r);return a.length>0?_o(Ul(t,a),n.shape):t},b:()=>{const t=zo(e,Za(n,"float32")),a=vi(s.shape,r);return a.length>0?_o(Ul(t,a),s.shape):t}}}},{kernelName:dn,gradFunc:e=>({x:()=>du(e)})},{kernelName:xn,inputsToSave:["indices"],gradFunc:(e,t)=>{const n=t[0];return{indices:()=>Au(n.shape,"float32")}}},{kernelName:bn,gradFunc:e=>({x:()=>Nl(e)})},rm,am,am,im,om,um,cm,hm,pm,dm,{kernelName:Dn,inputsToSave:["images"],gradFunc:(e,t,n)=>{const[s]=t,r={dy:e,images:s};return{images:()=>Or.runKernel(On,r,n)}}},{kernelName:Fn,inputsToSave:["images"],gradFunc:(e,t,n)=>{const[s]=t,r={dy:e,images:s};return{images:()=>Or.runKernel(_n,r,n)}}},{kernelName:Ln,gradFunc:(e,t,n)=>{const{dims:s}=n,r=j(s,e.shape);return{x:()=>mc(e,r)}}},{kernelName:zn,gradFunc:e=>({x:()=>Nl(e)})},fm,{kernelName:Vn,inputsToSave:["condition"],gradFunc:(e,t)=>{const[n]=t;return{condition:()=>Za(Nl(n),"float32"),t:()=>zo(e,Za(n,e.dtype)),e:()=>zo(e,Za(wu(n),e.dtype))}}},mm,{kernelName:Kn,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>zo(e,zo(n,gu(no(1),n)))}}},{kernelName:qn,gradFunc:e=>({x:()=>Nl(e)})},gm,ym,bm,{kernelName:es,outputsToSave:[!0],gradFunc:(e,t,n)=>{const[s]=t,{dim:r}=n,a=zo(e,s);return{logits:()=>gu(a,zo(Ul(a,[r],true),s))}}},xm,wm,wm,vm,vm,km,{kernelName:is,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,r=no(2);return{a:()=>zo(e,zo(r,gu(n,s))),b:()=>zo(e,zo(r,gu(s,n)))}}},Im,{kernelName:Is,gradFunc:e=>({x:()=>Nl(e)})},{kernelName:ps,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,r=ki(n.shape,s.shape);return{a:()=>{let t=e;const s=vi(n.shape,r);return s.length>0&&(t=Ul(t,s)),_o(t,n.shape)},b:()=>{let t=e;const n=vi(s.shape,r);return n.length>0&&(t=Ul(t,n)),_o(du(t),s.shape)}}}},Nm,Sm,{kernelName:fs,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>zo(gu(no(1),Vl(n)),e)}}},Tm,{kernelName:bs,gradFunc:(e,t,n)=>{const s=n,{perm:r}=s,a=Ml(r);return{x:()=>ah(e,a)}}},{kernelName:ws,gradFunc:(e,t,n)=>{const s=n,{axis:r}=s;return{value:()=>Bc(e,r)}}},Cm,{kernelName:ks,gradFunc:e=>({x:()=>Nl(e)})}];for(const e of $m)Ls(e); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.abs=function(){return this.throwIfDisposed(),ro(this)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.acos=function(){return this.throwIfDisposed(),ao(this)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.acosh=function(){return this.throwIfDisposed(),io(this)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.add=function(e){return this.throwIfDisposed(),oo(this,e)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.all=function(e,t){return this.throwIfDisposed(),uo(this,e,t)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.any=function(e,t){return this.throwIfDisposed(),co(this,e,t)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.argMax=function(e){return this.throwIfDisposed(),ho(this,e)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.argMin=function(e){return this.throwIfDisposed(),po(this,e)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.asScalar=function(){return this.throwIfDisposed(),O(1===this.size,(()=>"The array must have only 1 element.")),_o(this,[])}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.asType=function(e){return this.throwIfDisposed(),Za(this,e)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.as1D=function(){return this.throwIfDisposed(),_o(this,[this.size])}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.as2D=function(e,t){return this.throwIfDisposed(),_o(this,[e,t])}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.as3D=function(e,t,n){return this.throwIfDisposed(),_o(this,[e,t,n])}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.as4D=function(e,t,n,s){return this.throwIfDisposed(),_o(this,[e,t,n,s])}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.as5D=function(e,t,n,s,r){return this.throwIfDisposed(),_o(this,[e,t,n,s,r])}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.asin=function(){return this.throwIfDisposed(),fo(this)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.asinh=function(){return this.throwIfDisposed(),mo(this)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.atan=function(){return this.throwIfDisposed(),go(this)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.atan2=function(e){return this.throwIfDisposed(),yo(this,e)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.atanh=function(){return this.throwIfDisposed(),bo(this)},yr().prototype.avgPool=function(e,t,n,s){return this.throwIfDisposed(),Do(this,e,t,n,s)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.batchToSpaceND=function(e,t){return this.throwIfDisposed(),Uo(this,e,t)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.batchNorm=function(e,t,n,s,r){return this.throwIfDisposed(),Go(this,e,t,n,s,r)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.broadcastTo=function(e){return this.throwIfDisposed(),Yo(this,e)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.cast=function(e){return this.throwIfDisposed(),Za(this,e)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.ceil=function(){return this.throwIfDisposed(),Zo(this)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.clipByValue=function(e,t){return this.throwIfDisposed(),Qo(this,e,t)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.concat=function(e,t){return this.throwIfDisposed(),e instanceof gr&&(e=[e]),Mo([this,...e],t)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.conv1d=function(e,t,n,s,r,a){return this.throwIfDisposed(),al(this,e,t,n,s,r,a)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.conv2dTranspose=function(e,t,n,s,r){return this.throwIfDisposed(),ol(this,e,t,n,s,r)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.conv2d=function(e,t,n,s,r,a){return this.throwIfDisposed(),rl(this,e,t,n,s,r,a)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.cos=function(){return this.throwIfDisposed(),hl(this)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.cosh=function(){return this.throwIfDisposed(),pl(this)}, +/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the 'License'); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an 'AS IS' BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.cumprod=function(e,t,n){return this.throwIfDisposed(),dl(this,e,t,n)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.cumsum=function(e,t,n){return this.throwIfDisposed(),fl(this,e,t,n)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.depthToSpace=function(e,t){return this.throwIfDisposed(),gl(this,e,t)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.depthwiseConv2d=function(e,t,n,s,r,a){return this.throwIfDisposed(),yl(this,e,t,n,s,r,a)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.dilation2d=function(e,t,n,s,r){return this.throwIfDisposed(),xl(this,e,t,n,s,r)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.divNoNan=function(e){return this.throwIfDisposed(),Sl(this,e)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.div=function(e){return this.throwIfDisposed(),vl(this,e)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.dot=function(e){return this.throwIfDisposed(),Tl(this,e)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.elu=function(){return this.throwIfDisposed(),$l(this)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.equal=function(e){return this.throwIfDisposed(),kl(this,e)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.erf=function(){return this.throwIfDisposed(),El(this)}, +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.euclideanNorm=function(e,t){return this.throwIfDisposed(),jl(this,e,t)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.exp=function(){return this.throwIfDisposed(),ql(this)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.expandDims=function(e){return this.throwIfDisposed(),Kl(this,e)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.expm1=function(){return this.throwIfDisposed(),Xl(this)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.fft=function(){return this.throwIfDisposed(),_c(this)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.flatten=function(){return this.throwIfDisposed(),_o(this,[this.size])}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.floor=function(){return this.throwIfDisposed(),Jl(this)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.floorDiv=function(e){return this.throwIfDisposed(),wl(this,e)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.gather=function(e,t){return this.throwIfDisposed(),Ql(this,e,t)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.greaterEqual=function(e){return this.throwIfDisposed(),tu(this,e)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.greater=function(e){return this.throwIfDisposed(),eu(this,e)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.ifft=function(){return this.throwIfDisposed(),Dc(this)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.irfft=function(){return this.throwIfDisposed(),Oc(this)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.isFinite=function(){return this.throwIfDisposed(),su(this)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.isInf=function(){return this.throwIfDisposed(),ru(this)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.isNaN=function(){return this.throwIfDisposed(),au(this)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.leakyRelu=function(e){return this.throwIfDisposed(),iu(this,e)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.lessEqual=function(e){return this.throwIfDisposed(),lu(this,e)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.less=function(e){return this.throwIfDisposed(),ou(this,e)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.localResponseNormalization=function(e,t,n,s){return this.throwIfDisposed(),cu(this,e,t,n,s)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.logSigmoid=function(){return this.throwIfDisposed(),mu(this)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.logSoftmax=function(e){return this.throwIfDisposed(),yu(this,e)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.logSumExp=function(e,t){return this.throwIfDisposed(),bu(this,e,t)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.log=function(){return this.throwIfDisposed(),hu(this)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.log1p=function(){return this.throwIfDisposed(),pu(this)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.logicalAnd=function(e){return this.throwIfDisposed(),xu(this,e)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.logicalNot=function(){return this.throwIfDisposed(),wu(this)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.logicalOr=function(e){return this.throwIfDisposed(),vu(this,e)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.logicalXor=function(e){return this.throwIfDisposed(),ku(this,e)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.matMul=function(e,t,n){return this.throwIfDisposed(),Lo(this,e,t,n)},yr().prototype.maxPool=function(e,t,n,s){return this.throwIfDisposed(),Tu(this,e,t,n,s)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.max=function(e,t){return this.throwIfDisposed(),zl(this,e,t)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.maximum=function(e){return this.throwIfDisposed(),Eu(this,e)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.mean=function(e,t){return this.throwIfDisposed(),Ru(this,e,t)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.min=function(e,t){return this.throwIfDisposed(),Pl(this,e,t)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.minimum=function(e){return this.throwIfDisposed(),Du(this,e)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.mirrorPad=function(e,t){return this.throwIfDisposed(),Ou(this,e,t)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.mod=function(e){return this.throwIfDisposed(),Mu(this,e)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.mul=function(e){return this.throwIfDisposed(),zo(this,e)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.neg=function(){return this.throwIfDisposed(),du(this)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.norm=function(e,t,n){return this.throwIfDisposed(),Hl(this,e,t,n)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.notEqual=function(e){return this.throwIfDisposed(),Bu(this,e)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.oneHot=function(e,t=1,n=0){return this.throwIfDisposed(),Wu(this,e,t,n)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.onesLike=function(){return this.throwIfDisposed(),Vu(this)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.pad=function(e,t){return this.throwIfDisposed(),Gu(this,e,t)},yr().prototype.pool=function(e,t,n,s,r,a){return this.throwIfDisposed(),Yu(this,e,t,n,s,r,a)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.pow=function(e){return this.throwIfDisposed(),Bl(this,e)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.prelu=function(e){return this.throwIfDisposed(),Zu(this,e)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.prod=function(e,t){return this.throwIfDisposed(),Ju(this,e,t)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.reciprocal=function(){return this.throwIfDisposed(),pc(this)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.relu=function(){return this.throwIfDisposed(),dc(this)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.relu6=function(){return this.throwIfDisposed(),fc(this)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.reshapeAs=function(e){return this.throwIfDisposed(),_o(this,e.shape)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.reshape=function(e){return this.throwIfDisposed(),_o(this,e)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.resizeBilinear=function(e,t,n){return this.throwIfDisposed(),Zh(this,e,t,n)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.resizeNearestNeighbor=function(e,t,n){return this.throwIfDisposed(),Jh(this,e,t,n)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.reverse=function(e){return this.throwIfDisposed(),mc(this,e)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.rfft=function(){return this.throwIfDisposed(),Lc(this)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.round=function(){return this.throwIfDisposed(),wc(this)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.rsqrt=function(){return this.throwIfDisposed(),vc(this)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.selu=function(){return this.throwIfDisposed(),kc(this)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.separableConv2d=function(e,t,n,s,r,a){return this.throwIfDisposed(),Ic(this,e,t,n,s,r,a)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.sigmoid=function(){return this.throwIfDisposed(),Po(this)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.sign=function(){return this.throwIfDisposed(),Sc(this)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.sin=function(){return this.throwIfDisposed(),Tc(this)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.sinh=function(){return this.throwIfDisposed(),Cc(this)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.slice=function(e,t){return this.throwIfDisposed(),Bo(this,e,t)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.softmax=function(e){return this.throwIfDisposed(),Fc(this,e)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.softplus=function(){return this.throwIfDisposed(),fu(this)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.spaceToBatchND=function(e,t){return this.throwIfDisposed(),Xu(this,e,t)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.split=function(e,t){return this.throwIfDisposed(),Mc(this,e,t)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.sqrt=function(){return this.throwIfDisposed(),Wl(this)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.square=function(){return this.throwIfDisposed(),Vl(this)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.squaredDifference=function(e){return this.throwIfDisposed(),zc(this,e)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.squeeze=function(e){return this.throwIfDisposed(),Pc(this,e)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.stack=function(e,t){this.throwIfDisposed();const n=e instanceof gr?[this,e]:[this,...e];return Bc(n,t)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.step=function(e){return this.throwIfDisposed(),Wc(this,e)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.stridedSlice=function(e,t,n,s,r,a,i,o){return this.throwIfDisposed(),Vc(this,e,t,n,s,r,a,i,o)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.sub=function(e){return this.throwIfDisposed(),gu(this,e)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.sum=function(e,t){return this.throwIfDisposed(),Ul(this,e,t)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.tan=function(){return this.throwIfDisposed(),Uc(this)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.tanh=function(){return this.throwIfDisposed(),Wo(this)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.tile=function(e){return this.throwIfDisposed(),Yl(this,e)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.toBool=function(){return this.throwIfDisposed(),Za(this,"bool")}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.toFloat=function(){return this.throwIfDisposed(),Za(this,"float32")}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.toInt=function(){return this.throwIfDisposed(),Za(this,"int32")}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.topk=function(e,t){return this.throwIfDisposed(),Xc(this,e,t)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.transpose=function(e){return this.throwIfDisposed(),ah(this,e)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.unique=function(e){return this.throwIfDisposed(),Zc(this,e)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.unsortedSegmentSum=function(e,t){return this.throwIfDisposed(),Jc(this,e,t)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.unstack=function(e){return this.throwIfDisposed(),Qc(this,e)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.where=function(e,t){return this.throwIfDisposed(),Il(e,this,t)}, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +yr().prototype.zerosLike=function(){return this.throwIfDisposed(),Nl(this)}; +/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */ +class Em extends Error{constructor(e){super(e),Object.setPrototypeOf(this,Em.prototype)}}class Rm extends Error{constructor(e){super(e),Object.setPrototypeOf(this,Rm.prototype)}}class Am extends Error{constructor(e){super(e),Object.setPrototypeOf(this,Am.prototype)}}class Fm extends Error{constructor(e){super(e),Object.setPrototypeOf(this,Fm.prototype)}}class _m extends Error{constructor(e){super(e),Object.setPrototypeOf(this,_m.prototype)}}Error; +/** + * @license + * Copyright 2022 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */ +class Dm{constructor(e){this.maxEntries=e||100,this.cache=new Map}get(e){let t;return this.cache.has(e)&&(t=this.cache.get(e),this.cache.delete(e),this.cache.set(e,t)),t}put(e,t){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.maxEntries){const e=this.cache.keys().next().value;this.cache.delete(e)}this.cache.set(e,t)}getMaxEntries(){return this.maxEntries}setMaxEntries(e){if(e<0)throw new Error(`The maxEntries of LRU caches must be at least 0, but got ${e}.`);if(this.maxEntries>e)for(let t=0;tt.toUpperCase()))}let Vm={};function Um(e){if(null==e)return null;const t={};return t.className=e.getClassName(),t.config=e.getConfig(),t}function Gm(e){if(null!=e&&"object"==typeof e)if(Array.isArray(e))e.forEach((e=>Gm(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?Gm(t):e[n]=t.value)}}}function Hm(e,t={},n={},s="object",r=!1){if("string"==typeof e){const r=e;let a;if(r in n)a=n[r];else if(r in Vm)a=Vm[r];else if(a=t[r],null==a)throw new Am(`Unknown ${s}: ${e}. This may be due to one of the following reasons:\n1. The ${s} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.\n2. The custom ${s} 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 Am(`${s}: 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 Vm?[o,l]=Vm.className:i in t&&([o,l]=t[i]),null==o)throw new Am(`Unknown ${s}: ${i}. This may be due to one of the following reasons:\n1. The ${s} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.\n2. The custom ${s} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);if(null!=l){const e={};for(const t of Object.keys(Vm))e[t]=Vm[t];for(const t of Object.keys(n))e[t]=n[t];a.config.customObjects=e;const t=Object.assign({},Vm);for(const e of Object.keys(n))Vm[e]=n[e];Gm(a.config);const s=l(o,a.config,n,r);return Vm=Object.assign({},t),s}{const e=Object.assign({},Vm);for(const e of Object.keys(n))Vm[e]=n[e];const t=new o(a.config);return Vm=Object.assign({},e),t}}}function jm(e,t){return-1*function(e,t){return et?1:0}(e,t)}function qm(e){if(null==e)return e;const t=[];for(const n of e)-1===t.indexOf(n)&&t.push(n);return t}function Km(e){if(null==e)throw new Am(`Invalid value in obj: ${JSON.stringify(e)}`);for(const t in e)if(e.hasOwnProperty(t))return!1;return!0}function Xm(e,t,n){if(null!=n&&e.indexOf(n)<0)throw new Am(`${n} is not a valid ${t}. Valid values are ${e} or null/undefined.`)}function Ym(e,t,n=0,s=1/0){return Mm(n>=0),Mm(s>=n),Array.isArray(e)&&e.length>=n&&e.length<=s&&e.every((e=>typeof e===t))}function Zm(e,t){Array.isArray(e)?(O(e.length>0,(()=>`${t} is unexpectedly an empty array.`)),e.forEach(((e,n)=>Zm(e,`element ${n+1} of ${t}`)))):O(Number.isInteger(e)&&e>0,(()=>`Expected ${t} to be a positive integer, but got ${Jm(e)}.`))}function Jm(e){return null===e?"null":Array.isArray(e)?"["+e.map((e=>Jm(e))).join(",")+"]":"string"==typeof e?`"${e}"`:`${e}`}function Qm(e){return"relu"===e?"relu":"linear"===e?"linear":"elu"===e?"elu":null} +/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */ +let eg=0;function tg(){return eg++}const ng={};function sg(e=""){return e in ng||(ng[e]=0),ng[e]+=1,e+ng[e].toString()} +/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */ +const rg=["channelsFirst","channelsLast"],ag=["nearest","bilinear"],ig=["valid","same","causal"],og=["max","avg"],lg=["sum","mul","concat","ave"],ug=new Map;function cg(e){Xm(rg,"DataFormat",e)}function hg(e){Xm(ig,"PaddingMode",e)}function pg(e){Xm(og,"PoolMode",e)}const dg=[];function fg(e,t){dg.push(e);try{const e=t();return dg.pop(),e}catch(e){throw dg.pop(),e}}function mg(e){if(!bg(e))throw new Error("Not a valid tensor name: '"+e+"'");return(0===dg.length?"":dg.join("/")+"/")+e}function gg(e){if(!bg(e))throw new Error("Not a valid tensor name: '"+e+"'");ug.has(e)||ug.set(e,0);const t=ug.get(e);if(ug.set(e,ug.get(e)+1),t>0){const n=`${e}_${t}`;return ug.set(n,1),n}return e}const yg=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function bg(e){return!!e.match(yg)} +/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */ +function xg(e){return e===parseInt(e.toString(),10)}function wg(e,t,n){null==t&&(t=0),null==n&&(n=e.length);let s=1;for(let r=t;rt&&(t=s)}return t}function Ig(e,t){if(t{switch(e.rank){case 1:return $c(e,t,n);case 2:return Ec(e,[t,0],[n,e.shape[1]]);case 3:return Rc(e,[t,0,0],[n,e.shape[1],e.shape[2]]);case 4:return Ac(e,[t,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3]]);case 5:return Bo(e,[t,0,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3],e.shape[4]]);case 6:return Bo(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 Am(`sliceAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}}))}function Eg(e,t,n){return Zi((()=>{switch(e.rank){case 1:return $c(e,t,n);case 2:return Ec(e,[0,t],[e.shape[0],n]);case 3:return Rc(e,[0,0,t],[e.shape[0],e.shape[1],n]);case 4:return Ac(e,[0,0,0,t],[e.shape[0],e.shape[1],e.shape[2],n]);default:throw new Am(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}}))}function Rg(e,t,n,s){return Zi((()=>{switch(e.rank){case 1:return $c(e,t,n);case 2:switch(s){case 1:return $g(e,t,n);case 2:return Eg(e,t,n);default:throw new Am(`The axis is not within the rank of the tensor ${s}`)}case 3:switch(s){case 1:return $g(e,t,n);case 2:return Rc(e,[0,t,0],[e.shape[0],n,e.shape[2]]);case 3:return Eg(e,t,n);default:throw new Am(`The axis is not within the rank of the tensor ${s}`)}case 4:switch(s){case 1:return $g(e,t,n);case 2:return Ac(e,[0,t,0,0],[e.shape[0],n,e.shape[2],e.shape[3]]);case 3:return Ac(e,[0,0,t,0],[e.shape[0],e.shape[1],n,e.shape[3]]);case 4:return Eg(e,t,n);default:throw new Am(`The axis is not within the rank of the tensor ${s}`)}default:throw new Am(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}}))}function Ag(e,t=-1){let n;return t<0&&(n=e[0].rank,t=0!==n?n:0),t===e[0].rank&&(t=-1),Mo(e,t)}function Fg(e,t){switch(e.rank){case 1:return el([e,t]);case 2:return tl([e,t],0);case 3:return nl([e,t],0);case 4:return sl([e,t],0);default:throw new Am(`concatAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}}function _g(e,t){if(Array.isArray(t)||(t=[t]),e.rank!==t.length)throw new Am(`The length of input n (${t.length}) does not match the number of dimensions in input x (${e.rank})`);return Yl(e,t)}function Dg(e,t=0,n=1,s,r){return oc(e,t,n,s,r)}function Og(e,t,n,s){if(e.rank<2||t.rank<2)throw new Fm(`dot requires both inputs to be rank >= 2 but got x shape = ${e.shape} and y shape = ${t.shape}`);if(t.rank>=3){if(e.shape.slice(-1)[0]!==t.shape.slice(-2)[0])throw new Fm(`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 Th({a:e,b:t,transposeA:!1,transposeB:!1,bias:s?zg(e.rank,s,"channelsLast"):null,activation:n})}{const r=e.shape.slice(),a=r.pop();e=_o(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=_o(ah(t,c),[l,-1]);const h=[...r,...u];return _o(Th({a:e,b:t,transposeA:!1,transposeB:!1,bias:s?zg(e.rank,s,"channelsLast"):null,activation:n}),h)}}function Mg(e,t,n){return Zi((()=>(t=Array.isArray(t)?Gc(t,"int32"):Za(t,"int32"),Ql(e,t,n))))}function Lg(e){return zo(e,e)}function zg(e,t,n){const s=t.shape;if(1!==t.rank&&t.rank!==e)throw new Am(`Unexpected bias dimensions: ${t.rank}; expected it to be 1 or ${e}`);if(5===e){if("channelsFirst"===n)return 1===s.length?_o(t,[1,s[0],1,1,1]):_o(t,[1,s[3],s[0],s[1],s[2]]);if("channelsLast"===n)return 1===s.length?_o(t,[1,1,1,1,s[0]]):_o(t,[1].concat(s))}else if(4===e){if("channelsFirst"===n)return 1===s.length?_o(t,[1,s[0],1,1]):_o(t,[1,s[2],s[0],s[1]]);if("channelsLast"===n)return 1===s.length?_o(t,[1,1,1,s[0]]):_o(t,[1].concat(s))}else if(3===e){if("channelsFirst"===n)return 1===s.length?_o(t,[1,s[0],1]):_o(t,[1,s[1],s[0]]);if("channelsLast"===n)return 1===s.length?_o(t,[1,1,s[0]]):_o(t,[1].concat(s))}else if(e<3)return t;throw new Am(`Unsupported input rank by biasAdd: ${t.rank}`)}function Pg(e,t,n){return Zi((()=>(null==n&&(n="channelsLast"),cg(n),oo(e,zg(e.rank,t,n)))))}function Bg(e,t,n,s){return Zi((()=>dh(e,t,n,s)))}function Wg(e,t,n=!1){return n?e():t()} +/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */ +const Vg=["fanIn","fanOut","fanAvg"],Ug=["normal","uniform","truncatedNormal"];class Gg extends ji{fromConfigUsesCustomObjects(){return!1}getConfig(){return{}}}class Hg extends Gg{apply(e,t){return Au(e,t)}}Hg.className="Zeros",Ki(Hg);class jg extends Gg{apply(e,t){return Fu(e,t)}}jg.className="Ones",Ki(jg);class qg extends Gg{constructor(e){if(super(),"object"!=typeof e)throw new Am(`Expected argument of type ConstantConfig but got ${e}`);if(void 0===e.value)throw new Am(`config must have value set but got ${e}`);this.value=e.value}apply(e,t){return Zi((()=>zo(no(this.value),Fu(e,t))))}getConfig(){return{value:this.value}}}qg.className="Constant",Ki(qg);class Kg extends Gg{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 uc(e,this.minval,this.maxval,t)}getConfig(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}}}Kg.className="RandomUniform",Ki(Kg);class Xg extends Gg{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 Fm(`randomNormal does not support dType ${t}.`);return Dg(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}}Xg.className="RandomNormal",Ki(Xg);class Yg extends Gg{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 Fm(`truncatedNormal does not support dType ${t}.`);return Yc(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}}Yg.className="TruncatedNormal",Ki(Yg);class Zg extends Gg{constructor(e){super(),this.gain=null!=e.gain?e.gain:1}apply(e,t){return Zi((()=>{if(2!==e.length||e[0]!==e[1])throw new Am("Identity matrix initializer can only be used for 2D square matrices.");return zo(this.gain,Zl(e[0]))}))}getConfig(){return{gain:this.gain}}}Zg.className="Identity",Ki(Zg);class Jg extends Gg{constructor(e){if(super(),e.scale<0)throw new Am(`scale must be a positive float. Got: ${e.scale}`); +/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */ +var t;this.scale=null==e.scale?1:e.scale,this.mode=null==e.mode?"fanIn":e.mode,t=this.mode,Xm(Vg,"FanMode",t),this.distribution=null==e.distribution?"normal":e.distribution,function(e){Xm(Ug,"Distribution",e)}(this.distribution),this.seed=e.seed}apply(e,t){const n=function(e,t="channelsLast"){let n,s;if(cg(t),2===e.length)n=e[0],s=e[1];else if(-1!==[3,4,5].indexOf(e.length)){if("channelsFirst"===t){const t=wg(e,2);n=e[1]*t,s=e[0]*t}else if("channelsLast"===t){const t=wg(e,0,e.length-2);n=e[e.length-2]*t,s=e[e.length-1]*t}}else{const t=wg(e);n=Math.sqrt(t),s=Math.sqrt(t)}return[n,s]}(e),s=n[0],r=n[1];let a=this.scale;if("fanIn"===this.mode?a/=Math.max(1,s):"fanOut"===this.mode?a/=Math.max(1,r):a/=Math.max(1,(s+r)/2),"normal"===this.distribution){const n=Math.sqrt(a);if("float32"!==(t=t||"float32")&&"int32"!==t)throw new Fm(`${this.getClassName()} does not support dType ${t}.`);return Yc(e,0,n,t,this.seed)}{const n=Math.sqrt(3*a);return uc(e,-n,n,t)}}getConfig(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}}}Jg.className="VarianceScaling",Ki(Jg);class Qg extends Jg{constructor(e){super({scale:1,mode:"fanAvg",distribution:"uniform",seed:null==e?null:e.seed})}getClassName(){return Jg.className}}Qg.className="GlorotUniform",Ki(Qg);class ey extends Jg{constructor(e){super({scale:1,mode:"fanAvg",distribution:"normal",seed:null==e?null:e.seed})}getClassName(){return Jg.className}}ey.className="GlorotNormal",Ki(ey);class ty extends Jg{constructor(e){super({scale:2,mode:"fanIn",distribution:"normal",seed:null==e?null:e.seed})}getClassName(){return Jg.className}}ty.className="HeNormal",Ki(ty);class ny extends Jg{constructor(e){super({scale:2,mode:"fanIn",distribution:"uniform",seed:null==e?null:e.seed})}getClassName(){return Jg.className}}ny.className="HeUniform",Ki(ny);class sy extends Jg{constructor(e){super({scale:1,mode:"fanIn",distribution:"normal",seed:null==e?null:e.seed})}getClassName(){return Jg.className}}sy.className="LeCunNormal",Ki(sy);class ry extends Jg{constructor(e){super({scale:1,mode:"fanIn",distribution:"uniform",seed:null==e?null:e.seed})}getClassName(){return Jg.className}}ry.className="LeCunNormal",Ki(ry);class ay extends Gg{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 Fm("Random seed is not implemented for Orthogonal Initializer yet.")}apply(e,t){return Zi((()=>{if(e.length<2)throw new Fm("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=Dg(e[0]>e[1]?[e[1],e[0]]:e,0,1,"float32");let n=Sp.gramSchmidt(t);return e[0]>e[1]&&(n=ah(n)),zo(this.gain,n)}))}getConfig(){return{gain:this.gain,seed:this.seed}}}ay.className="Orthogonal",Ki(ay);const iy={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 oy(e,t={}){return Hm(e,qi.getMap().classNameMap,t,"initializer")}function ly(e){return Um(e)}function uy(e){if("string"==typeof e){const t=e in iy?iy[e]:e;if("GlorotNormal"===t)return new ey;if("GlorotUniform"===t)return new Qg;if("HeNormal"===t)return new ty;if("HeUniform"===t)return new ny;if("LeCunNormal"===t)return new sy;if("LeCunUniform"===t)return new ry;{const e={};return e.className=t,e.config={},oy(e)}}return e instanceof Gg?e:oy(e)} +/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */ +function cy(e){return Array.isArray(e)&&Array.isArray(e[0])}function hy(e){return 0===e.length?[]:Array.isArray(e[0])?e:[e]}function py(e){let t;if(Array.isArray(e)){if(1!==e.length)throw new Am(`Expected Tensor length to be 1; got ${e.length}`);t=e[0]}else t=e;return t}function dy(e){if(Array.isArray(e)&&Array.isArray(e[0])){if(1===e.length)return e[0];throw new Am(`Expected exactly 1 Shape; got ${e.length}`)}return e} +/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */ +function fy(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} +/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */ +const my="Variable";class gy{constructor(e,t="float32",n=my,s=!0,r=null){this.dtype=null==t?"float32":t,this.shape=e.shape,this.id=tg(),n=null==n?my:n,this.originalName=mg(n),this.name=gg(this.originalName),this.trainable_=s,this.constraint=r,this.val=th(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 yy(e){return e.map((e=>e.read()))}function by(e){e.forEach((e=>{e[0].write(e[1])}))} +/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */ +class xy{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 wy{constructor(e,t,n,s,r,a,i){this.dtype=e,this.shape=t,this.sourceLayer=n,this.inputs=s,this.callArgs=r,this.outputTensorIndex=i,this.id=tg(),null!=a&&(this.originalName=mg(a),this.name=gg(this.originalName)),this.rank=t.length}}let vy=0;class ky{constructor(e,t){this.callArgs=t,this.id=vy++,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 Iy=0;class Ny extends ji{constructor(e={}){super(),this._callHook=null,this._addedWeightNames=[],this._stateful=!1,this.id=Iy++,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=Bm(e)+"_"+sg(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 Rm(`The layer has never been called and thus has no defined ${t}.`);if(this.inboundNodes.length<=e)throw new Am(`Asked to get ${t} at node ${e}, but the layer has only ${this.inboundNodes.length} inbound nodes.`);return this.inboundNodes[e]}getInputAt(e){return zm(this.getNodeAtIndex(e,"input").inputTensors)}getOutputAt(e){return zm(this.getNodeAtIndex(e,"output").outputTensors)}get input(){if(this.inboundNodes.length>1)throw new Em(`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 Em(`Layer ${this.name} is not connected, no input to return.`);return zm(this.getNodeAtIndex(0,"input").inputTensors)}get output(){if(0===this.inboundNodes.length)throw new Em(`Layer ${this.name} has no inbound nodes.`);if(this.inboundNodes.length>1)throw new Em(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use \`getOutputAt(nodeIndex)\` instead.`);return zm(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=Pm(e),null==this.inputSpec||0===this.inputSpec.length)return;const t=Pm(this.inputSpec);if(e.length!==t.length)throw new Am(`Layer ${this.name} expects ${t.length} inputs, but it received ${e.length} input tensors. Input received: ${e}`);for(let n=0;nr.maxNDim)throw new Am(`Input ${n} is incompatible with layer ${this.name}: expected max_ndim=${r.maxNDim}, found ndim=${a}`);if(null!=r.minNDim&&a=0?e[s]:e[e.length+s];if(null!=a&&-1===[a,null].indexOf(i))throw new Am(`Input ${n} is incompatible with layer ${this.name}: expected axis ${s} of input shape to have value ${a} but got shape ${e}.`)}}if(null!=r.shape)for(let e=0;e{if(!this.built){this.assertInputCompatibility(e);const t=[];for(const n of Pm(e))t.push(n.shape);this.build(zm(t)),this.built=!0,this.initialWeights&&this.setWeights(this.initialWeights),null===this._refCount&&r&&(this._refCount=1)}if(this.assertInputCompatibility(e),r){let s=this.call(e,t);const r=Pm(s),a=[];for(let e of r)-1!==n.indexOf(e)&&(e=e.clone()),a.push(e);if(s=zm(a),null!=this.activityRegularizer)throw new Fm("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return s}{const n=function(e){e=Pm(e);const t=[];for(const n of e)t.push(n.shape);return zm(t)}(e),s=this.computeOutputShape(n);let r;const a="float32";if(this.warnOnIncompatibleInputShape(Array.isArray(e)?n[0]:n),r=null!=s&&s.length>0&&Array.isArray(s[0])?s.map(((n,s)=>new wy(a,n,this,Pm(e),t,this.name,s))):new wy(a,s,this,Pm(e),t,this.name),this.addInboundNode(e,r,null,null,n,s,t),this._refCount++,null!=this.activityRegularizer)throw new Fm("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return r}}))}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,s)=>{null!=n&&null!=e[s]&&e[s]!==n&&(t=!0)})),t&&console.warn(`The shape of the input tensor (${JSON.stringify(e)}) does not match the expectation of layer ${this.name}: ${JSON.stringify(this.batchInputShape)}`)}}get outputShape(){if(null==this.inboundNodes||0===this.inboundNodes.length)throw new Em(`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 Em(`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 Rm(`You tried to call countParams() on ${this.name}, but the layer is not built yet. Build it first by calling build(batchInputShape).`);return fy(this.weights)}build(e){this.built=!0}getWeights(e=!1){return yy(e?this.trainableWeights:this.weights)}setWeights(e){Zi((()=>{const t=this.weights;if(t.length!==e.length)throw new Am(`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=[],s=yy(t);for(let r=0;rr.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=Pm(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,s,r,a,i=null){const o=Pm(e);t=Pm(t),n=Pm(n),s=Pm(s),r=hy(r),a=hy(a);const l=[],u=[],c=[];for(const e of o)l.push(e.sourceLayer),u.push(e.nodeIndex),c.push(e.tensorIndex);new ky({outboundLayer:this,inboundLayers:l,nodeIndices:u,tensorIndices:c,inputTensors:o,outputTensors:t,inputMasks:n,outputMasks:s,inputShapes:r,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 Sy(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;ne.name)),l=[],u=t.names();for(const e of o)-1!==u.indexOf(e)?l.push(t.getValue(e)):l.push(null);null!=s&&(s.maxNumTensors=-1/0,s.minNumTensors=1/0);const c=o.join(",")+"|"+t.names().sort().join(",");let h,p=$y.get(c);if(null==p){const e=function(e,t){O(null!=e&&e.length>0,(()=>"Expected at least one fetch, got none"));let n=[],s={};if(1===e.length){const r=Fy(e[0],t);n=r.sorted,s=r.recipientMap}else{const r=new Set;for(const a of e){const{sorted:e,recipientMap:i}=Fy(a,t);for(const t of e)r.has(t.name)||(n.push(t),r.add(t.name));for(const e in i)null==s[e]&&(s[e]=new Set),i[e].forEach((t=>s[e].add(t)))}}return{sorted:n,recipientCounts:Ay(s)}}(i,t);p=e.sorted,h=e.recipientCounts,$y.put(c,p),Ey.put(c,h)}h={},r||Object.assign(h,Ey.get(c));const d=new Cy(t);for(let e=0;es.maxNumTensors&&(s.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(),s.push(e),n.add(e.name),t&&i.pop();else{i.push(a.length-1);for(const t of e.inputs)null==r[t.name]&&(r[t.name]=new Set),r[t.name].add(e.name),n.has(t.name)||a.push(t)}}return{sorted:s,recipientMap:r}}function _y(e){let t;if(1===e.sourceLayer.inboundNodes.length)t=e.sourceLayer.output;else{let n=null;for(let t=0;tWl(Ul(zo(e,e),t,!0))))}ye().registerFlag("TOPOLOGICAL_SORT_CACHE_MAX_ENTRIES",(()=>100),(function(e){null!=$y&&$y.setMaxEntries(e),null!=Ey&&Ey.setMaxEntries(e)}));class Oy extends ji{getConfig(){return{}}}class My extends Oy{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 Zi((()=>{const t=Dy(e,this.axis),n=Qo(t,0,this.maxValue);return zo(e,vl(n,oo(Sg(),t)))}))}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}}My.className="MaxNorm",Ki(My);class Ly extends Oy{constructor(e){super(),this.defaultAxis=0,this.axis=null!=e.axis?e.axis:this.defaultAxis}apply(e){return Zi((()=>vl(e,oo(Sg(),Dy(e,this.axis)))))}getConfig(){return{axis:this.axis}}}Ly.className="UnitNorm",Ki(Ly);class zy extends Oy{apply(e){return dc(e)}}zy.className="NonNeg",Ki(zy);class Py extends Oy{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 Zi((()=>{const t=Dy(e,this.axis),n=oo(zo(this.rate,Qo(t,this.minValue,this.maxValue)),zo(1-this.rate,t));return zo(e,vl(n,oo(Sg(),t)))}))}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}}Py.className="MinMaxNorm",Ki(Py);const By={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function Wy(e){return Um(e)}function Vy(e,t={}){return Hm(e,qi.getMap().classNameMap,t,"constraint")}function Uy(e){if(null==e)return null;if("string"==typeof e){return Vy({className:e in By?By[e]:e,config:{}})}return e instanceof Oy?e:Vy(e)} +/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */ +async function Gy(e){if(null==e)return;const t=[],n=[],s=[];for(const r in e){const a=e[r];if("number"!=typeof a){const e=a;t.push(e.data()),n.push(r),s.push(e)}}if(t.length>0){const r=await Promise.all(t);for(let t=0;too(this.totals[e],zo(s,n))));this.totals[e]=r,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:Zi((()=>{const n=zo(vl(1,this.seen),this.totals[e]);t[e]=n,this.totals[e].dispose(),Qi(t[e])})))}}class Yy extends qy{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 s in this.history){const r=this.history[s];for(let a=0;a{const i=null!=n?n():tr();return i-rnew Zy(e,t)))}class Qy{constructor(){}static registerCallbackConstructor(e,t){O(e>=0&&Number.isInteger(e),(()=>`Verbosity level is expected to be an integer >= 0, but got ${e}`)),Qy.checkForDuplicate(t),null==Qy.constructors[e]&&(Qy.constructors[e]=[]),Qy.constructors[e].push(t)}static checkForDuplicate(e){for(const t in Qy.constructors){Qy.constructors[+t].forEach((t=>{if(t===e)throw new Am("Duplicate callback constructor.")}))}}static clear(){Qy.constructors={}}static createCallbacks(e){const t=[];for(const n in Qy.constructors){const s=+n;e>=s&&t.push(...Qy.constructors[s])}return t.map((e=>new e))}}function eb(e,t,n,s,r,a,i,o,l){const u=new Yy,c=[new Xy,...Qy.createCallbacks(t)];null!=e&&c.push(...e),c.push(u);const h=new Ky(c);return h.setParams({epochs:n,initialEpoch:s,samples:r,steps:a,batchSize:i,verbose:t,doValidation:o,metrics:l}),{callbackList:h,history:u}} +/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */ +function tb(e,t={},n=!1){return Hm(e,qi.getMap().classNameMap,t,"layer",n)} +/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */ +function nb(e,t){return Zi((()=>{"float32"!==e.dtype&&(e=Za(e,"float32"));const n=Ul(Lg(e),t,!0),s=Jo(n.shape,Sg()),r=Wl(Eu(n,s));return vl(e,r)}))}function sb(e,t){return Zi((()=>Ru(Lg(gu(t,e)),-1)))}function rb(e,t){return Zi((()=>Ru(ro(gu(t,e)),-1)))}function ab(e,t){return Zi((()=>{const n=gu(e,t),s=Qo(ro(e),Sg(),Number.MAX_VALUE),r=ro(vl(n,s));return zo(100,Ru(r,-1))}))}function ib(e,t){return Zi((()=>{const n=Qo(t,Sg(),Number.MAX_VALUE),s=hu(oo(1,n)),r=Qo(e,Sg(),Number.MAX_VALUE),a=hu(oo(1,r));return Ru(Lg(gu(s,a)),-1)}))}function ob(e,t,n=!1){return Zi((()=>{if(n)t=Fc(t);else{const e=Ul(t,t.shape.length-1,!0);t=vl(t,e)}return t=Qo(t,Sg(),1-Sg()),du(Ul(zo(Za(e,"float32"),hu(t)),t.shape.length-1))}))}function lb(e,t,n=!1){return Zi((()=>{const s=Za(Jl(function(e){const t=[wg(e.shape)];return _o(e,t)}(e)),"int32"),r=(t=Qo(t,Sg(),1-Sg())).shape;return ob(_o(Wu(s,r[r.length-1]),r),t,n)}))}function ub(e,t){return Zi((()=>{let n;return n=Qo(t,Sg(),1-Sg()),n=hu(vl(n,gu(1,n))),Ru(function(e,t){if(!B(e.shape,t.shape))throw new Am(`logits and labels must have the same shape, but got shapes ${JSON.stringify(e.shape)} and ${JSON.stringify(t.shape)}`);return Zi((()=>{const n=dc(t),s=du(ro(t));return oo(gu(n,zo(t,e)),pu(ql(s)))}))}(e,n),-1)}))}function cb(e,t){return Zi((()=>{const n=Qo(e,Sg(),1),s=Qo(t,Sg(),1);return Ul(zo(e,hu(vl(n,s))),-1)}))}function hb(e,t){return Zi((()=>{const n=nb(e,-1),s=nb(t,-1),r=zo(n,s);return du(Ul(r,-1))}))}Qy.constructors={};const pb={meanSquaredError:sb,meanAbsoluteError:rb,meanAbsolutePercentageError:ab,meanSquaredLogarithmicError:ib,squaredHinge:function(e,t){return Zi((()=>{const n=Eu(0,gu(1,zo(e,t)));return Ru(Lg(n),-1)}))},hinge:function(e,t){return Zi((()=>{const n=Eu(0,gu(1,zo(e,t)));return Ru(n,-1)}))},categoricalHinge:function(e,t){return Zi((()=>{const n=Ul(zo(e,t),-1),s=zl(zo(gu(1,e),t),-1);return Eu(0,oo(1,gu(s,n)))}))},logcosh:function(e,t){return Zi((()=>{const n=Math.log(2),s=gu(t,e),r=gu(oo(s,fu(zo(-2,s))),n);return Ru(r,-1)}))},categoricalCrossentropy:ob,sparseCategoricalCrossentropy:lb,binaryCrossentropy:ub,kullbackLeiblerDivergence:cb,poisson:function(e,t){return Zi((()=>{const n=hu(oo(Sg(),t));return Ru(gu(t,zo(e,n)),-1)}))},cosineProximity:hb};function db(e){if("string"==typeof e){if(e in pb)return pb[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 Am(t)}return e} +/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */ +function fb(e,t){return Zi((()=>{const n=zo(.5,Vu(t)),s=Tg(eu(t,n),e.dtype);return Ru(kl(e,s),-1)}))}function mb(e,t){return Zi((()=>Tg(kl(ho(e,-1),ho(t,-1)),"float32")))}function gb(e,t){return Zi((()=>Za(Ul(xu(kl(e,1),kl(t,1))),"float32")))}function yb(e,t){return ub(e,t)}function bb(e,t){return e.rank===t.rank&&(e=Pc(e,[e.rank-1])),(t=ho(t,-1)).dtype!==e.dtype&&(t=Za(t,e.dtype)),Za(kl(e,t),"float32")}const xb=ob,wb=lb,vb={binaryAccuracy:fb,categoricalAccuracy:mb,precision:function(e,t){return Zi((()=>{const n=gb(e,t),s=function(e,t){return Zi((()=>Za(Ul(xu(kl(e,0),kl(t,1))),"float32")))}(e,t),r=oo(n,s);return Za(Il(eu(r,0),vl(n,r),0),"float32")}))},categoricalCrossentropy:xb,sparseCategoricalCrossentropy:wb,mse:sb,MSE:sb,mae:rb,MAE:rb,mape:ab,MAPE:ab,cosine:hb};function kb(e){if("string"==typeof e&&e in vb)return vb[e];if("string"!=typeof e&&null!=e)return e;throw new Am(`Unknown metric ${e}`)}function Ib(e){if(Mm(null!==e,`Unknown LossOrMetricFn ${e}`),"string"==typeof e)return e;{let t;for(const n of Object.keys(pb))if(pb[n]===e){t=n;break}if(void 0!==t)return t;for(const n of Object.keys(vb))if(vb[n]===e){t=n;break}return void 0!==t?t:e.name}} +/** + * @license + * Copyright 2019 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */ +const Nb=1048576;function Sb(e,t,n=!1){if(null==e||"object"!=typeof e||Object.getPrototypeOf(e)!==Object.prototype||!Tb(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>Nb&&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 Tb(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(!Tb(e[n]))return!1}return!0}if(Array.isArray(e)){for(const t of e)if(!Tb(t))return!1;return!0}return!1}{const t=typeof e;return"string"===t||"number"===t||"boolean"===t}} +/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */ +function Cb(e,t,n,s=console.log){const r=function(e){let t=!0;const n=[],s=[];for(const t in e.nodesByDepth)n.push(e.nodesByDepth[t]);for(const e of n){if(e.length>1||1===e.length&&e[0].inboundLayers.length>1){t=!1;break}s.push(...e)}if(t)for(const n of e.layers){let e=!1;for(const r of n.inboundNodes)if(-1!==s.indexOf(r)){if(e){t=!1;break}e=!0}if(!t)break}return t}(e),a=["Layer (type)","Input Shape","Output shape","Param #"];let i;if(r?(t=t||90,n=n||[.32,.61,.89,1]):(t=t||115,n=n||[.24,.48,.7,.8,1]),n[n.length-1]<=1&&(n=n.map((e=>Math.floor(t*e)))),!r){a.push("Receives inputs"),i=[];for(const t in e.nodesByDepth)i.push(...e.nodesByDepth[t])}s("_".repeat(t)),$b(a,n,s),s("=".repeat(t));const o=e.layers;for(let e=0;e0&&(s=s.slice(0,s.length-1)+" "),s+=e[n],s=s.slice(0,t[n]),s+=" ".repeat(t[n]-s.length);n(s)}function Eb(e,t,n){let s,r;try{r=e.inboundNodes.map((e=>JSON.stringify(e.inputShapes))).join(",")}catch(e){r="multiple"}try{s=JSON.stringify(e.outputShape)}catch(e){s="multiple"}$b([`${e.name} (${e.getClassName()})`,r,s,e.countParams().toString()],t,n)}function Rb(e,t,n,s){let r,a;try{a=e.inboundNodes.map((e=>JSON.stringify(e.inputShapes))).join(",")}catch(e){a="multiple"}try{r=JSON.stringify(e.outputShape)}catch(e){r="multiple"}const i=[];for(const t of e.inboundNodes)if(!(null!=n&&n.length>0&&-1===n.indexOf(t)))for(let e=0;ee.name))}`);qm(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,s=e.tensorIndex;this.outputLayers.push(t),this.outputLayersNodeIndices.push(n),this.outputLayersTensorIndices.push(s)}for(const e of this.inputs){const t=e.sourceLayer,n=e.nodeIndex,s=e.tensorIndex;Mm(0===n,"input layer has >1 nodes"),Mm(0===s,"input layer has >1 tensors"),this.inputLayers.push(t),this.inputLayersNodeIndices.push(n),this.inputLayersTensorIndices.push(s)}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={},s={},r={},a={},i=[],o=(e,t,n,s,r,l)=>{null!=s&&null!=r&&null!=l||(s=e.sourceLayer,r=e.nodeIndex,l=e.tensorIndex);const u=s.inboundNodes[r];if(-1!==n.indexOf(u))throw new Rm(`The tensor ${e.name} at layer "${s.name}" is part of a cycle.`);if(-1!==t.indexOf(u))return;this.containerNodes.add(Ob.nodeKey(s,r)),s.id in a||(a[s.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==s[e.outboundLayer.id]?0:s[e.outboundLayer.id];a=Math.max(a,i),s[e.outboundLayer.id]=a,r[e.outboundLayer.id]=e.outboundLayer,t[e.id]=a;for(let s=0;sparseInt(e,10))).sort(jm);this.layers=[];for(const e of d){const t=p[e];t.sort(((e,t)=>{const n=a[e.id],s=a[t.id];return ns?1:0}));for(const e of t)e instanceof Ob&&this.internalContainerRefs.push(e),this.layers.push(e)}this.layersByDepth=p,d=Object.keys(h).map((e=>parseInt(e,10))).sort(jm);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 Rm(`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 Rm(`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 ky({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 Am("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 s=0;for(const e of this.layers)for(const t of e.weights){if(null!=n[t.originalName])throw new Am(`Duplicate weight name: ${t.originalName}`);n[t.originalName]=t,s++}const r=[];for(const s in e){let a=s;if(null==n[s]){const e=s.split("/");a=e.slice(0,-2).concat([e[e.length-1]]).join("/")}if(null!=n[a])r.push([n[a],e[s]]);else if(t)throw new Am(`Provided weight data has no target variable: ${s}`);delete n[a]}if(t){const e=[];for(const t in n)e.push(t);if(e.length>0)throw new Am(`${e.length} of ${s} weights are not set: ${e}`)}by(r)}updatedConfig(){const e=this.getConfig(),t={};return t.className=this.getClassName(),t.config=e,t.kerasVersion=`tfjs-layers ${Db}`,t.backend="TensorFlow.js",t}toJSON(e,t=!0){const n=_b(this.updatedConfig());return t?JSON.stringify(n):n}call(e,t){return Zi((()=>{e=Pm(e);const n=new Cy;for(let t=0;t{let n;return e=Pm(e),n=null==t?Om(null,e.length):Pm(t),this.runInternalGraph(e,n)[1]}))}computeOutputShape(e){const t=hy(e);if(t.length!==this.inputLayers.length)throw new Am(`Invalid inputShape argument ${e}: model has ${this.inputLayers.length} tensor inputs.`);const n={};for(let e=0;eparseInt(e,10))).sort(jm);if(s.length>1)for(const e of s){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 s=[];for(let t=0;tparseInt(e,10))).sort(jm);for(const e of s){const t=this.nodesByDepth[e];for(const e of t){const t=e.outboundLayer,s=e.inputTensors,r=e.outputTensors,a=new Array;for(const e of s)e.id in n&&a.push(n[e.id]);if(a.length===s.length){let s,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=Pm(t.call(e,u)),l=Pm(t.computeMask(e,n)),s=[e],i=[n]}else s=a.map((e=>e[0])),i=a.map((e=>e[1])),null==u.mask&&(u.mask=i),o=Pm(t.call(s,u)),l=Pm(t.computeMask(s,i));if(t.activityRegularizer)throw new Fm("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(zm(n),s)}function l(e){const n=e.name,a=tb(e,null!=t.customObjects?t.customObjects:{});a.setFastWeightInitDuringBuild(s),r[n]=a;e.inboundNodes.forEach((e=>{if(!(e instanceof Array))throw new Am(`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(;!Km(a);)for(const e of c){const t=r[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],s=e[2];Mm(t in r);const a=r[t].inboundNodes[n].outputTensors;h.push(a[s])}const f=t.outputLayers;for(const e of f){const t=e[0],n=e[1],s=e[2];Mm(t in r);const a=r[t].inboundNodes[n].outputTensors;p.push(a[s])}return new e({inputs:h,outputs:p,name:u})}get stateful(){if(this._stateful)throw new Am("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(){Zi((()=>{this.layers.forEach((e=>{e.stateful&&e.resetStates()}))}))}} +/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */ +function Mb(e,t,n){const s=t.length;if(null==e||Array.isArray(e)&&0===e.length)return t.map((e=>null));if(1===s)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!==s)throw new Error(`Provided ${n} is an array of ${e.length} element(s), but the model has ${s} outputs. Make sure a set of weights is provided for each model output.`);return e}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 (${s}) outputs, so ${n} must be either an array with ${s} elements or an object with ${t} keys. Provided ${n} not understood: ${JSON.stringify(e)}`)}function Lb(e,t){return Mb(e,t,"classWeight")}async function zb(e,t,n,s){if(null!=t||null!=s)throw new Error("Support sampleWeight is not implemented yet");if(null!=n){const t=Zi((()=>{if(1===e.shape.length)return Ja(e);if(2===e.shape.length){if(e.shape[1]>1){return ho(e,1)}if(1===e.shape[1])return _o(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.`)})),s=Array.from(await t.data());Ji(t);const r=[];return s.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`);r.push(n[e])})),Gc(r,"float32")}return null}function Pb(e,t){return zo(e,t)}function Bb(e,t){let n,s;const r=t;n=r.xs,s=r.ys,O(null!=n&&null!=s,(()=>`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=Wb("input",e.inputNames,n),i=Wb("output",e.outputNames,s),o=a[0].shape[0];O(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)})`)),O(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 Wb(e,t,n){if(n instanceof gr)return[n];if(Array.isArray(n))return O(n.length===t.length,(()=>`Received an array of ${n.length} Tensors, but expected ${t.length} to match the ${e} keys ${t}.`)),n;{const s=[];for(const r of t){if(null==n[r])throw new Am(`The feature data generated by the dataset lacks the required ${e} key '${r}'.`);s.push(n[r])}return s}}async function Vb(e,t,n){const s=null!=n.batchesPerEpoch;if(O(null!=e.optimizer,(()=>"You must compile a model before training/testing. Use LayersModel.compile(modelCompileConfig).")),O(null!=n,(()=>"For fitDataset(), the 2nd argument (config) is required, but it is not provided in this call.")),O(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}`)),O(!s||n.batchesPerEpoch>0&&Number.isInteger(n.batchesPerEpoch),(()=>`For fitDataset(), config.batchesPerEpoch is expected to be a positive integer if specified, but got ${n.batchesPerEpoch}`)),O(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 r=null!=n.validationData;let a,i;if(r)if(Ub(n.validationData))O(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 Fm("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=r?l.slice().concat(l.map((e=>"val_"+e))):l.slice();const c=Jy(n.callbacks,n.yieldEvery),h=null==n.verbose?1:n.verbose,{callbackList:p,history:d}=eb(c,h,n.epochs,null,null,function(e,t){let n=null;null!=t.batchesPerEpoch?n=t.batchesPerEpoch:Number.isFinite(e.size)&&(n=e.size);return n}(t,n),null,r,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(r){let t;t=Ub(n.validationData)?Pm(await e.evaluateDataset(n.validationData,{batches:n.validationBatches})):Pm(e.evaluate(a,i,{batchSize:null==n.validationBatchSize?32:n.validationBatchSize,verbose:0}));for(let n=0;n0&&Number.isInteger(e),(()=>`batchSize is required to be a positive integer, but got ${e}`))}function Hb(e,t,n){return null==e?[null]:Array.isArray(e)?e.map((e=>$g(e,t,n-t))):$g(e,t,n-t)}function jb(e,t){return Zi((()=>null==e?null:Array.isArray(e)?e.map((e=>jb(e,t))):Mg(e,"int32"===t.dtype?t:Za(t,"int32"))))}function qb(e,t){const n=[];let s=0,r=null;for(;s=e&&(r=e),n.push([s,r]),s=r;return n}async function Kb(e,t,n,s={}){if(e.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");let r,a,i,o,l,u,c,h,p;e.isTraining=!0;try{const d=null==s.batchSize?32:s.batchSize;Gb(d);const f=!1,m=await e.standardizeUserData(t,n,s.sampleWeight,s.classWeight,f,d);r=m[0],a=m[1],p=m[2];let g,y=!1;if(null!=s.validationData&&s.validationData.length>0){if(y=!0,2!==s.validationData.length)throw 3===s.validationData.length?new Fm("validationData including sample weights is not supported yet."):new Am(`When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; ${s.validationData} is invalid.`);l=s.validationData[0],u=s.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!=s.validationSplit&&s.validationSplit>0&&s.validationSplit<1){y=!0;const e=Math.floor(r[0].shape[0]*(1-s.validationSplit)),t=r[0].shape[0];c=Hb(r,e,t),i=r,r=Hb(r,0,e),h=Hb(a,e,t),o=a,a=Hb(a,0,e),g=c.concat(h)}else null!=s.validationSteps&&(y=!0);const b=r.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=Jy(s.callbacks,s.yieldEvery),N=await async function(e,t,n,s,r,a,i,o,l,u,c,h,p,d,f){null==r&&(r=32),null==a&&(a=1),null==c&&(c=!0),null==p&&(p=0);let m=!1;if(null!=l&&null!=u&&(m=!0),null!=f&&(m=!0,null==d))throw new Am("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");const g=e.checkNumSamples(n,r,d,"steps_per_epoch");let y;null!=g&&(y=Ig(0,g)),null==i&&(i=1);const{callbackList:b,history:x}=eb(o,i,a,p,g,d,r,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=$g(i,p,d-p);h.batch=c,h.size=d-p;const g=jb(n,f),y=t(g);for(let e=0;en.push(e.id)));else if(null!=t)for(const e in t){const s=t[e];n.push(s.id)}const s=[];if(e instanceof gr)-1===n.indexOf(e.id)&&s.push(e);else if(Array.isArray(e))e.forEach((e=>{-1===n.indexOf(e.id)&&s.push(e)}));else if(null!=e)for(const t in e){const r=e[t];-1===n.indexOf(r.id)&&s.push(r)}s.forEach((e=>{e.isDisposed||e.dispose()}))}function Zb(e){return Array.isArray(e)}function Jb(e){return! +/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */ +function(e){return e instanceof gr}(e)&&!Zb(e)}function Qb(e,t,n,s=!0,r=""){if(null==t||0===t.length){if(null!=e){let t=!1;if(Zb(e)&&e.length>0)t=!0;else if(Jb(e)){for(const n in e)if(e.hasOwnProperty(n)){t=!0;break}}else t=!0;if(t)throw new Am(`Error when checking model ${r} expected no data, but got ${e}`)}return[]}if(null==e)return t.map((e=>null));let a;if(Jb(e)){a=[];for(const n of t){if(null==e[n])throw new Am(`No data provided for "${n}". Need data for each key in: ${t}`);a.push(e[n])}}else if(Zb(e)){if(e.length!==t.length)throw new Am(`Error when checking model ${r}: the Array of Tensors that you are passing to your model is not the size the model expected. Expected to see ${t.length} Tensor(s), but instead got the following list of Tensor(s): ${e}`);a=e}else{if(t.length>1)throw new Am(`The model ${r} expects ${t.length} Tensor(s), but only received one Tensor. Found: Tensor with shape ${e.shape}`);a=[e]}if(a=Xb(a),null!=n)for(let e=0;e=0&&a!==o)throw new Am(`${r} 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 ${r} 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 ex(e,t,n,s=!0,r=""){let a;if(Array.isArray(e)){if(e.length!==t.length)throw new Am(`Error when checking model ${r}: 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 Am(`The model expects ${t.length} ${r} Tensors, but only received one Tensor. Found: array with shape ${JSON.stringify(e.shape)}.`);a=[e]}if(null!=n)for(let e=0;eLp.adagrad(.01),Adadelta:()=>Lp.adadelta(1,.95,Sg()),Adam:()=>Lp.adam(.001,.9,.999,Sg()),Adamax:()=>Lp.adamax(.002,.9,.999,Sg(),0),RMSProp:()=>Lp.rmsprop(.001,.9,0,Sg()),SGD:()=>Lp.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 Am(`Unknown Optimizer ${e}`)}(e.optimizer),this.isOptimizerOwned=!0;else{if(!(e.optimizer instanceof so))throw new Am("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 Am(`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=>db(e)))}else{const n=db(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 Am(`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(db(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 s=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 s of t){let t=n.hasOwnProperty(s)?n[s]:[];Array.isArray(t)||(t=[t]),e.push(t)}return e}}(e.metrics,this.outputNames),r=(e,t,n)=>{this.outputNames.length>1&&(t=this.outputNames[e]+"_"+t),this.metricsNames.push(t),this.metricsTensors.push([n,e])};fg("metric",(()=>{for(let e=0;e{let n,s,a;for(const i of t){if("string"==typeof i&&-1!==["accuracy","acc","crossentropy","ce"].indexOf(i)){const t=this.internalOutputShapes[e];let r;1===t[t.length-1]||this.lossFunctions[e]===ub?-1!==["accuracy","acc"].indexOf(i)?s=fb:-1!==["crossentropy","ce"].indexOf(i)&&(s=yb):this.lossFunctions[e]===lb?-1!==["accuracy","acc"].indexOf(i)?s=bb:-1!==["crossentropy","ce"].indexOf(i)&&(s=wb):-1!==["accuracy","acc"].indexOf(i)?s=mb:-1!==["crossentropy","ce"].indexOf(i)&&(s=xb),-1!==["accuracy","acc"].indexOf(i)?r="acc":-1!==["crossentropy","ce"].indexOf(i)&&(r="ce"),a=s,n=""+r}else{const e=kb(i);a=e,n=""+Ib(i)}let t;fg(n,(()=>{t=a})),r(e,n,t)}})(s[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 s=null==n.batchSize?32:n.batchSize;Gb(s);const r=this.standardizeUserDataXY(e,t,!0,s);try{const e=r[0].concat(r[1]);this.makeTestFunction();const t=this.testFunction;return zm(this.testLoop(t,e,s,n.verbose,n.steps))}finally{Yb(r[0],e),Yb(r[1],t)}}async evaluateDataset(e,t){return this.makeTestFunction(),async function(e,t,n){const s=null!=(n=n||{}).batches,r=e.testFunction;let a=[];if(n.verbose>0)throw new Fm("Verbose mode is not implemented yet.");O(!s||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(;!s||l{if(t.value){const{xs:n,ys:s}=Bb(e,t.value),i=n.concat(s),u=Zi((()=>r(i)));if(Ji(i),0===l)for(let e=0;eoo(a[e],zo(c,t)))),l>0&&Ji(n)}Ji(u),o+=c,++l}return a})),t.done){s&&console.warn(`Your dataset iterator ran out of data during evaluateDataset(). Interrupting evalution. Make sure that your dataset can generate at least \`batches\` batches (in this case, ${n.batches} batches). You may need to use the repeat() function when building your dataset.`);break}}for(let e=0;ee.name));for(let s=0;s0){const n=[];throw t.forEach(((t,s)=>{null==t&&n.push(e[s])})),new Am(`Cannot find SymbolicTensors for output name(s): ${JSON.stringify(n)}`)}return t}predictLoop(e,t=32,n=!1){return Zi((()=>{const s=this.checkNumSamples(e);if(n)throw new Fm("Verbose predictLoop() is not implemented yet.");const r=qb(s,t),a=this.outputs.map((e=>[]));for(let t=0;t{const n=r[t][0],s=r[t][1],a=Hb(e,n,s),i=[];if(Array.isArray(a))for(let e=0;ea[t].push(e)))}return zm(a.map((e=>Mo(e,0))))}))}predict(e,t={}){const n=Xb(e);ex(n,this.inputNames,this.feedInputShapes,!1);try{const e=null==t.batchSize?32:t.batchSize;return Gb(e),this.predictLoop(n,e)}finally{Yb(n,e)}}predictOnBatch(e){ex(e,this.inputNames,this.feedInputShapes,!0);const t=(Array.isArray(e)?e[0]:e).shape[0];return this.predictLoop(e,t)}standardizeUserDataXY(e,t,n=!0,s){if(null==this.optimizer_)throw new Rm("You must compile a model before training/testing. Use LayersModel.compile(modelCompileArgs).");const r=[];for(let e=0;ee.shape[0])));n.sort();const s=qm(t.map((e=>e.shape[0])));if(s.sort(),n.length>1)throw new Am(`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 Am(`All target Tensors (y) should have the same number of samples. Got array shapes: ${JSON.stringify(t.map((e=>e.shape)))}`);if(n.length>0&&s.length>0&&!B(n,s))throw new Am(`Input Tensors should have the same number of samples as target Tensors. Found ${n[0]} input sample(s) and ${s[0]} target sample(s).`)}(e=Qb(e,this.feedInputNames,this.feedInputShapes,!1,"input"),t=Qb(t,this.feedOutputNames,r,!1,"target")),function(e,t,n){const s=[sb,ub,ob];for(let r=0;r0&&e[0].shape[0]%s!=0)throw new Am(`In a stateful network, you should only pass inputs with a number of samples that is divisible by the batch size ${s}. Found: ${e[0].shape[0]} sample(s).`);return[e,t]}async standardizeUserData(e,t,n,s,r=!0,a){const[i,o]=this.standardizeUserDataXY(e,t,r,a);if(null!=n)throw new Error("sample weight is not supported yet.");let l=null;if(null!=s){const e=Lb(s,this.outputNames);l=[];for(let t=0;t{const a=this.checkNumSamples(t,n,r,"steps"),i=[];if(s>0)throw new Fm("Verbose mode is not implemented yet.");if(null!=r)throw new Fm("steps mode in testLoop() is not implemented yet");{const s=qb(a,n),r=Gc(Ig(0,a));for(let n=0;n1){r+=`_${Lm(e.slice(0,n),s)}`}t.push(r)}return t}makeTrainFunction(){return e=>{const t=[],n=e.slice(0,this.inputs.length),s=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),r=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=oo(l,e)})),l}),!0,i)].concat(a)}}makeTestFunction(){this.testFunction=e=>Zi((()=>{const t=[];let n;const s=e.slice(0,this.inputs.length),r=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),a=[];for(let e=0;eBm(e)))}else{const t=Object.keys(this.loss);e={};const n=this.loss;for(const s of t){if("string"!=typeof n[s])throw new Error("Serialization of non-string loss is not supported.");e[s]=Bm(n[s])}}return e}getMetricIdentifiers(){if("string"==typeof this.metrics||"function"==typeof this.metrics)return[Bm(Ib(this.metrics))];if(Array.isArray(this.metrics))return this.metrics.map((e=>Bm(Ib(e))));{const e={};for(const t in this.metrics)e[t]=Bm(Ib(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=tb(Fb(e.optimizer_config));let n,s;if("string"==typeof e.loss)n=Wm(e.loss);else if(Array.isArray(e.loss))n=e.loss.map((e=>Wm(e)));else if(null!=e.loss){n={};for(const t in e.loss)n[t]=Wm(e.loss[t])}if(Array.isArray(e.metrics))s=e.metrics.map((e=>Wm(e)));else if(null!=e.metrics){s={};for(const t in e.metrics)s[t]=Wm(e.metrics[t])}this.compile({loss:n,metrics:s,optimizer:t})}async save(e,t){if("string"==typeof e){const t=ma(e);if(0===t.length)throw new Am(`Cannot find any save handlers for URL '${e}'`);if(t.length>1)throw new Am(`Found more than one (${t.length}) save handlers for URL '${e}'`);e=t[0]}if(null==e.save)throw new Am("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");const n=await Qr(this.getNamedWeights(t)),s={modelTopology:this.toJSON(null,!1),format:"layers-model",generatedBy:`TensorFlow.js tfjs-layers v${Db}`,convertedBy:null};if(null!=t&&t.includeOptimizer&&null!=this.optimizer){s.trainingConfig=this.getTrainingConfig();const e="optimizer",{data:t,specs:r}=await Qr(await this.optimizer.getWeights(),e);n.specs.push(...r),n.data=ra([n.data,t])}if(null!=this.userDefinedMetadata){const e=!0;Sb(this.userDefinedMetadata,this.name,e),s.userDefinedMetadata=this.userDefinedMetadata}return s.weightData=n.data,s.weightSpecs=n.specs,e.save(s)}setUserDefinedMetadata(e){Sb(e,this.name),this.userDefinedMetadata=e}getUserDefinedMetadata(){return this.userDefinedMetadata}}tx.className="Model",Ki(tx);class nx extends tx{}nx.className="Functional",Ki(nx);class sx extends tx{constructor(e){if(super({inputs:[],outputs:[]}),e=e||{},this.trainable=!0,this.built=!1,this.name=null!=e.name?e.name:sg("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 Am(`Negative dimension size caused by adding layer ${e.name} with input shape [${e.inboundNodes[0].inputTensors[0].shape}]`)}add(e){const t=e instanceof sx||e instanceof tx;let n;if(t){if(n=e,1!==n.outputs.length)throw new Am("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 Am("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 Am("The first layer in a Sequential model must get an `inputShape` or `batchInputShape` argument.");const t=function(e){if(null==e.batchShape&&null==e.shape)throw new Error("Please provide to Input either a `shape` or a `batchShape` argument. Note that `shape` does not include the batch dimension.");if(null!=e.batchShape&&null!=e.shape)throw new Am("Please provide either a `shape` or `batchShape` argument to Input, but not both.");let t=e.batchShape;null!=e.shape&&null==t&&(t=[null].concat(e.shape));let n=e.dtype;return null==n&&(n="float32"),new Ty({batchInputShape:t,name:e.name,dtype:n,sparse:e.sparse}).inboundNodes[0].outputTensors[0]}({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 Am(`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 Am("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=Sy(this.outputs[0])}this.inboundNodes=[],new ky({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:Om(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(dy(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 Rm("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 Rm("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 Rm("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 Rm("The model needs to be compiled before being used.");return this.model.fitDataset(e,t)}async trainOnBatch(e,t){return this.model.trainOnBatch(e,t)}static fromConfig(e,t,n={},s=!1){let r,a={};if(t instanceof Array){if(null==t[0].className||"Merge"===t[0].className)throw new Am("Legacy serialization format not supported yet.");r=t}else O(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.")),r=t.layers,delete t.layers,a=t;const i=new e(a);if(!(i instanceof sx))throw new Fm(`Sequential.fromConfig called on non-Sequential input: ${i}`);for(const e of r){const t=tb(e,void 0,s);s&&t.setFastWeightInitDuringBuild(!0),i.add(t)}return i}set stopTraining(e){if(null==this.model)throw new Am("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 Am("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}}}sx.className="Sequential",Ki(sx); +/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */ +class rx extends ji{getConfig(){return{}}}class ax extends rx{apply(e,t=1){return function(e,t=1){if(1!==t)throw new Fm(`Support for alpha values other than 1 (${t}) is not implemented yet.`);return $l(e)}(e,t)}}ax.className="elu",Ki(ax);class ix extends rx{apply(e){return kc(e)}}ix.className="selu",Ki(ix);class ox extends rx{apply(e){return dc(e)}}ox.className="relu",Ki(ox);class lx extends rx{apply(e){return Zi((()=>Du(6,dc(e))))}}lx.className="relu6",Ki(lx);class ux extends rx{apply(e){return e}}ux.className="linear",Ki(ux);class cx extends rx{apply(e){return Po(e)}}cx.className="sigmoid",Ki(cx);class hx extends rx{apply(e){return function(e){return Zi((()=>{const t=oo(.5,zo(.2,e));return Qo(t,0,1)}))}(e)}}hx.className="hardSigmoid",Ki(hx);class px extends rx{apply(e){return fu(e)}}px.className="softplus",Ki(px);class dx extends rx{apply(e){return function(e){return Zi((()=>vl(e,oo(ro(e),1))))}(e)}}dx.className="softsign",Ki(dx);class fx extends rx{apply(e){return Wo(e)}}fx.className="tanh",Ki(fx);class mx extends rx{apply(e,t=-1){return Fc(e,t)}}mx.className="softmax",Ki(mx);class gx extends rx{apply(e,t=-1){return yu(e,t)}}gx.className="logSoftmax",Ki(gx);class yx extends rx{apply(e,t=1){return Zi((()=>zo(Po(zo(e,t)),e)))}}yx.className="swish",Ki(yx);class bx extends rx{apply(e){return Zi((()=>zo(e,Wo(fu(e)))))}}function xx(e){return e.getClassName()}function wx(e,t={}){return Hm(e,qi.getMap().classNameMap,t,"activation")}function vx(e){if(null==e){const e={className:"linear",config:{}};return wx(e)}if("string"==typeof e){const t={};return t.className=e,t.config={},wx(t)}return e instanceof rx?e:wx(e)} +/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */ +function kx(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}`)}bx.className="mish",Ki(bx);class Ix extends ji{}class Nx extends Ix{constructor(e){super(),kx(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 Zi((()=>{let t=Au([1]);return this.hasL1&&(t=oo(t,Ul(zo(this.l1,ro(e))))),this.hasL2&&(t=oo(t,Ul(zo(this.l2,Lg(e))))),_o(t,[])}))}getConfig(){return{l1:this.l1,l2:this.l2}}static fromConfig(e,t){return new e({l1:t.l1,l2:t.l2})}}Nx.className="L1L2",Ki(Nx);const Sx={l1l2:"L1L2"};function Tx(e){return Um(e)}function Cx(e,t={}){return Hm(e,qi.getMap().classNameMap,t,"regularizer")}function $x(e){if(null==e)return null;if("string"==typeof e){return Cx({className:e in Sx?Sx[e]:e,config:{}})}return e instanceof Ix?e:Cx(e)} +/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */ +class Ex extends Ny{constructor(e){super(null==e?{}:e),this.supportsMasking=!0,null!=e&&(this.maxValue=e.maxValue)}call(e,t){e=py(e);let n=dc(e);return null!=this.maxValue&&(n=Qo(n,0,this.maxValue)),n}computeOutputShape(e){return e}getConfig(){const e={maxValue:this.maxValue},t=super.getConfig();return Object.assign(e,t),e}}Ex.className="ReLU",Ki(Ex);class Rx extends Ny{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=py(e);return iu(n,this.alpha)}computeOutputShape(e){return e}getConfig(){const e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}}Rx.className="LeakyReLU",Ki(Rx);class Ax extends Ny{constructor(e){if(super(null==e?{}:e),this.DEFAULT_ALPHA_INITIALIZER="zeros",null==e&&(e={}),this.supportsMasking=!0,this.alphaInitializer=uy(e.alphaInitializer||this.DEFAULT_ALPHA_INITIALIZER),this.alphaRegularizer=$x(e.alphaRegularizer),this.alphaConstraint=Uy(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 Am(`Expected sharedAxes to be a number or an array of numbers, but got ${e.sharedAxes}`);this.sharedAxes=[e.sharedAxes]}}build(e){const t=(e=dy(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(cg(t),"channelsFirst"===t?ah(e,[0,2,3,1]):e)))}function Px(e,t){return Zi((()=>(cg(t),"channelsFirst"===t?ah(e,[0,2,3,4,1]):e)))}function Bx(e,t,n,s=1,r="valid",a,i=1){return Zi((()=>{if(null==a&&(a="channelsLast"),cg(a),3!==e.shape.length)throw new Am(`The input of a conv1dWithBias operation should be 3, but is ${e.shape.length} instead.`);if(3!==t.shape.length)throw new Am(`The kernel for a conv1dWithBias operation should be 3, but is ${t.shape.length} instead`);if(null!=n&&1!==n.shape.length)throw new Am(`The bias for a conv1dWithBias operation should be 1, but is ${t.shape.length} instead`);if("channelsFirst"===a&&(e=ah(e,[0,2,1])),"causal"===r)throw new Fm("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");let o=al(e,t,s,"same"===r?"same":"valid","NWC",i);return null!=n&&(o=Pg(o,n)),o}))}function Wx(e,t,n,s=[1,1],r="valid",a,i,o=null){return Zi((()=>{if(null==a&&(a="channelsLast"),cg(a),3!==e.rank&&4!==e.rank)throw new Am(`conv2dWithBiasActivation expects input to be of rank 3 or 4, but received ${e.rank}.`);if(3!==t.rank&&4!==t.rank)throw new Am(`conv2dWithBiasActivation expects kernel to be of rank 3 or 4, but received ${e.rank}.`);let l=zx(e,a);if("causal"===r)throw new Fm("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");return l=kh({x:l,filter:t,strides:s,pad:"same"===r?"same":"valid",dilations:i,dataFormat:"NHWC",bias:n,activation:o}),"channelsFirst"===a&&(l=ah(l,[0,3,1,2])),l}))}function Vx(e,t,n,s=[1,1,1],r="valid",a,i){return Zi((()=>{if(null==a&&(a="channelsLast"),cg(a),4!==e.rank&&5!==e.rank)throw new Am(`conv3dWithBias expects input to be of rank 4 or 5, but received ${e.rank}.`);if(4!==t.rank&&5!==t.rank)throw new Am(`conv3dWithBias expects kernel to be of rank 4 or 5, but received ${e.rank}.`);let o=Px(e,a);if("causal"===r)throw new Fm("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");return o=ll(o,t,s,"same"===r?"same":"valid","NDHWC",i),null!=n&&(o=Pg(o,n)),"channelsFirst"===a&&(o=ah(o,[0,4,1,2,3])),o}))}Dx.className="Softmax",Ki(Dx);class Ux extends Ny{constructor(e,t){if(super(t),this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",Ux.verifyArgs(t),this.rank=e,Zm(this.rank,"rank"),1!==this.rank&&2!==this.rank&&3!==this.rank)throw new Fm(`Convolution layer for rank other than 1, 2, or 3 (${this.rank}) is not implemented yet.`);if(this.kernelSize=Ox(t.kernelSize,e,"kernelSize"),this.strides=Ox(null==t.strides?1:t.strides,e,"strides"),this.padding=null==t.padding?"valid":t.padding,hg(this.padding),this.dataFormat=null==t.dataFormat?"channelsLast":t.dataFormat,cg(this.dataFormat),this.activation=vx(t.activation),this.useBias=null==t.useBias||t.useBias,this.biasInitializer=uy(t.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.biasConstraint=Uy(t.biasConstraint),this.biasRegularizer=$x(t.biasRegularizer),this.activityRegularizer=$x(t.activityRegularizer),this.dilationRate=Ox(null==t.dilationRate?1:t.dilationRate,e,"dilationRate"),1===this.rank&&Array.isArray(this.dilationRate)&&1!==this.dilationRate.length)throw new Am(`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 Am(`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 Am(`dilationRate must be a number or array of three numbers for 3D convolution, but received ${JSON.stringify(this.dilationRate)}`)}static verifyArgs(e){if(Mm("kernelSize"in e,"required key 'kernelSize' not in config"),"number"!=typeof e.kernelSize&&!Ym(e.kernelSize,"number",1,3))throw new Am(`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:xx(this.activation),useBias:this.useBias,biasInitializer:ly(this.biasInitializer),biasRegularizer:Tx(this.biasRegularizer),activityRegularizer:Tx(this.activityRegularizer),biasConstraint:Wy(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}}class Gx extends Ux{constructor(e,t){super(e,t),this.kernel=null,Gx.verifyArgs(t),this.filters=t.filters,Zm(this.filters,"filters"),this.kernelInitializer=uy(t.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.kernelConstraint=Uy(t.kernelConstraint),this.kernelRegularizer=$x(t.kernelRegularizer)}build(e){e=dy(e);const t="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[t])throw new Am(`The channel dimension of the input should be defined. Found ${e[t]}`);const n=e[t],s=this.kernelSize.concat([n,this.filters]);this.kernel=this.addWeight("kernel",s,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[{ndim:this.rank+2,axes:{[t]:n}}],this.built=!0}call(e,t){return Zi((()=>{let t;e=py(e);const n=null==this.bias?null:this.bias.read(),s=Qm(this.activation.getClassName());if(null!=s&&2===this.rank)t=Wx(e,this.kernel.read(),n,this.strides,this.padding,this.dataFormat,this.dilationRate,s);else{if(1===this.rank)t=Bx(e,this.kernel.read(),n,this.strides[0],this.padding,this.dataFormat,this.dilationRate[0]);else if(2===this.rank)t=Wx(e,this.kernel.read(),n,this.strides,this.padding,this.dataFormat,this.dilationRate);else{if(3!==this.rank)throw new Fm("convolutions greater than 3D are not implemented yet.");t=Vx(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=dy(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 Hx extends Gx{constructor(e){super(2,e),Hx.verifyArgs(e)}getConfig(){const e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if("number"!=typeof e.kernelSize&&!Ym(e.kernelSize,"number",1,2))throw new Am(`Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received ${JSON.stringify(e.kernelSize)}.`)}}Hx.className="Conv2D",Ki(Hx);class jx extends Gx{constructor(e){super(3,e),jx.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 Am(`Conv3D expects config.kernelSize to be number or [number, number, number], but received ${JSON.stringify(e.kernelSize)}.`)}}jx.className="Conv3D",Ki(jx);class qx extends Hx{constructor(e){if(super(e),this.inputSpec=[new xy({ndim:4})],"same"!==this.padding&&"valid"!==this.padding)throw new Am(`Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(4!==(e=dy(e)).length)throw new Am("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 Am("The channel dimension of the inputs should be defined. Found `None`.");const n=e[t],s=this.kernelSize.concat([this.filters,n]);this.kernel=this.addWeight("kernel",s,"float32",this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[new xy({ndim:4,axes:{[t]:n}})],this.built=!0}call(e,t){return Zi((()=>{let t=py(e);if(4!==t.shape.length)throw new Am(`Conv2DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${t.shape.length}`);const n=t.shape,s=n[0];let r,a;"channelsFirst"===this.dataFormat?(r=2,a=3):(r=1,a=2);const i=n[r],o=n[a],l=this.kernelSize[0],u=this.kernelSize[1],c=this.strides[0],h=this.strides[1],p=[s,Lx(i,c,l,this.padding),Lx(o,h,u,this.padding),this.filters];"channelsLast"!==this.dataFormat&&(t=ah(t,[0,2,3,1]));let d=ol(t,this.kernel.read(),p,this.strides,this.padding);return"channelsLast"!==this.dataFormat&&(d=ah(d,[0,3,1,2])),null!=this.bias&&(d=Pg(d,this.bias.read(),this.dataFormat)),null!=this.activation&&(d=this.activation.apply(d)),d}))}computeOutputShape(e){const t=(e=dy(e)).slice();let n,s,r;"channelsFirst"===this.dataFormat?(n=1,s=2,r=3):(n=3,s=1,r=2);const a=this.kernelSize[0],i=this.kernelSize[1],o=this.strides[0],l=this.strides[1];return t[n]=this.filters,t[s]=Lx(t[s],o,a,this.padding),t[r]=Lx(t[r],l,i,this.padding),t}getConfig(){const e=super.getConfig();return delete e.dilationRate,e}}qx.className="Conv2DTranspose",Ki(qx);class Kx extends jx{constructor(e){if(super(e),this.inputSpec=[new xy({ndim:5})],"same"!==this.padding&&"valid"!==this.padding)throw new Am(`Conv3DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(5!==(e=dy(e)).length)throw new Am("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 Am("The channel dimension of the inputs should be defined. Found `None`.");const n=e[t],s=this.kernelSize.concat([this.filters,n]);this.kernel=this.addWeight("kernel",s,"float32",this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[new xy({ndim:5,axes:{[t]:n}})],this.built=!0}call(e,t){return Zi((()=>{let t=py(e);if(5!==t.shape.length)throw new Am(`Conv3DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${t.shape.length}`);const n=t.shape,s=n[0];let r,a,i;"channelsFirst"===this.dataFormat?(i=2,r=3,a=4):(i=1,r=2,a=3);const o=n[i],l=n[r],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=[s,Lx(o,d,c,this.padding),Lx(l,f,h,this.padding),Lx(u,m,p,this.padding),this.filters];"channelsLast"!==this.dataFormat&&(t=ah(t,[0,2,3,4,1]));let y=cl(t,this.kernel.read(),g,this.strides,this.padding);return"channelsLast"!==this.dataFormat&&(y=ah(y,[0,4,1,2,3])),null!==this.bias&&(y=Pg(y,this.bias.read(),this.dataFormat)),null!==this.activation&&(y=this.activation.apply(y)),y}))}computeOutputShape(e){const t=(e=dy(e)).slice();let n,s,r,a;"channelsFirst"===this.dataFormat?(n=1,s=2,r=3,a=4):(n=4,s=1,r=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[s]=Lx(t[s],u,i,this.padding),t[r]=Lx(t[r],c,o,this.padding),t[a]=Lx(t[a],h,l,this.padding),t}getConfig(){const e=super.getConfig();return delete e.dilationRate,e}}Kx.className="Conv3DTranspose",Ki(Kx);class Xx extends Gx{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 Am("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(null!=t.kernelInitializer||null!=t.kernelRegularizer||null!=t.kernelConstraint)throw new Am("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 Am(`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=uy(t.depthwiseInitializer||this.DEFAULT_DEPTHWISE_INITIALIZER),this.depthwiseRegularizer=$x(t.depthwiseRegularizer),this.depthwiseConstraint=Uy(t.depthwiseConstraint),this.pointwiseInitializer=uy(t.depthwiseInitializer||this.DEFAULT_POINTWISE_INITIALIZER),this.pointwiseRegularizer=$x(t.pointwiseRegularizer),this.pointwiseConstraint=Uy(t.pointwiseConstraint)}build(e){if((e=dy(e)).length{let t;if(e=py(e),1===this.rank)throw new Fm("1D separable convolution is not implemented yet.");return 2===this.rank&&("channelsFirst"===this.dataFormat&&(e=ah(e,[0,2,3,1])),t=Ic(e,this.depthwiseKernel.read(),this.pointwiseKernel.read(),this.strides,this.padding,this.dilationRate,"NHWC")),this.useBias&&(t=Pg(t,this.bias.read(),this.dataFormat)),null!=this.activation&&(t=this.activation.apply(t)),"channelsFirst"===this.dataFormat&&(t=ah(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=ly(this.depthwiseInitializer),e.pointwiseInitializer=ly(this.pointwiseInitializer),e.depthwiseRegularizer=Tx(this.depthwiseRegularizer),e.pointwiseRegularizer=Tx(this.pointwiseRegularizer),e.depthwiseConstraint=Wy(this.depthwiseConstraint),e.pointwiseConstraint=Wy(this.pointwiseConstraint),e}}Xx.className="SeparableConv";class Yx extends Xx{constructor(e){super(2,e)}}Yx.className="SeparableConv2D",Ki(Yx);class Zx extends Gx{constructor(e){super(1,e),Zx.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&&!Ym(e.kernelSize,"number",1,1))throw new Am(`Conv1D expects config.kernelSize to be number or number[] with length 1, but received ${JSON.stringify(e.kernelSize)}.`)}}Zx.className="Conv1D",Ki(Zx);class Jx extends Ny{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 Zi((()=>{if(e=py(e),"channelsLast"===this.dataFormat){const t=Rg(e,this.cropping[0][0],e.shape[1]-this.cropping[0][0]-this.cropping[0][1],2);return Rg(t,this.cropping[1][0],e.shape[2]-this.cropping[1][1]-this.cropping[1][0],3)}{const t=Rg(e,this.cropping[0][0],e.shape[2]-this.cropping[0][0]-this.cropping[0][1],3);return Rg(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}}Jx.className="Cropping2D",Ki(Jx);class Qx extends Ny{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,cg(this.dataFormat),this.interpolation=null==e.interpolation?"nearest":e.interpolation,t=this.interpolation,Xm(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 Zi((()=>{let t=py(e);const n=t.shape;if("channelsFirst"===this.dataFormat){t=ah(t,[0,2,3,1]);const e=this.size[0]*n[2],s=this.size[1]*n[3],r="nearest"===this.interpolation?Np.resizeNearestNeighbor(t,[e,s]):Np.resizeBilinear(t,[e,s]);return ah(r,[0,3,1,2])}{const e=this.size[0]*n[1],s=this.size[1]*n[2];return"nearest"===this.interpolation?Np.resizeNearestNeighbor(t,[e,s]):Np.resizeBilinear(t,[e,s])}}))}getConfig(){const e={size:this.size,dataFormat:this.dataFormat,interpolation:this.interpolation},t=super.getConfig();return Object.assign(e,t),e}}Qx.className="UpSampling2D",Ki(Qx);class ew extends Ux{constructor(e){super(2,e),this.depthwiseKernel=null,this.depthMultiplier=null==e.depthMultiplier?1:e.depthMultiplier,this.depthwiseInitializer=uy(e.depthwiseInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.depthwiseConstraint=Uy(e.depthwiseConstraint),this.depthwiseRegularizer=$x(e.depthwiseRegularizer)}build(e){if((e=dy(e)).length<4)throw new Am(`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 Am(`The channel dimension of the inputs to DepthwiseConv2D should be defined, but is not (${e[t]}).`);const n=e[t],s=[this.kernelSize[0],this.kernelSize[1],n,this.depthMultiplier];this.depthwiseKernel=this.addWeight("depthwise_kernel",s,null,this.depthwiseInitializer,this.depthwiseRegularizer,!0,this.depthwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[n*this.depthMultiplier],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return Zi((()=>{let t= +/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */ +function(e,t,n=[1,1],s="valid",r,a){return Zi((()=>{null==r&&(r="channelsLast"),cg(r);let i=zx(e,r);if(4!==e.rank)throw new Am(`Input for depthwiseConv2d is required to be 4-D, but is instead ${e.rank}-D`);if(4!==t.rank)throw new Am(`depthwiseKernel is required to be 4-D, but is instead ${t.rank}-D`);return i=yl(i,t,n,"same"===s?"same":"valid","NHWC",a),"channelsFirst"===r&&(i=ah(i,[0,3,1,2])),i}))}(e=py(e),this.depthwiseKernel.read(),this.strides,this.padding,this.dataFormat,null);return this.useBias&&(t=Pg(t,this.bias.read(),this.dataFormat)),null!=this.activation&&(t=this.activation.apply(t)),t}))}computeOutputShape(e){e=dy(e);const t="channelsFirst"===this.dataFormat?e[2]:e[1],n="channelsFirst"===this.dataFormat?e[3]:e[2],s="channelsFirst"===this.dataFormat?e[1]*this.depthMultiplier:e[3]*this.depthMultiplier,r=Mx(t,this.kernelSize[0],this.padding,this.strides[0]),a=Mx(n,this.kernelSize[1],this.padding,this.strides[1]);return"channelsFirst"===this.dataFormat?[e[0],s,r,a]:[e[0],r,a,s]}getConfig(){const e=super.getConfig();return e.depthMultiplier=this.depthMultiplier,e.depthwiseInitializer=ly(this.depthwiseInitializer),e.depthwiseRegularizer=Tx(this.depthwiseRegularizer),e.depthwiseConstraint=Wy(this.depthwiseRegularizer),e}} +/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */ +function tw(e,t,n,s){if(Array.isArray(e)){if(null!=t||null!=n)throw new Am("When inputs is an array, neither initialState or constants should be provided");null!=s&&(n=e.slice(e.length-s,e.length),e=e.slice(0,e.length-s)),e.length>1&&(t=e.slice(1,e.length)),e=e[0]}function r(e){return null==e||Array.isArray(e)?e:[e]}return{inputs:e,initialState:t=r(t),constants:n=r(n)}}function nw(e,t,n,s=!1,r,a,i=!1,o=!1){return Zi((()=>{const l=t.shape.length;if(l<3)throw new Am(`Input should be at least 3D, but is ${l}D.`);const u=[1,0].concat(Ig(2,l));if(t=ah(t,u),null!=a)throw new Fm("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!=r&&((r=Za(Za(r,"bool"),"float32")).rank===l-1&&(r=Kl(r,-1)),r=ah(r,u)),s&&(t=mc(t,0),null!=r&&(r=mc(r,0)));const c=[];let h,p=n;const d=t.shape[0],f=Qc(t);let m,g;null!=r&&(m=Qc(r));for(let t=0;te(n,p)));if(null==r)h=s[0],p=s[1];else{const e=Zi((()=>{const e=m[t],n=gu(Vu(e),e);return{output:oo(zo(s[0],e),zo(p[0],n)),newStates:p.map(((t,r)=>oo(zo(s[1][r],e),zo(t,n))))}}));h=e.output,p=e.newStates}o&&c.push(h)}if(o){g=Bc(c,1)}return[h,g,p]}))}ew.className="DepthwiseConv2D",Ki(ew);class sw extends Ny{constructor(e){let t;if(super(e),null==e.cell)throw new Am("cell property is missing for the constructor of RNN.");if(t=Array.isArray(e.cell)?new hw({cells:e.cell}):e.cell,null==t.stateSize)throw new Am("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 xy({ndim:3})],this.stateSpec=null,this.states_=null,this.numConstants=null,this.keptStates=[]}getStates(){if(null==this.states_){return Ig(0,Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1).map((e=>null))}return this.states_}setStates(e){this.states_=e}computeOutputShape(e){cy(e)&&(e=e[0]);let t=this.cell.stateSize;Array.isArray(t)||(t=[t]);const n=t[0];let s;if(s=this.returnSequences?[e[0],e[1],n]:[e[0],n],this.returnState){const n=[];for(const s of t)n.push([e[0],s]);return[s].concat(n)}return s}computeMask(e,t){return Zi((()=>{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])),r))throw new Am(`An initialState was passed that is not compatible with cell.stateSize. Received stateSpec=${this.stateSpec}; However cell.stateSize is ${this.cell.stateSize}`)}else this.stateSpec=r.map((e=>new xy({shape:[null,e]})));this.stateful&&this.resetStates()}resetStates(e,t=!1){Zi((()=>{if(!this.stateful)throw new Em("Cannot call resetStates() on an RNN Layer that is not stateful.");const n=this.inputSpec[0].shape[0];if(null==n)throw new Am("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=>Au([n,e]))):this.states_=[Au([n,this.cell.stateSize])];else if(null==e)Ji(this.states_),null!=this.keptStates&&(Ji(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map((e=>Au([n,e]))):this.states_[0]=Au([n,this.cell.stateSize]);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new Am(`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()):Ji(this.states_);for(let t=0;tQi(e.clone())))}))}apply(e,t){let n=null==t?null:t.initialState,s=null==t?null:t.constants;null==t&&(t={});const r=tw(e,n,s,this.numConstants);e=r.inputs,n=r.initialState,s=r.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 xy({shape:e.shape}));i=i.concat(this.stateSpec)}null!=s&&(t.constants=s,a=a.concat(s),this.numConstants=s.length);if(a[0]instanceof wy){const n=[e].concat(a),s=this.inputSpec.concat(i),r=this.inputSpec;this.inputSpec=s;const o=super.apply(n,t);return this.inputSpec=r,o}return super.apply(e,t)}call(e,t){return Zi((()=>{const n=null==t?null:t.mask,s=null==t?null:t.training;let r=null==t?null:t.initialState;e=py(e),null==r&&(r=this.stateful?this.states_:this.getInitialState(e));const a=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;if(r.length!==a)throw new Am(`RNN Layer has ${a} state(s) but was passed ${r.length} initial state(s).`);this.unroll&&console.warn("Ignoring unroll = true for RNN layer, due to imperative backend.");const i={training:s},o=nw(((e,t)=>{const n=this.cell.call([e].concat(t),i);return[n[0],n.slice(1)]}),e,r,this.goBackwards,n,null,this.unroll,this.returnSequences),l=o[0],u=o[1],c=o[2];this.stateful&&this.resetStates(c,s);const h=this.returnSequences?u:l;return this.returnState?[h].concat(c):h}))}getInitialState(e){return Zi((()=>{let t=Au(e.shape);return t=Ul(t,[1,2]),t=Cg(t),Array.isArray(this.cell.stateSize)?this.cell.stateSize.map((e=>e>1?_g(t,[1,e]):t)):this.cell.stateSize>1?[_g(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()===sw.className&&(t.cell={className:this.cell.getClassName(),config:n}),Object.assign({},n,e,t)}static fromConfig(e,t,n={}){const s=tb(t.cell,n);return new e(Object.assign(t,{cell:s}))}}sw.className="RNN",Ki(sw);class rw extends Ny{}class aw extends rw{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,Zm(this.units,"units"),this.activation=vx(null==e.activation?this.DEFAULT_ACTIVATION:e.activation),this.useBias=null==e.useBias||e.useBias,this.kernelInitializer=uy(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=uy(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=uy(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=$x(e.kernelRegularizer),this.recurrentRegularizer=$x(e.recurrentRegularizer),this.biasRegularizer=$x(e.biasRegularizer),this.kernelConstraint=Uy(e.kernelConstraint),this.recurrentConstraint=Uy(e.recurrentConstraint),this.biasConstraint=Uy(e.biasConstraint),this.dropout=vg([1,kg([0,null==e.dropout?0:e.dropout])]),this.recurrentDropout=vg([1,kg([0,null==e.recurrentDropout?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=dy(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 Zi((()=>{if(2!==e.length)throw new Am(`SimpleRNNCell expects 2 input Tensors, got ${e.length}.`);let n=e[1];e=e[0];const s=null!=t.training&&t.training;let r;0Vu(e),rate:this.dropout,training:s,dropoutFunc:this.dropoutFunc})),0Vu(n),rate:this.recurrentDropout,training:s,dropoutFunc:this.dropoutFunc}));const a=this.dropoutMask,i=this.recurrentDropoutMask;r=Og(null!=a?zo(e,a):e,this.kernel.read()),null!=this.bias&&(r=Pg(r,this.bias.read())),null!=i&&(n=zo(n,i));let o=oo(r,Og(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:xx(this.activation),useBias:this.useBias,kernelInitializer:ly(this.kernelInitializer),recurrentInitializer:ly(this.recurrentInitializer),biasInitializer:ly(this.biasInitializer),kernelRegularizer:Tx(this.kernelRegularizer),recurrentRegularizer:Tx(this.recurrentRegularizer),biasRegularizer:Tx(this.biasRegularizer),activityRegularizer:Tx(this.activityRegularizer),kernelConstraint:Wy(this.kernelConstraint),recurrentConstraint:Wy(this.recurrentConstraint),biasConstraint:Wy(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout};return Object.assign({},e,t)}}aw.className="SimpleRNNCell",Ki(aw);class iw extends sw{constructor(e){e.cell=new aw(e),super(e)}call(e,t){return Zi((()=>{null!=this.cell.dropoutMask&&(Ji(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(Ji(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const n=null==t?null:t.mask,s=null==t?null:t.training,r=null==t?null:t.initialState;return super.call(e,{mask:n,training:s,initialState:r})}))}static fromConfig(e,t){return new e(t)}}iw.className="SimpleRNN",Ki(iw);class ow extends rw{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 Am("GRUCell does not support reset_after parameter set to true.");this.units=e.units,Zm(this.units,"units"),this.activation=vx(void 0===e.activation?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=vx(void 0===e.recurrentActivation?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=null==e.useBias||e.useBias,this.kernelInitializer=uy(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=uy(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=uy(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=$x(e.kernelRegularizer),this.recurrentRegularizer=$x(e.recurrentRegularizer),this.biasRegularizer=$x(e.biasRegularizer),this.kernelConstraint=Uy(e.kernelConstraint),this.recurrentConstraint=Uy(e.recurrentConstraint),this.biasConstraint=Uy(e.biasConstraint),this.dropout=vg([1,kg([0,null==e.dropout?0:e.dropout])]),this.recurrentDropout=vg([1,kg([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=dy(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 Zi((()=>{if(2!==e.length)throw new Am(`GRUCell expects 2 input Tensors (inputs, h, c), got ${e.length}.`);const n=null!=t.training&&t.training;let s=e[1];e=e[0],0Vu(e),rate:this.dropout,training:n,count:3,dropoutFunc:this.dropoutFunc})),0Vu(s),rate:this.recurrentDropout,training:n,count:3,dropoutFunc:this.dropoutFunc}));const r=this.dropoutMask,a=this.recurrentDropoutMask;let i,o,l;0{null!=this.cell.dropoutMask&&(Ji(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(Ji(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const n=null==t?null:t.mask,s=null==t?null:t.training,r=null==t?null:t.initialState;return super.call(e,{mask:n,training:s,initialState:r})}))}static fromConfig(e,t){return 0===t.implmentation&&(t.implementation=1),new e(t)}}lw.className="GRU",Ki(lw);class uw extends rw{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,Zm(this.units,"units"),this.activation=vx(void 0===e.activation?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=vx(void 0===e.recurrentActivation?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=null==e.useBias||e.useBias,this.kernelInitializer=uy(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=uy(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=uy(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.unitForgetBias=e.unitForgetBias,this.kernelRegularizer=$x(e.kernelRegularizer),this.recurrentRegularizer=$x(e.recurrentRegularizer),this.biasRegularizer=$x(e.biasRegularizer),this.kernelConstraint=Uy(e.kernelConstraint),this.recurrentConstraint=Uy(e.recurrentConstraint),this.biasConstraint=Uy(e.biasConstraint),this.dropout=vg([1,kg([0,null==e.dropout?0:e.dropout])]),this.recurrentDropout=vg([1,kg([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=dy(e))[e.length-1];let s;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;s=new((t=class extends Gg{apply(t,s){const r=e.apply([n]),a=(new jg).apply([n]),i=e.apply([2*n]);return Fg(Fg(r,a),i)}}).className="CustomInit",t)}else s=this.biasInitializer;this.bias=this.addWeight("bias",[4*this.units],null,s,this.biasRegularizer,!0,this.biasConstraint)}else this.bias=null;this.built=!0}call(e,t){return Zi((()=>{const n=null!=t.training&&t.training;if(3!==e.length)throw new Am(`LSTMCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);let s=e[1];const r=e[2];e=e[0],0Vu(e),rate:this.dropout,training:n,count:4,dropoutFunc:this.dropoutFunc})),0Vu(s),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&&(Ji(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(Ji(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const n=null==t?null:t.mask,s=null==t?null:t.training,r=null==t?null:t.initialState;return super.call(e,{mask:n,training:s,initialState:r})}))}static fromConfig(e,t){return 0===t.implmentation&&(t.implementation=1),new e(t)}}cw.className="LSTM",Ki(cw);class hw extends rw{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 Zi((()=>{let n=e.slice(1);const s=[];for(const e of this.cells.slice().reverse())Array.isArray(e.stateSize)?s.push(n.splice(0,e.stateSize.length)):s.push(n.splice(0,1));s.reverse();const r=[];let a;for(let i=0;i{fg(`RNNCell_${s}`,(()=>{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 s=[];for(const e of t.cells)s.push(tb(e,n));return new e({cells:s})}get trainableWeights(){if(!this.trainable)return[];const e=[];for(const t of this.cells)e.push(...t.trainableWeights);return e}get nonTrainableWeights(){const e=[];for(const t of this.cells)e.push(...t.nonTrainableWeights);if(!this.trainable){const t=[];for(const 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 yy(e)}setWeights(e){const t=[];for(const n of this.cells){const s=n.weights.length,r=e.splice(s);for(let e=0;enull!=a?a(t(),n):Bg(t(),n),o=()=>Wg(i,t,s);if(!r||r<=1)return Qi(o().clone());return Array(r).fill(void 0).map(o).map((e=>Qi(e.clone())))}hw.className="StackedRNNCells",Ki(hw); +/** + * @license + * Copyright 2020 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */ +var dw=function(e,t){var n={};for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.indexOf(s)<0&&(n[s]=e[s]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(s=Object.getOwnPropertySymbols(e);r{if(null!=this.cell.dropoutMask&&(Ji(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(Ji(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null),t&&t.constants)throw new Am("ConvRNN2D cell does not support constants");const n=null==t?null:t.mask,s=null==t?null:t.training,r=null==t?null:t.initialState;return super.call(e,{mask:n,training:s,initialState:r})}))}computeOutputShape(e){let t=this.computeSingleOutputShape(e);return this.returnSequences||(t=[t[0],...t.slice(2)]),this.returnState&&(t=[t,...Array(2).fill([e[0],...t.slice(-3)])]),t}getInitialState(e){return Zi((()=>{const{stateSize:t}=this.cell,n=e.shape,s=this.computeSingleOutputShape(n),r=Au([s[0],...s.slice(2)]);return Array.isArray(t)?Array(t.length).fill(r):[r]}))}resetStates(e,t=!1){Zi((()=>{if(!this.stateful)throw new Em("Cannot call resetStates() on an RNN Layer that is not stateful.");const n=this.inputSpec[0].shape,s=this.computeSingleOutputShape(n),r=[s[0],...s.slice(2)];if(null==n[0])throw new Am("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((()=>Au(r))):this.states_=[Au(r)];else if(null==e)Ji(this.states_),null!=this.keptStates&&(Ji(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map((()=>Au(r))):this.states_[0]=Au(r);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new Am(`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()):Ji(this.states_);for(let t=0;tQi(e.clone())))}))}computeSingleOutputShape(e){const{dataFormat:t,filters:n,kernelSize:s,padding:r,strides:a,dilationRate:i}=this.cell,o="channelsFirst"===t,l=e[o?3:2],u=e[o?4:3],c=Mx(l,s[0],r,a[0],i[0]),h=Mx(u,s[1],r,a[1],i[1]);return[...e.slice(0,2),...o?[n,c,h]:[c,h,n]]}}fw.className="ConvRNN2D";class mw extends uw{constructor(e){const{filters:t,kernelSize:n,strides:s,padding:r,dataFormat:a,dilationRate:i}=e;super(Object.assign({},e,{units:t})),this.filters=t,Zm(this.filters,"filters"),this.kernelSize=Ox(n,2,"kernelSize"),this.kernelSize.forEach((e=>Zm(e,"kernelSize"))),this.strides=Ox(s||1,2,"strides"),this.strides.forEach((e=>Zm(e,"strides"))),this.padding=r||"valid",hg(this.padding),this.dataFormat=a||"channelsLast",cg(this.dataFormat),this.dilationRate=Ox(i||1,2,"dilationRate"),this.dilationRate.forEach((e=>Zm(e,"dilationRate")))}build(e){var t;e=dy(e);const n="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[n])throw new Am(`The channel dimension of the input should be defined. Found ${e[n]}`);const s=e[n],r=this.kernelSize.concat([s,4*this.filters]);this.kernel=this.addWeight("kernel",r,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,s=this.filters;e=new((t=class extends Gg{apply(e,t){return Ag([n.apply([s]),Fu([s]),n.apply([2*s])])}}).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 Zi((()=>{if(3!==e.length)throw new Am(`ConvLSTM2DCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);const n=t.training||!1,s=e[0],r=e[1],a=e[2];0Vu(s),rate:this.dropout,training:n,count:4,dropoutFunc:this.dropoutFunc}));const i=this.dropoutMask,o=(e,t,n)=>t&&t[n]?zo(t[n],e):e;let l=o(s,i,0),u=o(s,i,1),c=o(s,i,2),h=o(s,i,3);0Vu(r),rate:this.recurrentDropout,training:n,count:4,dropoutFunc:this.dropoutFunc}));const p=this.recurrentDropoutMask;let d=o(r,p,0),f=o(r,p,1),m=o(r,p,2),g=o(r,p,3);const[y,b,x,w]=Mc(this.kernel.read(),4,3),[v,k,I,N]=this.useBias?Mc(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,$]=Mc(this.recurrentKernel.read(),4,3);d=this.recurrentConv(d,S),f=this.recurrentConv(f,T),m=this.recurrentConv(m,C),g=this.recurrentConv(g,$);const E=this.recurrentActivation.apply(oo(l,d)),R=this.recurrentActivation.apply(oo(u,f)),A=oo(zo(R,a),zo(E,this.activation.apply(oo(c,m)))),F=zo(this.recurrentActivation.apply(oo(h,g)),this.activation.apply(A));return[F,F,A]}))}getConfig(){const e=super.getConfig(),{units:t}=e,n=dw(e,["units"]),s={filters:this.filters,kernelSize:this.kernelSize,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,strides:this.strides};return Object.assign({},n,s)}inputConv(e,t,n,s){const r=rl(e,t,this.strides,s||"valid","channelsFirst"===this.dataFormat?"NCHW":"NHWC",this.dilationRate);return n?Pg(r,n,this.dataFormat):r}recurrentConv(e,t){return rl(e,t,1,"same","channelsFirst"===this.dataFormat?"NCHW":"NHWC")}}mw.className="ConvLSTM2DCell",Ki(mw);class gw extends fw{constructor(e){const t=new mw(e);super(Object.assign({},e,{cell:t}))}static fromConfig(e,t){return new e(t)}}gw.className="ConvLSTM2D",Ki(gw); +/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */ +class yw extends Ny{constructor(e){super(e),this.rate=Math.max(Math.min(e.rate,1),0),this.noiseShape=e.noiseShape,this.seed=e.seed,this.supportsMasking=!0}getNoiseShape(e){if(null==this.noiseShape)return this.noiseShape;const t=e.shape,n=[];for(let e=0;e{this.invokeCallHook(e,t);const n=py(e);if(0Bg(n,this.rate,s,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()}}yw.className="Dropout",Ki(yw);class bw extends yw{constructor(e){super(e),this.inputSpec=[{ndim:3}]}getNoiseShape(e){const t=e.shape;return[t[0],1,t[2]]}}bw.className="SpatialDropout1D",Ki(bw);class xw extends Ny{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,Zm(this.units,"units"),this.activation=vx(e.activation),null!=e.useBias&&(this.useBias=e.useBias),this.kernelInitializer=uy(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.biasInitializer=uy(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelConstraint=Uy(e.kernelConstraint),this.biasConstraint=Uy(e.biasConstraint),this.kernelRegularizer=$x(e.kernelRegularizer),this.biasRegularizer=$x(e.biasRegularizer),this.activityRegularizer=$x(e.activityRegularizer),this.supportsMasking=!0,this.inputSpec=[{minNDim:2}]}build(e){const t=(e=dy(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=dy(e)).slice();return t[t.length-1]=this.units,t}call(e,t){return Zi((()=>{this.invokeCallHook(e,t);const n=py(e),s=Qm(this.activation.getClassName());let r;return null!=s?r=Og(n,this.kernel.read(),s,this.bias?this.bias.read():null):(r=Og(n,this.kernel.read()),null!=this.bias&&(r=Pg(r,this.bias.read())),null!=this.activation&&(r=this.activation.apply(r))),r}))}getConfig(){const e={units:this.units,activation:xx(this.activation),useBias:this.useBias,kernelInitializer:ly(this.kernelInitializer),biasInitializer:ly(this.biasInitializer),kernelRegularizer:Tx(this.kernelRegularizer),biasRegularizer:Tx(this.biasRegularizer),activityRegularizer:Tx(this.activityRegularizer),kernelConstraint:Wy(this.kernelConstraint),biasConstraint:Wy(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}}xw.className="Dense",Ki(xw);class ww extends Ny{constructor(e){super(e=e||{}),this.inputSpec=[{minNDim:3}],this.dataFormat=e.dataFormat}computeOutputShape(e){e=dy(e);for(const t of e.slice(1))if(null==t)throw new Am(`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],wg(e,1)]}call(e,t){return Zi((()=>{this.invokeCallHook(e,t);let n=py(e);if("channelsFirst"===this.dataFormat&&n.rank>1){const e=[0];for(let t=2;t{this.invokeCallHook(e,t);const n=py(e);return this.activation.apply(n)}))}getConfig(){const e={activation:xx(this.activation)},t=super.getConfig();return Object.assign(e,t),e}}vw.className="Activation",Ki(vw);class kw extends Ny{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 Zi((()=>function(e,t){return Zi((()=>{if(2!==e.shape.length)throw new Am(`repeat() expects a rank-2 tensor, but received a rank-${e.shape.length} tensor.`);return _g(Cg(e,1),[1,t,1])}))}(e=py(e),this.n)))}getConfig(){const e={n:this.n},t=super.getConfig();return Object.assign(e,t),e}}kw.className="RepeatVector",Ki(kw);class Iw extends Ny{constructor(e){super(e),this.targetShape=e.targetShape;for(let e=0;e{this.invokeCallHook(e,t);const n=py(e),s=n.shape,r=s.slice(0,1).concat(this.fixUnknownDimension(s.slice(1),this.targetShape));return _o(n,r)}))}getConfig(){const e={targetShape:this.targetShape},t=super.getConfig();return Object.assign(e,t),e}}Iw.className="Reshape",Ki(Iw);class Nw extends Ny{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=Ig(1,e.dims.length+1);if(!B(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 xy({ndim:this.dims.length+1})]}computeOutputShape(e){const t=(e=dy(e)).slice();return this.dims.forEach(((n,s)=>{t[s+1]=e[n]})),t}call(e,t){return ah(py(e),this.dimsIncludingBatch)}getConfig(){const e={dims:this.dims},t=super.getConfig();return Object.assign(e,t),e}}Nw.className="Permute",Ki(Nw);class Sw extends Ny{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=py(e);return co(Bu(n,this.maskValue),-1)}call(e,t){return Zi((()=>{this.invokeCallHook(e,t);const n=py(e),s=co(Bu(n,this.maskValue),-1,!0);return zo(n,Za(s,n.dtype))}))}}Sw.className="Masking",Ki(Sw); +/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */ +class Tw extends Ny{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(Pm(e.inputLength))}this.inputDim=e.inputDim,Zm(this.inputDim,"inputDim"),this.outputDim=e.outputDim,Zm(this.outputDim,"outputDim"),this.embeddingsInitializer=uy(e.embeddingsInitializer||this.DEFAULT_EMBEDDINGS_INITIALIZER),this.embeddingsRegularizer=$x(e.embeddingsRegularizer),this.activityRegularizer=$x(e.activityRegularizer),this.embeddingsConstraint=Uy(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 Zi((()=>this.maskZero?(e=py(e),Bu(e,Nl(e))):null))}computeOutputShape(e){if(e=dy(e),null==this.inputLength)return[...e,this.outputDim];const t=Pm(this.inputLength);if(t.length!==e.length-1)throw new Am(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);{let n=0;for(let s=0;s{this.invokeCallHook(e,t);let n=py(e);"int32"!==n.dtype&&(n=Tg(n,"int32"));const s=Mg(this.embeddings.read(),_o(n,[n.size]));return _o(s,dy(this.computeOutputShape(n.shape)))}))}getConfig(){const e={inputDim:this.inputDim,outputDim:this.outputDim,embeddingsInitializer:ly(this.embeddingsInitializer),embeddingsRegularizer:Tx(this.embeddingsRegularizer),activityRegularizer:Tx(this.activityRegularizer),embeddingsConstraint:Wy(this.embeddingsConstraint),maskZero:this.maskZero,inputLength:this.inputLength},t=super.getConfig();return Object.assign(e,t),e}}Tw.className="Embedding",Ki(Tw); +/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */ +class Cw extends Ny{constructor(e){super(e||{}),this.supportsMasking=!0}mergeFunction(e){throw new Fm}computeElementwiseOpOutputShape(e,t){if(null==e||null==t)return null;if(e.length1)throw new Am(`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===qm(s).length?this.reshapeRequired=!1:this.reshapeRequired=!0}call(e,t){return Zi((()=>{if(this.reshapeRequired){const t=[],n=e.map((e=>e.rank));if(-1===n.indexOf(null)){const s=kg(n);for(let n of e){const e=n.rank;for(let t=0;t1){const r=Ig(1,e).concat([0]);t.push(ah(s,r)),n=!0}else t.push(s)}let s=this.mergeFunction(t);const r=s.rank;if(n)if(null==r){const e=s.shape,t=e[e.length-1],n=[t].concat(e.slice(0,e.length-1));s=_o(ah(_o(s,[-1,t]),[1,0]),n)}else if(r>1){const e=[r-1].concat(Ig(0,r-1));s=ah(s,e)}return s}}return this.mergeFunction(e)}))}computeOutputShape(e){let t;t=null==e[0]?null:e[0].slice(1);for(let n=1;n{if(null==t)return null;if(!Array.isArray(t))throw new Am("`mask` should be an Array");if(!Array.isArray(e))throw new Am("`inputs` should be an Array");if(t.length!==e.length)throw new Am(`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:Kl(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 Am("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(e))}mergeFunction(e){return Zi((()=>Ag(e,this.axis)))}computeOutputShape(e){if(!Array.isArray(e)||!Array.isArray(e[0]))throw new Am("A `Concatenate` layer should be called on a list of inputs.");const t=e,n=t[0].slice(),s=this.axis<0?n.length+this.axis:this.axis;for(const e of t.slice(1)){if(null==n[s]||null==e[s]){n[s]=null;break}n[s]+=e[s]}return n}computeMask(e,t){if(null==t)return null;if(!Array.isArray(t))throw new Am("`mask` should be an array for Concatenate");if(!Array.isArray(e))throw new Am("`inputs` should be an array for Concatenate");if(t.length!==e.length)throw new Am(`Mismatch in the length of mask (${t.length}) and the legnth of inputs (${e.length})`);return Zi((()=>{let n=!0;if(t.forEach((e=>{null==e||(n=!1)})),n)return null;const s=[];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 Fm("Dot layer does not support tensors of 4D or higher rank yet.");const s=this.interpretAxes(t,n);if(t[s[0]]!==n[s[1]])throw new Am(`Dimension incompatibility: ${t[s[0]]} !== ${n[s[1]]}`)}mergeFunction(e){if(2!==e.length)throw new Am(`A \`Dot\` layer must be called on exactly 2 inputs, but received ${e.length} input(s).`);let t,n=e[0],s=e[1];return t=Array.isArray(this.axes)?this.axes.map(((t,n)=>Dw(t,e[n].shape.length))):[Dw(this.axes,n.shape.length),Dw(this.axes,s.shape.length)],this.normalize&&(n=nb(n,t[0]),s=nb(s,t[1])),function(e,t,n){if(e.shape.length>3||t.shape.length>3)throw new Fm("batchDot is not implemented for tensors of 4D or higher rank yet");if(O(e.shape.length>=2,(()=>`batchDot requires the rank of x to be >= 2, but got ${e.shape.length}`)),O(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 Fm("batchDot is not implemented for complex64-type Tensors yet.");const s=e.shape.length,r=t.shape.length;null==n&&(n=[s-1,r-2]);const a=n;return Zi((()=>{let n,i;if(s>r){n=s-r;const e=[];for(let t=0;ts){n=r-s;const t=[];for(let e=0;e0){let e;e=s>r?s+r-3:s-1;const t=[];for(let s=e;s"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 Fm("Dot layer does not support tensors of 4D or higher rank yet.");const s=this.interpretAxes(t,n);t.splice(s[0],1),n.splice(s[1],1),n.splice(0,1);const r=t.concat(n);return 1===r.length&&r.push(1),r}computeMask(e,t){return null}getConfig(){const e={axes:this.axes,normalize:this.normalize},t=super.getConfig();return Object.assign(e,t),e}}Ow.className="Dot",Ki(Ow); +/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */ +class Mw extends Ny{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 Zi((()=>{this.invokeCallHook(e,t);const n=py(e);return Wg((()=>oo(Dg(n.shape,0,this.stddev),n)),(()=>n),t.training||!1)}))}}Mw.className="GaussianNoise",Ki(Mw);class Lw extends Ny{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 Zi((()=>{this.invokeCallHook(e,t);const n=py(e);if(this.rate>0&&this.rate<1){return Wg((()=>{const e=Math.sqrt(this.rate/(1-this.rate));return zo(n,Dg(n.shape,1,e))}),(()=>n),t.training||!1)}return n}))}}Lw.className="GaussianDropout",Ki(Lw);class zw extends Ny{constructor(e){super(e),this.supportsMasking=!0,this.rate=e.rate,this.noiseShape=e.noiseShape}_getNoiseShape(e){return this.noiseShape||py(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 Zi((()=>{if(this.rate<1&&this.rate>0){const n=this._getNoiseShape(e),s=()=>{const t=py(e),s=-1.7580993408473766;let r=tu(uc(n),this.rate);r=Tg(r,"float32");const a=((1-this.rate)*(1+this.rate*s**2))**-.5,i=-a*s*this.rate,o=oo(zo(t,r),zo(oo(r,-1),s));return oo(zo(o,a),i)};return Wg(s,(()=>py(e)),t.training||!1)}return e}))}} +/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */ +function Pw(e,t,n,s,r,a=.001){let i;if(2===e.rank)i=Ho(e,t,n,s,r,a);else if(3===e.rank)i=jo(e,t,n,s,r,a);else{if(4!==e.rank)throw new Fm(`batchNormalization is not implemented for array of rank ${e.rank} yet`);i=qo(e,t,n,s,r,a)}return i}function Bw(e,t,n,s,r=.001){return B(s.slice().sort(),Ig(0,e.rank-1))?function(e,t,n,s,r=.001){return Zi((()=>{const a=Lu(e,s),i=a.mean,o=a.variance;return[Pw(e,i,o,n,t,r),i,o]}))}(e,t,n,s,r):function(e,t,n,s,r=.001){return Zi((()=>{const a=Lu(e,s),i=a.mean,o=a.variance,l=[];for(const t of Ig(0,e.rank))-1!==s.indexOf(t)?l.push(1):l.push(e.shape[t]);const u=_o(i,l),c=_o(o,l),h=null==t?null:_o(t,l),p=null==n?null:_o(n,l);return[Pw(e,u,c,p,h,r),i,o]}))}(e,t,n,s,r)}zw.className="AlphaDropout",Ki(zw);class Ww extends Ny{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=uy(e.betaInitializer||"zeros"),this.gammaInitializer=uy(e.gammaInitializer||"ones"),this.movingMeanInitializer=uy(e.movingMeanInitializer||"zeros"),this.movingVarianceInitializer=uy(e.movingVarianceInitializer||"ones"),this.betaConstraint=Uy(e.betaConstraint),this.gammaConstraint=Uy(e.gammaConstraint),this.betaRegularizer=$x(e.betaRegularizer),this.gammaRegularizer=$x(e.gammaRegularizer)}build(e){e=dy(e);const t=this.axis>=0?this.axis:this.axis+e.length,n=e[t];if(null==n)throw new Am(`Axis ${t} of input tensor should have a defined dimension but the layer received an input with shape ${JSON.stringify(e)}.`);this.inputSpec=[new xy({ndim:e.length,axes:{[t]:n}})];const s=[n];this.scale&&(this.gamma=this.addWeight("gamma",s,null,this.gammaInitializer,this.gammaRegularizer,!0,this.gammaConstraint)),this.center&&(this.beta=this.addWeight("beta",s,null,this.betaInitializer,this.betaRegularizer,!0,this.betaConstraint)),this.movingMean=this.addWeight("moving_mean",s,null,this.movingMeanInitializer,null,!1),this.movingVariance=this.addWeight("moving_variance",s,null,this.movingVarianceInitializer,null,!1),this.built=!0}call(e,t){return Zi((()=>{const n=null!=t.training&&t.training,s=py(e),r=s.shape,a=r.length,i=Ig(0,a),o=this.axis>=0?this.axis:this.axis+a;i.splice(o,1);const l=Om(1,a);l[o]=r[o];const u=i.slice();u.sort();const c=!B(u,Ig(0,a).slice(0,a-1));if(!n)return(()=>{if(c){const e=_o(this.movingMean.read(),l),t=_o(this.movingVariance.read(),l),n=this.center?_o(this.beta.read(),l):null,r=this.scale?_o(this.gamma.read(),l):null;return Pw(s,e,t,n,r,this.epsilon)}return Pw(s,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]=Bw(s,this.gamma.read(),this.beta.read(),i,this.epsilon),f=(e,t,n)=>{Zi((()=>{const s=1-n,r=e.read(),a=zo(gu(r,t),s);e.write(gu(r,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:ly(this.betaInitializer),gammaInitializer:ly(this.gammaInitializer),movingMeanInitializer:ly(this.movingMeanInitializer),movingVarianceInitializer:ly(this.movingVarianceInitializer),betaRegularizer:Tx(this.betaRegularizer),gammaRegularizer:Tx(this.gammaRegularizer),betaConstraint:Wy(this.betaConstraint),gammaConstraint:Wy(this.gammaConstraint)},t=super.getConfig();return Object.assign(e,t),e}}Ww.className="BatchNormalization",Ki(Ww);class Vw extends Ny{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=uy(e.betaInitializer||"zeros"),this.gammaInitializer=uy(e.gammaInitializer||"ones"),this.betaRegularizer=$x(e.betaRegularizer),this.gammaRegularizer=$x(e.gammaRegularizer),this.supportsMasking=!0}build(e){const t=(e=dy(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!==qm(this.axis).length)throw new Error(`Found duplicate axes in: ${this.axis}`);const n=this.axis.map((t=>e[t])),s=!0;this.scale?this.gamma=this.addWeight("gamma",n,"float32",this.gammaInitializer,this.gammaRegularizer,s):this.gamma=null,this.center?this.beta=this.addWeight("beta",n,"float32",this.betaInitializer,this.betaRegularizer,s):this.beta=null,this.built=!0}call(e,t){const n=py(e),s=n.shape,r=s.length;return Zi((()=>{let{mean:e,variance:t}=Lu(n,this.axis,!0);const a=Om(1,r);for(const e of this.axis)a[e]=s[e];const i=e=>null!=e&&e.shape.length!==r?_o(e,a):e;let o=this.scale?i(this.gamma.read()):null,l=this.center?i(this.beta.read()):null;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 Zi((()=>function(e,t,n){return Zi((()=>{if(4!==e.rank)throw new Am(`temporalPadding expects input tensor to be 4-D, but received a ${e.rank}-D tensor.`);if(null==t&&(t=[[1,1],[1,1]]),2!==t.length||2!==t[0].length||2!==t[1].length)throw new Am("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");if(null==n&&(n="channelsLast"),"channelsLast"!==n&&"channelsFirst"!==n)throw new Am(`Unknown data format: ${n}. Supported data formats are 'channelsLast' and 'channelsFirst.`);let s;return s="channelsFirst"===n?[[0,0],[0,0],t[0],t[1]]:[[0,0],t[0],t[1],[0,0]],Gu(e,s)}))}(py(e),this.padding,this.dataFormat)))}getConfig(){const e={padding:this.padding,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}} +/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */ +function Gw(e,t,n,s,r,a){return Zi((()=>{let i;cg(r),pg(a),hg(s),null==n&&(n=[1,1]),null==s&&(s="valid"),null==r&&(r="channelsLast"),null==a&&(a="max"),e=zx(e,r);const o="same"===s?"same":"valid";return i="max"===a?Tu(e,t,n,o):Do(e,t,n,o),"channelsFirst"===r&&(i=ah(i,[0,3,1,2])),i}))}function Hw(e,t,n,s,r,a){return Zi((()=>{let i;cg(r),pg(a),hg(s),null==n&&(n=[1,1,1]),null==s&&(s="valid"),null==r&&(r="channelsLast"),null==a&&(a="max"),e=Px(e,r);const o="same"===s?"same":"valid";return i="max"===a?Cu(e,t,n,o):Oo(e,t,n,o),"channelsFirst"===r&&(i=ah(i,[0,4,1,2,3])),i}))}Uw.className="ZeroPadding2D",Ki(Uw);class jw extends Ny{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 Am(`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(Zm(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 Am(`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}Zm(this.strides,"strides"),this.padding=null==e.padding?"valid":e.padding,hg(this.padding),this.inputSpec=[new xy({ndim:3})]}computeOutputShape(e){const t=Mx((e=dy(e))[1],this.poolSize[0],this.padding,this.strides[0]);return[e[0],t,e[2]]}call(e,t){return Zi((()=>{this.invokeCallHook(e,t),e=Cg(py(e),2);const n=this.poolingFunction(py(e),[this.poolSize[0],1],[this.strides[0],1],this.padding,"channelsLast");return Pc(n,[2])}))}getConfig(){const e={poolSize:this.poolSize,padding:this.padding,strides:this.strides},t=super.getConfig();return Object.assign(e,t),e}}class qw extends jw{constructor(e){super(e)}poolingFunction(e,t,n,s,r){return cg(r),hg(s),Gw(e,t,n,s,r,"max")}}qw.className="MaxPooling1D",Ki(qw);class Kw extends jw{constructor(e){super(e)}poolingFunction(e,t,n,s,r){return cg(r),hg(s),Gw(e,t,n,s,r,"avg")}}Kw.className="AveragePooling1D",Ki(Kw);class Xw extends Ny{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 Am(`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];Zm(this.poolSize,"poolSize"),Zm(this.strides,"strides"),this.padding=null==e.padding?"valid":e.padding,this.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,cg(this.dataFormat),hg(this.padding),this.inputSpec=[new xy({ndim:4})]}computeOutputShape(e){e=dy(e);let t="channelsFirst"===this.dataFormat?e[2]:e[1],n="channelsFirst"===this.dataFormat?e[3]:e[2];return t=Mx(t,this.poolSize[0],this.padding,this.strides[0]),n=Mx(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 Zi((()=>(this.invokeCallHook(e,t),this.poolingFunction(py(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 Yw extends Xw{constructor(e){super(e)}poolingFunction(e,t,n,s,r){return cg(r),hg(s),Gw(e,t,n,s,r,"max")}}Yw.className="MaxPooling2D",Ki(Yw);class Zw extends Xw{constructor(e){super(e)}poolingFunction(e,t,n,s,r){return cg(r),hg(s),Gw(e,t,n,s,r,"avg")}}Zw.className="AveragePooling2D",Ki(Zw);class Jw extends Ny{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 Am(`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];Zm(this.poolSize,"poolSize"),Zm(this.strides,"strides"),this.padding=null==e.padding?"valid":e.padding,this.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,cg(this.dataFormat),hg(this.padding),this.inputSpec=[new xy({ndim:5})]}computeOutputShape(e){e=dy(e);let t="channelsFirst"===this.dataFormat?e[2]:e[1],n="channelsFirst"===this.dataFormat?e[3]:e[2],s="channelsFirst"===this.dataFormat?e[4]:e[3];return t=Mx(t,this.poolSize[0],this.padding,this.strides[0]),n=Mx(n,this.poolSize[1],this.padding,this.strides[1]),s=Mx(s,this.poolSize[2],this.padding,this.strides[2]),"channelsFirst"===this.dataFormat?[e[0],e[1],t,n,s]:[e[0],t,n,s,e[4]]}call(e,t){return Zi((()=>(this.invokeCallHook(e,t),this.poolingFunction(py(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 Qw extends Jw{constructor(e){super(e)}poolingFunction(e,t,n,s,r){return cg(r),hg(s),Hw(e,t,n,s,r,"max")}}Qw.className="MaxPooling3D",Ki(Qw);class ev extends Jw{constructor(e){super(e)}poolingFunction(e,t,n,s,r){return cg(r),hg(s),Hw(e,t,n,s,r,"avg")}}ev.className="AveragePooling3D",Ki(ev);class tv extends Ny{constructor(e){super(e),this.inputSpec=[new xy({ndim:3})]}computeOutputShape(e){return[e[0],e[2]]}call(e,t){throw new Fm}}class nv extends tv{constructor(e){super(e||{})}call(e,t){return Zi((()=>{const t=py(e);return Ru(t,1)}))}}nv.className="GlobalAveragePooling1D",Ki(nv);class sv extends tv{constructor(e){super(e||{})}call(e,t){return Zi((()=>{const t=py(e);return zl(t,1)}))}}sv.className="GlobalMaxPooling1D",Ki(sv);class rv extends Ny{constructor(e){super(e),this.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,cg(this.dataFormat),this.inputSpec=[new xy({ndim:4})]}computeOutputShape(e){return"channelsLast"===this.dataFormat?[e[0],e[3]]:[e[0],e[1]]}call(e,t){throw new Fm}getConfig(){const e={dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}class av extends rv{call(e,t){return Zi((()=>{const t=py(e);return"channelsLast"===this.dataFormat?Ru(t,[1,2]):Ru(t,[2,3])}))}}av.className="GlobalAveragePooling2D",Ki(av);class iv extends rv{call(e,t){return Zi((()=>{const t=py(e);return"channelsLast"===this.dataFormat?zl(t,[1,2]):zl(t,[2,3])}))}}iv.className="GlobalMaxPooling2D",Ki(iv); +/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */ +class ov extends Ny{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 s=tb(t.layer,n);delete t.layer;const r={layer:s};return Object.assign(r,t),new e(r)}}class lv extends ov{constructor(e){super(e),this.supportsMasking=!0}build(e){if((e=dy(e)).length<3)throw new Am(`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=dy(e))[0]].concat(e.slice(2)),n=this.layer.computeOutputShape(t),s=e[1];return[n[0],s].concat(n.slice(1))}call(e,t){return Zi((()=>nw(((e,n)=>[py(this.layer.call(e,t)),[]]),e=py(e),[],!1,null,null,!1,!0)[1]))}}lv.className="TimeDistributed",Ki(lv);class uv extends ov{constructor(e){super(e);const t=e.layer.getConfig(),n={};n.className=e.layer.getClassName(),n.config=t,this.forwardLayer=tb(n),t.goBackwards=!0!==t.goBackwards;const s={};var r;if(s.className=e.layer.getClassName(),s.config=t,this.backwardLayer=tb(s),this.forwardLayer.name="forward_"+this.forwardLayer.name,this.backwardLayer.name="backward_"+this.backwardLayer.name,this.mergeMode=void 0===e.mergeMode?"concat":e.mergeMode,r=this.mergeMode,Xm(lg,"BidirectionalMergeMode",r),e.weights)throw new Fm("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,s,r=this.forwardLayer.computeOutputShape(e);return Array.isArray(r)&&Array.isArray(r[0])||(r=[r]),this.returnState?(s=r.slice(1),t=r[0]):t=r[0],"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(s).concat(s.slice()):[t].concat(s).concat(s.slice()):zm(n)}apply(e,t){let n=null==t?null:t.initialState,s=null==t?null:t.constants;null==t&&(t={});const r=tw(e,n,s,this.numConstants);if(e=r.inputs,n=r.initialState,s=r.constants,Array.isArray(e)&&(n=e.slice(1),e=e[0]),(null==n||0===n.length)&&null==s)return super.apply(e,t);const a=[],i=[];if(null!=n){const e=n.length;if(e%2>0)throw new Am("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 s=n.map((e=>new xy({shape:e.shape})));this.forwardLayer.stateSpec=s.slice(0,e/2),this.backwardLayer.stateSpec=s.slice(e/2),i.push(...s)}if(null!=s)throw new Fm("Support for constants in Bidirectional layers is not implemented yet.");const o=a[0]instanceof wy;for(const e of a)if(e instanceof wy!==o)throw new Am("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),s=this.inputSpec.concat(i),r=this.inputSpec;this.inputSpec=s;const o=super.apply(n,t);return this.inputSpec=r,o}return super.apply(e,t)}call(e,t){return Zi((()=>{const n=t.initialState;let s,r,a,i;if(null==n)s=this.forwardLayer.call(e,t),r=this.backwardLayer.call(e,t);else{const a=n.slice(0,n.length/2),i=n.slice(n.length/2);s=this.forwardLayer.call(e,Object.assign(t,{initialState:a})),r=this.backwardLayer.call(e,Object.assign(t,{initialState:i}))}return this.returnState&&(Array.isArray(s)&&(a=s.slice(1).concat(r.slice(1))),s=s[0],r=r[0]),this.returnSequences&&(r=mc(r,1)),"concat"===this.mergeMode?i=Ag([s,r]):"sum"===this.mergeMode?i=oo(s,r):"ave"===this.mergeMode?i=zo(.5,oo(s,r)):"mul"===this.mergeMode?i=zo(s,r):null==this.mergeMode&&(i=[s,r]),this.returnState?null==this.mergeMode?i.concat(a):[i].concat(a):i}))}resetStates(e){this.forwardLayer.resetStates(),this.backwardLayer.resetStates()}build(e){fg(this.forwardLayer.name,(()=>{this.forwardLayer.build(e)})),fg(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=tb(t.layer);if(delete t.layer,null!=t.numConstants)throw new Fm("Deserialization of a Bidirectional layer with numConstants present is not supported yet.");const s=t;return s.layer=n,new e(s)}}uv.className="Bidirectional",Ki(uv); +/** + * @license + * Copyright 2022 CodeSmith LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */ +class cv extends Ny{constructor(e){super(e),this.scale=e.scale,e.offset?this.offset=e.offset:this.offset=0}getConfig(){const e={scale:this.scale,offset:this.offset},t=super.getConfig();return Object.assign(e,t),e}call(e,t){return Zi((()=>("float32"!==(e=py(e)).dtype&&(e=Tg(e,"float32")),oo(zo(e,this.scale),this.offset))))}}cv.className="Rescaling",Ki(cv); +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============================================================================= + */ +var hv,pv;ye().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"}(hv||(hv={})),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={}))}(pv||(pv={})); +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +const dv={};function fv(e){return dv[e]} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function mv(e,t,n,s,r){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 gv(t.inputNames[a.inputIndexStart],n,s,r);if("tensors"===a.type){return t.inputNames.slice(e,i).map((e=>gv(e,n,s,r)))}const o=gv(t.inputNames.slice(e)[0],n,s,r),l=o.dataSync();return"number"===a.type?l[0]:ie(o.shape,l)}const i=t.attrParams[e];return i&&i.value}function gv(e,t,n,s){const[r,a]=xv(e);if(null!=s){const e=s.getHashTableHandleByName(r);if(null!=e)return e}const i=n.currentContextIds.find((e=>!!t[bv(r,e)]));return void 0!==i?t[bv(r,i)][a]:void 0}function yv(e,t){const[n,s,r]=xv(e);return[bv(n,t&&t.currentContextId),s,r]}function bv(e,t){return t?`${e}-${t}`:e}function xv(e){const t=e.split(":");if(1===t.length)return[e,0,void 0];const n=t[0],s=3===t.length?t[1]:void 0;return[n,Number(t[t.length-1]),s]}function wv(e,t,n){let s=mv("pad",e,t,n);if("explicit"===s){s=mv("explicitPaddings",e,t,n);const r=[[0,0],[0,0],[0,0],[0,0]];for(let e=0;e<4;e++)r[e][0]=s[2*e],r[e][1]=s[2*e+1];return r}return s}function vv(e){return e.kept?e:Ja(e)} +/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +const kv=[{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}]}],Iv=[{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}]}],Nv=[{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:"TensorListConcatV2",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"}]},{tfOpName:"TensorListLength",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"}]},{tfOpName:"TensorListResize",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"size",type:"number"}]}],Sv=[{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",defaultValue:.2}]},{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"}]}],Tv=[{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"}]},{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:"RandomStandardNormal",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"seed",name:"seed",type:"number",defaultValue:0},{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:"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"}]}],Cv=[{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}]}],$v=[{tfOpName:"LowerBound",category:"evaluation",inputs:[{start:0,name:"sortedSequence",type:"tensor"},{start:1,name:"values",type:"tensor"}]},{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:"UpperBound",category:"evaluation",inputs:[{start:0,name:"sortedSequence",type:"tensor"},{start:1,name:"values",type:"tensor"}]},{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"}]}],Ev=[{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"}]}],Rv=[{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"}]}],Av=[{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"}]},{tfOpName:"ImageProjectiveTransformV3",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"transforms",type:"tensor"},{start:2,name:"outputShape",type:"number[]"},{start:3,name:"fillValue",type:"number"}],attrs:[{tfName:"interpolation",name:"interpolation",type:"string"},{tfName:"fill_mode",name:"fillMode",type:"string"}]}],Fv=[{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}]}],_v=[{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:"leakyrelu_alpha",name:"leakyreluAlpha",type:"number",defaultValue:.2},{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"}]}],Dv=[{tfOpName:"EuclideanNorm",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool",defaultValue:!1}]},{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}]}],Ov=[{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:"Cumprod",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"}]},{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"}]}],Mv=[{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}]}],Lv=[{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"}]}],zv=[{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}]}],Pv=[{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"}]}],Bv=[{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:[]}]; +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class Wv{static get Instance(){return this._instance||(this._instance=new this)}constructor(){const e=[].concat(...[o,l,u,c,h,p,d,f,m,g,y,b,x,w,v,k,I,N,S].map((e=>e.json)));this.opMappers=e.reduce(((e,t)=>(e[t.tfOpName]=t,e)),{})}transformGraph(e,t={}){const n=e.node,s=[],r=[],a=[],i=n.reduce(((e,t)=>(e[t.name]=this.mapNode(t),t.op.startsWith("Placeholder")?s.push(e[t.name]):"Const"===t.op?r.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[s,,r]=yv(e),a=i[s];if(null!=a.outputs){const e=a.outputs.indexOf(r);if(-1!==e){const r=`${s}:${e}`;t.inputNames[n]=r}}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]=yv(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]=yv(e),n=i[t];n&&(n.signatureKey=u[e],o.push(n))})):o=s;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:r,placeholders:s,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=fv(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.slice(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 s=n.type;let r;switch(n.type){case"string":r=Uv(e.attr,n.tfName,n.defaultValue),void 0===r&&n.tfDeprecatedName&&(r=Uv(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"string[]":r=Qv(e.attr,n.tfName,n.defaultValue),void 0===r&&n.tfDeprecatedName&&(r=Qv(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"number":r=Hv(e.attr,n.tfName,n.defaultValue||0),void 0===r&&n.tfDeprecatedName&&(r=Hv(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"number[]":r=Jv(e.attr,n.tfName,n.defaultValue),void 0===r&&n.tfDeprecatedName&&(r=Jv(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"bool":r=Gv(e.attr,n.tfName,n.defaultValue),void 0===r&&n.tfDeprecatedName&&(r=Gv(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"bool[]":r=tk(e.attr,n.tfName,n.defaultValue),void 0===r&&n.tfDeprecatedName&&(r=tk(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"shape":r=Zv(e.attr,n.tfName,n.defaultValue),void 0===r&&n.tfDeprecatedName&&(r=Zv(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"shape[]":r=ek(e.attr,n.tfName,n.defaultValue),void 0===r&&n.tfDeprecatedName&&(r=ek(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"dtype":r=Kv(e.attr,n.tfName,n.defaultValue),void 0===r&&n.tfDeprecatedName&&(r=Kv(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"dtype[]":r=Xv(e.attr,n.tfName,n.defaultValue),void 0===r&&n.tfDeprecatedName&&(r=Xv(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"func":r=qv(e.attr,n.tfName,n.defaultValue),void 0===r&&n.tfDeprecatedName&&(r=qv(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:r,type:s},t}),{})),n}mapFunction(e){const t=e.nodeDef,n=[];let s={};null!=t&&(s=t.reduce(((e,t)=>(e[t.name]=this.mapNode(t),"Const"===t.op&&n.push(e[t.name]),e)),{}));const r=[],a=[];e.signature.inputArg.forEach((e=>{const[t]=yv(e.name),n={name:t,op:"Placeholder",inputs:[],inputNames:[],category:"graph",inputParams:{},attrParams:{dtype:{value:jv(e.type),type:"dtype"}},children:[]};n.signatureKey=e.name,r.push(n),s[t]=n}));Object.keys(s).forEach((e=>{const t=s[e];t.inputNames.forEach(((e,n)=>{const[r,,a]=yv(e),i=s[r];if(null!=i.outputs){const e=i.outputs.indexOf(a);if(-1!==e){const s=`${r}:${e}`;t.inputNames[n]=s}}t.inputs.push(i),i.children.push(t)}))}));const i=e.ret;e.signature.outputArg.forEach((e=>{const[t,n]=yv(i[e.name]),r=s[t];null!=r&&(r.defaultOutput=n,a.push(r))}));const o=this.mapArgsToSignature(e);return{nodes:s,inputs:r,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 Vv(e,t){const n=Array.isArray(e)?String.fromCharCode.apply(null,e):function(e){const t=ye().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 Uv(e,t,n,s=!1){const r=e[t];return null!=r?Vv(r.s,s):n}function Gv(e,t,n){const s=e[t];return s?s.b:n}function Hv(e,t,n){const s=e[t]||{},r=null!=s.i?s.i:null!=s.f?s.f:n;return"number"==typeof r?r:parseInt(r,10)}function jv(e){switch("string"==typeof e&&(e=hv[e]),e){case hv.DT_FLOAT:case hv.DT_HALF:return"float32";case hv.DT_INT32:case hv.DT_INT64:case hv.DT_INT8:case hv.DT_UINT8:return"int32";case hv.DT_BOOL:return"bool";case hv.DT_DOUBLE:return"float32";case hv.DT_STRING:return"string";default:return null}}function qv(e,t,n){const s=e[t];return s&&s.func?s.func.name:n}function Kv(e,t,n){const s=e[t];return s&&s.type?jv(s.type):n}function Xv(e,t,n){const s=e[t];return s&&s.list&&s.list.type?s.list.type.map((e=>jv(e))):n}function Yv(e){if(!e.unknownRank)return null!=e.dim?e.dim.map((e=>"number"==typeof e.size?e.size:parseInt(e.size,10))):[]}function Zv(e,t,n){const s=e[t];return s&&s.shape?Yv(s.shape):n}function Jv(e,t,n){const s=e[t];return s?((s.list.f&&s.list.f.length?s.list.f:s.list.i)||[]).map((e=>"number"==typeof e?e:parseInt(e,10))):n}function Qv(e,t,n,s=!1){const r=e[t];return r&&r.list&&r.list.s?r.list.s.map((e=>Vv(e,s))):n}function ek(e,t,n){const s=e[t];return s&&s.list&&s.list.shape?s.list.shape.map((e=>Yv(e))):n}function tk(e,t,n){const s=e[t];return s&&s.list&&s.list.b?s.list.b:n} +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class nk{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 gv(e,this.tensorMap,this.context)}getAttr(e,t){const n=this.node.rawAttrs[e];if(null!=n.tensor)return gv(e,this.tensorMap,this.context);if(null!=n.i||null!=n.f)return Hv(this.node.rawAttrs,e,t);if(null!=n.s)return Uv(this.node.rawAttrs,e,t);if(null!=n.b)return Gv(this.node.rawAttrs,e,t);if(null!=n.shape)return Zv(this.node.rawAttrs,e,t);if(null!=n.type)return Kv(this.node.rawAttrs,e,t);if(null!=n.list){if(null!=n.list.i||null!=n.list.f)return Jv(this.node.rawAttrs,e,t);if(null!=n.list.s)return Qv(this.node.rawAttrs,e,t);if(null!=n.list.shape)return ek(this.node.rawAttrs,e,t);if(null!=n.list.b)return tk(this.node.rawAttrs,e,t);if(null!=n.list.type)return Xv(this.node.rawAttrs,e,t)}return t}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function sk(e,t,n=""){if("number"!=typeof e&&"number"!=typeof t){O(e.length===t.length,(()=>n+` Shapes ${e} and ${t} must match`));for(let s=0;sn+` Shapes ${e} and ${t} must match`))}}}function rk(e){return"number"!=typeof e&&!e.some((e=>e<0))}function ak(e,t,n){let s=ik(e,n);const r=!rk(s);if(r&&0===t.length)throw new Error(`Tried to calculate elements of an empty list with non-fully-defined elementShape: ${s}`);if(r&&t.forEach((e=>{s=ik(e.shape,s)})),!rk(s))throw new Error(`Non-fully-defined elementShape: ${s}`);return s}function ik(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 s=0;s=0&&a>=0&&r!==a)throw new Error(`Incompatible shape during merge: ${e} vs. ${t}`);n[s]=r>=0?r:a}return n} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class ok{constructor(e,t,n,s,r,a,i){this.name=e,this.dtype=t,this.maxSize=n,this.elementShape=s,this.identicalElementShapes=r,this.dynamicSize=a,this.clearAfterRead=i,this.tensors=[],this.closed_=!1,this.idTensor=no(0),Qi(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),sk(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,Qi(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,Qc(t,0))}split(e,t){if(t.dtype!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${t.dtype}`);let n=0;const s=e.map((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 r=0===n?0:t.size/n,a=[];Zi((()=>{t=_o(t,[1,n,r]);for(let n=0;n{if(n!==e.dtype)throw new Error(`Invalid data types; op elements ${n}, but list elements ${e.dtype}`);sk(t,e.shape,"TensorList shape mismatch: "),Qi(e)})),this.idTensor=no(0),this.maxNumElements=s,Qi(this.idTensor)}get id(){return this.idTensor.id}copy(){return new lk([...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.`);sk(e,this.elementShape,"TensorList shape mismatch: ");const s=ak(this.elementShape,this.tensors,e);return Zi((()=>{const e=this.tensors.map((e=>_o(e,s)));return Bc(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=ak(this.elementShape,this.tensors,e),s=this.tensors.pop();return s.kept=!1,sk(s.shape,e,"TensorList shape mismatch: "),_o(s,n)}pushBack(e){if(e.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${this.elementDtype}`);if(sk(e.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");Qi(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}.`);const t=new lk([],this.elementShape,this.elementDtype,this.maxNumElements);t.tensors.length=e;for(let n=0;nthis.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.`);sk(this.tensors[e].shape,t,"TensorList shape mismatch: ");const s=ak(this.elementShape,this.tensors,t);return _o(this.tensors[e],s)}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.`);sk(this.elementShape,t.shape,"TensorList shape mismatch: "),Qi(t),null!=this.tensors[e]&&(this.tensors[e].kept=!1),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}`);sk(this.elementShape,n,"TensorList shape mismatch: "),e=e.slice(0,this.size());const s=ak(this.elementShape,this.tensors,n);return 0===e.length?Yr([],[0].concat(s)):Zi((()=>{const t=e.map((e=>_o(this.tensors[e],s)));return Bc(t,0)}))}concat(e,t){if(e&&e!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${e}`);sk(this.elementShape,t,"TensorList shape mismatch: ");const n=ak(this.elementShape,this.tensors,t);return 0===this.size()?Yr([],[0].concat(n)):Zi((()=>{const e=this.tensors.map((e=>_o(e,n)));return Mo(e,0)}))}} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +const uk=async(e,t,n)=>{switch(e.op){case"If":case"StatelessIf":{const s=mv("thenBranch",e,t,n),r=mv("elseBranch",e,t,n),a=mv("cond",e,t,n),i=mv("args",e,t,n);return(await a.data())[0]?n.functionMap[s].executeFunctionAsync(i,n.tensorArrayMap,n.tensorListMap):n.functionMap[r].executeFunctionAsync(i,n.tensorArrayMap,n.tensorListMap)}case"While":case"StatelessWhile":{const s=mv("body",e,t,n),r=mv("cond",e,t,n),a=mv("args",e,t,n),i=await n.functionMap[r].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[s].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[r].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[vv(mv("pred",e,t,n))];case"Switch":{const s=mv("pred",e,t,n);let r=mv("data",e,t,n);return r.kept||(r=vv(r)),(await s.data())[0]?[void 0,r]:[r,void 0]}case"Merge":{const s=e.inputNames.find((e=>void 0!==gv(e,t,n)));if(s){return[vv(gv(s,t,n))]}return}case"Enter":{const s=mv("frameName",e,t,n),r=mv("tensor",e,t,n);return n.enterFrame(s),[vv(r)]}case"Exit":{const s=mv("tensor",e,t,n);return n.exitFrame(),[vv(s)]}case"NextIteration":{const s=mv("tensor",e,t,n);return n.nextIteration(),[vv(s)]}case"TensorArrayV3":{const s=mv("size",e,t,n),r=mv("dtype",e,t,n),a=mv("elementShape",e,t,n),i=mv("dynamicSize",e,t,n),o=mv("clearAfterRead",e,t,n),l=mv("identicalElementShapes",e,t,n),u=mv("name",e,t,n),c=new ok(u,r,s,a,l,i,o);return n.addTensorArray(c),[c.idTensor,no(1)]}case"TensorArrayWriteV3":{const s=mv("tensorArrayId",e,t,n),r=mv("index",e,t,n),a=mv("tensor",e,t,n),i=n.getTensorArray(s.id);return i.write(r,a),[i.idTensor]}case"TensorArrayReadV3":{const s=mv("tensorArrayId",e,t,n),r=mv("index",e,t,n);return[n.getTensorArray(s.id).read(r)]}case"TensorArrayGatherV3":{const s=mv("tensorArrayId",e,t,n),r=mv("indices",e,t,n),a=mv("dtype",e,t,n);return[n.getTensorArray(s.id).gather(r,a)]}case"TensorArrayScatterV3":{const s=mv("tensorArrayId",e,t,n),r=mv("indices",e,t,n),a=mv("tensor",e,t,n),i=n.getTensorArray(s.id);return i.scatter(r,a),[i.idTensor]}case"TensorArrayConcatV3":{const s=mv("tensorArrayId",e,t,n),r=n.getTensorArray(s.id),a=mv("dtype",e,t,n);return[r.concat(a)]}case"TensorArraySplitV3":{const s=mv("tensorArrayId",e,t,n),r=mv("tensor",e,t,n),a=mv("lengths",e,t,n),i=n.getTensorArray(s.id);return i.split(a,r),[i.idTensor]}case"TensorArraySizeV3":{const s=mv("tensorArrayId",e,t,n);return[no(n.getTensorArray(s.id).size(),"int32")]}case"TensorArrayCloseV3":{const s=mv("tensorArrayId",e,t,n),r=n.getTensorArray(s.id);return r.clearAndClose(),[r.idTensor]}case"TensorListSetItem":{const s=mv("tensorListId",e,t,n),r=mv("index",e,t,n),a=mv("tensor",e,t,n),i=n.getTensorList(s.id);return i.setItem(r,a),[i.idTensor]}case"TensorListGetItem":{const s=mv("tensorListId",e,t,n),r=mv("index",e,t,n),a=mv("elementShape",e,t,n),i=mv("elementDType",e,t,n);return[n.getTensorList(s.id).getItem(r,a,i)]}case"TensorListScatterV2":case"TensorListScatter":{const s=mv("indices",e,t,n),r=function(e,t,n,s){if(t.length!==e.shape[0])throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${t.length} vs. ${e.shape[0]}`);const r=Math.max(...t);if(null!=s&&-1!==s&&r>=s)throw new Error(`Max index must be < array size (${r} vs. ${s})`);const a=new lk([],n,e.dtype,s),i=Qc(e,0);return t.forEach(((e,t)=>{a.setItem(e,i[t])})),a}(mv("tensor",e,t,n),s,mv("elementShape",e,t,n),mv("numElements",e,t,n));return n.addTensorList(r),[r.idTensor]}case"TensorListReserve":case"EmptyTensorList":{const s=mv("elementShape",e,t,n),r=mv("elementDType",e,t,n);let a;a="TensorListReserve"===e.op?"numElements":"maxNumElements";const i=mv(a,e,t,n),o=function(e,t,n,s){return new lk([],e,t,s)}(s,r,0,"TensorListReserve"===e.op?-1:i);return n.addTensorList(o),[o.idTensor]}case"TensorListGather":{const s=mv("tensorListId",e,t,n),r=mv("indices",e,t,n),a=mv("elementShape",e,t,n),i=mv("elementDType",e,t,n);return[n.getTensorList(s.id).gather(r,i,a)]}case"TensorListStack":{const s=mv("tensorListId",e,t,n),r=mv("elementShape",e,t,n),a=mv("elementDType",e,t,n),i=mv("numElements",e,t,n);return[n.getTensorList(s.id).stack(r,a,i)]}case"TensorListFromTensor":{const s=function(e,t,n){const s=e.dtype;if(e.shape.length<1)throw new Error(`Tensor must be at least a vector, but saw shape: ${e.shape}`);if(e.dtype!==n)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${n}`);sk(e.shape.slice(1),t,"TensorList shape mismatch: ");const r=Qc(e);return new lk(r,t,s)}(mv("tensor",e,t,n),mv("elementShape",e,t,n),mv("elementDType",e,t,n));return n.addTensorList(s),[s.idTensor]}case"TensorListConcat":case"TensorListConcatV2":{const s=mv("tensorListId",e,t,n),r=n.getTensorList(s.id),a=mv("dtype",e,t,n),i=mv("elementShape",e,t,n);return[r.concat(a,i)]}case"TensorListPushBack":{const s=mv("tensorListId",e,t,n),r=mv("tensor",e,t,n),a=n.getTensorList(s.id);return a.pushBack(r),[a.idTensor]}case"TensorListPopBack":{const s=mv("tensorListId",e,t,n),r=mv("elementShape",e,t,n),a=mv("elementDType",e,t,n);return[n.getTensorList(s.id).popBack(r,a)]}case"TensorListSplit":{const s=mv("tensor",e,t,n),r=mv("elementShape",e,t,n),a=function(e,t,n){let s=0;const r=t.map((e=>(s+=e,s)));if(s!==e.shape[0])throw new Error(`Expected sum of lengths to be equal to\n tensor.shape[0], but sum of lengths is\n ${s}, and tensor's shape is: ${e.shape}`);const a=ik(e.shape.slice(1),n),i=0===s?0:e.size/s,o=Zi((()=>{const n=[];e=_o(e,[1,s,i]);for(let s=0;se.dispose())),this.tensorMap.clear(),this.handle.dispose()}size(){return this.tensorMap.size}tensorSize(){return no(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(),Zi((()=>{const e=Qc(t),s=n.length,r=e.length;O(s===r,(()=>`The number of elements doesn't match, keys has ${s} elements, the values has ${r} elements.`));for(let t=0;t{const e=[];for(let s=0;s{switch(e.category){case"arithmetic":return r((()=>((e,t,n,s=T)=>{switch(e.op){case"BiasAdd":case"AddV2":case"Add":return[s.add(mv("a",e,t,n),mv("b",e,t,n))];case"AddN":return[s.addN(mv("tensors",e,t,n))];case"FloorMod":case"Mod":return[s.mod(mv("a",e,t,n),mv("b",e,t,n))];case"Mul":return[s.mul(mv("a",e,t,n),mv("b",e,t,n))];case"RealDiv":case"Div":return[s.div(mv("a",e,t,n),mv("b",e,t,n))];case"DivNoNan":return[s.divNoNan(mv("a",e,t,n),mv("b",e,t,n))];case"FloorDiv":return[s.floorDiv(mv("a",e,t,n),mv("b",e,t,n))];case"Sub":return[s.sub(mv("a",e,t,n),mv("b",e,t,n))];case"Minimum":return[s.minimum(mv("a",e,t,n),mv("b",e,t,n))];case"Maximum":return[s.maximum(mv("a",e,t,n),mv("b",e,t,n))];case"Pow":return[s.pow(mv("a",e,t,n),mv("b",e,t,n))];case"SquaredDifference":return[s.squaredDifference(mv("a",e,t,n),mv("b",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"basic_math":return r((()=>((e,t,n,s=T)=>{switch(e.op){case"Abs":case"ComplexAbs":return[s.abs(mv("x",e,t,n))];case"Acos":return[s.acos(mv("x",e,t,n))];case"Acosh":return[s.acosh(mv("x",e,t,n))];case"Asin":return[s.asin(mv("x",e,t,n))];case"Asinh":return[s.asinh(mv("x",e,t,n))];case"Atan":return[s.atan(mv("x",e,t,n))];case"Atan2":return[s.atan2(mv("x",e,t,n),mv("y",e,t,n))];case"Atanh":return[s.atanh(mv("x",e,t,n))];case"Ceil":return[s.ceil(mv("x",e,t,n))];case"Complex":return[s.complex(mv("real",e,t,n),mv("imag",e,t,n))];case"Cos":return[s.cos(mv("x",e,t,n))];case"Cosh":return[s.cosh(mv("x",e,t,n))];case"Elu":return[s.elu(mv("x",e,t,n))];case"Erf":return[s.erf(mv("x",e,t,n))];case"Exp":return[s.exp(mv("x",e,t,n))];case"Expm1":return[s.expm1(mv("x",e,t,n))];case"Floor":return[s.floor(mv("x",e,t,n))];case"Log":return[s.log(mv("x",e,t,n))];case"Log1p":return[s.log1p(mv("x",e,t,n))];case"Imag":return[s.imag(mv("x",e,t,n))];case"Neg":return[s.neg(mv("x",e,t,n))];case"Reciprocal":return[s.reciprocal(mv("x",e,t,n))];case"Real":return[s.real(mv("x",e,t,n))];case"Relu":return[s.relu(mv("x",e,t,n))];case"Round":return[s.round(mv("x",e,t,n))];case"Selu":return[s.selu(mv("x",e,t,n))];case"Sigmoid":return[s.sigmoid(mv("x",e,t,n))];case"Sin":return[s.sin(mv("x",e,t,n))];case"Sign":return[s.sign(mv("x",e,t,n))];case"Sinh":return[s.sinh(mv("x",e,t,n))];case"Softplus":return[s.softplus(mv("x",e,t,n))];case"Sqrt":return[s.sqrt(mv("x",e,t,n))];case"Square":return[s.square(mv("x",e,t,n))];case"Tanh":return[s.tanh(mv("x",e,t,n))];case"Tan":return[s.tan(mv("x",e,t,n))];case"ClipByValue":return[s.clipByValue(mv("x",e,t,n),mv("clipValueMin",e,t,n),mv("clipValueMax",e,t,n))];case"Relu6":return[s.relu6(mv("x",e,t,n))];case"Rsqrt":return[s.rsqrt(gv(e.inputNames[0],t,n))];case"Prod":return[s.prod(mv("x",e,t,n),mv("axes",e,t,n))];case"LeakyRelu":return[s.leakyRelu(mv("x",e,t,n),mv("alpha",e,t,n))];case"Prelu":return[s.prelu(mv("x",e,t,n),mv("alpha",e,t,n))];case"IsNan":return[s.isNaN(gv(e.inputNames[0],t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"control":return uk(e,t,n);case"convolution":return r((()=>((e,t,n,s=T)=>{switch(e.op){case"Conv1D":{const r=mv("stride",e,t,n),a=mv("pad",e,t,n),i=mv("dataFormat",e,t,n).toUpperCase(),o=mv("dilation",e,t,n);return[s.conv1d(mv("x",e,t,n),mv("filter",e,t,n),r,a,i,o)]}case"Conv2D":{const r=mv("strides",e,t,n),a=wv(e,t,n),i=mv("dataFormat",e,t,n).toUpperCase(),o=mv("dilations",e,t,n);return[s.conv2d(mv("x",e,t,n),mv("filter",e,t,n),[r[1],r[2]],a,i,[o[1],o[2]])]}case"_FusedConv2D":{const{stride:r,pad:a,dataFormat:i,dilations:o,biasArg:l,preluArg:u,activationFunc:c,leakyreluAlpha:h}=ck(e,t,n);return[s.fused.conv2d({x:mv("x",e,t,n),filter:mv("filter",e,t,n),strides:[r[1],r[2]],pad:a,dataFormat:i,dilations:[o[1],o[2]],bias:l,activation:c,preluActivationWeights:u,leakyreluAlpha:h})]}case"FusedDepthwiseConv2dNative":{const{stride:r,pad:a,dataFormat:i,dilations:o,biasArg:l,preluArg:u,activationFunc:c,leakyreluAlpha:h}=ck(e,t,n);return[s.fused.depthwiseConv2d({x:mv("x",e,t,n),filter:mv("filter",e,t,n),strides:[r[1],r[2]],pad:a,dataFormat:i,dilations:[o[1],o[2]],bias:l,activation:c,preluActivationWeights:u,leakyreluAlpha:h})]}case"Conv2DBackpropInput":case"Conv2dTranspose":{const r=mv("outputShape",e,t,n),a=mv("strides",e,t,n),i=wv(e,t,n);return[s.conv2dTranspose(mv("x",e,t,n),mv("filter",e,t,n),r,[a[1],a[2]],i)]}case"DepthwiseConv2dNative":case"DepthwiseConv2d":{const r=mv("strides",e,t,n),a=wv(e,t,n),i=mv("dilations",e,t,n),o=mv("dataFormat",e,t,n).toUpperCase();return[s.depthwiseConv2d(mv("input",e,t,n),mv("filter",e,t,n),[r[1],r[2]],a,o,[i[1],i[2]])]}case"Conv3D":{const r=mv("strides",e,t,n),a=mv("pad",e,t,n),i=mv("dataFormat",e,t,n).toUpperCase(),o=mv("dilations",e,t,n);return[s.conv3d(mv("x",e,t,n),mv("filter",e,t,n),[r[1],r[2],r[3]],a,i,[o[1],o[2],o[3]])]}case"AvgPool":{const r=mv("strides",e,t,n),a=mv("pad",e,t,n),i=mv("kernelSize",e,t,n);return[s.avgPool(mv("x",e,t,n),[i[1],i[2]],[r[1],r[2]],a)]}case"MaxPool":{const r=mv("strides",e,t,n),a=mv("pad",e,t,n),i=mv("kernelSize",e,t,n);return[s.maxPool(mv("x",e,t,n),[i[1],i[2]],[r[1],r[2]],a)]}case"MaxPoolWithArgmax":{const r=mv("strides",e,t,n),a=mv("pad",e,t,n),i=mv("kernelSize",e,t,n),o=mv("includeBatchInIndex",e,t,n),{result:l,indexes:u}=s.maxPoolWithArgmax(mv("x",e,t,n),[i[1],i[2]],[r[1],r[2]],a,o);return[l,u]}case"AvgPool3D":{const r=mv("strides",e,t,n),a=mv("pad",e,t,n),i=mv("kernelSize",e,t,n);return[s.avgPool3d(mv("x",e,t,n),[i[1],i[2],i[3]],[r[1],r[2],r[3]],a)]}case"MaxPool3D":{const r=mv("strides",e,t,n),a=mv("pad",e,t,n),i=mv("kernelSize",e,t,n);return[s.maxPool3d(mv("x",e,t,n),[i[1],i[2],i[3]],[r[1],r[2],r[3]],a)]}case"Dilation2D":{const r=mv("strides",e,t,n),a=mv("pad",e,t,n),i=mv("dilations",e,t,n),o=r[1],l=r[2],u=i[1],c=i[2];return[s.dilation2d(mv("x",e,t,n),mv("filter",e,t,n),[o,l],a,[u,c],"NHWC")]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"creation":return r((()=>((e,t,n,s=T)=>{switch(e.op){case"Fill":{const r=mv("shape",e,t,n),a=mv("dtype",e,t,n),i=mv("value",e,t,n);return[s.fill(r,i,a)]}case"LinSpace":{const r=mv("start",e,t,n),a=mv("stop",e,t,n),i=mv("num",e,t,n);return[s.linspace(r,a,i)]}case"Multinomial":{const r=mv("logits",e,t,n),a=mv("numSamples",e,t,n),i=mv("seed",e,t,n);return[s.multinomial(r,a,i)]}case"OneHot":{const r=mv("indices",e,t,n),a=mv("depth",e,t,n),i=mv("onValue",e,t,n),o=mv("offValue",e,t,n),l=mv("dtype",e,t,n);return[s.oneHot(r,a,i,o,l)]}case"Ones":return[s.ones(mv("shape",e,t,n),mv("dtype",e,t,n))];case"OnesLike":return[s.onesLike(mv("x",e,t,n))];case"RandomStandardNormal":return[s.randomStandardNormal(mv("shape",e,t,n),mv("dtype",e,t,n),mv("seed",e,t,n))];case"RandomUniform":return[s.randomUniform(mv("shape",e,t,n),mv("minval",e,t,n),mv("maxval",e,t,n),mv("dtype",e,t,n))];case"Range":{const r=mv("start",e,t,n),a=mv("stop",e,t,n),i=mv("step",e,t,n);return[s.range(r,a,i,mv("dtype",e,t,n))]}case"TruncatedNormal":{const r=mv("shape",e,t,n),a=mv("mean",e,t,n),i=mv("stdDev",e,t,n),o=mv("seed",e,t,n);return[s.truncatedNormal(r,a,i,mv("dtype",e,t,n),o)]}case"Zeros":return[s.zeros(mv("shape",e,t,n),mv("dtype",e,t,n))];case"ZerosLike":return[s.zerosLike(mv("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"dynamic":return(async(e,t,n,s,r=T)=>{switch(e.op){case"NonMaxSuppressionV5":{const{boxes:s,scores:a,maxOutputSize:i,iouThreshold:o,scoreThreshold:l,softNmsSigma:u}=hk(e,t,n),c=await r.image.nonMaxSuppressionWithScoreAsync(s,a,i,o,l,u);return[c.selectedIndices,c.selectedScores]}case"NonMaxSuppressionV4":{const{boxes:s,scores:a,maxOutputSize:i,iouThreshold:o,scoreThreshold:l}=hk(e,t,n),u=mv("padToMaxOutputSize",e,t,n),c=await r.image.nonMaxSuppressionPaddedAsync(s,a,i,o,l,u);return[c.selectedIndices,c.validOutputs]}case"NonMaxSuppressionV3":case"NonMaxSuppressionV2":{const{boxes:s,scores:a,maxOutputSize:i,iouThreshold:o,scoreThreshold:l}=hk(e,t,n);return[await r.image.nonMaxSuppressionAsync(s,a,i,o,l)]}case"Where":{const s=r.cast(mv("condition",e,t,n),"bool"),a=[await r.whereAsync(s)];return s.dispose(),a}case"ListDiff":return r.setdiff1dAsync(mv("x",e,t,n),mv("y",e,t,n));default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n);case"evaluation":return r((()=>((e,t,n,s=T)=>{switch(e.op){case"LowerBound":{const r=mv("sortedSequence",e,t,n),a=mv("values",e,t,n);return[s.lowerBound(r,a)]}case"TopKV2":{const r=mv("x",e,t,n),a=mv("k",e,t,n),i=mv("sorted",e,t,n),o=s.topk(r,a,i);return[o.values,o.indices]}case"UpperBound":{const r=mv("sortedSequence",e,t,n),a=mv("values",e,t,n);return[s.upperBound(r,a)]}case"Unique":{const r=mv("x",e,t,n),a=s.unique(r);return[a.values,a.indices]}case"UniqueV2":{const r=mv("x",e,t,n),a=mv("axis",e,t,n),i=s.unique(r,a);return[i.values,i.indices]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"image":return r((()=>((e,t,n,s=T)=>{switch(e.op){case"ResizeBilinear":{const r=mv("images",e,t,n),a=mv("size",e,t,n),i=mv("alignCorners",e,t,n),o=mv("halfPixelCenters",e,t,n);return[s.image.resizeBilinear(r,[a[0],a[1]],i,o)]}case"ResizeNearestNeighbor":{const r=mv("images",e,t,n),a=mv("size",e,t,n),i=mv("alignCorners",e,t,n),o=mv("halfPixelCenters",e,t,n);return[s.image.resizeNearestNeighbor(r,[a[0],a[1]],i,o)]}case"CropAndResize":{const r=mv("image",e,t,n),a=mv("boxes",e,t,n),i=mv("boxInd",e,t,n),o=mv("cropSize",e,t,n),l=mv("method",e,t,n),u=mv("extrapolationValue",e,t,n);return[s.image.cropAndResize(r,a,i,o,l,u)]}case"ImageProjectiveTransformV3":{const r=mv("images",e,t,n),a=mv("transforms",e,t,n),i=mv("outputShape",e,t,n),o=mv("fillValue",e,t,n),l=mv("interpolation",e,t,n),u=mv("fillMode",e,t,n);return[s.image.transform(r,a,l.toLowerCase(),u.toLowerCase(),o,i)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"graph":return r((()=>((e,t,n,s=T)=>{switch(e.op){case"Const":return t[e.name];case"PlaceholderWithDefault":const r=mv("default",e,t,n);return[gv(e.name,t,n)||r];case"Placeholder":return[gv(e.name,t,n)];case"Identity":case"StopGradient":case"FakeQuantWithMinMaxVars":case"Snapshot":return[vv(mv("x",e,t,n))];case"IdentityN":return mv("x",e,t,n).map((e=>vv(e)));case"Shape":return[s.tensor1d(mv("x",e,t,n).shape,"int32")];case"ShapeN":return mv("x",e,t,n).map((e=>s.tensor1d(e.shape)));case"Size":return[s.scalar(mv("x",e,t,n).size,"int32")];case"Rank":return[s.scalar(mv("x",e,t,n).rank,"int32")];case"NoOp":return[s.scalar(1)];case"Print":const a=mv("x",e,t,n),i=mv("data",e,t,n),o=mv("message",e,t,n),l=mv("summarize",e,t,n);console.warn("The graph has a tf.print() operation,usually used for debugging, which slows down performance."),console.log(o);for(let e=0;e((e,t,n,s=T)=>{switch(e.op){case"Equal":return[s.equal(mv("a",e,t,n),mv("b",e,t,n))];case"NotEqual":return[s.notEqual(mv("a",e,t,n),mv("b",e,t,n))];case"Greater":return[s.greater(mv("a",e,t,n),mv("b",e,t,n))];case"GreaterEqual":return[s.greaterEqual(mv("a",e,t,n),mv("b",e,t,n))];case"Less":return[s.less(mv("a",e,t,n),mv("b",e,t,n))];case"LessEqual":return[s.lessEqual(mv("a",e,t,n),mv("b",e,t,n))];case"LogicalAnd":return[s.logicalAnd(mv("a",e,t,n),mv("b",e,t,n))];case"LogicalNot":return[s.logicalNot(mv("a",e,t,n))];case"LogicalOr":return[s.logicalOr(mv("a",e,t,n),mv("b",e,t,n))];case"Select":case"SelectV2":return[s.where(mv("condition",e,t,n),mv("a",e,t,n),mv("b",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"matrices":return r((()=>((e,t,n,s=T)=>{switch(e.op){case"BatchMatMul":case"BatchMatMulV2":case"MatMul":return[s.matMul(mv("a",e,t,n),mv("b",e,t,n),mv("transposeA",e,t,n),mv("transposeB",e,t,n))];case"Einsum":return[s.einsum(mv("equation",e,t,n),...mv("tensors",e,t,n))];case"Transpose":return[s.transpose(mv("x",e,t,n),mv("perm",e,t,n))];case"_FusedMatMul":const[r,a]=mv("fusedOps",e,t,n),i="biasadd"===r,o="prelu"===a,l=mv("numArgs",e,t,n),u=mv("leakyreluAlpha",e,t,n);if(i){if(o&&2!==l)throw new Error("Fused MatMul with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!o&&1!==l)throw new Error("Fused MatMul with BiasAdd must have one extra argument: bias.")}const[c,h]=mv("args",e,t,n);return[s.fused.matMul({a:mv("a",e,t,n),b:mv("b",e,t,n),transposeA:mv("transposeA",e,t,n),transposeB:mv("transposeB",e,t,n),bias:c,activation:a,preluActivationWeights:h,leakyreluAlpha:u})];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"normalization":return r((()=>((e,t,n,s=T)=>{switch(e.op){case"EuclideanNorm":return[s.euclideanNorm(mv("x",e,t,n),mv("axis",e,t,n),mv("keepDims",e,t,n))];case"FusedBatchNorm":case"FusedBatchNormV2":case"FusedBatchNormV3":return[s.batchNorm(mv("x",e,t,n),mv("mean",e,t,n),mv("variance",e,t,n),mv("offset",e,t,n),mv("scale",e,t,n),mv("epsilon",e,t,n))];case"LRN":return[s.localResponseNormalization(mv("x",e,t,n),mv("radius",e,t,n),mv("bias",e,t,n),mv("alpha",e,t,n),mv("beta",e,t,n))];case"Softmax":return[s.softmax(mv("x",e,t,n))];case"LogSoftmax":return[s.logSoftmax(mv("x",e,t,n))];case"SparseToDense":return[s.sparseToDense(mv("sparseIndices",e,t,n),mv("outputShape",e,t,n),mv("sparseValues",e,t,n),mv("defaultValue",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"reduction":return r((()=>((e,t,n,s=T)=>{switch(e.op){case"Max":{const r=mv("axis",e,t,n),a=mv("keepDims",e,t,n);return[s.max(mv("x",e,t,n),r,a)]}case"Mean":{const r=mv("axis",e,t,n),a=mv("keepDims",e,t,n);return[s.mean(mv("x",e,t,n),r,a)]}case"Min":{const r=mv("axis",e,t,n),a=mv("keepDims",e,t,n);return[s.min(mv("x",e,t,n),r,a)]}case"Sum":{const r=mv("axis",e,t,n),a=mv("keepDims",e,t,n);return[s.sum(mv("x",e,t,n),r,a)]}case"All":{const r=mv("axis",e,t,n),a=mv("keepDims",e,t,n);return[s.all(mv("x",e,t,n),r,a)]}case"Any":{const r=mv("axis",e,t,n),a=mv("keepDims",e,t,n);return[s.any(mv("x",e,t,n),r,a)]}case"ArgMax":{const r=mv("axis",e,t,n);return[s.argMax(mv("x",e,t,n),r)]}case"ArgMin":{const r=mv("axis",e,t,n);return[s.argMin(mv("x",e,t,n),r)]}case"Prod":{const r=mv("axis",e,t,n),a=mv("keepDims",e,t,n);return[s.prod(mv("x",e,t,n),r,a)]}case"Cumprod":{const r=mv("axis",e,t,n),a=mv("exclusive",e,t,n),i=mv("reverse",e,t,n);return[s.cumprod(mv("x",e,t,n),r,a,i)]}case"Cumsum":{const r=mv("axis",e,t,n),a=mv("exclusive",e,t,n),i=mv("reverse",e,t,n);return[s.cumsum(mv("x",e,t,n),r,a,i)]}case"Bincount":const r=mv("x",e,t,n),a=mv("weights",e,t,n),i=mv("size",e,t,n);return[s.bincount(r,a,i)];case"DenseBincount":{const r=mv("x",e,t,n),a=mv("weights",e,t,n),i=mv("size",e,t,n),o=mv("binaryOutput",e,t,n);return[s.denseBincount(r,a,i,o)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"slice_join":return r((()=>((e,t,n,s=T)=>{switch(e.op){case"ConcatV2":case"Concat":{const r=mv("n",e,t,n),a=mv("axis",e,t,n);let i=mv("tensors",e,t,n);return i=i.slice(0,r),[s.concat(i,a)]}case"Gather":{const r=mv("x",e,t,n),a=mv("indices",e,t,n);return[s.gather(r,s.cast(a,"int32"),0)]}case"GatherV2":{const r=mv("axis",e,t,n),a=mv("batchDims",e,t,n),i=mv("x",e,t,n),o=mv("indices",e,t,n);return[s.gather(i,s.cast(o,"int32"),r,a)]}case"Reverse":{const r=mv("dims",e,t,n),a=[];for(let e=0;e{const r=mv("axis",e,t,n),a=mv("tensors",e,t,n),i=a[0].shape,o=s.squeeze(a[0]).shape,l=a.map((e=>{const t=B(e.shape,i);if(!t&&!B(s.squeeze(e).shape,o))throw new Error("the input tensors shape does not match");return t?e:s.reshape(e,i)}));return[s.stack(l,r)]}));case"Unpack":{const r=mv("axis",e,t,n),a=mv("tensor",e,t,n);return s.unstack(a,r)}case"Tile":{const r=mv("reps",e,t,n);return[s.tile(mv("x",e,t,n),r)]}case"Split":case"SplitV":{const r=mv("axis",e,t,n),a=mv("numOrSizeSplits",e,t,n),i=mv("x",e,t,n);return s.split(i,a,r)}case"ScatterNd":{const r=mv("indices",e,t,n),a=mv("values",e,t,n),i=mv("shape",e,t,n);return[s.scatterND(r,a,i)]}case"GatherNd":{const r=mv("x",e,t,n),a=mv("indices",e,t,n);return[s.gatherND(r,a)]}case"SparseToDense":{const r=mv("sparseIndices",e,t,n),a=mv("outputShape",e,t,n),i=mv("sparseValues",e,t,n),o=mv("defaultValue",e,t,n);return[s.sparseToDense(r,i,a,i.dtype===o.dtype?o:s.cast(o,i.dtype))]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"sparse":return r((()=>((e,t,n,s=T)=>{switch(e.op){case"SparseFillEmptyRows":{const{outputIndices:r,outputValues:a,emptyRowIndicator:i,reverseIndexMap:o}=s.sparse.sparseFillEmptyRows(mv("indices",e,t,n),mv("values",e,t,n),mv("denseShape",e,t,n),mv("defaultValue",e,t,n));return[r,a,i,o]}case"SparseReshape":{const{outputIndices:r,outputShape:a}=s.sparse.sparseReshape(mv("inputIndices",e,t,n),mv("inputShape",e,t,n),mv("newShape",e,t,n));return[r,a]}case"SparseSegmentMean":return[s.sparse.sparseSegmentMean(mv("data",e,t,n),mv("indices",e,t,n),mv("segmentIds",e,t,n))];case"SparseSegmentSum":return[s.sparse.sparseSegmentSum(mv("data",e,t,n),mv("indices",e,t,n),mv("segmentIds",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"spectral":return r((()=>((e,t,n,s=T)=>{switch(e.op){case"FFT":return[s.fft(mv("x",e,t,n))];case"IFFT":return[s.ifft(mv("x",e,t,n))];case"RFFT":return[s.rfft(mv("x",e,t,n))];case"IRFFT":return[s.irfft(mv("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"string":return r((()=>((e,t,n,s=T)=>{switch(e.op){case"StringNGrams":{const{nGrams:r,nGramsSplits:a}=s.string.stringNGrams(mv("data",e,t,n),mv("dataSplits",e,t,n),mv("separator",e,t,n),mv("nGramWidths",e,t,n),mv("leftPad",e,t,n),mv("rightPad",e,t,n),mv("padWidth",e,t,n),mv("preserveShortSequences",e,t,n));return[r,a]}case"StringSplit":{const{indices:r,values:a,shape:i}=s.string.stringSplit(mv("input",e,t,n),mv("delimiter",e,t,n),mv("skipEmpty",e,t,n));return[r,a,i]}case"StringToHashBucketFast":return[s.string.stringToHashBucketFast(mv("input",e,t,n),mv("numBuckets",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"transformation":return r((()=>((e,t,n,s=T)=>{switch(e.op){case"Cast":return[s.cast(mv("x",e,t,n),mv("dtype",e,t,n))];case"ExpandDims":{const r=mv("axis",e,t,n);return[s.expandDims(mv("x",e,t,n),r)]}case"Squeeze":{const r=mv("axis",e,t,n);return[s.squeeze(mv("x",e,t,n),r)]}case"Reshape":return[s.reshape(mv("x",e,t,n),mv("shape",e,t,n))];case"MirrorPad":return[s.mirrorPad(mv("x",e,t,n),mv("padding",e,t,n),mv("mode",e,t,n))];case"PadV2":case"Pad":return[s.pad(mv("x",e,t,n),mv("padding",e,t,n),mv("constantValue",e,t,n))];case"SpaceToBatchND":{const r=mv("blockShape",e,t,n),a=mv("paddings",e,t,n);return[s.spaceToBatchND(mv("x",e,t,n),r,a)]}case"BatchToSpaceND":{const r=mv("blockShape",e,t,n),a=mv("crops",e,t,n);return[s.batchToSpaceND(mv("x",e,t,n),r,a)]}case"DepthToSpace":{const r=mv("blockSize",e,t,n),a=mv("dataFormat",e,t,n).toUpperCase();return[s.depthToSpace(mv("x",e,t,n),r,a)]}case"BroadcastTo":return[s.broadcastTo(mv("x",e,t,n),mv("shape",e,t,n))];case"BroadcastArgs":return[s.broadcastArgs(mv("s0",e,t,n),mv("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,s)=>{switch(e.op){case"HashTable":case"HashTableV2":{const r=mv("keyDType",e,t,n),a=mv("valueDType",e,t,n),i=new pk(r,a);return s.addHashTable(e.name,i),[i.handle]}case"LookupTableImport":case"LookupTableImportV2":{const r=mv("tableHandle",e,t,n,s),a=mv("keys",e,t,n),i=mv("values",e,t,n),o=s.getHashTableById(r.id);return[await o.import(a,i)]}case"LookupTableFind":case"LookupTableFindV2":{const r=mv("tableHandle",e,t,n,s),a=mv("keys",e,t,n),i=mv("defaultValue",e,t,n),o=s.getHashTableById(r.id);return[await o.find(a,i)]}case"LookupTableSize":case"LookupTableSizeV2":{const r=mv("tableHandle",e,t,n,s);return[s.getHashTableById(r.id).tensorSize()]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n,s);case"custom":const a=fv(e.op);if(a&&a.customExecutor)return a.customExecutor(new nk(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 de(a)?a.then((e=>[].concat(e))):[].concat(a)}class fk{constructor(e={},t={},n={},s={}){this.weightMap=e,this.tensorArrayMap=t,this.tensorListMap=n,this.functionMap=s,this.rootContext={id:0,frameName:"",iterationId:0},this.contexts=[this.rootContext],this.lastId=0,this.generateCurrentContextIds()}newFrame(e,t){return{id:e,frameName:t,iterationId:0}}set currentContext(e){this.contexts!==e&&(this.contexts=e,this.generateCurrentContextIds())}get currentContext(){return this.contexts}get currentContextId(){return this._currentContextIds[0]}get currentContextIds(){return this._currentContextIds}generateCurrentContextIds(){const e=[];for(let t=0;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)}} +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function mk(e,t,n,s){const r=new Set,a=[];let i=null,o=null;const l=new Set,u=Object.keys(e).map((e=>xv(e)[0]));let c=[];null!=s&&(c=s.map((e=>xv(e.name)[0])));const h=[...t];for(;h.length>0;){const e=h.pop();(xk(e)||wk(e)||vk(e))&&null==i&&(i=e,o=i.children.map((e=>e.name)).filter((e=>r.has(e)))),r.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:r,missingInputs:a,dynamicNode:i,syncInputs:o}}const gk=["Switch","Merge","Enter","Exit","NextIteration","StatelessIf","StatelessWhile","if","While"],yk=["NonMaxSuppressionV2","NonMaxSuppressionV3","NonMaxSuppressionV5","Where"],bk=["HashTable","HashTableV2","LookupTableImport","LookupTableImportV2","LookupTableFind","LookupTableFindV2","LookupTableSize","LookupTableSizeV2"];function xk(e){return gk.indexOf(e.op)>=0}function wk(e){return yk.indexOf(e.op)>=0}function vk(e){return bk.indexOf(e.op)>=0} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class kk{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 kk(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(),s=t.map((e=>e.name)).sort();return n.join(this.SEPERATOR)+"--"+s.join(this.SEPERATOR)}compile(e,t){const n=mk(e,t,this.weightMap,this._initNodes),{missingInputs:s,dynamicNode:r,syncInputs:a}=n;if(null!=r)throw new Error(`This execution contains the node '${r.name}', which has the dynamic op '${r.op}'. Please use model.executeAsync() instead. Alternatively, to avoid the dynamic ops, specify the inputs [${a}]`);if(s.length>0){const n=t.map((e=>e.name)),r=Object.keys(e);throw new Error(`Cannot compute the outputs [${n}] from the provided inputs [${r}]. Missing the following inputs: [${s}]`)}return function(e,t,n){const{usedNodes:s,inputs:r}=n,a=[],i=Object.keys(r).map((e=>xv(e)[0])).map((t=>e.nodes[t])),o=e.initNodes;i.forEach((e=>{s.has(e.name)&&a.push(e)})),e.weights.forEach((e=>{s.has(e.name)&&a.push(e)})),null!=o&&o.forEach((e=>{s.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)&&s.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 s=n.map((e=>this.graph.nodes[xv(e)[0]])),r=t.map((e=>xv(e)[0]));let a=r.map((e=>this.graph.nodes[e]));this.resetIntermediateTensors(),0===a.length&&(a=this._outputs);const i=this.getCompilationKey(s,a);let o=this.compiledMap.get(i);null==o&&(o=this.compile(e,a),this.compiledMap.set(i,o));const l={},u={};return Zi((()=>{const n=new fk(this.weightMap,l,u,this.functionExecutorMap),s=Object.assign({},this.weightMap);Object.keys(e).forEach((t=>{const[n,r]=xv(t),a=[];a[r]=e[t],s[n]=a}));const a=this.getFrozenTensorIds(s),i={};for(let e=0;egv(e,s,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,s,r,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[bv(e,n.currentContextId)]}(e.name,n,s);null!=a&&a.forEach((e=>{if(e&&!e.kept&&!r.has(e.id)){const n=i[e.id];if(1===n){if(this.keepTensorForDebug){const[n,r]=yv(t.name,s);this.intermediateTensors[n]||(this.intermediateTensors[n]=[]),this.intermediateTensors[n][r]=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,s={},r={}){n||(e=this.mapInputs(e),this.checkInputs(e),this.checkInputShapeAndType(e),t=this.mapOutputs(t),this.checkOutputs(t));try{this.keepTensorForDebug=ye().getBool("KEEP_INTERMEDIATE_TENSORS")}catch(e){console.warn(e.message)}this.resetIntermediateTensors();const a=new fk(this.weightMap,s,r,this.functionExecutorMap);this.tensorsMap=await this.executeWithControlFlow(e,a,t,n);const i=t.map((e=>gv(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 s=e.reduce(((e,t,n)=>(e[this.inputs[n].name]=t,e)),{});return this._executeAsync(s,this.outputNodes,!0,t,n)}async executeWithControlFlow(e,t,n,s){const r=Object.keys(e),a=r.map((e=>this.graph.nodes[xv(e)[0]])),i=n.map((e=>xv(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}=mk(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,s]=xv(t),r=[];r[s]=e[t],d[n]=r}));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||s||console.warn("This model execution did not contain any nodes with control flow or dynamic output shapes. You can use model.execute() instead.");const y=o.filter((e=>!xk(e)&&!gv(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 [${r}]. Consider providing the following inputs: [${u}]. ${e}`)}return d}processStack(e,t,n,s,r,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&&mv("isConstant",e.node,s,n)&&([c]=yv(e.node.name,n)),null==s[e.node.name]){const h=dk(e.node,s,n,this._resourceManager);c||([c]=yv(e.node.name,n));const p=n.currentContext;de(h)?u.push(h.then((u=>(s[c]=u,n.currentContext=p,this.checkTensorForDisposal(c,e.node,s,n,a,i,o),this.processChildNodes(e.node,t,n,s,r,l),u)))):(s[c]=h,this.checkTensorForDisposal(c,e.node,s,n,a,i,o),this.processChildNodes(e.node,t,n,s,r,l))}else this.processChildNodes(e.node,t,n,s,r,l)}return u}processChildNodes(e,t,n,s,r,a){e.children.forEach((e=>{const[i]=yv(e.name,n);!r[i]&&a.has(e.name)&&("Merge"===e.op?e.inputNames.some((e=>!!gv(e,s,n)))&&(r[i]=!0,t.push({contexts:n.currentContext,node:e})):e.inputNames.every((e=>!!gv(e,s,n)))&&(r[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],[s]=xv(t),r=this.graph.nodes[s];if(r.attrParams.shape&&r.attrParams.shape.value){const e=r.attrParams.shape.value;O(e.length===n.shape.length&&n.shape.every(((t,n)=>-1===e[n]||e[n]===t)),(()=>`The shape of dict['${r.name}'] provided in model.execute(dict) must be [${e}], but was [${n.shape}]`))}r.attrParams.dtype&&r.attrParams.dtype.value&&O(n.dtype===r.attrParams.dtype.value,(()=>`The dtype of dict['${r.name}'] provided in model.execute(dict) must be ${r.attrParams.dtype.value}, but was ${n.dtype}`))}))}mapInputs(e){const t={};for(const n in e)if(null!=this._signature&&null!=this._signature.inputs&&null!=this._signature.inputs[n]){t[this._signature.inputs[n].name]=e[n]}else t[n]=e[n];return t}checkInputs(e){const t=Object.keys(e).filter((e=>{const[t]=xv(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=>{if(null!=this._signature&&null!=this._signature.outputs&&null!=this._signature.outputs[e]){return this._signature.outputs[e].name}return e}),{})}checkOutputs(e){e.forEach((e=>{const[t]=xv(e);if(!this.graph.nodes[t])throw new Error(`The output '${e}' is not found in the graph`)}))}}class Ik{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]}} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +const Nk="?tfjs-format=file",Sk="model.json";class Tk{constructor(t,n={},s=e){this.modelUrl=t,this.loadOptions=n,this.version="n/a",this.io=s,null==n&&(this.loadOptions={}),this.resourceManager=new Ik}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}get modelStructuredOutputKeys(){return this.structuredOutputKeys}findIOHandler(){const e=this.modelUrl;if(null!=e.load)this.handler=e;else if(null!=this.loadOptions.requestInit)this.handler=this.io.browserHTTPRequest(e,this.loadOptions);else{const t=this.io.getLoadHandlers(e,this.loadOptions);if(0===t.length)t.push(this.io.browserHTTPRequest(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]}}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=this.handler.load();return de(e)?e.then((e=>this.loadSync(e))):this.loadSync(e)}loadSync(e){this.artifacts=e;const t=this.artifacts.modelTopology;let n=this.artifacts.signature;if(null!=this.artifacts.userDefinedMetadata){const e=this.artifacts.userDefinedMetadata;null!=e.signature&&(n=e.signature),null!=e.structuredOutputKeys&&(this.structuredOutputKeys=e.structuredOutputKeys)}this.signature=n,this.version=`${t.versions.producer}.${t.versions.minConsumer}`;const s=this.io.decodeWeights(this.artifacts.weightData,this.artifacts.weightSpecs);if(this.executor=new kk(Wv.Instance.transformGraph(t,this.signature)),this.executor.weightMap=this.convertTensorMapToTensorsMap(s),this.executor.resourceManager=this.resourceManager,null!=e.modelInitializer&&null!=e.modelInitializer.node){const t=Wv.Instance.transformGraph(e.modelInitializer);this.initializer=new kk(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=this.io.getSaveHandlers(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){const n=this.execute(e,this.outputNodes);if(this.structuredOutputKeys){const e={};return(n instanceof gr?[n]:n).forEach(((t,n)=>e[this.structuredOutputKeys[n]]=t)),e}return n}normalizeInputs(e){if(!(e instanceof gr||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,s)=>(t[n]=e[s],t)),{})}normalizeOutputs(e){return e=e||this.outputNodes,Array.isArray(e)?e:[e]}execute(e,t){e=this.normalizeInputs(e),t=this.normalizeOutputs(t);const n=this.executor.execute(e,t);return n.length>1?n:n[0]}async executeAsync(e,t){e=this.normalizeInputs(e),t=this.normalizeOutputs(t);const n=await this.executor.executeAsync(e,t);return n.length>1?n:n[0]}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 Ck(t,n={},s=e){if(null==t)throw new Error("modelUrl in loadGraphModel() cannot be null. Please provide a url or an IOHandler that loads the model");null==n&&(n={}),n.fromTFHub&&"string"==typeof t&&(t=function(e){e.endsWith("/")||(e+="/");return`${e}${Sk}${Nk}`}(t));const r=new Tk(t,n,s);return await r.load(),r}function $k(e,t,n=new Map,s=new Set){if(null==e)return null;if("function"==typeof Blob&&e instanceof Blob)return e.slice();if(s.has(e))throw new Error("Circular references are not supported.");if(n.has(e))return n.get(e);const r=t(e);if(r.recurse&&null!==r.value)throw new Error("A deep map function may not return both a value and recurse=true.");if(r.recurse){if(Fk(e)){const r=Array.isArray(e)?[]:{};s.add(e);for(const a in e){const i=$k(e[a],t,n,s);r[a]=i}return s.delete(e),e.__proto__&&(r.__proto__=e.__proto__),r}throw new Error(`Can't recurse into non-iterable type: ${e}`)}return n.set(e,r.value),r.value}function Ek(e,t=Ak){return Rk(e,t)}function Rk(e,t,n=new Set){const s=e[0];if(n.has(s))throw new Error("Circular references are not supported.");const r=t(e);if(r.recurse&&null!==r.value)throw new Error("A deep zip function may not return both a value and recurse=true.");if(r.recurse){if(Fk(s)){const r=Array.isArray(s)?[]:{};n.add(s);for(const a in s){const s=e.map((e=>e[a])),i=Rk(s,t,n);r[a]=i}return n.delete(s),r}throw new Error(`Can't recurse into non-iterable type: ${s}`)}return r.value}function Ak(e){return null===e?null:Fk(e[0])?{value:null,recurse:!0}:{value:e,recurse:!1}}function Fk(e){let t=!1;if(ye().get("IS_BROWSER"))t=e instanceof TextDecoder;else{const{StringDecoder:s}=n(551);t=e instanceof s}return null!=e&&!ArrayBuffer.isView(e)&&(Array.isArray(e)||"object"==typeof e&&!(e instanceof gr)&&!(e instanceof Promise)&&!t)} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============================================================================= + */ +function _k(e){ +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============================================================================= + */ +return function(e,t){return $k(e,t)}(e,Dk)}function Dk(e){return e instanceof gr?{value:e.clone(),recurse:!1}:Fk(e)?{value:null,recurse:!0}:{value:e,recurse:!1}} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============================================================================= + */ +class Ok{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}} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============================================================================= + */ +class Mk extends Ok{constructor(){super(Mk.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 Hk(this,e,t)}columnMajorBatch(e,t=!0,n=Ak){return this.rowMajorBatch(e,t).map((e=>Ek(e,n)))}concatenate(e,t){return new Jk(new Bk([this,e]),t)}take(e){return e<0||null==e?this:new Gk(this,e)}skip(e){return e<0||null==e?this:new Uk(this,e)}prefetch(e){return new eI(this,e)}shuffle(e,t){return new tI(this,e,t)}serial(){return new Vk(this)}}class Bk extends Pk{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:_k(e),done:!1}}}class Wk extends Pk{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 Vk extends Pk{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 Uk extends Pk{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 Hk extends Pk{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 jk extends Pk{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;Ji(e.value)}}}class qk extends Pk{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=Er(e.value),n=this.transform(e.value),s=Er(n);for(const e of t)$r(e,s)||e.dispose();return{value:n,done:!1}}}class Kk extends Pk{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 Xk extends Pk{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=Er(e.value),n=await this.transform(e.value),s=Er(n);for(const e of t)$r(e,s)||e.dispose();return{value:n,done:!1}}}class Yk extends Pk{constructor(){super(),this.outputQueue=new Mk,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 Zk extends Yk{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=Er(e.value),n=this.transform(e.value),s=Er(n);this.outputQueue.pushAll(n);for(const e of t)$r(e,s)||e.dispose();return!0}}class Jk extends Pk{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 Qk;!function(e){e[e.FAIL=0]="FAIL",e[e.SHORTEST=1]="SHORTEST",e[e.LONGEST=2]="LONGEST"}(Qk||(Qk={}));class eI extends Pk{constructor(e,t){super(),this.upstream=e,this.bufferSize=t,this.buffer=new Ok(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 tI extends eI{constructor(e,t,n){super(e,t),this.upstream=e,this.windowSize=t,this.upstreamExhausted=!1,this.random=nc.alea(n||tr().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}}} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============================================================================= + */ +class nI{constructor(){this.size=null}batch(e,t=!0){const n=this;let s;return O(e>0,(()=>`batchSize needs to be positive, but it is\n ${e}`)),s=this.size===1/0||null==this.size?this.size:t?Math.ceil(this.size/e):Math.floor(this.size/e),sI((async()=>(await n.iterator()).columnMajorBatch(e,t,rI)),s)}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,sI((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,sI((async()=>(await t.iterator()).filter((t=>Zi((()=>e(t)))))),n)}async forEachAsync(e){return(await this.iterator()).forEachAsync(e)}map(e){const t=this;return sI((async()=>(await t.iterator()).map((t=>Zi((()=>e(t)))))),this.size)}mapAsync(e){const t=this;return sI((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 sI((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,sI((async()=>zk(Lk((async()=>({value:await t.iterator(),done:!1}))).take(e))),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 s=this,r=nc.alea(t||tr().toString());return sI((async()=>{let t=r.int32();return n&&(t+=r.int32()),(await s.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,sI((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 sI(e,t=null){return new class extends nI{constructor(){super(...arguments),this.size=t}async iterator(){return e()}}}function rI(e){if(null===e)return null;const t=e[0];if(null==(n=t)||null===(s=n)||"object"!=typeof s&&"function"!=typeof s||Array.isArray(n)||"object"==typeof n&&n instanceof gr||Z(n)){return{value:function(e){if(0===e.length)throw new Error("Can't make a batch of zero elements.");return e[0]instanceof gr?Bc(e):Yr(e)}(e),recurse:!1}}var n,s;return{value:null,recurse:!0}}nI.MAX_BUFFER_SIZE=1e4; +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============================================================================= + */ +Symbol("out"),Symbol("field"),Symbol("quote"),Symbol("quoteafterquote"),Symbol("quoteinquote"); +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function aI(e,t){Array.isArray(e)||(e=[e]),e.forEach((e=>{null!=e&&O("complex64"!==e.dtype,(()=>`${t} does not support complex64 tensors in the CPU backend.`))}))} +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +const iI=nh;class oI extends E{constructor(){super(),this.blockSize=48,this.firstUse=!0,this.data=new $(this,Xi())}nextDataId(){return oI.nextDataId++}write(e,t,n){this.firstUse&&(this.firstUse=!1,ye().get("IS_NODE")&&Es("\n============================\nHi, looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, visit https://github.com/tensorflow/tfjs-node for more details. \n============================"));const s={id:this.nextDataId()};return this.data.set(s,{values:e,dtype:n,refCount:1}),s}makeTensorInfo(e,t,n){let s;if("string"===t&&null!=n&&n.length>0&&Q(n[0])){const r=n.map((e=>nr(e)));s=this.write(r,e,t)}else s=this.write(n,e,t);return{dataId:s,shape:e,dtype:t}}refCount(e){if(this.data.has(e)){return this.data.get(e).refCount}return 0}incRef(e){this.data.get(e).refCount++}decRef(e){if(this.data.has(e)){this.data.get(e).refCount--}}move(e,t,n,s,r){this.data.set(e,{values:t,dtype:s,refCount:r})}numDataIds(){return this.data.numDataIds()}async read(e){return this.readSync(e)}readSync(e){const{dtype:t,complexTensorInfos:n}=this.data.get(e);if("complex64"===t){return cd(this.readSync(n.real.dataId),this.readSync(n.imag.dataId))}return this.data.get(e).values}bufferSync(e){const t=this.readSync(e.dataId);if("string"===e.dtype)try{const n=t.map((e=>sr(e)));return Ya(e.shape,e.dtype,n)}catch(e){throw new Error("Failed to decode encoded string bytes into utf-8")}return Ya(e.shape,e.dtype,t)}makeOutput(e,t,n){return Xi().makeTensorFromTensorInfo(this.makeTensorInfo(t,n,e),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=tr();e();return{kernelMs:tr()-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){aI([e],"where");const t=this.readSync(e.dataId);return iI(e.shape,t)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}}oI.nextDataId=0; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function lI(e,t,n){return({inputs:s,attrs:r,backend:a})=>{const{x:i}=s;if(aI(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=P(i.shape),c=n||i.dtype,h=X(c,u);for(let e=0;e{const{x:i}=s;if(aI(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,r);return o.makeTensorInfo(i.shape,u,c)}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +eo("cpu",(()=>new oI),1); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +const cI=lI(bt,(e=>e>=0?e:Math.exp(e)-1)),hI={kernelName:bt,backendName:"cpu",kernelFunc:cI}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function pI(e){const{inputs:t,backend:n}=e,{x:s}=t;return n.incRef(s.dataId),{dataId:s.dataId,shape:s.shape,dtype:s.dtype}}const dI={kernelName:Ot,backendName:"cpu",kernelFunc:pI}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function fI(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{alpha:a}=s;aI([r],"leakyRelu");const i=P(r.shape),o=n.data.get(r.dataId).values,l=K("float32",i);for(let e=0;e{const i=ki(t,n),o=i.length,l=re(i),u=K(a,P(i)),c=t.length,h=n.length,p=re(t),d=re(n),f=wi(t,i),m=wi(n,i);if(f.length+m.length===0)for(let t=0;ta[e]=0));const i=he(a,c,p),g=n.slice(-h);m.forEach((e=>g[e]=0));const y=he(g,h,d);u[t]=e(s[i],r[y])}return[u,i]}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +const yI=gI(((e,t)=>e<0?t*e:e));function bI(e){const{inputs:t,backend:n}=e,{x:s,alpha:r}=t;aI([s,r],"prelu");const a=n.data.get(s.dataId).values,i=n.data.get(r.dataId).values,[o,l]=yI(s.shape,r.shape,a,i,"float32");return n.makeTensorInfo(l,"float32",o)}const xI={kernelName:In,backendName:"cpu",kernelFunc:bI},wI=lI(Rn,(e=>Math.max(0,e))),vI={kernelName:Rn,backendName:"cpu",kernelFunc:wI},kI=lI(Mn,(e=>Math.min(Math.max(0,e),6))),II={kernelName:Mn,backendName:"cpu",kernelFunc:kI}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function NI(e){return(t,n,s)=>{const r=K(n,t.length);for(let n=0;n1/(1+Math.exp(-e)))),TI=lI(Kn,(e=>1/(1+Math.exp(-e)))),CI={kernelName:Kn,backendName:"cpu",kernelFunc:TI}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function $I(e,t,n,s,r){if("linear"===n)return pI({inputs:{x:t},backend:e});if("relu"===n)return wI({inputs:{x:t},backend:e});if("elu"===n)return cI({inputs:{x:t},backend:e});if("relu6"===n)return kI({inputs:{x:t},backend:e});if("prelu"===n)return bI({inputs:{x:t,alpha:s},backend:e});if("leakyrelu"===n)return fI({inputs:{x:t},backend:e,attrs:{alpha:r}});if("sigmoid"===n)return TI({inputs:{x:t},backend:e});throw new Error(`Activation ${n} has not been implemented for the CPU backend.`)} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function EI(e){const{inputs:t,backend:n}=e,{real:s,imag:r}=t,a=n.data.get(s.dataId).values,i=n.data.get(r.dataId).values,o=n.makeTensorInfo(s.shape,"complex64");return n.data.get(o.dataId).complexTensorInfos={real:n.makeTensorInfo(s.shape,"float32",a),imag:n.makeTensorInfo(r.shape,"float32",i)},o}const RI={kernelName:qe,backendName:"cpu",kernelFunc:EI}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function AI(e,t,n="float32"){if("complex64"===n){return EI({inputs:{real:AI(e,t,"float32"),imag:AI(e,t,"float32")},backend:e})}const s=le(P(t),n);return e.makeTensorInfo(t,n,s)} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function FI(e){const{inputs:t,backend:n}=e,{input:s}=t,r=n.data.get(s.dataId).complexTensorInfos.real,a=n.data.get(r.dataId).values;return n.makeTensorInfo(r.shape,r.dtype,a)}const _I={kernelName:$n,backendName:"cpu",kernelFunc:FI}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function DI(e,t,n,s){if("int32"===s){return[t,"int32",Int32Array.from(e)]}if("bool"===s){const s=er([0],n),[r,a]=gI(((e,t)=>e!==t?1:0))(t,[],e,s,"bool");return[a,"bool",r]}throw new Error(`Error in Cast: failed to cast ${n} to ${s}`)}function OI(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{dtype:a}=s;if("complex64"===a){if("complex64"===r.dtype)return pI({inputs:{x:r},backend:n});const e=AI(n,r.shape,r.dtype),t=OI({inputs:{x:r},backend:n,attrs:{dtype:"float32"}}),s=EI({inputs:{real:t,imag:e},backend:n});return n.disposeIntermediateTensorInfo(e),n.disposeIntermediateTensorInfo(t),s}if("complex64"===r.dtype){const e=FI({inputs:{input:r},backend:n}),t=OI({inputs:{x:e},backend:n,attrs:{dtype:a}});return n.disposeIntermediateTensorInfo(e),t}if(!Y(r.dtype,a)){const e=pI({inputs:{x:r},backend:n});return{dataId:e.dataId,shape:e.shape,dtype:a}}const i=n.data.get(r.dataId).values,[o,l,u]=DI(i,r.shape,r.dtype,a);return n.makeTensorInfo(o,l,u)}const MI={kernelName:Ge,backendName:"cpu",kernelFunc:OI}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function LI(e,t,n,s){return null==n?({inputs:n,backend:r})=>{const{a,b:i}=n,o=r;aI([a,i],e);const l=o.data.get(a.dataId).values,u=o.data.get(i.dataId).values,c="string"===a.dtype?Gd(l):l,h="string"===a.dtype?Gd(u):u,p=s||a.dtype,[d,f]=t(a.shape,i.shape,c,h,p);return o.makeTensorInfo(f,p,d)}:({inputs:e,backend:r})=>{const{a,b:i}=e,o=r;if("complex64"===a.dtype||"complex64"===i.dtype){const e=OI({inputs:{x:a},backend:o,attrs:{dtype:"complex64"}}),t=o.data.get(e.dataId),s=t.complexTensorInfos.real,r=t.complexTensorInfos.imag,l=o.data.get(s.dataId).values,u=o.data.get(r.dataId).values,c=OI({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=EI({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,r=s||a.dtype,[l,u]=t(a.shape,i.shape,e,n,r);return o.makeTensorInfo(u,r,l)}}}function zI(e){return(t,n,s,r,a,i)=>{const o=ki(t,n),l=P(o),u=o.length,c=re(o),h=K("float32",l),p=K("float32",l),d=wi(t,o),f=wi(n,o),m=cd(s,r),g=cd(a,i),y=t.length,b=re(t),x=n.length,w=re(n);if(d.length+f.length===0)for(let t=0;ts[e]=0));const r=he(s,y,b),a=n.slice(-x);f.forEach((e=>a[e]=0));const i=he(a,x,w),o=e(m[2*r],m[2*r+1],g[2*i],g[2*i+1]);h[t]=o.real,p[t]=o.imag}return[h,p,o]}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +const PI=gI(((e,t)=>e+t)),BI=zI(((e,t,n,s)=>({real:e+n,imag:t+s}))),WI=LI(Se,PI,BI),VI={kernelName:Se,backendName:"cpu",kernelFunc:WI}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function UI(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{shape:a}=s,i=P(r.shape),o=H(a,i),l=P(o);O(i===l,(()=>`The new shape (${o}) has ${l} elements and the old shape (${r.shape}) has ${i} elements. The new shape and old shape must have the same number of elements.`)),n.incRef(r.dataId);const u=n.data.get(r.dataId);if(null!=u.complexTensorInfos){const e=u.complexTensorInfos.real,t=u.complexTensorInfos.imag;e.shape=o,t.shape=o}return{dataId:r.dataId,shape:o,dtype:r.dtype}}const GI={kernelName:An,backendName:"cpu",kernelFunc:UI}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function HI(e){const{inputs:t,backend:n,attrs:s}=e,{a:r,b:a}=t,{transposeA:i,transposeB:o}=s;aI([r,a],"matMul");const l=r.shape.length,u=a.shape.length,c=i?r.shape[l-2]:r.shape[l-1],h=o?a.shape[u-1]:a.shape[u-2],p=i?r.shape[l-1]:r.shape[l-2],d=o?a.shape[u-2]:a.shape[u-1],f=r.shape.slice(0,-2),m=a.shape.slice(0,-2),g=P(f),y=P(m),b=ki(r.shape.slice(0,-2),a.shape.slice(0,-2)).concat([p,d]);O(c===h,(()=>`Error in matMul: inner shapes (${c}) and (${h}) of Tensors with shapes ${r.shape} and ${a.shape} and transposeA=${i} and transposeB=${o} must match.`));const x=o?[y,d,h]:[y,h,d],w=UI({inputs:{x:r},backend:n,attrs:{shape:i?[g,c,p]:[g,p,c]}}),v=UI({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,$=re(w.shape),E=re(v.shape),[R,A,F]=i?[$[0],1,$[1]]:[$[0],$[1],1],[_,D,M]=o?[1,E[1],E[0]]:[E[1],1,E[0]],L=I*N,z=Ya([S,I,N],w.dtype),B=z.values,W=n.blockSize;for(let e=0;e{const{x:t}=e.inputs,n=e.backend;aI(t,"abs");let s=new Float32Array(P(t.shape));return s=KI(n.data.get(t.dataId).values),n.makeOutput(s,t.shape,t.dtype)}},YI=lI(Ie,(e=>Math.acos(e))),ZI={kernelName:Ie,backendName:"cpu",kernelFunc:YI},JI=lI(Ne,(e=>Math.acosh(e))),QI={kernelName:Ne,backendName:"cpu",kernelFunc:JI};const eN={kernelName:Te,backendName:"cpu",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n}=e,s=t;aI(t,"addN");const r=s.map((e=>n.data.get(e.dataId).values)),a=Ya(s[0].shape,s[0].dtype),i=a.values;for(let e=0;en&&(n=r,s=e)}p[e]=s}return u.forEach((e=>n.disposeIntermediateTensorInfo(e))),n.makeTensorInfo(c,"int32",p)}};const oN={kernelName:Re,backendName:"cpu",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a}=s;aI(r,"argMin");let i=j(a,r.shape);const o=Ol(i,r.shape.length);let l=r;const u=[];null!=o&&(l=nN({inputs:{x:r},backend:n,attrs:{perm:o}}),u.push(l),i=Ll(i.length,l.shape.length)),i=[i[0]],Dl("argMin",i,l.shape.length);const[c,h]=Fl(l.shape,i),p=le(P(c),"int32"),d=P(h),f=n.data.get(l.dataId).values;for(let e=0;en.disposeIntermediateTensorInfo(e))),n.makeTensorInfo(c,"int32",p)}},lN=lI(Ae,(e=>Math.asin(e))),uN={kernelName:Ae,backendName:"cpu",kernelFunc:lN},cN=lI(Fe,(e=>Math.asinh(e))),hN={kernelName:Fe,backendName:"cpu",kernelFunc:cN},pN=lI(_e,(e=>Math.atan(e))),dN={kernelName:_e,backendName:"cpu",kernelFunc:pN},fN=gI(((e,t)=>Math.atan2(e,t))),mN=LI(Oe,fN),gN={kernelName:Oe,backendName:"cpu",kernelFunc:mN},yN=lI(De,(e=>Math.atanh(e))),bN={kernelName:De,backendName:"cpu",kernelFunc:yN}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function xN(e,t,n,s,r,a){const i=r.strideHeight,o=r.strideWidth,l=r.dilationHeight,u=r.dilationWidth,c=r.effectiveFilterHeight,h=r.effectiveFilterWidth,p=r.padInfo.top,d=r.padInfo.left,f="max"===a?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,m=Ya(r.outShape,n),g=m.values,y=r.outShape[1]*r.outShape[2]*r.outShape[3],b=r.outShape[2]*r.outShape[3],x=r.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 wN(e,t,n,s,r=!1,a=!1){const i=Ya(s.outShape,"int32"),o=s.strideHeight,l=s.strideWidth,u=s.dilationHeight,c=s.dilationWidth,h=s.effectiveFilterHeight,p=s.effectiveFilterWidth,d=s.padInfo.top,f=s.padInfo.left,m=Ya(t,n,e);for(let e=0;ew&&(w=u,v=r?a?((e*s.inHeight+n)*s.inWidth+o)*s.inChannels+t:(n*s.inWidth+o)*s.inChannels+t:i*p+l)}}i.set(v,e,n,o,t)}}return i}function vN(e,t,n,s,r,a){const i=r.strideDepth,o=r.strideHeight,l=r.strideWidth,u=r.dilationDepth,c=r.dilationHeight,h=r.dilationWidth,p=r.effectiveFilterDepth,d=r.effectiveFilterHeight,f=r.effectiveFilterWidth,m=r.padInfo.front,g=r.padInfo.top,y=r.padInfo.left,b="max"===a?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,x=Ya(r.outShape,n),w=x.values,v=r.outShape[1]*r.outShape[2]*r.outShape[3]*r.outShape[4],k=r.outShape[2]*r.outShape[3]*r.outShape[4],I=r.outShape[3]*r.outShape[4],N=r.outShape[4];for(let t=0;tk?k=r:"avg"===a&&(I+=r,S++),isNaN(k))break}if(isNaN(k))break}if(isNaN(k))break}w[g+t]="avg"===a?I/S:k}}}}return x}const kN={kernelName:Me,backendName:"cpu",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t;aI(r,"avgPool");const{filterSize:a,strides:i,pad:o,dimRoundingMode:l}=s;O(Ro(i,1),(()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${i} and dilations '1'`));const u=wo(r.shape,a,i,1,o,l);let c;if(1===u.filterWidth&&1===u.filterHeight&&B(u.inShape,u.outShape))c=pI({inputs:{x:r},backend:n});else{const e=n.data.get(r.dataId).values,t=re(r.shape),s=xN(e,r.shape,r.dtype,t,u,"avg");c=n.makeTensorInfo(u.outShape,r.dtype,s.values)}return c}};const IN={kernelName:ze,backendName:"cpu",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{filterSize:a,strides:i,pad:o,dimRoundingMode:l,dataFormat:u}=s;aI(r,"avgPool3d");const c=vo(r.shape,a,i,1,o,l,u),h=vN(n.data.get(r.dataId).values,r.shape,r.dtype,re(r.shape),c,"avg");return n.makeTensorInfo(h.shape,"float32",h.values)}};const NN={kernelName:Pe,backendName:"cpu",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{dy:r,input:a}=t,{filterSize:i,strides:o,pad:l,dimRoundingMode:u}=s;aI([r,a],"avgPool3DGrad");const c=vo(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=Ya(a.shape,"float32"),C=1/(f*m*g),$=n.bufferSync(r);for(let e=0;e=c.outDepth||Math.floor(s)!==s))for(let n=0;n=c.outHeight||Math.floor(r)!==r))for(let n=0;n=c.outWidth||Math.floor(a)!==a)continue;l+=$.get(e,s,r,a,t)}}}T.set(l*C,e,n,s,r,t)}return n.makeTensorInfo(T.shape,T.dtype,T.values)}};const SN={kernelName:Le,backendName:"cpu",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{dy:r,input:a}=t,i=a;aI([r,a],"avgPoolGrad");const{filterSize:o,strides:l,pad:u}=s,c=wo(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=Ya(i.shape,"float32"),k=1/(d*f),I=n.data.get(r.dataId).values,N=Ya(r.shape,"float32",I);for(let e=0;e=c.outHeight||Math.floor(s)!==s))for(let n=0;n=c.outWidth||Math.floor(r)!==r)continue;i+=N.get(e,s,r,t)}}v.set(i*k,e,n,s,t)}return n.makeTensorInfo(v.shape,v.dtype,v.values)}};const TN={kernelName:Rt,backendName:"cpu",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,scale:a,offset:i,mean:o,variance:l}=t;O(o.shape.length===l.shape.length,(()=>"Batch normalization gradient requires mean and variance to have equal ranks.")),O(null==i||o.shape.length===i.shape.length,(()=>"Batch normalization gradient requires mean and offset to have equal ranks.")),O(null==a||o.shape.length===a.shape.length,(()=>"Batch normalization gradient requires mean and scale to have equal ranks.")),aI([r,o,l,a,i],"batchNorm");let{varianceEpsilon:u}=s;null==u&&(u=.001);const c=n.data.get(r.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(r.shape,r.dtype,m)}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function CN(e,t,n,s,r){const a=Wi(s,t,n),i=P(n),o=re(s);if(a){const n=Vi(t,o);return"string"===r?e.slice(n,n+i):e.subarray(n,n+i)}const l=Ya(s,r,"string"===r?Gd(e):e),u=Ya(n,r);for(let e=0;ee+t[n]));u.set(l.get(...s),...n)}return"string"===r?Hd(u.values):u.values}function $N(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{begin:a,size:i}=s;aI(r,"slice");const[o,l]=Ui(r,a,i);Ei(r,o,l);const u=CN(n.data.get(r.dataId).values,o,l,r.shape,r.dtype);return n.makeTensorInfo(l,r.dtype,u)}const EN={kernelName:Gn,backendName:"cpu",kernelFunc:$N};const RN={kernelName:We,backendName:"cpu",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{blockShape:a,crops:i}=s;aI([r],"batchToSpaceND");const o=a.reduce(((e,t)=>e*t)),l=Yp(r.shape,a,o),u=Zp(l.length,a.length),c=Jp(r.shape,a,o),h=Qp(i,a.length),p=ed(c,i,a.length),d=UI({inputs:{x:r},backend:n,attrs:{shape:l}}),f=nN({inputs:{x:d},backend:n,attrs:{perm:u}}),m=UI({inputs:{x:f},backend:n,attrs:{shape:c}}),g=$N({inputs:{x:m},backend:n,attrs:{begin:h,size:p}});return n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),g}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function AN(e,t,n,s,r){const a=P(s),i=le(r,n);for(let n=0;n=r||(i[s]+=a>0?t[n]:1)}return i}function FN(e,t,n,s=!1){const r=e.shape[0],a=e.shape[1],i=Ya([r,n],t.dtype);for(let o=0;o=n||(s?i.set(1,o,a):t.size>0?i.set(i.get(o,a)+t.get(o,r),o,a):i.set(i.get(o,a)+1,o,a))}return i}const _N={kernelName:Ve,backendName:"cpu",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,weights:a}=t,{size:i}=s,o=AN(n.data.get(r.dataId).values,n.data.get(a.dataId).values,a.dtype,a.shape,i);return n.makeTensorInfo([i],a.dtype,o)}};const DN={kernelName:Ue,backendName:"cpu",kernelFunc: +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n}=e,{s0:s,s1:r}=t,a=n.data.get(s.dataId).values,i=n.data.get(r.dataId).values,o=ki(Array.from(a),Array.from(i));return n.makeTensorInfo([o.length],"int32",Int32Array.from(o))}},ON=NI((e=>Math.ceil(e))),MN=uI(He,ON),LN={kernelName:He,backendName:"cpu",kernelFunc:MN},zN=lI(je,((e,t)=>{const n=t;return e>n.clipValueMax?n.clipValueMax:e{const{x:t}=e.inputs,n=e.backend,s=new Float32Array(P(t.shape)),r=n.data.get(t.dataId),a=r.complexTensorInfos.real,i=r.complexTensorInfos.imag,o=n.data.get(a.dataId).values,l=n.data.get(i.dataId).values;for(let e=0;e{const n=P(e.shape);r.set(e.vals,t),t+=n}))}else{let s=0;e.forEach((e=>{const a="string"===n?Gd(e.vals):e.vals;let i=0;for(let n=0;ne.shape)),a);let i=Wp(t.map((e=>e.shape)),a);if(0===P(i))return n.makeTensorInfo(i,t[0].dtype,[]);const o=t.filter((e=>P(e.shape)>0));if(1===o.length)return pI({inputs:{x:o[0]},backend:n});if("complex64"===o[0].dtype){const e=o.map((e=>FI({inputs:{input:e},backend:n}))),t=o.map((e=>VN({inputs:{input:e},backend:n}))),s=GN({inputs:e,backend:n,attrs:{axis:a}}),r=GN({inputs:t,backend:n,attrs:{axis:a}}),i=EI({inputs:{real:s,imag:r},backend:n});return e.forEach((e=>n.disposeIntermediateTensorInfo(e))),t.forEach((e=>n.disposeIntermediateTensorInfo(e))),n.disposeIntermediateTensorInfo(s),n.disposeIntermediateTensorInfo(r),i}const l=o.map((e=>{const t=P(e.shape.slice(a));return UI({inputs:{x:e},backend:n,attrs:{shape:[-1,t]}})})),u=l.map((e=>({vals:n.data.get(e.dataId).values,shape:e.shape})));i=Wp(l.map((e=>e.shape)),1);const c=1===l[0].shape[0],h=WN(u,i,t[0].dtype,c),p=Wp(o.map((e=>e.shape)),a),d=n.makeTensorInfo(p,t[0].dtype,h);return l.forEach((e=>n.disposeIntermediateTensorInfo(e))),d}const HN={kernelName:Xe,backendName:"cpu",kernelFunc:GN}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function jN(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a}=t,{strides:i,pad:o,dataFormat:l,dilations:u,dimRoundingMode:c}=s;aI([r,a],"conv2d");const h=Ao(l),p=ko(r.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 pr(p.outShape,r.dtype),v=re(r.shape),k=re(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],$=x?w.strides[1]:w.strides[2],E=x?w.strides[2]:1,R=x?1:w.strides[1],A=n.data.get(r.dataId).values,F=n.data.get(a.dataId).values,_=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 r=i+s*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 r=a+e*S[1],o=i+s*N[2];for(let e=0;e=u.inWidth)continue;const a=r+e*S[2],i=o+t*u.inChannels;let l=a;for(let e=0;eMath.cos(e))),eS={kernelName:nt,backendName:"cpu",kernelFunc:QN},tS=lI(st,(e=>Math.cosh(e))),nS={kernelName:st,backendName:"cpu",kernelFunc:tS};const sS={kernelName:it,backendName:"cpu",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{image:r,boxes:a,boxInd:i}=t,{cropSize:o,method:l,extrapolationValue:u}=s,[c,h,p,d]=r.shape,f=a.shape[0],[m,g]=o,y=Ya([f,m,g,d],"float32"),b=n.data.get(a.dataId).values,x=n.data.get(i.dataId).values,w=n.data.get(r.dataId).values,v=re(r.shape),k=re(y.shape);for(let e=0;e=c)continue;const o=m>1?(r-n)*(h-1)/(m-1):0,f=g>1?(a-s)*(p-1)/(g-1):0;for(let t=0;t1?n*(h-1)+t*o:.5*(n+r)*(h-1);if(c<0||c>h-1)for(let n=0;n1?s*(p-1)+l*f:.5*(s+a)*(p-1);if(c<0||c>p-1){for(let n=0;n1?s*(p-1)+n*f:.5*(s+a)*(p-1);if(r<0||r>p-1){for(let s=0;se+f-t-1:(e,t)=>e+t;for(let e=0;ee+f-t-1:(e,t)=>e+t;for(let e=0;e`Only NHWC dataFormat supported on CPU for depthToSpace. Got ${i}`));const o=r.shape[0],l=r.shape[1],u=r.shape[2],c=r.shape[3],h=l*a,p=u*a,d=c/(a*a),f=n.data.get(r.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=ko(r.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 pr(d.outShape,r.dtype),I=n.data.get(r.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 r=a+e*h[1],o=i+s*d.inChannels;let l=t,u=r;for(let e=0;e{const{x:s,filter:r}=e,{strides:a,pad:i,dilations:o}=n,l=t,u=l.data.get(s.dataId).values,c=s.shape.length,h=l.data.get(r.dataId).values,p=r.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}=xo(s.shape,r.shape,a,i,"NHWC",o),C=P(T),$=T.length,E=X(s.dtype,C);for(let e=0;e=0&&a=0&&dl&&(l=m)}}}E[he([e,t,a,o],$,re(T))]=l}}}return{dataId:l.write(er(E,s.dtype),T,s.dtype),shape:T,dtype:s.dtype}}},fS={kernelName:mt,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:s,filter:r,dy:a}=e,{strides:i,pad:o,dilations:l}=n,u=t,c=ie(s.shape,u.data.get(s.dataId).values),h=ie(r.shape,u.data.get(r.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}=xo(s.shape,r.shape,i,o,"NHWC",l);O(a.rank===S.length,(()=>`Error in ${mt}, dy must have the same rank as output ${S.length}, but got ${a.rank}`));const T=ie(S,u.data.get(a.dataId).values),C=ue(r.shape,r.dtype);for(let e=0;e=0&&s=0&&ui&&(i=r,o=t,l=n)}}}C[o][l][a]+=T[e][t][s][a]}}}return{dataId:u.write(er(C,s.dtype),r.shape,r.dtype),shape:r.shape,dtype:r.dtype}}},mS={kernelName:ft,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:s,filter:r,dy:a}=e,{strides:i,pad:o,dilations:l}=n,u=t,c=ie(s.shape,u.data.get(s.dataId).values),h=ie(r.shape,u.data.get(r.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}=xo(s.shape,r.shape,i,o,"NHWC",l);O(a.rank===S.length,(()=>`Error in ${ft}, dy must have the same rank as output ${S.length}, but got ${a.rank}`));const T=ie(S,u.data.get(a.dataId).values),C=ue(s.shape,s.dtype);for(let e=0;e=0&&s=0&&ui&&(i=r,o=s,l=u)}}}C[e][o][l][a]+=T[e][t][s][a]}}}return{dataId:u.write(er(C,s.dtype),s.shape,s.dtype),shape:s.shape,dtype:s.dtype}}},gS=gI(((e,t)=>e*t)),yS=zI(((e,t,n,s)=>({real:e*n-t*s,imag:e*s+t*n}))),bS=LI(pn,gS,yS),xS={kernelName:pn,backendName:"cpu",kernelFunc:bS}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function wS(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:i}=s;let o;aI(r,"sum"),o="bool"===r.dtype?OI({inputs:{x:r},backend:n,attrs:{dtype:"int32"}}):pI({inputs:{x:r},backend:n});const l=o.shape.length,u=j(a,o.shape),c=Ol(u,l);let h=u,p=o;null!=c&&(p=nN({inputs:{x:o},backend:n,attrs:{perm:c}}),h=Ll(h.length,l)),Dl("sum",h,p.shape.length);const[d,f]=Fl(p.shape,h);let m=AI(n,d,Sr(p.dtype,"int32"));const g=P(f),y=n.data.get(m.dataId).values,b=n.data.get(p.dataId).values;for(let e=0;e=0&&(p=wS({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}};const IS={kernelName:xt,backendName:"cpu",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n}=e,{dy:s,y:r}=t;aI([s,r],"eluGrad");const a=new Float32Array(P(r.shape)),i=n.data.get(r.dataId).values,o=n.data.get(s.dataId).values;for(let e=0;e=1?o[e]:o[e]*(t+1)}return n.makeTensorInfo(r.shape,"float32",a)}},NS=gI(((e,t)=>e===t?1:0)),SS=LI(vt,NS,null,"bool"),TS={kernelName:vt,backendName:"cpu",kernelFunc:SS},CS=rd,$S=ad,ES=id,RS=od,AS=ld,FS=ud,_S=lI(wt,(e=>{const t=Math.sign(e),n=Math.abs(e),s=1/(1+CS*n);return t*(1-((((FS*s+AS)*s+RS)*s+ES)*s+$S)*s*Math.exp(-n*n))})),DS={kernelName:wt,backendName:"cpu",kernelFunc:_S},OS=NI((e=>Math.exp(e))),MS=uI(kt,OS,"float32"),LS={kernelName:kt,backendName:"cpu",kernelFunc:MS}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function zS(e){const{inputs:t,backend:n,attrs:s}=e,{input:r}=t,{dim:a}=s,i=r.shape.length,o=r.shape.slice();let l=a;return a<0&&(O(-(i+1)<=a,(()=>`Axis must be in the interval [${-(i+1)}, ${i}]`)),l=i+a+1),o.splice(l,0,1),UI({inputs:{x:r},backend:n,attrs:{shape:o}})}const PS={kernelName:It,backendName:"cpu",kernelFunc:zS},BS=NI((e=>Math.expm1(e))),WS=uI(Nt,BS),VS={kernelName:Nt,backendName:"cpu",kernelFunc:WS},US=gI(((e,t)=>e/t)),GS=LI(gt,US),HS={kernelName:gt,backendName:"cpu",kernelFunc:GS},jS=gI(((e,t)=>e-t)),qS=zI(((e,t,n,s)=>({real:e-n,imag:t-s}))),KS=LI(ps,jS,qS),XS={kernelName:ps,backendName:"cpu",kernelFunc:KS}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function YS(e,t,n){const s=e.shape,r=s[0],a=s[1],i=n.data.get(e.dataId),o=i.complexTensorInfos.real,l=i.complexTensorInfos.imag,u=[r,a],c=P(u),h=K("float32",c),p=K("float32",c);for(let e=0;e{const{image:s}=e,r=n,a=K(s.dtype,P(s.shape)),[i,o,l,u]=s.shape,c=r.data.get(s.dataId).values;for(let e=0;e=0&&iMath.floor(e))),rT=uI($t,sT),aT={kernelName:$t,backendName:"cpu",kernelFunc:rT},iT=gI(((e,t)=>Math.floor(e/t))),oT=LI(Et,iT,null,"int32"),lT={kernelName:Et,backendName:"cpu",kernelFunc:oT};const uT={kernelName:Cs,backendName:"cpu",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dataFormat:c,dilations:h,dimRoundingMode:p,activation:d,leakyreluAlpha:f}=s;let m=jN({inputs:{x:r,filter:a},backend:n,attrs:{strides:l,pad:u,dataFormat:c,dilations:h,dimRoundingMode:p}});if(i){const e=m;if("NCHW"===c&&1===i.shape.length&&1!==i.shape[0]){const e=UI({inputs:{x:i},backend:n,attrs:{shape:[i.shape[0],1,1]}});m=WI({inputs:{a:m,b:e},backend:n}),n.disposeIntermediateTensorInfo(e)}else m=WI({inputs:{a:m,b:i},backend:n});n.disposeIntermediateTensorInfo(e)}if(d){const e=m;if("NCHW"===c&&"prelu"===d&&1===o.shape.length&&1!==o.shape[0]){const e=UI({inputs:{x:o},backend:n,attrs:{shape:[o.shape[0],1,1]}});m=$I(n,m,d,e,f),n.disposeIntermediateTensorInfo(e)}else m=$I(n,m,d,o,f);n.disposeIntermediateTensorInfo(e)}return m}};const cT={kernelName:$s,backendName:"cpu",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dataFormat:c,dilations:h,dimRoundingMode:p,activation:d,leakyreluAlpha:f}=s;let m=lS({inputs:{x:r,filter:a},backend:n,attrs:{strides:l,pad:u,dataFormat:c,dilations:h,dimRoundingMode:p}});if(i){const e=m;m=WI({inputs:{a:m,b:i},backend:n}),n.disposeIntermediateTensorInfo(e)}if(d){const e=m;m=$I(n,m,d,o,f),n.disposeIntermediateTensorInfo(e)}return m}}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function hT(e,t,n,s,r,a,i,o,l){const u=Ya([s,a],n);for(let n=0;n=l/a)throw new Error(`Invalid indices: ${s} 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=P(a.shape),d=Ud(r,a,l,h),f=UI({inputs:{x:r},backend:n,attrs:{shape:[d.batchSize,d.outerSize,d.dimSize,d.sliceSize]}}),m=UI({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=dT(n.bufferSync(f),y,g);return n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),n.makeTensorInfo(d.outputShape,b.dtype,b.values)}},mT=gI(((e,t)=>e>t?1:0)),gT=LI(_t,mT,null,"bool"),yT={kernelName:_t,backendName:"cpu",kernelFunc:gT},bT=gI(((e,t)=>e>=t?1:0)),xT=LI(Dt,bT,null,"bool"),wT={kernelName:Dt,backendName:"cpu",kernelFunc:xT};const vT={kernelName:Mt,backendName:"cpu",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n}=e,{input:s}=t,r=P(s.shape),a=s.shape[s.shape.length-1],i=UI({inputs:{x:s},backend:n,attrs:{shape:[r/a,a]}}),o=YS(i,!0,n),l=UI({inputs:{x:o},backend:n,attrs:{shape:s.shape}});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(o),l}},kT=lI(zt,(e=>Number.isFinite(e)?1:0),"bool"),IT={kernelName:zt,backendName:"cpu",kernelFunc:kT},NT=lI(Pt,(e=>Math.abs(e)===1/0?1:0),"bool"),ST={kernelName:Pt,backendName:"cpu",kernelFunc:NT},TT=lI(Bt,(e=>Number.isNaN(e)?1:0),"bool"),CT={kernelName:Bt,backendName:"cpu",kernelFunc:TT},$T=gI(((e,t)=>ee<=t?1:0)),FT=LI(Ut,AT,null,"bool"),_T={kernelName:Ut,backendName:"cpu",kernelFunc:FT}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function DT(e,t,n){const s=(t-e)/(n-1),r=le(n,"float32");r[0]=e;for(let e=1;eMath.log(e))),LT=uI(Ht,MT),zT={kernelName:Ht,backendName:"cpu",kernelFunc:LT},PT=lI(jt,(e=>Math.log1p(e))),BT={kernelName:jt,backendName:"cpu",kernelFunc:PT},WT=gI(((e,t)=>e&&t)),VT=LI(qt,WT,null,"bool"),UT={kernelName:qt,backendName:"cpu",kernelFunc:VT},GT=lI(Kt,(e=>e?0:1),"bool"),HT={kernelName:Kt,backendName:"cpu",kernelFunc:GT},jT=gI(((e,t)=>e||t)),qT=LI(Xt,jT,null,"bool"),KT={kernelName:Xt,backendName:"cpu",kernelFunc:qT};const XT={kernelName:Yt,backendName:"cpu",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{depthRadius:a,bias:i,alpha:o,beta:l}=s;aI(r,"LRN");const u=r.shape[3],c=u-1,h=n.data.get(r.dataId).values,p=P(r.shape),d=new Float32Array(p);function f(e){const t=e%u;let n=e-t+Math.max(0,t-a);const s=e-t+Math.min(t+a,c);let r=0;for(;n<=s;n++){const e=h[n];r+=e*e}return r}for(let e=0;ea)&&(a=t)}r[n]=a}return r} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function JT(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{reductionIndices:a,keepDims:i}=s,o=n;let l=r.shape;const u=l.length,c=j(a,l);let h=c;const p=Ol(h,u);let d=o.data.get(r.dataId).values;if(null!=p){const e=new Array(u);for(let t=0;tMath.max(e,t))),tC=LI(Qt,eC),nC={kernelName:Qt,backendName:"cpu",kernelFunc:tC};const sC={kernelName:en,backendName:"cpu",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t;aI(r,"maxPool");const{filterSize:a,strides:i,pad:o,dimRoundingMode:l}=s;O(Ro(i,1),(()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${i} and dilations '1'`));const u=wo(r.shape,a,i,1,o,l);let c;if(1===u.filterWidth&&1===u.filterHeight&&B(u.inShape,u.outShape))c=pI({inputs:{x:r},backend:n});else{const e=n.data.get(r.dataId).values,t=re(r.shape),s=xN(e,r.shape,r.dtype,t,u,"max");c=n.makeTensorInfo(u.outShape,r.dtype,s.values)}return c}};const rC={kernelName:nn,backendName:"cpu",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{filterSize:a,strides:i,pad:o,dimRoundingMode:l,dataFormat:u}=s;aI(r,"maxPool3d");const c=vo(r.shape,a,i,1,o,l,u),h=vN(n.data.get(r.dataId).values,r.shape,r.dtype,re(r.shape),c,"max");return n.makeTensorInfo(h.shape,"float32",h.values)}};const aC={kernelName:sn,backendName:"cpu",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{dy:r,input:a}=t,{filterSize:i,strides:o,pad:l,dimRoundingMode:u}=s;aI([r,a],"maxPool3DGrad");const c=vo(a.shape,i,o,1,l,u),h=function(e,t){const n=Ya(t.outShape,"int32"),s=t.strideDepth,r=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+r*c+i)}}}n.set(S,m,y,s,r,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=Ya(a.shape,"float32"),S=n.bufferSync(r);for(let e=0;e=c.outDepth||Math.floor(s)!==s))for(let r=0;r=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,s,a,u,t)===n*x*w+r*w+i?1:0;if(0===p)continue;l+=S.get(e,s,a,u,t)*p}}}N.set(l,e,n,s,r,t)}return n.makeTensorInfo(N.shape,N.dtype,N.values)}};const iC={kernelName:tn,backendName:"cpu",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{dy:r,input:a,output:i}=t,o=a;aI([a,i],"maxPoolGrad");const{filterSize:l,strides:u,pad:c,dimRoundingMode:h}=s,p=wo(o.shape,l,u,1,c,h),d=n.data.get(o.dataId).values,f=Ya(p.outShape,o.dtype,wN(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=Ya(o.shape,"float32"),N=n.data.get(r.dataId).values,S=Ya(r.shape,"float32",N);for(let e=0;e=p.outHeight||Math.floor(s)!==s))for(let r=0;r=p.outWidth||Math.floor(o)!==o)continue;const l=x*w-1-f.get(e,s,o,t)===n*w+r?1:0;if(0===l)continue;i+=S.get(e,s,o,t)*l}}I.set(i,e,n,s,t)}return n.makeTensorInfo(I.shape,I.dtype,I.values)}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +const oC={kernelName:rn,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:s}=e,{filterSize:r,strides:a,pad:i,includeBatchInIndex:o}=t,l=n;aI(s,"MaxPoolWithArgmax");const u=l.data.get(s.dataId).values,c=wo(s.shape,r,a,[1,1],i),[h,p]= +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n,s,r){const a=xN(e,0,n,re(t),r,"max"),i=wN(e,t,n,r,!0,s);return[a.values,i.values]}(u,s.shape,s.dtype,o,c),d=l.write(h,c.outShape,s.dtype),f=l.write(p,c.outShape,s.dtype);return[{dataId:d,shape:c.outShape,dtype:s.dtype},{dataId:f,shape:c.outShape,dtype:"int32"}]}};const lC={kernelName:an,backendName:"cpu",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:i}=s,o=j(a,r.shape),l=P(Fl(r.shape,o)[1]),u=[],c=n.makeTensorInfo([],"float32",new Float32Array([l]));u.push(c);const h=OI({inputs:{x:r},backend:n,attrs:{dtype:"float32"}});u.push(h);const p=GS({inputs:{a:h,b:c},backend:n});u.push(p);const d=wS({inputs:{x:p},backend:n,attrs:{axis:a,keepDims:i}});return u.forEach((e=>n.disposeIntermediateTensorInfo(e))),d}};const uC={kernelName:on,backendName:"cpu",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:i}=s;aI(r,"min");const o=j(a,r.shape);let l=o;const u=Ol(l,r.shape.length);let c=r;null!=u&&(c=nN({inputs:{x:r},backend:n,attrs:{perm:u}}),l=Ll(l.length,r.shape.length)),Dl("min",l,c.shape.length);const[h,p]=Fl(c.shape,l),d=P(p),f=le(P(h),c.dtype),m=n.data.get(c.dataId).values;for(let e=0;eMath.min(e,t))),hC=LI(ln,cC),pC={kernelName:ln,backendName:"cpu",kernelFunc:hC};const dC={kernelName:un,backendName:"cpu",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{paddings:a,mode:i}=s;aI(r,"mirrorPad");const o=a.map(((e,t)=>e[0]+r.shape[t]+e[1])),l=a.map((e=>e[0])),u=a.map(((e,t)=>e[0]+r.shape[t])),c="reflect"===i?0:1,h=n.data.get(r.dataId).values,p=r.shape.length,d=re(r.shape),f=P(o),m=o.length,g=re(o),y=K(r.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=he(t,p,d);y[e]=h[n]}return{dataId:n.write(y,o,r.dtype),shape:o,dtype:r.dtype}}},fC=gI(((e,t)=>{const n=e%t;return e<0&&t<0||e>=0&&t>=0?n:(n+t)%t})),mC=LI(cn,fC),gC={kernelName:cn,backendName:"cpu",kernelFunc:mC}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function yC(e){const{inputs:t,backend:n,attrs:s}=e,{logits:r}=t,{dim:a}=s,i=r.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=j([o],r.shape),u=JT({inputs:{x:r},backend:n,attrs:{reductionIndices:l,keepDims:!1}}),c=_l(u.shape,l),h=UI({inputs:{x:u},backend:n,attrs:{shape:c}}),p=KS({inputs:{a:r,b:h},backend:n}),d=MS({inputs:{x:p},backend:n}),f=wS({inputs:{x:d},backend:n,attrs:{axis:l,keepDims:!1}}),m=UI({inputs:{x:f},backend:n,attrs:{shape:c}}),g=GS({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 bC={kernelName:es,backendName:"cpu",kernelFunc:yC};const xC={kernelName:hn,backendName:"cpu",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{logits:r}=t,{numSamples:a,seed:i,normalized:o}=s;aI(r,"multinomial");const l=o?r:yC({inputs:{logits:r},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(P(p),"int32");for(let e=0;ee!==t?1:0)),EC=LI(fn,$C,null,"bool"),RC={kernelName:fn,backendName:"cpu",kernelFunc:EC};const AC={kernelName:xn,backendName:"cpu",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{indices:r}=t,{dtype:a,depth:i,onValue:o,offValue:l}=s;aI(r,"oneHot");const u=P(r.shape),c=new Float32Array(u*i);c.fill(l);const h=n.data.get(r.dataId).values;for(let e=0;e=0&&h[e]{M(a,e.shape,"All tensors passed to stack must have matching shapes"),O(i===e.dtype,(()=>"All tensors passed to stack must have matching dtypes"))}));const o=[],l=GN({inputs:t.map((e=>{const t=zS({inputs:{input:e},backend:n,attrs:{dim:r}});return o.push(t),t})),backend:n,attrs:{axis:r}});return o.forEach((e=>n.disposeIntermediateTensorInfo(e))),l}const MC={kernelName:wn,backendName:"cpu",kernelFunc:OC};const LC={kernelName:vn,backendName:"cpu",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{paddings:a,constantValue:i}=s;aI(r,"pad");const o=a.map(((e,t)=>e[0]+r.shape[t]+e[1])),l=a.map((e=>e[0])),u=n.data.get(r.dataId).values,c=P(r.shape),h=r.shape.length,p=re(r.shape),d=P(o),f=o.length,m=re(o),g=K(r.dtype,d);0!==i&&g.fill(i);for(let e=0;ee+l[t])),f,m)]=u[e]}return{dataId:n.write(g,o,r.dtype),shape:o,dtype:r.dtype}}},zC=gI(((e,t)=>Math.pow(e,t))),PC=LI(kn,zC),BC={kernelName:kn,backendName:"cpu",kernelFunc:PC}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function WC(e,t,n,s){const[r,a]=Fl(e,s),i=Sr(t,"int32"),o=le(P(r),i),l=P(a);for(let e=0;en.disposeIntermediateTensorInfo(e))),n.makeTensorInfo(y,g,f)}};function UC(e,t,n,s){const r=[];let a=0;const i=t.length-1+n.length,o=new Array(i).fill(null).map((()=>[0]));!function(e,t){for(let n=0;nr)throw new Error("Ragged splits must not point past values");for(let e=1;es[e])throw new Error("Ragged splits must be sorted in ascending order")}}(n,s);let l=1;for(let e=0;e=0){const e=o[r],t=e[e.length-1]-s[i];for(let e=i;e{if(e<0||e>=n){const r=pe(s,t.length,re(t)).join(",");throw new Error(`indices[${r}] = ${e} is not in [0, ${n})`)}}))}(a,i,t[0][0]-1),0===s.length)throw new Error("params.rank must be nonzero");const l=s[0],{outSplits:u,valueSlices:c,numValues:h}=UC(a,i,e,l),p=function(e){const t=[];for(let n=0;ns[t]=e))}return t}(u),d=HC(n,s,r,c,h);return[p,d[0],d[1]]}const qC={kernelName:Sn,backendName:"cpu",kernelFunc: +/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{paramsNestedSplits:r,paramsDenseValues:a,indices:i}=t,{outputRaggedRank:o}=s,l=r.map((e=>n.data.get(e.dataId).values)),u=r.map((e=>e.shape)),c=n.data.get(a.dataId).values,h=n.data.get(i.dataId).values,[p,d,f]=jC(l,u,c,a.shape,a.dtype,h,i.shape),m=p.map((e=>n.makeTensorInfo([e.length],"int32",e))),g=n.makeTensorInfo(f,a.dtype,d);return m.concat([g])}}; +/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +var KC=Vp;class XC{constructor(e,t,n,s,r,a,i,o,l,u){this.shape=e,this.shapeShape=t,this.values=n,this.valuesShape=s,this.valuesDType=r,this.defaultValue=a,this.defaultValueShape=i,this.rowPartitionValues=o,this.rowPartitionValuesShapes=l,this.rowPartitionTypes=Gp(u),this.raggedRank=Hp(this.rowPartitionTypes)}getRowPartitionTypeByDimension(e){return this.rowPartitionTypes[0]===KC.FIRST_DIM_SIZE?this.rowPartitionTypes[e+1]:this.rowPartitionTypes[e]}getRowPartitionTensor(e){return this.rowPartitionTypes[0]===KC.FIRST_DIM_SIZE?this.rowPartitionValues[e+1]:this.rowPartitionValues[e]}getMaxWidth(e){const t=this.getRowPartitionTensor(e-1);switch(this.getRowPartitionTypeByDimension(e-1)){case KC.VALUE_ROWIDS:return XC.getMaxWidthValueRowID(t);case KC.ROW_SPLITS:return XC.getMaxWidthRowSplit(t);default:throw new Error(`Cannot handle partition type ${KC[this.getRowPartitionTypeByDimension(e-1)]}`)}}static getMaxWidthRowSplit(e){const t=e.length;if(0===t||1===t)return 0;let n=0;for(let s=0;sn&&(n=t)}return n}static getMaxWidthValueRowID(e){const t=e.length;if(0===t)return 0;let n=0,s=e[0],r=0;for(let a=1;a"Final length of result must be equal to firstDimension.")),r}calculateOutputIndexRowSplit(e,t,n,s){const r=e.length,a=[];for(let i=0;i0&&a.length!==e[r-1])throw new Error("Invalid row split size.");return a}calculateOutputIndexValueRowID(e,t,n,s){const r=e.length,a=[];if(0===r)return[];let i=0,o=e[0];if(o>=t.length)throw new Error(`Got currentValueRowId=${o}, which is not less than ${t.length}`);let l=t[o];a.push(l);for(let u=1;u=0&&(++i,i=t.length)throw new Error(`Got nextValueRowId=${r} which is not less than ${t.length}`);l=t[r]}a.push(l)}if(a.length!==e.length)throw new Error("Invalid row ids.");return a}calculateOutputIndex(e,t,n,s){const r=this.getRowPartitionTensor(e),a=this.getRowPartitionTypeByDimension(e);switch(a){case KC.VALUE_ROWIDS:return this.calculateOutputIndexValueRowID(r,t,n,s);case KC.ROW_SPLITS:if(r.length-1>t.length)throw new Error(`Row partition size is greater than output size: ${r.length-1} > ${t.length}`);return this.calculateOutputIndexRowSplit(r,t,n,s);default:throw new Error(`Unsupported partition type: ${KC[a]}`)}}getFirstDimensionSize(){const e=this.rowPartitionValues[0];if(0===this.rowPartitionTypes.length)throw new Error("No row_partition_types given.");const t=this.rowPartitionTypes[0];switch(t){case KC.FIRST_DIM_SIZE:return e[0];case KC.VALUE_ROWIDS:throw new Error("Cannot handle VALUE_ROWIDS in first dimension.");case KC.ROW_SPLITS:return this.rowPartitionValuesShapes[0][0]-1;default:throw new Error(`Cannot handle type ${KC[t]}`)}}compute(){if(this.rowPartitionValues[0].length<=0)throw new Error("Invalid first partition input. Tensor requires at least one element.");const e=this.getFirstDimensionSize(),t=this.calculateOutputSize(e),n=new Array(this.raggedRank+1);n[n.length-1]=1;for(let e=n.length-2;e>=0;--e)n[e]=n[e+1]*t[e+1];const s=ZC(t,!1),r=X(this.valuesDType,P(s));if(n[0]*t[0]>0){let a=this.calculateFirstParentOutputIndex(e,n[0],t[0]);for(let e=1;e<=this.raggedRank;++e){a=this.calculateOutputIndex(e-1,a,n[e],t[e])}this.setOutput(this.raggedRank,a,r,s)}return[s,r]}setOutput(e,t,n,s){if(0===n.length)return;const r=this.values,a=n;let i=s.slice();i=i.slice(e+1);const o=P(i),l=t.length;let u=this.defaultValue;if(u.length!==o&&1!==u.length){const e=this.defaultValueShape;Zi((()=>{const t=_o(u,e),n=Yo(t,i);u=n.dataSync()}))}let c=0,h=0,p=0;for(let e=0;e<=l;++e){let s=e=l){const e=n.length;s=Math.floor(e/o)}if(s>p)if(1===this.defaultValue.length)a.subarray(p*o,s*o).fill(this.defaultValue[0]),p=s;else for(;s>p;){YC(a.slice(p*o),u,o),++p}s<0?(c=e+1,h=p):(c=e,h=p,p=h+1)}else++p}}}function YC(e,t,n){for(let s=0;s= 0`);if(s<-1)throw new Error(`Dimension ${s} must be >= -1`);s=-1}n.push(s)}return n}function JC(e,t,n,s,r,a,i,o,l,u){return new XC(e,t,n,s,r,a,i,o,l,u).compute()}const QC={kernelName:Tn,backendName:"cpu",kernelFunc: +/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{shape:r,values:a,defaultValue:i,rowPartitionTensors:o}=t,{rowPartitionTypes:l}=s,u=n.data.get(r.dataId).values,c=n.data.get(a.dataId).values,h=n.data.get(i.dataId).values,p=o.map((e=>n.data.get(e.dataId).values)),d=o.map((e=>e.shape)),[f,m]=JC(u,r.shape,c,a.shape,a.dtype,h,i.shape,p,d,l);return n.makeTensorInfo(f,a.dtype,m)}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function e$(e,t,n,s){if(e===t||e1)return le(0,s);const r=le(Math.abs(Math.ceil((t-e)/n)),s);t1/e)),s$={kernelName:En,backendName:"cpu",kernelFunc:n$};const r$={kernelName:Dn,backendName:"cpu",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{images:r}=t,{alignCorners:a,halfPixelCenters:i,size:o}=s;aI(r,"resizeBilinear");const l=re(r.shape),[u,c]=o,[h,p,d,f]=r.shape,m=n.data.get(r.dataId).values,g=new Float32Array(P([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 r=p+t*l[2],a=t*w;s===Math.min(h-1,i?Math.round(a):Math.floor(a))&&(o+=g[r+n])}}m[a+n]=o}}}}return n.makeTensorInfo(r.shape,r.dtype,m)}};const l$={kernelName:Ln,backendName:"cpu",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{dims:a}=s;aI(r,"reverse");const i=r.shape.length,o=j(a,r.shape);if(0===i)return pI({inputs:{x:r},backend:n});const l=new pr(r.shape,r.dtype),u=n.bufferSync(r);for(let e=0;en[e]=r.shape[e]-1-n[e])),l.set(u.get(...n),...t)}return n.makeTensorInfo(l.shape,l.dtype,l.values)}},u$={kernelName:Ss,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{image:s}=e,{radians:r,fillValue:a,center:i}=t,o=n,l=K(s.dtype,P(s.shape)),[u,c,h,p]=s.shape,[d,f]=Xp(i,c,h),m=Math.sin(r),g=Math.cos(r),y=o.data.get(s.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})),h$={kernelName:zn,backendName:"cpu",kernelFunc:c$},p$=NI((e=>1/Math.sqrt(e))),d$=uI(Pn,p$),f$={kernelName:Pn,backendName:"cpu",kernelFunc:d$}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function m$(e,t,n,s,r,a,i,o,l,u){const c=[s/r,r],h=e.values,p=t.values;if(0===s)return Ya(n,t.dtype);const d=Ya(c,t.dtype);"string"==typeof l||"number"==typeof l?d.values.fill(l):"boolean"==typeof l&&d.values.fill(+l);for(let e=0;e=s/r)throw new Error(`Invalid indices: ${a} does not index into ${n}`);for(let n=0;n1||1===r.shape.length?1:P(r.shape.slice(1));for(let e=0;ee>=0?k$*e:v$*(Math.exp(e)-1))),N$={kernelName:Un,backendName:"cpu",kernelFunc:I$},S$=lI(qn,(e=>e<0?-1:e>0?1:0)),T$={kernelName:qn,backendName:"cpu",kernelFunc:S$},C$=lI(Hn,(e=>Math.sin(e))),$$={kernelName:Hn,backendName:"cpu",kernelFunc:C$},E$=lI(jn,(e=>Math.sinh(e))),R$={kernelName:jn,backendName:"cpu",kernelFunc:E$},A$=Math.log(1.1920928955078125e-7)+2,F$=lI(Xn,(e=>{const t=e>-A$,n=e=l)throw new Error(Ad(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=s;for(let e=0;eNumber(e))))),n.makeTensorInfo([m.length],s.dtype,new Int32Array(m))]}}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function L$(e,t,n,s,r){const a=P(s),i=t[0],o=r.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]*s[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=X(n,i*o);for(let t=0;t0?r[o-1]+1:0;if(c<0)throw new Error("segment ids must be >= 0");const h=t.slice();h[0]=c;const p=X(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=r[d];for(;;){let t=0;if(f=t)throw new Error("segment ids are not increasing")}if(g<0||g>=c)throw new Error(Pd(g,c));g>m&&p.fill(i,m*u,g*u);for(let t=d;t=l[0])throw new Error(Bd(t,s[t],l[0]));for(let t=0;to)break}return m{const t=[...c];t[o]=e;const s=$N({inputs:{x:r},backend:n,attrs:{begin:u,size:t}});return u[o]+=e,s}))}},G$=NI((e=>Math.sqrt(e))),H$=lI(Yn,(e=>Math.sqrt(e))),j$={kernelName:Yn,backendName:"cpu",kernelFunc:H$},q$={kernelName:os,backendName:"cpu",kernelFunc:({inputs:e,backend:t})=>{const{x:n}=e,s=t;aI(n,"square");const r=s.data.get(n.dataId).values,a=new Float32Array(r.length);for(let e=0;e{const n=e-t;return n*n})),X$=LI(is,K$),Y$={kernelName:is,backendName:"cpu",kernelFunc:X$},Z$=lI(Is,((e,t)=>{const n=t;return isNaN(e)?NaN:e>0?1:n.alpha})),J$={kernelName:Is,backendName:"cpu",kernelFunc:Z$}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function Q$(e,t,n,s){const r=Ya(e,t.dtype);for(let e=0;e=1,(()=>`Input must have rank at least 1, got: ${r.shape.length}`));const e=Ai(b,x,w),t=$N({inputs:{x:r},backend:n,attrs:{begin:b,size:e}});v=UI({inputs:{x:t},backend:n,attrs:{shape:f}}),n.disposeIntermediateTensorInfo(t)}else{const e=Q$(d,n.bufferSync(r),w,b);v=n.makeTensorInfo(f,e.dtype,e.values)}return v}}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class tE{constructor(e,t,n,s,r,a){this.separator=nr(e),this.nGramWidths=t,this.leftPad=nr(n),this.rightPad=nr(s),this.padWidth=r,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,s,r,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 r=1;r=e;if(s=s&&t[r]<=n,!s)throw new Error(`Invalid split value ${t[r]}, must be in [${e}, ${n}]`);e=t[r]}if(e!==n)throw new Error(`Last split value must be data size. Expected ${n}, got ${e}`)}const r=s-1,a=X("int32",s);if(0===n||0===s){const e=new Array(n);for(let e=0;e<=r;++e)a[e]=0;return[e,a]}a[0]=0;for(let e=1;e<=r;++e){const n=t[e]-t[e-1];let s=0;this.nGramWidths.forEach((e=>{s+=this.getNumNGrams(n,e)})),this.preserveShort&&n>0&&0===s&&(s=1),a[e]=a[e-1]+s}const i=new Array(a[r]);for(let n=0;n{const o=t[n+1]-t[n],l=this.getNumNGrams(o,a);this.createNGrams(e,s,i,r,l,a),r+=l})),this.preserveShort&&r===a[n]){const a=t[n+1]-t[n];if(0===a)continue;const o=a+2*this.padWidth,l=1;this.createNGrams(e,s,i,r,l,o)}}return[i,a]}}function nE(e,t,n,s,r,a,i,o){return new tE(n,s,r,a,i,o).compute(e,t)}const sE={kernelName:us,backendName:"cpu",kernelFunc: +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{separator:r,nGramWidths:a,leftPad:i,rightPad:o,padWidth:l,preserveShortSequences:u}=s,{data:c,dataSplits:h}=t,p=n.data.get(c.dataId).values,d=n.data.get(h.dataId).values,[f,m]=nE(p,d,r,a,i,o,l,u);return[n.makeTensorInfo([f.length],"string",f),n.makeTensorInfo(h.shape,"int32",m)]}}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function rE(e,t,n,s){if(!e.length)return;if(0===t.length){for(let t=0;tMath.tan(e))),cE={kernelName:ds,backendName:"cpu",kernelFunc:uE},hE=lI(fs,(e=>Math.tanh(e))); +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function pE(e,t){const n=new Array(e.rank);for(let s=0;s{const n=t.value-e.value;return 0===n?e.index-t.index:n};function mE(e,t,n=0,s=e.length-1){for(;s>n;){if(s-n>600){const r=s-n+1,a=t-n+1,i=Math.log(r),o=.5*Math.exp(2*i/3),l=.5*Math.sqrt(i*o*(r-o)/r)*Math.sign(a-r/2);mE(e,t,Math.max(n,Math.floor(t-a*o/r+l)),Math.min(s,Math.floor(t+(r-a)*o/r+l)))}const r=e[t];let a=n,i=s;for(D(e,n,t),fE(e[s],r)>0&&D(e,n,s);a0;)i-=1}0===fE(e[n],r)?D(e,n,i):(i+=1,D(e,i,s)),i<=t&&(n=i+1),t<=i&&(s=i-1)}}function gE(e,t,n,s,r){const a=t[t.length-1],[i,o]=[e.length/a,a],l=K(n,i*s),u=K("int32",i*s);for(let t=0;ti[t]={value:e,index:t})),st-1)if(t<=1)n=0;else{const e=2*t;n-=e*Math.trunc(n/e),n>=t&&(n=e-n-1)}return F(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 F(0,n,t-1)}(e,t);case"nearest":return function(e,t){return F(0,e,t-1)}(e,t);default:return function(e){return e}(e)}}function wE(e,t,n,s,r,a,i,o,l,u,c){return 0<=o&&o{for(let n=0;nn.disposeIntermediateTensorInfo(e))),h}},CE=[qI,XI,ZI,QI,VI,eN,rN,aN,iN,oN,uN,hN,dN,gN,bN,kN,IN,NN,SN,jI,TN,RN,_N,DN,MI,LN,PN,RI,BN,HN,qN,KN,XN,YN,ZN,JN,eS,nS,sS,rS,aS,iS,oS,uS,cS,hS,pS,dS,fS,mS,kS,hI,IS,TS,DS,LS,PS,VS,QS,tT,nT,aT,lT,uT,cT,pT,fT,yT,wT,dI,vT,UN,IT,ST,CT,mI,RT,_T,OT,zT,BT,UT,HT,KT,XT,YT,QT,nC,sC,rC,aC,iC,oC,lC,uC,pC,dC,gC,xC,xS,vC,IC,SC,CC,RC,AC,DC,MC,LC,BC,xI,VC,qC,QC,t$,_I,HS,s$,vI,II,GI,r$,a$,i$,o$,l$,u$,h$,f$,g$,x$,w$,N$,CI,T$,$$,R$,EN,bC,_$,D$,M$,z$,B$,W$,V$,U$,j$,q$,Y$,J$,eE,sE,iE,lE,XS,vS,cE,{kernelName:fs,backendName:"cpu",kernelFunc:hE},dE,yE,bE,sN,NE,SE,TE,_C];for(const e of CE)Ms(e); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +const $E={},EE={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function RE(e,t){if(!(e in $E)||null!=t){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;n.addEventListener("webglcontextlost",(t=>{t.preventDefault(),delete $E[e]}),!1),ye().getBool("SOFTWARE_WEBGL_ENABLED")&&(EE.failIfMajorPerformanceCaveat=!1);if(1===e)return n.getContext("webgl",EE)||n.getContext("experimental-webgl",EE);return n.getContext("webgl2",EE)}(e,t);if(null===n)return console.log("Could not get context for WebGL version",e),null;$E[e]=n}const n=$E[e];return null==n||n.isContextLost()?(delete $E[e],RE(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),$E[e])} +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +var AE,FE,_E;function DE(e,t){return[t,e]}function OE(e){const t=P(e);return V(Math.ceil(t/4))}function ME(e,t){return[Math.max(1,Math.ceil(t/2)),Math.max(1,Math.ceil(e/2))]}function LE(e,t){const n=e;let s,r,a,i,o,l,u,c,h,p;return 2===ye().getNumber("WEBGL_VERSION")?(s=n.R32F,r=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):(s=e.RGBA,r=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:s,internalFormatHalfFloat:r,internalFormatPackedHalfFloat:a,internalFormatPackedFloat:i,textureFormatFloat:o,downloadTextureFormat:l,downloadUnpackNumChannels:u,defaultNumChannels:c,textureTypeHalfFloat:h,textureTypeFloat:p}} +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function zE(e,t){const n=t();return ye().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(e){e[e.DENSE=0]="DENSE",e[e.SHARED_BATCH=1]="SHARED_BATCH"}(AE||(AE={})),function(e){e[e.RENDER=0]="RENDER",e[e.UPLOAD=1]="UPLOAD",e[e.PIXELS=2]="PIXELS",e[e.DOWNLOAD=3]="DOWNLOAD"}(FE||(FE={})),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"}(_E||(_E={}));function PE(e){return!!(ye().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||0===e||5.96e-8e.getExtension(t)),'Extension "'+t+'" not supported on this browser.')}const WE=/ERROR: [0-9]+:([0-9]+):/g;function VE(e,t){const n=WE.exec(t);if(null==n)return console.log(`Couldn't parse line number in error: ${t}`),void console.log(e);const s=+n[1],r=e.split("\n"),a=r.length.toString().length+2,i=r.map(((e,t)=>U((t+1).toString(),a)+e));let o=0;for(let e=0;ee.validateProgram(t))),!1===e.getProgramParameter(t,e.VALIDATE_STATUS))throw console.log(e.getProgramInfoLog(t)),new Error("Shader program validation failed.")}function GE(e,t,n,s,r,a,i){const o=e.getAttribLocation(t,n);return-1!==o&&(zE(e,(()=>e.bindBuffer(e.ARRAY_BUFFER,s))),zE(e,(()=>e.vertexAttribPointer(o,r,e.FLOAT,!1,a,i))),zE(e,(()=>e.enableVertexAttribArray(o))),!0)}function HE(e,t,n,s){zE(e,(()=>function(e,t,n){YE(e,n),zE(e,(()=>e.activeTexture(e.TEXTURE0+n))),zE(e,(()=>e.bindTexture(e.TEXTURE_2D,t)))}(e,t,s))),zE(e,(()=>e.uniform1i(n,s)))}function jE(e,t,n){zE(e,(()=>e.bindFramebuffer(e.FRAMEBUFFER,n))),zE(e,(()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0)))}function qE(e,t){zE(e,(()=>e.bindFramebuffer(e.FRAMEBUFFER,t))),zE(e,(()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0)))}function KE(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 XE(e,t,n){const s=zE(e,(()=>t()));if(null==s)throw new Error(n);return s}function YE(e,t){const n=e.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,s=t+e.TEXTURE0;if(sn){throw new Error(`textureUnit must be in ${`[gl.TEXTURE0, gl.TEXTURE${n}]`}.`)}}function ZE(e,t=2){return P(e.slice(0,e.length-t))}function JE(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 QE(e){let t=[1,1,1];return 0===e.length||1===e.length&&1===e[0]||(t=[ZE(e),...JE(e)]),t}function eR(e){return e%2==0}function tR(e,t){if(B(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],s=t.slice(-1)[0];if(n===s)return!0;if(eR(n)&&eR(s)&&(1===e[0]||1===t[0]))return!0}return e[1]===t[1]&&eR(e[0])&&eR(t[0])}let nR,sR;function rR(e,t){return null!=e.getExtension(t)}function aR(e){try{if(null!=RE(e))return!0}catch(e){return console.log("Error when getting WebGL context: ",e),!1}return!1}function iR(e){if(0===e)return!1;const t=RE(e);if(1!==e){if(rR(t,"EXT_color_buffer_float"))return oR(t);const e="EXT_color_buffer_half_float";if(rR(t,e)){const n=t.getExtension(e);return function(e,t){const n=LE(e,t),s=e.createTexture();e.bindTexture(e.TEXTURE_2D,s);const r=1,a=1;e.texImage2D(e.TEXTURE_2D,0,n.internalFormatHalfFloat,r,a,0,n.textureFormatFloat,n.textureTypeHalfFloat,null);const i=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,i),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,s,0);const o=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(s),e.deleteFramebuffer(i),o}(t,n)}return!1}if(!rR(t,"OES_texture_float"))return!1;if(!rR(t,"WEBGL_color_buffer_float"))return!1;return oR(t)}function oR(e){const t=LE(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 s=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,s),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,n,0);const r=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(n),e.deleteFramebuffer(s),r}function lR(e,t){Array.isArray(e)||(e=[e]),e.forEach((e=>{null!=e&&O("complex64"!==e.dtype,(()=>`${t} does not support complex64 tensors in the WebGL backend.`))}))} +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +const uR=ye(); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function cR(){let e,t,n,s,r,a,i,o,l,u;return 2===ye().getNumber("WEBGL_VERSION")?(e="#version 300 es",t="in",n="out",s="in",r="texture",a="outputColor",i="out vec4 outputColor;",o=ye().getBool("WEBGL2_ISNAN_CUSTOM")?"\n bool isnan_custom(float val) {\n uint floatToUint = floatBitsToUint(val);\n return (floatToUint & 0x7fffffffu) > 0x7f800000u;\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",s="varying",r="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:s,texture2D:r,output:a,defineOutput:i,defineSpecialNaN:o,defineSpecialInf:l,defineRound:u}} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function hR(e,t,n="index"){const s=re(t);return s.map(((t,r)=>`${`int ${e[r]} = ${n} / ${t}`}; ${r===s.length-1?`int ${e[r+1]} = ${n} - ${e[r]} * ${t}`:`index -= ${e[r]} * ${t}`};`)).join("")}function pR(e,t,n="index"){const s=re(t);return s.map(((t,r)=>`${`int ${e[r]} = ${n} / outShapeStrides[${r}]`}; ${r===s.length-1?`int ${e[r+1]} = ${n} - ${e[r]} * outShapeStrides[${r}]`:`index -= ${e[r]} * outShapeStrides[${r}]`};`)).join("")}function dR(e,t,n="index"){const s=function(e,t){const n=e.length,s=e.map((e=>`${t}[${e}]`)),r=new Array(n-1);r[n-2]=s[n-1];for(let e=n-3;e>=0;--e)r[e]=`(${r[e+1]} * ${s[e+1]})`;return r}(e.map(((e,t)=>t)),t);return s.map(((t,r)=>`${`int ${e[r]} = ${n} / ${s[r]}`}; ${r===s.length-1?`int ${e[r+1]} = ${n} - ${e[r]} * ${s[r]}`:`index -= ${e[r]} * ${s[r]}`};`)).join("")}function fR(e){const t=re(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`}uR.registerFlag("HAS_WEBGL",(()=>uR.getNumber("WEBGL_VERSION")>0)),uR.registerFlag("WEBGL_VERSION",(()=>aR(2)?2:aR(1)?1:0)),uR.registerFlag("WEBGL_CHECK_NUMERICAL_PROBLEMS",(()=>!1)),uR.registerFlag("WEBGL_BUFFER_SUPPORTED",(()=>2===uR.get("WEBGL_VERSION"))),uR.registerFlag("WEBGL_CPU_FORWARD",(()=>!0)),uR.registerFlag("WEBGL_FORCE_F16_TEXTURES",(()=>!1)),uR.registerFlag("WEBGL_PACK",(()=>uR.getBool("HAS_WEBGL"))),uR.registerFlag("WEBGL_PACK_NORMALIZATION",(()=>uR.getBool("WEBGL_PACK"))),uR.registerFlag("WEBGL_PACK_CLIP",(()=>uR.getBool("WEBGL_PACK"))),uR.registerFlag("WEBGL_PACK_DEPTHWISECONV",(()=>uR.getBool("WEBGL_PACK"))),uR.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",(()=>uR.getBool("WEBGL_PACK"))),uR.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",(()=>uR.getBool("WEBGL_PACK"))),uR.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",(()=>uR.getBool("WEBGL_PACK"))),uR.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",(()=>uR.getBool("WEBGL_PACK"))),uR.registerFlag("WEBGL_PACK_REDUCE",(()=>uR.getBool("WEBGL_PACK"))),uR.registerFlag("WEBGL_LAZILY_UNPACK",(()=>uR.getBool("WEBGL_PACK"))),uR.registerFlag("WEBGL_CONV_IM2COL",(()=>uR.getBool("WEBGL_PACK"))),uR.registerFlag("WEBGL_MAX_TEXTURE_SIZE",(()=>function(e){if(null==nR){const t=RE(e);nR=t.getParameter(t.MAX_TEXTURE_SIZE)}return nR}(uR.getNumber("WEBGL_VERSION")))),uR.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",(()=>function(e){if(null==sR){const t=RE(e);sR=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,sR)}(uR.getNumber("WEBGL_VERSION")))),uR.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",(()=>{const e=uR.getNumber("WEBGL_VERSION");return 0===e?0:function(e){if(0===e)return 0;let t;const n=RE(e);return t=rR(n,"EXT_disjoint_timer_query_webgl2")&&2===e?2:rR(n,"EXT_disjoint_timer_query")?1:0,t}(e)})),uR.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",(()=>uR.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!zr())),uR.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",(()=>function(e){if(0===e)return!1;const t=RE(e);if(1===e){if(!rR(t,"OES_texture_float"))return!1}else if(!rR(t,"EXT_color_buffer_float"))return!1;return oR(t)}(uR.getNumber("WEBGL_VERSION")))),uR.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",(()=>!uR.getBool("WEBGL_FORCE_F16_TEXTURES")&&uR.getBool("WEBGL_RENDER_FLOAT32_CAPABLE"))),uR.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",(()=>iR(uR.getNumber("WEBGL_VERSION")))),uR.registerFlag("WEBGL_FENCE_API_ENABLED",(()=>{return 2===(e=uR.getNumber("WEBGL_VERSION"))&&null!=RE(e).fenceSync;var e})),uR.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",(()=>uR.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0)),uR.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}.`)})),uR.registerFlag("WEBGL_FLUSH_THRESHOLD",(()=>zr()?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}.`)})),uR.registerFlag("CPU_HANDOFF_SIZE_THRESHOLD",(()=>128)),uR.registerFlag("WEBGL_USE_SHAPES_UNIFORMS",(()=>!1)),uR.registerFlag("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD",(()=>1e5)),uR.registerFlag("TOPK_K_CPU_HANDOFF_THRESHOLD",(()=>128)),uR.registerFlag("WEBGL_EXP_CONV",(()=>!1)),uR.registerFlag("SOFTWARE_WEBGL_ENABLED",(()=>uR.getBool("IS_TEST"))),uR.registerFlag("WEBGL_MAX_SIZE_FOR_NARROW_TEXTURE",(()=>1/0)),uR.registerFlag("WEBGL_AUTO_SQUARIFY_NARROW_TEXTURE_SHAPE",(()=>!1)),uR.registerFlag("WEBGL2_ISNAN_CUSTOM",(()=>!1));const mR="\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:gR}=i;function yR(e,t,n){const s=[];if(e.forEach((e=>{const t=P(e.shapeInfo.logicalShape);if(e.shapeInfo.isUniform?s.push(`uniform float ${e.name}${t>1?`[${t}]`:""};`):(s.push(`uniform sampler2D ${e.name};`),s.push(`uniform int offset${e.name};`)),n.enableShapeUniforms){const{uniformShape:t}=$R(n.packedInputs,e.shapeInfo.logicalShape,e.shapeInfo.texShape);switch(t.length){case 1:s.push(`uniform int ${e.name}Shape;`);break;case 2:s.push(`uniform ivec2 ${e.name}Shape;`);break;case 3:s.push(`uniform ivec3 ${e.name}Shape;`);break;case 4:s.push(`uniform ivec4 ${e.name}Shape;`)}s.push(`uniform ivec2 ${e.name}TexShape;`)}})),n.enableShapeUniforms){switch(t.logicalShape.length){case 1:s.push("uniform int outShape;");break;case 2:s.push("uniform ivec2 outShape;"),s.push("uniform int outShapeStrides;");break;case 3:s.push("uniform ivec3 outShape;"),s.push("uniform ivec2 outShapeStrides;");break;case 4:s.push("uniform ivec4 outShape;"),s.push("uniform ivec3 outShapeStrides;")}s.push("uniform ivec2 outTexShape;")}n.customUniforms&&n.customUniforms.forEach((e=>{s.push(`uniform ${e.type} ${e.name}${e.arrayIndex?`[${e.arrayIndex}]`:""};`)}));const r=s.join("\n"),a=e.map((e=>function(e,t,n=!1,s){let r="";r+=n?xR(e,s):bR(e,s);const a=e.shapeInfo.logicalShape,i=t.logicalShape;a.length<=i.length&&(r+=n?function(e,t){const n=e.name,s=n.charAt(0).toUpperCase()+n.slice(1),r="get"+s+"AtOutCoords",a=e.shapeInfo.logicalShape.length,i=t.logicalShape.length,o=gR(e.shapeInfo.logicalShape,t.logicalShape),l=CR(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===P(e.shapeInfo.logicalShape),m=P(t.logicalShape),g=1===m;if(1!==a||f||g){if(f&&!g)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 ${r}() {\n ${l} coords = getOutputCoords();\n ${c}\n vec4 outputValue = get${s}(${p});\n ${d}\n }\n `}(e,t):function(e,t){const n=e.name,s=n.charAt(0).toUpperCase()+n.slice(1),r="get"+s+"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&&B(i,a))return`\n float ${r}() {\n return sampleTexture(${n}, resultUV);\n }\n `;const u=CR(l),c=gR(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="";f=l<2&&o>0?"coords":e.shapeInfo.logicalShape.map(((e,t)=>`coords.${d[t+h]}`)).join(", ");return`\n float ${r}() {\n ${u} coords = getOutputCoords();\n ${p}\n return get${s}(${f});\n }\n `}(e,t));return r}(e,t,n.packedInputs,n.enableShapeUniforms))).join("\n"),i=t.texShape,o=cR(),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){const t=`${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 ${wR}\n ${vR}\n ${kR}\n `;return t}(o);t.isPacked?(u=function(e,t,n){switch(e.length){case 0:return NR();case 1:return function(e,t,n){const s=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(1===s[0])return 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 * ${s[1]}.0);\n }\n `;if(1===s[1])return 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 * ${s[0]}.0);\n }\n `;if(n)return"\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 ";return`\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${s[0]}, ${s[1]}));\n return 2 * (resTexRC.x * ${s[1]} + resTexRC.y);\n }\n `}(0,t,n);case 2:return function(e,t,n){const s=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(B(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(${s[0]}, ${s[1]}));\n }\n `;const r=Math.ceil(e[1]/2);if(n)return"\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 ";return`\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${s[0]}, ${s[1]}));\n\n int index = resTexRC.x * ${s[1]} + resTexRC.y;\n int r = 2 * (index / ${r});\n int c = imod(index, ${r}) * 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 s=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],r=Math.ceil(e[2]/2),a=r*Math.ceil(e[1]/2);return`\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${s[0]}, ${s[1]}));\n int index = resTexRC.x * ${s[1]} + resTexRC.y;\n\n int b = index / ${a};\n index -= b * ${a};\n\n int r = 2 * (index / ${r});\n int c = imod(index, ${r}) * 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 s=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],r=Math.ceil(e[e.length-1]/2),a=r*Math.ceil(e[e.length-2]/2);let i=a,o="",l="b, r, c";for(let t=2;t1&&!B(t,n)&&s.lengthe[t])).join(", ")} +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function AR(e,t,n,s){const r=n.map(((e,n)=>{const s={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&&(s.flatOffset=e.texData.slice.flatOffset),{name:t.variableNames[n],shapeInfo:s}})),a=r.map((e=>e.shapeInfo)),i={logicalShape:s.shape,texShape:s.texData.texShape,isUniform:!1,isPacked:s.texData.isPacked,flatOffset:null},o=yR(r,i,t),l=function(e,t){const n=XE(e,(()=>e.createShader(e.FRAGMENT_SHADER)),"Unable to create fragment WebGLShader.");if(zE(e,(()=>e.shaderSource(n,t))),zE(e,(()=>e.compileShader(n))),ye().get("ENGINE_COMPILE_ONLY"))return n;if(!1===e.getShaderParameter(n,e.COMPILE_STATUS))throw VE(t,e.getShaderInfoLog(n)),new Error("Failed to compile fragment shader.");return n}(e.gl,o),u=e.createProgram(l);return ye().get("ENGINE_COMPILE_ONLY")?{program:t,fragmentShader:l,source:o,webGLProgram:u,inShapeInfos:a,outShapeInfo:i,uniformLocations:null,customUniformLocations:null,infLoc:null,nanLoc:null,inShapesLocations:null,inTexShapesLocations:null,outShapeLocation:null,outShapeStridesLocation:null,outTexShapeLocation:null}:Object.assign({program:t,fragmentShader:l,source:o,webGLProgram:u,inShapeInfos:a,outShapeInfo:i},FR(e,t,u))}function FR(e,t,n){const s={},r={},a={},i=[];let o,l,u,c=null,h=null;h=e.getUniformLocation(n,"NAN",!1),1===ye().getNumber("WEBGL_VERSION")&&(c=e.getUniformLocation(n,"INFINITY",!1));const p=!1;for(let i=0;i{i[s]=e.getUniformLocation(n,t.name,p)})),{uniformLocations:s,customUniformLocations:i,infLoc:c,nanLoc:h,inShapesLocations:r,inTexShapesLocations:a,outShapeLocation:o,outShapeStridesLocation:u,outTexShapeLocation:l}}function _R(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 s=e.logicalShape,r=t[n],a=r.shape;if(!B(s,a))throw Error(`Binary was compiled with different shapes than the current args. Shapes ${s} and ${a} must match`);if(e.isUniform&&r.isUniform)return;const i=e.texShape,o=r.isUniform?null:r.texData.texShape;if(!B(i,o))throw Error(`Binary was compiled with different texture shapes than the current args. Shape ${i} and ${o} must match`)}))}function DR(e){return ye().getBool("WEBGL_USE_SHAPES_UNIFORMS")&&e<=4} +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class OR{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=AE.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];const t=cR();this.outputShape=e,this.enableShapeUniforms=DR(this.outputShape.length),this.userCode=`\n ivec3 outCoordsFromFlatIndex(int index) {\n ${this.enableShapeUniforms?pR(["r","c","d"],e):hR(["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 `}} +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class MR{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=AE.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];const t=cR();this.outputShape=e,this.enableShapeUniforms=DR(this.outputShape.length),this.userCode=`\n ivec3 outCoordsFromFlatIndex(int index) {\n ${this.enableShapeUniforms?pR(["r","c","d"],e):hR(["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 `}} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class LR{constructor(e){this.variableNames=["A"],this.outTexUsage=FE.DOWNLOAD;const t=cR();this.outputShape=e,this.userCode=`\n ${mR}\n\n void main() {\n float x = getAAtOutCoords();\n ${t.output} = encode_float(x);\n }\n `}} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class zR{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=FE.DOWNLOAD;const t=cR();this.outputShape=e,this.userCode=`\n ${mR}\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 `}} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class PR{constructor(e,t=!1){this.variableNames=["A"],this.customUniforms=[{name:"texShape",type:"ivec2"}];const n=cR();this.outputShape=e,this.enableShapeUniforms=DR(this.outputShape.length);let s="result";t&&(s="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":fR(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(${s}, 0., 0., 0.);\n }\n `}} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class BR{constructor(e,t=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.customUniforms=[{name:"texShape",type:"ivec2"}];const n=cR();this.outputShape=e,this.enableShapeUniforms=DR(this.outputShape.length);let s="",r="result";t&&(r="floor(result * 255. + 0.5)");for(let t=0;t<=1;t++)for(let r=0;r<=1;r++){const a=2*t+r;s+=`\n localCoords = coords;\n if(localCoords[2] + ${r} < ${this.enableShapeUniforms?"outShape[2]":`${e[2]}`}) {\n localCoords[2] += ${r};\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":fR(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 ${s}\n\n ${n.output} = ${r};\n }\n `}} +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function WR(e){const t=cR();return function(e,t){const n=XE(e,(()=>e.createShader(e.VERTEX_SHADER)),"Unable to create vertex WebGLShader.");if(zE(e,(()=>e.shaderSource(n,t))),zE(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 }`)}function VR(e){return function(e,t){const n=XE(e,(()=>e.createBuffer()),"Unable to create WebGLBuffer");return zE(e,(()=>e.bindBuffer(e.ARRAY_BUFFER,n))),zE(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]))}function UR(e){return function(e,t){const n=XE(e,(()=>e.createBuffer()),"Unable to create WebGLBuffer");return zE(e,(()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,n))),zE(e,(()=>e.bufferData(e.ELEMENT_ARRAY_BUFFER,t,e.STATIC_DRAW))),n}(e,new Uint16Array([0,1,2,2,1,3]))}function GR(e,t,n,s,r,a){!function(e,t){const n=ye().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 XE(e,(()=>e.createTexture()),"Unable to create WebGLTexture.")}(e),o=e.TEXTURE_2D;return zE(e,(()=>e.bindTexture(o,i))),zE(e,(()=>e.texParameteri(o,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE))),zE(e,(()=>e.texParameteri(o,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE))),zE(e,(()=>e.texParameteri(o,e.TEXTURE_MIN_FILTER,e.NEAREST))),zE(e,(()=>e.texParameteri(o,e.TEXTURE_MAG_FILTER,e.NEAREST))),1===ye().getNumber("WEBGL_VERSION")?zE(e,(()=>e.texImage2D(o,0,s,t,n,0,r,a,null))):zE(e,(()=>e.texStorage2D(o,1,s,t,n))),zE(e,(()=>e.bindTexture(e.TEXTURE_2D,null))),{texture:i,texShape:[n,t]}}function HR(e){return e.internalFormatFloat}function jR(e){return e.internalFormatHalfFloat}function qR(e){return e.downloadTextureFormat}function KR(e){return e.internalFormatPackedFloat}function XR(e){return e.internalFormatPackedHalfFloat}function YR(e,t,n,s,r,a,i,o){const l=e,u=new Float32Array(function(e,t){const[n,s]=ME(e,t);return n*s*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} +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class ZR{constructor(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];const t=ye().getNumber("WEBGL_VERSION");null!=e?(this.gl=e,function(e,t){$E[e]=t}(t,e)):this.gl=RE(t);let n="WEBGL_color_buffer_float";const s="EXT_color_buffer_half_float";if(this.parallelCompilationExtension=this.gl.getExtension("KHR_parallel_shader_compile"),1===ye().getNumber("WEBGL_VERSION")){const e="OES_texture_float",t="OES_texture_half_float";if(this.textureFloatExtension=BE(this.gl,e),rR(this.gl,t))this.textureHalfFloatExtension=BE(this.gl,t);else if(ye().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),rR(this.gl,s))this.colorBufferHalfFloatExtension=BE(this.gl,s);else if(ye().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",rR(this.gl,n))this.colorBufferFloatExtension=this.gl.getExtension(n);else{if(!rR(this.gl,s))throw new Error("GL context does not support color renderable floats");this.colorBufferHalfFloatExtension=this.gl.getExtension(s)}this.vertexBuffer=VR(this.gl),this.indexBuffer=UR(this.gl),this.framebuffer=function(e){return XE(e,(()=>e.createFramebuffer()),"Unable to create WebGLFramebuffer.")}(this.gl),this.textureConfig=LE(this.gl,this.textureHalfFloatExtension)}get debug(){return ye().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;zE(e,(()=>e.finish())),zE(e,(()=>e.bindFramebuffer(e.FRAMEBUFFER,null))),zE(e,(()=>e.deleteFramebuffer(this.framebuffer))),zE(e,(()=>e.bindBuffer(e.ARRAY_BUFFER,null))),zE(e,(()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null))),zE(e,(()=>e.deleteBuffer(this.indexBuffer))),this.disposed=!0}createFloat32MatrixTexture(e,t){return this.throwIfDisposed(),function(e,t,n,s){const[r,a]=DE(t,n);return GR(e,r,a,HR(s),s.textureFormatFloat,e.FLOAT)}(this.gl,e,t,this.textureConfig)}createFloat16MatrixTexture(e,t){return this.throwIfDisposed(),function(e,t,n,s){const[r,a]=DE(t,n);return GR(e,r,a,jR(s),s.textureFormatFloat,s.textureTypeHalfFloat)}(this.gl,e,t,this.textureConfig)}createUnsignedBytesMatrixTexture(e,t){return this.throwIfDisposed(),function(e,t,n,s){const[r,a]=DE(t,n);return GR(e,r,a,qR(s),e.RGBA,e.UNSIGNED_BYTE)}(this.gl,e,t,this.textureConfig)}uploadPixelDataToTexture(e,t){this.throwIfDisposed(),function(e,t,n){zE(e,(()=>e.bindTexture(e.TEXTURE_2D,t))),n.data instanceof Uint8Array?2===ye().getNumber("WEBGL_VERSION")?zE(e,(()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,n.width,n.height,e.RGBA,e.UNSIGNED_BYTE,n.data))):zE(e,(()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,n.width,n.height,0,e.RGBA,e.UNSIGNED_BYTE,n.data))):2===ye().getNumber("WEBGL_VERSION")?zE(e,(()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,e.RGBA,e.UNSIGNED_BYTE,n))):zE(e,(()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,n))),zE(e,(()=>e.bindTexture(e.TEXTURE_2D,null)))}(this.gl,e,t)}uploadDenseMatrixToTexture(e,t,n,s){this.throwIfDisposed(),function(e,t,n,s,r,a){let i,o,l;zE(e,(()=>e.bindTexture(e.TEXTURE_2D,t))),r instanceof Uint8Array?(i=new Uint8Array(n*s*4),o=e.UNSIGNED_BYTE,l=e.RGBA):(i=new Float32Array(n*s*4),o=e.FLOAT,l=a.internalFormatPackedFloat),i.set(r),2===ye().getNumber("WEBGL_VERSION")?zE(e,(()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,s,e.RGBA,o,i))):zE(e,(()=>e.texImage2D(e.TEXTURE_2D,0,l,n,s,0,e.RGBA,o,i))),zE(e,(()=>e.bindTexture(e.TEXTURE_2D,null)))}(this.gl,e,t,n,s,this.textureConfig)}createFloat16PackedMatrixTexture(e,t){return this.throwIfDisposed(),function(e,t,n,s){const[r,a]=ME(t,n);return GR(e,r,a,XR(s),e.RGBA,s.textureTypeHalfFloat)}(this.gl,e,t,this.textureConfig)}createPackedMatrixTexture(e,t){return this.throwIfDisposed(),function(e,t,n,s){const[r,a]=ME(t,n);return GR(e,r,a,KR(s),e.RGBA,e.FLOAT)}(this.gl,e,t,this.textureConfig)}deleteMatrixTexture(e){this.throwIfDisposed(),this.outputTexture===e&&(qE(this.gl,this.framebuffer),this.outputTexture=null),zE(this.gl,(()=>this.gl.deleteTexture(e)))}downloadByteEncodedFloatMatrixFromOutputTexture(e,t,n){return this.downloadMatrixDriver(e,(()=>function(e,t,n,s){const[r,a]=DE(t,n),i=new Uint8Array(t*n*4);return zE(e,(()=>e.readPixels(0,0,r,a,s.downloadTextureFormat,e.UNSIGNED_BYTE,i))),new Float32Array(i.buffer)}(this.gl,t,n,this.textureConfig)))}downloadPackedMatrixFromBuffer(e,t,n,s,r,a){return YR(this.gl,e,0,0,0,r,a,this.textureConfig)}downloadFloat32MatrixFromBuffer(e,t){return function(e,t,n){const s=e,r=new Float32Array(n);return s.bindBuffer(s.PIXEL_PACK_BUFFER,t),s.getBufferSubData(s.PIXEL_PACK_BUFFER,0,r),s.bindBuffer(s.PIXEL_PACK_BUFFER,null),r}(this.gl,e,t)}createBufferFromTexture(e,t,n){this.bindTextureToFrameBuffer(e);const s=function(e,t,n){const s=e.createBuffer();zE(e,(()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,s)));const r=16*t*n;return zE(e,(()=>e.bufferData(e.PIXEL_PACK_BUFFER,r,e.STREAM_READ))),zE(e,(()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,0))),zE(e,(()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,null))),s}(this.gl,t,n,this.textureConfig);return this.unbindTextureToFrameBuffer(),s}createAndWaitForFence(){const e=this.createFence(this.gl);return this.pollFence(e)}createFence(e){let t,n;if(ye().getBool("WEBGL_FENCE_API_ENABLED")){const s=e,r=s.fenceSync(s.SYNC_GPU_COMMANDS_COMPLETE,0);e.flush(),n=()=>{const e=s.clientWaitSync(r,0,0);return e===s.ALREADY_SIGNALED||e===s.CONDITION_SATISFIED},t=r}else ye().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(t=this.beginQuery(),this.endQuery(),n=()=>this.isQueryAvailable(t,ye().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 s=new Float32Array(t*n*4);return zE(e,(()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,s))),s}(this.gl,t,n)))}createProgram(e){this.throwIfDisposed();const t=this.gl;null==this.vertexShader&&(this.vertexShader=WR(t));const n=function(e){return XE(e,(()=>e.createProgram()),"Unable to create WebGLProgram.")}(t);return zE(t,(()=>t.attachShader(n,this.vertexShader))),zE(t,(()=>t.attachShader(n,e))),function(e,t){if(zE(e,(()=>e.linkProgram(t))),!ye().get("ENGINE_COMPILE_ONLY")&&!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&&UE(t,n),this.vertexAttrsAreBound||(this.setProgram(n),this.vertexAttrsAreBound=function(e,t,n){return zE(e,(()=>e.bindBuffer(e.ARRAY_BUFFER,n))),GE(e,t,"clipSpacePos",n,3,20,0)&&GE(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&&zE(this.gl,(()=>this.gl.deleteProgram(e)))}setProgram(e){this.throwIfDisposed(),this.program=e,null!=this.program&&this.debug&&UE(this.gl,this.program),zE(this.gl,(()=>this.gl.useProgram(e)))}getUniformLocation(e,t,n=!0){return this.throwIfDisposed(),n?function(e,t,n){return XE(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(),zE(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(),HE(this.gl,e,t,n)}setOutputMatrixTexture(e,t,n){this.setOutputMatrixTextureDriver(e,n,t)}setOutputPackedMatrixTexture(e,t,n){this.throwIfDisposed();const[s,r]=ME(t,n);this.setOutputMatrixTextureDriver(e,s,r)}setOutputMatrixWriteRegion(e,t,n,s){this.setOutputMatrixWriteRegionDriver(n,e,s,t)}setOutputPackedMatrixWriteRegion(e,t,n,s){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")}debugValidate(){null!=this.program&&UE(this.gl,this.program),KE(this.gl)}executeProgram(){this.throwIfDisposed(),this.throwIfNoProgram();const e=this.gl;this.debug&&this.debugValidate(),zE(e,(()=>e.drawElements(e.TRIANGLES,6,e.UNSIGNED_SHORT,0)))}blockUntilAllProgramsCompleted(){this.throwIfDisposed(),zE(this.gl,(()=>this.gl.finish()))}getQueryTimerExtension(){return null==this.disjointQueryTimerExtension&&(this.disjointQueryTimerExtension=BE(this.gl,2===ye().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===ye().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===ye().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 G((()=>this.disposed||this.isQueryAvailable(e,ye().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")))),this.getQueryTime(e,ye().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(),s=t.getQueryParameter(e,t.QUERY_RESULT_AVAILABLE);return null==this.disjoint&&(this.disjoint=this.gl.getParameter(n.GPU_DISJOINT_EXT)),s&&!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){if(this.itemsToPoll.push({isDoneFn:e,resolveFn:t}),this.itemsToPoll.length>1)return;let n;"setTimeoutCustom"in ye().platform&&(n=ye().platform.setTimeoutCustom.bind(ye().platform)),G((()=>(this.pollItems(),0===this.itemsToPoll.length)),(()=>0),null,n)}bindTextureToFrameBuffer(e){this.throwIfDisposed(),jE(this.gl,e,this.framebuffer),this.debug&&KE(this.gl)}unbindTextureToFrameBuffer(){null!=this.outputTexture?(jE(this.gl,this.outputTexture,this.framebuffer),this.debug&&KE(this.gl)):qE(this.gl,this.framebuffer)}downloadMatrixDriver(e,t){this.bindTextureToFrameBuffer(e);const n=t();return this.unbindTextureToFrameBuffer(),n}setOutputMatrixTextureDriver(e,t,n){this.throwIfDisposed();const s=this.gl;jE(s,e,this.framebuffer),this.debug&&KE(s),this.outputTexture=e,zE(s,(()=>s.viewport(0,0,t,n))),zE(s,(()=>s.scissor(0,0,t,n)))}setOutputMatrixWriteRegionDriver(e,t,n,s){this.throwIfDisposed(),zE(this.gl,(()=>this.gl.scissor(e,t,n,s)))}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.")}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +const{mx:JR,XI:QR,Nk:eA,ct:tA,YG:nA,hH:sA,z3:rA,sG:aA,uM:iA,vS:oA,qB:lA,GG:uA,rq:cA,lg:hA,WR:pA,cu:dA,GE:fA,px:mA,jC:gA,He:yA,hE:bA,BF:xA,Dk:wA,cl:vA,_B:kA,ub:IA,Ku:NA,qy:SA,Zy:TA,bu:CA,zv:$A,dH:EA,HS:RA,yH:AA,l3:FA,z9:_A,x6:DA,eW:OA,GK:MA,SP:LA,f6:zA,dl:PA,Dw:BA,xT:WA,_X:VA,wz:UA}=C; +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function GA(e,t){return["x","y","z","w","u","v"].slice(0,t).map((t=>`${e}.${t}`))}function HA(e,t){return 1===t?[e]:GA(e,t)} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class jA{constructor(e){if(this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outputShape=e,this.rank=e.length,this.enableShapeUniforms=DR(this.outputShape.length),0===this.rank)this.userCode="\n void main() {\n setOutput(vec4(getA(), 0., 0., 0.));\n }\n ";else{const e=HA("rc",this.rank),t=CR(this.rank),n=this.getOutOfBoundsCondition(e),s=this.getSetup(e),r=this.getOutput(e);this.userCode=`\n void main() {\n ${t} rc = getOutputCoords();\n\n if(${n}) {\n setOutput(vec4(0));\n } else {\n ${s}\n\n setOutput(vec4(${r}));\n }\n }\n `}}getSourceCoordsArr(e){const t=[];for(let n=0;n<=1;n++)for(let s=0;s<=1;s++){let r=`${0===n?"r":"rp1"}, ${0===s?"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 >= ${s};\n `}getOutput(e){const t=this.getSourceCoordsArr(e);if(1===this.rank){return`getA(rc), (rc + 1 >= ${this.enableShapeUniforms?"outShape":this.outputShape[0]} ? 0. : getA(rc + 1)), 0, 0`}return`getA(${t[0]}),\n cEdge ? 0. : getA(${t[1]}),\n rEdge ? 0. : getA(${t[2]}),\n rEdge || cEdge ? 0. : getA(${t[3]})`}} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class qA{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec3"}],this.outputShape=e,this.enableShapeUniforms=DR(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 s,r;this.userCode=`\n ${s=t,r=this.enableShapeUniforms,`\n ivec3 inputCoordsFromReshapedOutCoords(int index) {\n ${r?dR(["r","c","d"],"inputShape"):hR(["r","c","d"],s)}\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":fR(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 `}} +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class KA{constructor(e){this.gpgpu=e,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0,this.freeTextures={},this.logEnabled=!1,this.usedTextures={}}acquireTexture(e,t,n){const s=YA(t,n),r=ZA(e,s,n);r in this.freeTextures||(this.freeTextures[r]=[]),r in this.usedTextures||(this.usedTextures[r]=[]);const a=XA(e,s,this.gpgpu.gl,this.gpgpu.textureConfig,n);if(this.freeTextures[r].length>0){this.numFreeTextures--,this.numUsedTextures++,this._numBytesFree-=a,this.log();const e=this.freeTextures[r].shift();return this.usedTextures[r].push(e),e}let i;return s===_E.PACKED_2X2_FLOAT32?i=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):s===_E.PACKED_2X2_FLOAT16?i=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):s===_E.UNPACKED_FLOAT32?i=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):s===_E.UNPACKED_FLOAT16?i=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):s===_E.PACKED_4X1_UNSIGNED_BYTE&&(i=this.gpgpu.createUnsignedBytesMatrixTexture(e[0],e[1])),this.usedTextures[r].push(i),this.numUsedTextures++,this._numBytesAllocated+=a,this.log(),i}releaseTexture(e,t,n,s){if(null==this.freeTextures)return;const r=YA(n,s),a=ZA(t,r,s);a in this.freeTextures||(this.freeTextures[a]=[]);const i=XA(t,r,this.gpgpu.gl,this.gpgpu.textureConfig,s),o=ye().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 XA(e,t,n,s,r){const a=function(e,t){switch(e){case _E.PACKED_2X2_FLOAT32:return KR(t);case _E.PACKED_2X2_FLOAT16:return XR(t);case _E.UNPACKED_FLOAT32:return HR(t);case _E.UNPACKED_FLOAT16:return jR(t);case _E.PACKED_4X1_UNSIGNED_BYTE:return qR(t);default:throw new Error(`Unknown physical texture type ${e}`)}}(t,s);let i;if(r){const[t,n]=ME(e[0],e[1]);i=t*n}else{const[t,n]=DE(e[0],e[1]);i=t*n}const o=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);return i*o}function YA(e,t){if(e===FE.UPLOAD)return _E.PACKED_2X2_FLOAT32;if(e===FE.RENDER||null==e)return function(e){return ye().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?_E.PACKED_2X2_FLOAT32:_E.UNPACKED_FLOAT32:e?_E.PACKED_2X2_FLOAT16:_E.UNPACKED_FLOAT16}(t);if(e===FE.DOWNLOAD||e===FE.PIXELS)return _E.PACKED_4X1_UNSIGNED_BYTE;throw new Error(`Unknown logical texture type ${e}`)}function ZA(e,t,n){return`${e[0]}_${e[1]}_${t}_${n}`} +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class JA{constructor(e,t){this.variableNames=["A"],this.outputShape=e,this.enableShapeUniforms=DR(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 QA="if (isnan(x)) return x;",eF="return abs(x);";const tF=QA+"\n return (x < 0.0) ? 0.0 : x;\n",nF=QA+"\n return (x < 0.0) ? 0.0 : min(6.0, x);\n",sF="return x;";class rF{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.enableShapeUniforms=DR(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 `}} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class aF{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e,this.enableShapeUniforms=DR(this.outputShape.length);const t=e.length,n=HA("rc",t),s=CR(t),r=function(e,t){if(1===e)return"rc";let n="";for(let s=0;st.push(e)))}const t=this.texData.get(e),{values:n,shape:s,slice:r,dtype:a,complexTensorInfos:i,isPacked:o}=t;if(null!=r){let t;t=o?new rF(s,sF):new JA(s,sF);const n=this.runWebGLProgram(t,[{dataId:e,shape:s,dtype:a}],a),r=this.read(n.dataId);return this.disposeIntermediateTensorInfo(n),r}if(null!=n)return this.convertAndCacheOnCPU(e);if(ye().getBool("DEBUG")&&!ye().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&2===ye().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&&ye().get("WEBGL_BUFFER_SUPPORTED")){l=this.decode(e);const t=this.texData.get(l.dataId);c=this.gpgpu.createBufferFromTexture(t.texture.texture,...OE(s))}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=cd(e[0],e[1])}else if(null==c)u=this.getValuesFromTexture(e);else{const e=P(s);u=this.gpgpu.downloadFloat32MatrixFromBuffer(c,e)}if(null!=l&&this.disposeIntermediateTensorInfo(l),null!=c){const e=this.gpgpu.gl;zE(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)&&Xi().removeDataId(e,this),this.pendingDeletes--),h}readToGPU(e,t={}){const n=this.texData.get(e),{values:s,shape:r,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 rF(r,sF):new JA(r,sF);const s=this.runWebGLProgram(n,[{dataId:e,shape:r,dtype:i}],i),a=this.readToGPU(s,t);return this.disposeIntermediateTensorInfo(s),a}if(null==l)throw null!=s?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=Xi().makeTensorFromTensorInfo(u),h=this.texData.get(u.dataId);return Object.assign({tensorRef:c},h.texture)}bufferSync(e){const t=this.readSync(e.dataId);if("string"===e.dtype)try{const n=t.map((e=>sr(e)));return Ya(e.shape,e.dtype,n)}catch(e){throw new Error("Failed to decode encoded string bytes into utf-8")}return Ya(e.shape,e.dtype,t)}checkNumericalProblems(e){if(null!=e)for(let t=0;t0}time(e){const t=this.activeTimers,n=[];let s=!1;null==this.programTimersStack?(this.programTimersStack=n,s=!0):this.activeTimers.push(n),this.activeTimers=n,e();const r=z(this.activeTimers.map((e=>e.query))).filter((e=>null!=e)),a=z(this.activeTimers.map((e=>e.name))).filter((e=>null!=e));this.activeTimers=t,s&&(this.programTimersStack=null);const i={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null};return(async()=>{if(ye().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0){const e=await Promise.all(r);i.kernelMs=function(e){let t=0;for(let n=0;ne.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 ye().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:tr(),endMs:null}}endTimer(e){return ye().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),e):(e.endMs=tr(),e)}async getQueryTime(e){if(ye().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:s,usage:r,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(s,n),this.textureManager.releaseTexture(t,s,r,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=lF){return ye().getBool("WEBGL_CPU_FORWARD")&&e.every((e=>null==this.texData.get(e.dataId).texture&&P(e.shape)0&&Q(n[0])){const r=n.map((e=>nr(e)));s=this.write(r,e,t)}else s=this.write(n,e,t);return this.texData.get(s).usage=null,{dataId:s,shape:e,dtype:t}}makeOutput(e,t,n){return Xi().makeTensorFromTensorInfo(this.makeTensorInfo(e,t,n),this)}unpackTensor(e){const t=new aF(e.shape);return this.runWebGLProgram(t,[e],e.dtype)}packTensor(e){const t=new jA(e.shape);return this.runWebGLProgram(t,[e],e.dtype,null,!0)}packedReshape(e,t){const n=[ZE(e.shape),...JE(e.shape)],s={dtype:e.dtype,shape:n,dataId:e.dataId},r=[ZE(t),...JE(t)],a=new qA(r,n),i=[n],o=this.runWebGLProgram(a,[s],e.dtype,i,!0);return{dataId:o.dataId,shape:t,dtype:o.dtype}}decode(e,t){const n=this.texData.get(e),{isPacked:s,shape:r,dtype:a}=n;if(null!=t){O(P(r)<=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=QE(r);let o;o=s?new MR(i):new OR(i);const l=[null!=t?t:OE(i)];return{dtype:a,shape:r,dataId:this.runWebGLProgram(o,[{shape:i,dtype:a,dataId:e}],a,l,!0,t).dataId}}runWebGLProgram(e,t,n,s,r=!1,a){const i=this.makeTensorInfo(e.outputShape,n),o=this.texData.get(i.dataId);if(e.packedOutput&&(o.isPacked=!0),e.outPackingScheme===AE.DENSE){const t=null!=a?a:OE(e.outputShape);o.texShape=t.map((e=>2*e))}if(null!=e.outTexUsage&&(o.usage=e.outTexUsage),0===P(i.shape))return o.values=K(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&&P(t.shape)<=ye().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&&!tR(n.shape,t.shape)){const e=t,s=t.shape;t.shape=n.shape,t=this.packedReshape(t,s),l.push(t),n=this.texData.get(t.dataId),e.shape=s}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 s="";t.concat(n).forEach((t=>{const r=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}=$R(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=re(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&&B(t.shape,a),f=1===P(t.shape),m=wi(t.shape,n.shape),g=!e.packedInputs&&p===n.shape.length&&B(a,n.texData.texShape),y=e.packedInputs||o.length>2?"":`${a[0]>1}_${a[1]>1}`;s+=`${p}_${g}_${i?l:""}_${o.length}_${f}_${m}_${d}_${u}_${c}_${h}_${y}_${r}`}else{const e=t.isUniform?"uniform":t.texData.texShape;s+=`${t.shape}_${e}_${r}`}}));const r=e.userCode;let a=e.constructor.name;return a+="_"+s+"_"+r+`${ye().getNumber("WEBGL_VERSION")}`,a}(e,u,c),p=this.getAndSaveBinary(h,(()=>AR(this.gpgpu,e,u,c))),d=null!=this.activeTimers;let f;d&&(f=this.startTimer()),ye().get("ENGINE_COMPILE_ONLY")||function(e,t,n,s,r){t.program.enableShapeUniforms||(_R(t.inShapeInfos,n),_R([t.outShapeInfo],[s]));const a=s.texData.texture,i=s.texData.texShape;s.texData.isPacked?e.setOutputPackedMatrixTexture(a.texture,i[0],i[1]):e.setOutputMatrixTexture(a.texture,i[0],i[1]),e.setProgram(t.webGLProgram),1===ye().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,s)=>{const r=t.program.variableNames[s],a=t.uniformLocations[r],i=t.uniformLocations[`offset${r}`],o=t.inShapesLocations[`${r}Shape`],l=t.inTexShapesLocations[`${r}TexShape`];if(o){const{uniformShape:s}=$R(t.program.packedInputs,n.shape,n.texData.texShape);switch(s.length){case 1:e.gl.uniform1iv(o,new Int32Array(s));break;case 2:e.gl.uniform2iv(o,new Int32Array(s));break;case 3:e.gl.uniform3iv(o,new Int32Array(s));break;case 4:e.gl.uniform4iv(o,new Int32Array(s))}}if(l&&e.gl.uniform2i(l,n.texData.texShape[0],n.texData.texShape[1]),null!=a)if(n.isUniform)if(P(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,s)}));const o=t.outShapeLocation;if(o)switch(s.shape.length){case 1:e.gl.uniform1iv(o,new Int32Array(s.shape));break;case 2:e.gl.uniform2iv(o,new Int32Array(s.shape));break;case 3:e.gl.uniform3iv(o,new Int32Array(s.shape));break;case 4:e.gl.uniform4iv(o,new Int32Array(s.shape))}if(t.outShapeStridesLocation){const n=re(s.shape);switch(s.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,s.texData.texShape[0],s.texData.texShape[1]),t.program.customUniforms&&r&&t.program.customUniforms.forEach(((n,s)=>{const a=t.customUniformLocations[s],i=r[s];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,s),l.forEach((e=>this.disposeIntermediateTensorInfo(e))),d&&(f=this.endTimer(f),this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(f)}));const m=ye().get("WEBGL_FLUSH_THRESHOLD");if(m>0){const e=tr();e-this.lastGlFlushTime>m&&(this.gpgpu.gl.flush(),this.lastGlFlushTime=e)}if(!ye().getBool("WEBGL_LAZILY_UNPACK")&&o.isPacked&&!1===r){const e=this.unpackTensor(i);return this.disposeIntermediateTensorInfo(i),e}return i}compileAndRun(e,t,n,s,r=!1){n=n||t[0].dtype;return this.runWebGLProgram(e,t,n,s,r)}getAndSaveBinary(e,t){return e in this.binaryCache||(this.binaryCache[e]=t()),this.binaryCache[e]}getTextureManager(){return this.textureManager}dispose(){if(!this.disposed){if(!ye().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=Zi((()=>{if(!ye().get("WEBGL_RENDER_FLOAT32_ENABLED")){const e=ye().getBool("DEBUG");ye().set("DEBUG",!1);const t=this.abs(no(1e-8)).dataSync()[0];if(ye().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:s,values:r,texture:a,usage:i,isPacked:o}=t;if(null!=a)return;const l=null!=this.activeTimers;let u;l&&(u=tr());let c=t.texShape;if(null==c&&(c=function(e,t=!1){let n=ye().getNumber("WEBGL_MAX_TEXTURE_SIZE"),s=ye().getNumber("WEBGL_MAX_SIZE_FOR_NARROW_TEXTURE");if(s===1/0&&ye().getBool("WEBGL_AUTO_SQUARIFY_NARROW_TEXTURE_SHAPE")&&(s=n/2),t&&(n*=2,s*=2,1===(e=e.map(((t,n)=>n>=e.length-2?_(e[n]):e[n]))).length&&(e=[2,e[0]])),2!==e.length){const t=q(e);e=t.newShape}let r=P(e),a=null;e.length<=1&&r<=n?a=[1,r]:2===e.length&&e[0]<=n&&e[1]<=n?a=e:3===e.length&&e[0]*e[1]<=n&&e[2]<=n?a=[e[0]*e[1],e[2]]:3===e.length&&e[0]<=n&&e[1]*e[2]<=n?a=[e[0],e[1]*e[2]]:4===e.length&&e[0]*e[1]*e[2]<=n&&e[3]<=n?a=[e[0]*e[1]*e[2],e[3]]:4===e.length&&e[0]<=n&&e[1]*e[2]*e[3]<=n&&(a=[e[0],e[1]*e[2]*e[3]]);const i=null!=a&&Math.max(...a)>s&&Math.min(...a)<=(t?2:1)&&Math.min(...a)>0;if(null==a||i)if(t){const t=ZE(e);let n=2,s=2;e.length&&([n,s]=JE(e)),r=t*(n/2)*(s/2),a=V(r).map((e=>2*e))}else a=V(r);return a}(n,o),t.texShape=c),null!=r){const e=QE(n);let a,i=c[1],h=c[0];const p=r instanceof Uint8Array||r instanceof Uint8ClampedArray;!o&&p||([i,h]=ME(c[0],c[1])),a=o?new BR(e,p):new PR(e,p);const d=p?[h,i]:c,f=this.makeTensorInfo(d,s),m=this.texData.get(f.dataId);m.usage=p?FE.PIXELS:FE.UPLOAD,m.texShape=d,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(f.dataId),i,h,r);const g=[[h,i]],y=!0,b=this.runWebGLProgram(a,[f],s,g,y),x=this.texData.get(b.dataId);t.texShape=x.texShape,t.isPacked=x.isPacked,t.usage=x.usage,ye().get("ENGINE_COMPILE_ONLY")?this.disposeData(b.dataId):(t.texture=x.texture,t.values=null,this.texData.delete(b.dataId)),this.disposeIntermediateTensorInfo(f),l&&(this.uploadWaitMs+=tr()-u)}else{const e=this.acquireTexture(c,i,s,o);t.texture=e}}convertAndCacheOnCPU(e,t){const n=this.texData.get(e),{dtype:s}=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,s)}computeBytes(e,t){return e[0]*e[1]*J(t)}checkCompileCompletion(){for(const[,e]of Object.entries(this.binaryCache))this.checkCompletion_(e)}async checkCompileCompletionAsync(){const e=[];if(this.gpgpu.parallelCompilationExtension){for(const[,t]of Object.entries(this.binaryCache))e.push(this.checkCompletionAsync_(t));return Promise.all(e)}for(const[,t]of Object.entries(this.binaryCache)){const n=new Promise((e=>{try{this.checkCompletion_(t),e(!0)}catch(e){throw e}}));e.push(n)}return Promise.all(e)}async checkCompletionAsync_(e){return this.gpgpu.gl.getProgramParameter(e.webGLProgram,this.gpgpu.parallelCompilationExtension.COMPLETION_STATUS_KHR)?this.checkCompletion_(e):(await Pp(),this.checkCompletionAsync_(e))}checkCompletion_(e){if(!1===this.gpgpu.gl.getProgramParameter(e.webGLProgram,this.gpgpu.gl.LINK_STATUS)){if(console.log(this.gpgpu.gl.getProgramInfoLog(e.webGLProgram)),!1===this.gpgpu.gl.getShaderParameter(e.fragmentShader,this.gpgpu.gl.COMPILE_STATUS))throw VE(e.source,this.gpgpu.gl.getShaderInfoLog(e.fragmentShader)),new Error("Failed to compile fragment shader.");throw new Error("Failed to link vertex and fragment shaders.")}return!0}getUniformLocations(){for(const[,e]of Object.entries(this.binaryCache)){const{uniformLocations:t,customUniformLocations:n,infLoc:s,nanLoc:r,inShapesLocations:a,inTexShapesLocations:i,outShapeLocation:o,outShapeStridesLocation:l,outTexShapeLocation:u}=FR(this.gpgpu,e.program,e.webGLProgram);e.uniformLocations=t,e.customUniformLocations=n,e.infLoc=s,e.nanLoc=r,e.inShapesLocations=a,e.inTexShapesLocations=i,e.outShapeLocation=o,e.outShapeStridesLocation=l,e.outTexShapeLocation=u}}}uF.nextDataId=0; +/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +Pr()&&eo("webgl",(()=>new uF),2);const cF="\n if (isnan(a)) return a;\n if (isnan(b)) return b;\n";class hF{constructor(e,t,n){this.variableNames=["A","B"],this.outputShape=ki(t,n),this.enableShapeUniforms=DR(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 `}} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +const pF="\n result.r = isNaN.r ? NAN : result.r;\n result.g = isNaN.g ? NAN : result.g;\n result.b = isNaN.b ? NAN : result.b;\n result.a = isNaN.a ? NAN : result.a;\n";class dF{constructor(e,t,n,s=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=ki(t,n);const r=this.outputShape.length;this.enableShapeUniforms=DR(r);let a="";if(s)if(0===r||1===P(this.outputShape))a="\n result.y = 0.;\n result.z = 0.;\n result.w = 0.;\n ";else{if(a=`\n ${CR(r)} coords = getOutputCoords();\n `,1===r)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=HA("coords",r);this.enableShapeUniforms?a+=`\n bool nextRowOutOfBounds =\n (${e[r-2]} + 1) >= outShape[${r} - 2];\n bool nextColOutOfBounds =\n (${e[r-1]} + 1) >= outShape[${r} - 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[r-2]} + 1) >= ${this.outputShape[r-2]};\n bool nextColOutOfBounds =\n (${e[r-1]} + 1) >= ${this.outputShape[r-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 `}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function fF(e){const{inputs:t,backend:n}=e,{x:s}=t;return n.incRef(s.dataId),{dataId:s.dataId,shape:s.shape,dtype:s.dtype}}const mF={kernelName:Ot,backendName:"webgl",kernelFunc:fF}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function gF(e){const{inputs:t,backend:n}=e,{real:s,imag:r}=t,a=n.makeTensorInfo(s.shape,"complex64"),i=n.texData.get(a.dataId),o=fF({inputs:{x:s},backend:n}),l=fF({inputs:{x:r},backend:n});return i.complexTensorInfos={real:o,imag:l},a}const yF={kernelName:qe,backendName:"webgl",kernelFunc:gF},bF="return (a < 0.) ? b * a : a;",xF="\n vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));\n return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\n";const wF={kernelName:Wt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{alpha:a}=s,i=n.makeTensorInfo([],"float32",Qs(a,"float32")),o=ye().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new dF(xF,r.shape,i.shape):new hF(bF,r.shape,i.shape),l=n.runWebGLProgram(o,[r,i],"float32");return n.disposeIntermediateTensorInfo(i),l}},vF="return (a < 0.) ? b * a : a;",kF="\n vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));\n return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\n";const IF={kernelName:In,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:s,alpha:r}=t,a=ye().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new dF(kF,s.shape,r.shape):new hF(vF,s.shape,r.shape);return n.runWebGLProgram(a,[s,r],"float32")}},NF="if (isnan(x)) return x;";function SF({opSnippet:e,packedOpSnippet:t,cpuKernelImpl:n,dtype:s}){return({inputs:r,backend:a})=>{const{x:i}=r,o=a,l=s||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=ye().getBool("WEBGL_PACK_UNARY_OPERATIONS")&&null!=t?new rF(i.shape,t):new JA(i.shape,e),o.runWebGLProgram(u,[i],l)}}function TF({opSnippet:e,packedOpSnippet:t,checkOutOfBounds:n=!1,supportsComplex:s=!1,cpuKernelImpl:r,dtype:a}){return({inputs:i,backend:o})=>{const{a:l,b:u}=i,c=o;if(s&&"complex64"===l.dtype){const t=c.texData.get(l.dataId),n=c.texData.get(u.dataId),[s,r]=[[t.complexTensorInfos.real,n.complexTensorInfos.real],[t.complexTensorInfos.imag,n.complexTensorInfos.imag]].map((t=>{const[n,s]=t,r={dataId:n.dataId,dtype:n.dtype,shape:l.shape},a={dataId:s.dataId,dtype:s.dtype,shape:u.shape},i=new hF(e,l.shape,u.shape);return c.runWebGLProgram(i,[r,a],Sr(n.dtype,s.dtype))})),a=gF({inputs:{real:s,imag:r},backend:c});return c.disposeIntermediateTensorInfo(s),c.disposeIntermediateTensorInfo(r),a}const h=a||Sr(l.dtype,u.dtype);if(("string"===l.dtype||"string"===u.dtype||c.shouldExecuteOnCPU([l,u]))&&null!=r){const e=c.texData.get(l.dataId).values,t=c.texData.get(u.dataId).values,n="string"===l.dtype?Gd(e):e,s="string"===l.dtype?Gd(t):t,[a,i]=r(l.shape,u.shape,n,s,h),o=c.makeTensorInfo(i,h);return c.texData.get(o.dataId).values=a,o}let p;return p=ye().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&null!=t?new dF(t,l.shape,u.shape,n):new hF(e,l.shape,u.shape),c.runWebGLProgram(p,[l,u],h)}}function CF(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":tF;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":nF;if("prelu"===e)return t?kF:vF;if("leakyrelu"===e)return t?xF:bF;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.`)} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class $F{constructor(e,t,n,s=!1,r=!1,a=!1,i=null,o=!1,l=!1){this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=n,this.enableShapeUniforms=DR(this.outputShape.length);const u=s?e[1]:e[2],c=Math.ceil(u/2),h=s?"i * 2, rc.y":"rc.y, i * 2",p=r?"rc.z, i * 2":"i * 2, rc.z",d=s?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],f=r?["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 (${r.shape}) has ${o} elements. The new shape and old shape must have the same number of elements.`));const c=i.texData.get(r.dataId);return!c.isPacked||tR(r.shape,l)||null!==c.texture&&tR(c.shape,l)?(i.incRef(r.dataId),{dataId:r.dataId,shape:l,dtype:r.dtype}): +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n){const s=[ZE(e.shape),...JE(e.shape)],r={dtype:e.dtype,shape:s,dataId:e.dataId},a=[ZE(t),...JE(t)],i=new qA(a,s),o=[s],l=n.runWebGLProgram(i,[r],e.dtype,o,!0);return{dataId:l.dataId,shape:t,dtype:l.dtype}}(r,l,i)}const MF={kernelName:An,backendName:"webgl",kernelFunc:OF}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class LF{constructor(e,t){this.variableNames=["x"];const{windowSize:n,batchSize:s,inSize:r,outSize:a}=e;this.outputShape=[s,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 * ${W(e)?e.toPrecision(2):e}, ones);`}let u="";r%n>0&&(u=`\n if (inIdx < 0 || inIdx >= ${r}) {\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 `}} +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class zF{constructor(e,t){this.variableNames=["x"];const{windowSize:n,batchSize:s,inSize:r,outSize:a}=e;this.outputShape=[s,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="";r%n>0&&(d=`\n if (inIdx < 0 || inIdx >= ${r}) {\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 PF(e,t,n,s){const r= +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +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],s=Kp(n);t.push({inSize:n,windowSize:s,outSize:Math.ceil(n/s)})}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"],s=new Array(t);for(let t=0;t6)throw Error(`Packed transpose for rank ${this.rank} is not yet supported.`);const s=CR(this.rank),r=GA("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=${s} must match.`));const w=n?[y,h,d]:[y,d,h],v=s?[b,f,p]:[b,p,f],k=OF({inputs:{x:e},backend:r,attrs:{shape:w}}),I=OF({inputs:{x:t},backend:r,attrs:{shape:v}}),N=[k,I],S=Math.max(y,b),T=n?k.shape[1]:k.shape[2],C=null!=a,$=null!=i,E="leakyrelu"===l,R=null!=l?CF(l,!0):null;let A;if((1===d||1===f)&&T>1e3&&!1===(C||$||E||null!=R)){let e=k,t=I;n&&(e=HF({inputs:{x:k},backend:r,attrs:{perm:[0,2,1]}}),N.push(e)),s&&(t=HF({inputs:{x:I},backend:r,attrs:{perm:[0,2,1]}}),N.push(t));const a=1===f;let i=e;1!==f&&(i=OF({inputs:{x:e},backend:r,attrs:{shape:[S,T,1]}}),N.push(i));const o=1===f?2:1;let l=t;a&&(l=OF({inputs:{x:t},backend:r,attrs:{shape:[S,1,T]}}),N.push(l));const u=_F({inputs:{a:i,b:l},backend:r});A=UF({inputs:{x:u},backend:r,attrs:{axis:o,keepDims:!0}}),N.push(u)}else{const l=Sr(e.dtype,t.dtype),u=new $F(w,v,[S,d,f],n,s,C,R,$,E),c=[k,I];if(null!=a&&c.push(a),$&&c.push(i),E){const e=r.makeTensorInfo([],"float32",Qs(o,"float32"));c.push(e),N.push(e)}A=r.runWebGLProgram(u,c,l)}const F=OF({inputs:{x:A},backend:r,attrs:{shape:x}});N.push(A);for(const e of N)r.disposeIntermediateTensorInfo(e);return F}const KF={kernelName:Ts,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{a:r,b:a,bias:i,preluActivationWeights:o}=t,{transposeA:l,transposeB:u,activation:c,leakyreluAlpha:h}=s;return qF({a:r,b:a,transposeA:l,transposeB:u,backend:n,bias:i,preluActivationWeights:o,leakyreluAlpha:h,activation:c})}},XF="return abs(x);";const YF={kernelName:ke,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:s}=t;if(n.shouldExecuteOnCPU([s])&&"complex64"!==s.dtype){const e=n.texData.get(s.dataId),t=EA(e.values);return n.makeTensorInfo(s.shape,s.dtype,t)}let r;return r=ye().getBool("WEBGL_PACK_UNARY_OPERATIONS")?new rF(s.shape,XF):new JA(s.shape,XF),n.runWebGLProgram(r,[s],s.dtype)}},ZF=SF({opSnippet:QA+"\n if (abs(x) > 1.) {\n return NAN;\n }\n return acos(x);\n"}),JF={kernelName:Ie,backendName:"webgl",kernelFunc:ZF},QF=SF({opSnippet:QA+"\n if (x < 1.0) return NAN;\nreturn log(x + sqrt(x * x - 1.0));"}),e_={kernelName:Ne,backendName:"webgl",kernelFunc:QF},t_="return a + b;",n_=TF({opSnippet:t_,packedOpSnippet:t_,supportsComplex:!0,cpuKernelImpl:JR}),s_={kernelName:Se,backendName:"webgl",kernelFunc:n_}; +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class r_{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 s=this.variableNames.map((e=>`v${e}`)).join(" + ");this.userCode=`\n void main() {\n ${n.join("\n ")}\n\n float result = ${s};\n setOutput(result);\n }\n `}} +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class a_{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 s=this.variableNames.map((e=>`v${e}`)).join(" + ");this.userCode=`\n void main() {\n ${n.join("\n ")}\n\n vec4 result = ${s};\n setOutput(result);\n }\n `}}const i_={kernelName:Te,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function e(t){const{inputs:n,backend:s}=t,r=n;if(1===r.length)return fF({inputs:{x:r[0]},backend:s});if(r.length>ye().get("WEBGL_MAX_TEXTURES_IN_SHADER")){const t=Math.floor(r.length/2),n=e({inputs:r.slice(0,t),backend:s}),a=e({inputs:r.slice(t),backend:s});return e({inputs:[n,a],backend:s})}const a=r.map((e=>e.dtype)).reduce(((e,t)=>Sr(e,t))),i=r.map((e=>e.shape)),o=ye().getBool("WEBGL_PACK")?new a_(r[0].shape,i):new r_(r[0].shape,i);return s.runWebGLProgram(o,r,a)}};const o_={kernelName:Ce,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:i}=s,o=r.shape.length,l=j(a,r.shape);let u=l;const c=Ol(u,o);let h=r;null!=c&&(h=HF({inputs:{x:r},backend:n,attrs:{perm:c}}),u=Ll(u.length,o)),Dl("all",u,o);const[p,d]=Fl(h.shape,u),f=OF({inputs:{x:h},backend:n,attrs:{shape:[-1,P(d)]}}),m=PF(f,f.dtype,"all",n);let g;if(i){g=OF({inputs:{x:m},backend:n,attrs:{shape:_l(p,l)}})}else g=OF({inputs:{x:m},backend:n,attrs:{shape:p}});return n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),null!=c&&n.disposeIntermediateTensorInfo(h),g}};const l_={kernelName:$e,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:i}=s,o=r.shape.length,l=j(a,r.shape);let u=l;const c=Ol(u,o);let h=r;null!=c&&(h=HF({inputs:{x:r},backend:n,attrs:{perm:c}}),u=Ll(u.length,o)),Dl("any",u,o);const[p,d]=Fl(h.shape,u),f=OF({inputs:{x:h},backend:n,attrs:{shape:[-1,P(d)]}}),m=PF(f,f.dtype,"any",n);let g;if(i){g=OF({inputs:{x:m},backend:n,attrs:{shape:_l(p,l)}})}else g=OF({inputs:{x:m},backend:n,attrs:{shape:p}});return n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),null!=c&&n.disposeIntermediateTensorInfo(h),g}}; +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class u_{constructor(e,t,n){this.variableNames=["A"];const{windowSize:s,batchSize:r,outSize:a}=e;n||this.variableNames.push("bestIndicesA"),this.outputShape=[r,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 * ${s};\n\n int bestIndex = inOffset;\n float bestValue = getA(batch, bestIndex);\n\n for (int i = 0; i < ${s}; 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 `}} +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class c_{constructor(e,t,n,s){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,O(e.length>2,(()=>`Packed arg${n.charAt(0).toUpperCase()+n.slice(1)} supports only inputs with rank above 2.`));const r=e[e.length-1],a=Math.ceil(r/t);this.outputShape=e.slice(0,-1),a>1&&this.outputShape.push(a),s||this.variableNames.push("bestIndicesA");const i=this.outputShape,o=i.length,l=CR(o),u=HA("coords",o);let c,h;if(1===a){h=o+1;const e=CR(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=HA("sourceLocR",h-1).concat("inIdx.r"),g=HA("sourceLocG",h-1).concat("inIdx.g"),y=HA("sourceLocB",h-1).concat("inIdx.b"),b=HA("sourceLocA",h-1).concat("inIdx.a"),x="max"===n?"greaterThan":"lessThan",w=s?"":`\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=s?"":`\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 `}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function h_(e,t,n,s=null){let r=t.shape[0],a=t.shape[1];null!=s&&(r=s.shape[0],a=s.shape[1]);const i=Kp(a),o={windowSize:i,inSize:a,batchSize:r,outSize:Math.ceil(a/i)},l=new u_(o,n,null==s),u=[t];null!=s&&u.push(s);const c=e.runWebGLProgram(l,u,"int32");if(1===c.shape[1])return c;const h=h_(e,t,n,c);return e.disposeIntermediateTensorInfo(c),h}function p_(e,t,n,s=null){const r=null!=s?s.shape:t.shape,a=Kp(r[r.length-1]),i=new c_(r,a,n,null==s),o=null==s?[t]:[t,s],l=e.runWebGLProgram(i,o,"int32");if(l.shape.length===t.shape.length){const s=p_(e,t,n,l);return e.disposeIntermediateTensorInfo(l),s}return l}function d_(e,t,n,s){const r=[n];if(Dl("arg"+s.charAt(0).toUpperCase()+s.slice(1),r,t.shape.length),!ye().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]=Fl(i.shape,r),u=P(l),c=OF({inputs:{x:i},backend:e,attrs:{shape:[-1,u]}});n.push(c);const h=h_(e,c,s);n.push(h);const p=OF({inputs:{x:h},backend:e,attrs:{shape:o}});return n.forEach((t=>e.disposeIntermediateTensorInfo(t))),p}return p_(e,t,s)}const f_={kernelName:Ee,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a}=s;let i=j(a,r.shape);const o=Ol(i,r.shape.length);let l=r;const u=[];null!=o&&(l=HF({inputs:{x:r},backend:n,attrs:{perm:o}}),u.push(l),i=Ll(i.length,l.shape.length)),Dl("argMax",[i[0]],l.shape.length);const c=d_(n,l,i[0],"max");return u.forEach((e=>n.disposeIntermediateTensorInfo(e))),c}};const m_={kernelName:Re,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a}=s;let i=j(a,r.shape);const o=Ol(i,r.shape.length);let l=r;const u=[];null!=o&&(l=HF({inputs:{x:r},backend:n,attrs:{perm:o}}),u.push(l),i=Ll(i.length,l.shape.length)),Dl("argMin",[i[0]],l.shape.length);const c=d_(n,l,i[0],"min");return u.forEach((e=>n.disposeIntermediateTensorInfo(e))),c}},g_=SF({opSnippet:QA+"\n if (abs(x) > 1.) {\n return NAN;\n }\n return asin(x);\n"}),y_={kernelName:Ae,backendName:"webgl",kernelFunc:g_},b_=SF({opSnippet:QA+"return log(x + sqrt(x * x + 1.0));"}),x_={kernelName:Fe,backendName:"webgl",kernelFunc:b_},w_=SF({opSnippet:QA+"\n return atan(x);\n"}),v_={kernelName:_e,backendName:"webgl",kernelFunc:w_},k_=TF({opSnippet:cF+"\n return atan(a, b);\n",packedOpSnippet:"\n vec4 result = atan(a, b);\n bvec4 isNaNA = isnan(a);\n bvec4 isNaNB = isnan(b);\n bvec4 isNaN = bvec4(isNaNA.x || isNaNB.x, isNaNA.y || isNaNB.y, isNaNA.z || isNaNB.z, isNaNA.w || isNaNB.w);\n "+pF+"\n return result;\n"}),I_={kernelName:Oe,backendName:"webgl",kernelFunc:k_},N_=SF({opSnippet:QA+"\n if ((x < -1.0) || (x > 1.0)) return NAN;\nreturn (log(1.0 + x) - log(1.0 - x)) / 2.0;"}),S_={kernelName:De,backendName:"webgl",kernelFunc:N_}; +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class T_{constructor(e,t,n,s=!1,r=!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 = ${s?r?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 C_{constructor(e,t,n,s=!1,r=!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 = ${s?r?`(((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 $_={kernelName:Me,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t;lR(r,"avgPool");const{filterSize:a,strides:i,pad:o,dimRoundingMode:l}=s;O(Ro(i,1),(()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${i} and dilations '1'`));const u=wo(r.shape,a,i,1,o,l);if(1===u.filterWidth&&1===u.filterHeight&&B(u.inShape,u.outShape))return fF({inputs:{x:r},backend:n});const c=new T_(u,"avg",!1);return n.runWebGLProgram(c,[r],"float32")}};const E_={kernelName:ze,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{filterSize:a,strides:i,pad:o,dimRoundingMode:l,dataFormat:u}=s,c=vo(r.shape,a,i,[1,1,1],o,l,u),h=new C_(c,"avg",!1);return n.runWebGLProgram(h,[r],"float32")}}; +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class R_{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;const t=e.filterHeight,n=e.filterWidth,s=e.strideHeight,r=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) / ${s}.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) / ${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(b, idyR, idyC, d);\n\n dotProd += dyValue * avgMultiplier;\n }\n }\n setOutput(dotProd);\n }\n `}}class A_{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;const t=e.filterDepth,n=e.filterHeight,s=e.filterWidth,r=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*s);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) / ${r}.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 F_={kernelName:Pe,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{dy:r,input:a}=t,i=a,{filterSize:o,strides:l,pad:u,dimRoundingMode:c}=s,h=vo(i.shape,o,l,[1,1,1],u,c),p=new A_(h);return n.runWebGLProgram(p,[r],i.dtype)}};const __={kernelName:Le,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{dy:r,input:a}=t,i=a;lR([r,a],"avgPoolGrad");const{filterSize:o,strides:l,pad:u}=s,c=wo(i.shape,o,l,1,u),h=new R_(c);return n.runWebGLProgram(h,[r],i.dtype)}};const D_={kernelName:Be,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{a:r,b:a}=t,{transposeA:i,transposeB:o}=s;return qF({a:r,b:a,transposeA:i,transposeB:o,backend:n})}}; +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class O_{constructor(e,t,n,s,r,a){this.outputShape=[],this.variableNames=["x","mean","variance"],ki(e,t),ki(e,n);let i="0.0";null!=s&&(ki(e,s),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");let o="1.0";null!=r&&(ki(e,r),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 `}} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class M_{constructor(e,t,n,s,r,a){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],ki(e,t),ki(e,n);let i="vec4(0.0)";null!=s&&(ki(e,s),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");let o="vec4(1.0)";null!=r&&(ki(e,r),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 `}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +const L_={kernelName:Rt,backendName:"webgl",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:s,mean:r,variance:a,offset:i,scale:o}=e;O(r.shape.length===a.shape.length,(()=>"Batch normalization gradient requires mean and variance to have equal ranks.")),O(null==i||r.shape.length===i.shape.length,(()=>"Batch normalization gradient requires mean and offset to have equal ranks.")),O(null==o||r.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=[s,r,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=ye().getBool("WEBGL_PACK_NORMALIZATION")?new M_(s.shape,r.shape,a.shape,c,h,l):new O_(s.shape,r.shape,a.shape,c,h,l);return t.runWebGLProgram(p,u,u[0].dtype)}}; +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class z_{constructor(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;const t=CR(this.rank);this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];const n=function(e){if(1===e)return"sourceLoc";if(e<=6)return P_.slice(0,e).map((e=>"sourceLoc."+e)).join(",");throw Error(`Slicing for rank ${e} is not yet supported`)}(this.rank);let s;s=`\n ${t} sourceLoc;\n ${t} coords = getOutputCoords();\n ${e.map(((e,t)=>`sourceLoc.${P_[t]} = start[${t}] + coords.${P_[t]};`)).join("\n")}\n `,this.userCode=`\n void main() {\n ${s}\n setOutput(getSource(${n}));\n }\n `}}const P_=["x","y","z","w","u","v"]; +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class B_{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=CR(this.rank),n=HA("coords",this.rank),s=HA("sourceLoc",this.rank),r=1===this.rank?"sourceLoc":`vec2(${s.slice(-2).join()})`,a=`getChannel(getSource(${s.join()}), ${r})`,i=`\n result.x = ${a};\n if (++${n[this.rank-1]} < ${e[this.rank-1]}) {\n ++${s[this.rank-1]};\n result.y = ${a};\n --${s[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 ++${s[this.rank-2]};\n result.z = ${a};\n if (++${n[this.rank-1]} < ${e[this.rank-1]}) {\n ++${s[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)=>`${s[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 W_(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{begin:a,size:i}=s,[o,l]=Ui(r,a,i);if(Ei(r,o,l),0===P(l))return n.makeTensorInfo(l,r.dtype,[]);if(n.shouldExecuteOnCPU([r])||"string"===r.dtype){const e=n.texData.get(r.dataId),t=RA(e.values,o,l,r.shape,r.dtype);return n.makeTensorInfo(l,r.dtype,t)}const{isPacked:u}=n.texData.get(r.dataId),c=Wi(r.shape,o,l);if(u||!c){const e=ye().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new B_(l):new z_(l),t=[o];return n.runWebGLProgram(e,[r],r.dtype,t)}return n.uploadToGPU(r.dataId), +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n,s){const r=s.texData.get(e.dataId),a=s.makeTensorInfo(n,e.dtype),i=s.texData.get(a.dataId);Object.assign(i,r),i.refCount=1,i.shape=n,i.dtype=e.dtype;let o=Vi(t,re(e.shape));r.slice&&(o+=r.slice.flatOffset),i.slice={flatOffset:o,origDataId:r.slice&&r.slice.origDataId||e.dataId};const l=s.dataRefCount.get(i.slice.origDataId)||1;return s.dataRefCount.set(i.slice.origDataId,l+1),a}(r,o,l,n)}const V_={kernelName:Gn,backendName:"webgl",kernelFunc:W_},U_={kernelName:We,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{blockShape:a,crops:i}=s;O(r.shape.length<=4,(()=>"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet"));const o=a.reduce(((e,t)=>e*t)),l=Yp(r.shape,a,o),u=Zp(l.length,a.length),c=Jp(r.shape,a,o),h=Qp(i,a.length),p=ed(c,i,a.length),d=[],f=OF({inputs:{x:r},backend:n,attrs:{shape:l}}),m=HF({inputs:{x:f},backend:n,attrs:{perm:u}}),g=OF({inputs:{x:m},backend:n,attrs:{shape:c}}),y=W_({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}};const G_={kernelName:Ve,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,weights:a}=t,{size:i}=s,o=n.readSync(r.dataId),l=n.readSync(a.dataId),u=QR(o,l,a.dtype,a.shape,i);return n.makeTensorInfo([i],a.dtype,u)}};const H_={kernelName:Ue,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n}=e,{s0:s,s1:r}=t,a=n.readSync(s.dataId),i=n.readSync(r.dataId),o=ki(Array.from(a),Array.from(i));return n.makeTensorInfo([o.length],"int32",Int32Array.from(o))}},j_=TF({opSnippet:"return float(a != b);",cpuKernelImpl:vA,dtype:"bool"}),q_={kernelName:fn,backendName:"webgl",kernelFunc:j_}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function K_(e){const{inputs:t,backend:n}=e,{input:s}=t;return fF({inputs:{x:n.texData.get(s.dataId).complexTensorInfos.real},backend:n})}const X_={kernelName:$n,backendName:"webgl",kernelFunc:K_};const Y_={kernelName:Ge,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function e(t){const{inputs:n,backend:s,attrs:r}=t,{x:a}=n,{dtype:i}=r;if("complex64"===i){if("complex64"===a.dtype)return fF({inputs:{x:a},backend:s});const t=Au(a.shape),n=e({inputs:{x:a},backend:s,attrs:{dtype:"float32"}}),r=gF({inputs:{real:n,imag:t},backend:s});return t.dispose(),s.disposeIntermediateTensorInfo(n),r}if("complex64"===a.dtype){const t=K_({inputs:{input:a},backend:s}),n=e({inputs:{x:t},backend:s,attrs:{dtype:i}});return s.disposeIntermediateTensorInfo(t),n}if(!Y(a.dtype,i)){const e=fF({inputs:{x:a},backend:s});return{dataId:e.dataId,shape:e.shape,dtype:i}}if(s.shouldExecuteOnCPU([a])){const e=s.texData.get(a.dataId).values,[t,n,r]=tA(e,a.shape,a.dtype,i);return s.makeTensorInfo(t,n,r)}if("int32"===i)return function(e,t){const n=new JA(e.shape,"return float(int(x));"),s=t.runWebGLProgram(n,[e],"int32");return{dataId:s.dataId,shape:s.shape,dtype:s.dtype}}(a,s);if("bool"===i){const e=s.makeTensorInfo([],"bool",K("bool",1)),t=j_({inputs:{a,b:e},backend:s});return s.disposeIntermediateTensorInfo(e),t}throw new Error(`Error in Cast: failed to cast ${a.dtype} to ${i}`)}},Z_="return ceil(x);",J_=SF({opSnippet:Z_,packedOpSnippet:Z_,cpuKernelImpl:nA}),Q_={kernelName:He,backendName:"webgl",kernelFunc:J_}; +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class eD{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 "}} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class tD{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 nD={kernelName:je,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{clipValueMin:a,clipValueMax:i}=s;let o;o=ye().getBool("WEBGL_PACK_CLIP")?new tD(r.shape):new eD(r.shape);const l=[[a],[i]];return n.runWebGLProgram(o,[r],r.dtype,l)}}; +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class sD{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 "}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function rD(e,t){return{dataId:t.dataId,dtype:t.dtype,shape:e.shape}}const aD={kernelName:Ke,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:s}=t,r=n.texData.get(s.dataId),a=new sD(s.shape),i=[rD(s,r.complexTensorInfos.real),rD(s,r.complexTensorInfos.imag)];return n.runWebGLProgram(a,i,i[0].dtype)}}; +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class iD{constructor(e){this.outputShape=[],this.outputShape=Wp(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}(${lD(i,l,t)}),\n vec2(${lD(u,l,t)}));\n }`}const p=o.length,d=o[o.length-1];h+=`\n return getChannel(\n getT${p}(${lD(i,l,d)}),\n vec2(${lD(u,l,d)}));`,this.userCode=`\n float getValue(${i.map((e=>"int "+e))}) {\n ${h}\n }\n\n void main() {\n ${r} coords = getOutputCoords();\n vec4 result = vec4(getValue(${a}), 0., 0., 0.);\n\n ${a[s-1]} = ${a[s-1]} + 1;\n if (${a[s-1]} < ${n[s-1]}) {\n result.g = getValue(${a});\n }\n\n ${a[s-2]} = ${a[s-2]} + 1;\n if (${a[s-2]} < ${n[s-2]}) {\n result.a = getValue(${a});\n }\n\n ${a[s-1]} = ${a[s-1]} - 1;\n if (${a[s-2]} < ${n[s-2]} &&\n ${a[s-1]} < ${n[s-1]}) {\n result.b = getValue(${a});\n }\n setOutput(result);\n }\n `}}function lD(e,t,n){const s=e.indexOf(t);return e.map(((e,t)=>t===s?`${e} - ${n}`:e)).join()} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function uD(e){const{inputs:t,backend:n}=e,{input:s}=t;return fF({inputs:{x:n.texData.get(s.dataId).complexTensorInfos.imag},backend:n})}const cD={kernelName:Lt,backendName:"webgl",kernelFunc:uD}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function hD(e,t,n){const s=e[0].dtype;if("complex64"===s){const s=e.map((e=>K_({inputs:{input:e},backend:n}))),r=e.map((e=>uD({inputs:{input:e},backend:n}))),a=hD(s,t,n),i=hD(r,t,n),o=gF({inputs:{real:a,imag:i},backend:n});return s.forEach((e=>n.disposeIntermediateTensorInfo(e))),r.forEach((e=>n.disposeIntermediateTensorInfo(e))),n.disposeIntermediateTensorInfo(a),n.disposeIntermediateTensorInfo(i),o}let r=n.shouldExecuteOnCPU(e);if("string"===s&&(r=!0),r){const r=e.map((e=>{const s=P(e.shape.slice(t));return OF({inputs:{x:e},backend:n,attrs:{shape:[-1,s]}})})),a=r.map((e=>({vals:n.readSync(e.dataId),shape:e.shape}))),i=Wp(r.map((e=>e.shape)),1),o=1===r[0].shape[0],l=sA(a,i,s,o),u=Wp(e.map((e=>e.shape)),t),c=n.makeTensorInfo(u,s,l);return r.forEach((e=>n.disposeIntermediateTensorInfo(e))),c}const a=ye().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER");if(e.length>a){const s=[];for(let r=0;r1){const r=new oD(e.map((e=>e.shape)),t);return n.runWebGLProgram(r,e,s)}const{tensors2D:i,outShape:o}=function(e,t,n){const s=Wp(e.map((e=>e.shape)),t),r=e.map((e=>OF({inputs:{x:e},attrs:{shape:[-1,P(e.shape.slice(t))]},backend:n})));return{tensors2D:r,outShape:s}}(e,t,n),l=new iD(i.map((e=>e.shape))),u=n.runWebGLProgram(l,i,s);i.forEach((e=>n.disposeIntermediateTensorInfo(e)));const c=OF({inputs:{x:u},attrs:{shape:o},backend:n});return n.disposeIntermediateTensorInfo(u),c} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function pD(e){const{inputs:t,backend:n,attrs:s}=e,{axis:r}=s,a=j(r,t[0].shape)[0];Bp(t.map((e=>e.shape)),a);const i=Wp(t.map((e=>e.shape)),a);if(0===P(i))return n.makeTensorInfo(i,t[0].dtype,[]);const o=t.filter((e=>P(e.shape)>0));return 1===o.length?fF({inputs:{x:o[0]},backend:n}):hD(o,a,n)}const dD={kernelName:Xe,backendName:"webgl",kernelFunc:pD}; +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class fD{constructor(e,t=!1,n=null,s=!1,r=!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=s?`float activation(float a) {\n float b = getPreluActivationWeightsAtOutCoords();\n ${n}\n }`:r?`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"),s&&this.variableNames.push("preluActivationWeights"),r&&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 mD{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;const t=e.padInfo.front,n=e.padInfo.top,s=e.padInfo.left,r=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(${r}, ${a}, ${i});\n const ivec3 pads = ivec3(${t}, ${n}, ${s});\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 `}} +/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class gD{constructor(e,t=!1,n=null,s=!1,r=!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=DR(this.outputShape.length);const a=e.padInfo.left,i=e.strideWidth,o=e.dilationWidth,l=e.filterHeight,u=e.filterWidth,c=u;let h="\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 t=0;t<(c+1)/2;t++){const n=2*t;if(h+=`\n xC = xCCorner + ${n*o};\n `,1===i){if(n= 0 && xCOffset < inDims[1] && xTexelC${n}Ready == 0) {\n xTexelC${n} = 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${n}.zw = vec2(0.0);\n }\n xTexelC${n}Ready = 1;\n }\n `,h+=1===o&&n>0?`\n xC${n} = vec4(xTexelC${n-2}.zw, xTexelC${n}.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${n} = vec4(previous.zw, xTexelC${n}.xy);\n } else {\n xC${n} = vec4(0.0, 0.0, xTexelC${n}.xy);\n }\n `):h+=`\n if (xC >= 0 && xC < inDims[1] && xTexelC${n}Ready == 0) {\n xTexelC${n} = getX(batch, xR, xC, d1);\n if (xC + 1 >= inDims[1]) {\n xTexelC${n}.zw = vec2(0.0);\n }\n xTexelC${n}Ready = 1;\n }\n\n xC${n} = xTexelC${n};\n `,n+1= 0 && xCOffset < inDims[1] && xTexelC${n+1}Ready == 0) {\n xTexelC${n+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${n+1}.zw = vec2(0.0);\n }\n xTexelC${n+1}Ready = 1;\n }\n `,h+=o>1?`\n xCOffset -= 2;\n if (xCOffset >= 0 && xCOffset < inDims[1]) {\n previous = getX(batch, xR, xCOffset, d1);\n xC${n+1} = vec4(previous.zw, xTexelC${n+1}.xy);\n } else {\n xC${n+1} = vec4(0.0, 0.0, xTexelC${n+1}.xy);\n }\n `:`\n xC${n+1} = vec4(xTexelC${n}.zw, xTexelC${n+1}.xy);\n `):h+=1===e?`\n xC${n+1} = xTexelC${n};\n `:`\n xCOffset = xC + ${e};\n\n if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${n+1}Ready == 0) {\n xTexelC${n+1} = getX(batch, xR, xCOffset, d1);\n if (xCOffset + 1 >= inDims[1]) {\n xTexelC${n+1}.zw = vec2(0.0);\n }\n xTexelC${n+1}Ready = 1;\n }\n\n xC${n+1} = xTexelC${n+1};\n `}}else n= 0 && xCOffset < inDims[1] && xTexelC${n}Ready == 0) {\n xTexelC${n} = 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${n}.zw = vec2(0.0);\n }\n xTexelC${n}Ready = 1;\n }\n\n if(xC + 1 >= 0 && xC + 1 < inDims[1] && xTexelC${n+1}Ready == 0) {\n xTexelC${n+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${n+1}.zw = vec2(0.0);\n }\n xTexelC${n+1}Ready = 1;\n }\n\n xC${n} = vec4(xTexelC${n}.zw, xTexelC${n+1}.zw);\n `,n+1= 0 && xCOffset < inDims[1]) {\n final = getX(batch, xR, xCOffset, d1);\n }\n xC${n+1} = vec4(xTexelC${n+1}.xy, final.xy);\n `)):(h+=`\n if(xC >= 0 && xC < inDims[1] && xTexelC${n}Ready == 0) {\n xTexelC${n} = getX(batch, xR, xC, d1);\n if (xC + 1 >= inDims[1]) {\n xTexelC${n}.zw = vec2(0.0);\n }\n xTexelC${n}Ready = 1;\n }\n\n xCOffset = xC + strides[1];\n if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${n+1}Ready == 0) {\n xTexelC${n+1} = getX(batch, xR, xCOffset, d1);\n if (xCOffset + 1 >= inDims[1]) {\n xTexelC${n+1}.zw = vec2(0.);\n }\n xTexelC${n+1}Ready = 1;\n }\n\n xC${n} = vec4(\n xTexelC${n}.xy, xTexelC${n+1}.xy);\n `,n+1= 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 (${r}) {\n innerDims = vec2(d1, ch);\n result[${2*e+t}] = getChannel(\n getA(rc.x, d0, int(innerDims.x),\n int(innerDims.y)), innerDims);\n } else {\n innerDims = vec2(d0, d1);\n result[${2*e+t}] = getChannel(\n getA(rc.x, ch, int(innerDims.x),\n int(innerDims.y)), innerDims);\n }\n }\n }\n }\n `;this.userCode=`\n void main() {\n ivec3 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 ${s.output} = result;\n }\n `}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function bD(e,t){const n=e.length;return n>=3?t?[...e.slice(0,-3),e[n-3]*e[n-2],e[n-1]]:[...e.slice(0,-3),e[n-3],e[n-2]*e[n-1]]:!t&&1===n&&e[0]>1?[e[0],1]:null}function xD({x:e,filter:t,convInfo:n,backend:s,bias:r=null,preluActivationWeights:a=null,leakyreluAlpha:i=0,activation:o=null}){const l=e.shape,u=s.texData.get(e.dataId),c=n.inChannels,h=l[0]*l[1]*l[2],p=n.outChannels,d="channelsLast"===n.dataFormat,f=!1;let m;const g=[];if(null!=a){const e=bD(a.shape,d);null!=e&&(a=OF({inputs:{x:a},backend:s,attrs:{shape:e}}),g.push(a))}if(null!=r){const e=bD(r.shape,d);null!=e&&(r=OF({inputs:{x:r},backend:s,attrs:{shape:e}}),g.push(r))}if(!((1===h||1===p)&&c>1e3)&&u.isPacked&&d&&null!=u.texture&&l[2]%2!=0&&B(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]++,O(tR(u.shape,h.shape),(()=>`packed reshape ${u.shape} to ${h.shape} isn't free`));const d=OF({inputs:{x:t},backend:s,attrs:{shape:[1,n.inChannels,n.outChannels]}});g.push(d);const y=qF({a:h,b:d,backend:s,transposeA:false,transposeB:f,bias:r,activation:o,preluActivationWeights:a,leakyreluAlpha:i}),b=s.texData.get(y.dataId);O(b.isPacked,(()=>"batchMatMul result is expected to be packed")),u.shape=p,b.shape=n.outShape,m=fF({inputs:{x:y},backend:s}),m.shape=n.outShape,g.push(y)}else{const l=n.outHeight*n.outWidth,u=OF({inputs:{x:e},backend:s,attrs:{shape:d?[n.batchSize,l,n.inChannels]:[n.batchSize,n.inChannels,l]}}),c=OF({inputs:{x:t},backend:s,attrs:{shape:[1,n.inChannels,n.outChannels]}}),h=qF({a:d?u:c,b:d?c:u,transposeA:!d,transposeB:f,backend:s,bias:r,activation:o,preluActivationWeights:a,leakyreluAlpha:i});m=OF({inputs:{x:h},backend:s,attrs:{shape:n.outShape}}),g.push(u),g.push(c),g.push(h)}for(const e of g)s.disposeIntermediateTensorInfo(e);return m}function wD({x:e,filter:t,convInfo:n,backend:s,bias:r=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=[n.batchSize,m,g],b=[];if(null!=a){const e=bD(a.shape,f);null!=e&&(a=OF({inputs:{x:a},backend:s,attrs:{shape:e}}),b.push(a))}if(null!=r){const e=bD(r.shape,f);null!=e&&(r=OF({inputs:{x:r},backend:s,attrs:{shape:e}}),b.push(r))}const x=OF({inputs:{x:t},backend:s,attrs:{shape:[1,m,P(t.shape)/m]}});b.push(x);const w=new yD(y,n),v=[e.shape,[n.padInfo.top,n.padInfo.left],[n.strideHeight,n.strideWidth],[n.dilationHeight,n.dilationWidth],[n.inChannels],[n.filterWidth*n.inChannels],[n.outWidth]],k=s.runWebGLProgram(w,[e],"float32",v),I=OF({inputs:{x:k},backend:s,attrs:{shape:y}});b.push(k),b.push(I);const N=null!=r,S=null!=a,T="leakyrelu"===o,C=o?CF(o,!0):null,$=new $F(f?I.shape:x.shape,f?x.shape:I.shape,f?[n.batchSize,g,n.outChannels]:[n.batchSize,n.outChannels,g],!0,!1,N,C,S,T),E=f?[I,x]:[x,I];if(r&&E.push(r),S&&E.push(a),T){const e=s.makeTensorInfo([],"float32",Qs(i,"float32"));E.push(e),b.push(e)}const R=s.runWebGLProgram($,E,"float32"),A=OF({inputs:{x:R},backend:s,attrs:{shape:n.outShape}});b.push(R);for(const e of b)s.disposeIntermediateTensorInfo(e);return A}const vD={kernelName:Ye,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a}=t,{strides:i,pad:o,dataFormat:l,dilations:u,dimRoundingMode:c}=s,h=Ao(l),p=ko(r.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(p.strideWidth<=2&&"channelsLast"===h&&ye().getBool("WEBGL_EXP_CONV")){const e=new gD(p),t=[[p.padInfo.top,p.padInfo.left],[p.strideHeight,p.strideWidth],[p.dilationHeight,p.dilationWidth],[p.inHeight,p.inWidth]];d=n.runWebGLProgram(e,[r,a],"float32",t)}else if(ye().getBool("WEBGL_CONV_IM2COL"))d=wD({x:r,filter:a,convInfo:p,backend:n});else{const e=new fD(p);d=n.runWebGLProgram(e,[r,a],"float32")}else d=xD({x:r,filter:a,convInfo:p,backend:n});const f=OF({inputs:{x:d},backend:n,attrs:{shape:p.outShape}});return n.disposeIntermediateTensorInfo(d),f}}; +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class kD{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;const t=e.strideHeight,n=e.strideWidth,s=e.padInfo.top,r=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} - ${s};\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} - ${r};\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 ID{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterHeight,n=e.filterWidth,s=e.strideHeight,r=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) / ${s}.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) / ${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 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 ND{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;const t=e.strideDepth,n=e.strideHeight,s=e.strideWidth,r=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} - ${r};\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 * ${s} - ${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 SD{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterDepth,n=e.filterHeight,s=e.filterWidth,r=e.strideDepth,a=e.strideHeight,i=e.strideWidth,o=t-1-e.padInfo.front,l=n-1-e.padInfo.top,u=s-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) / ${r}.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 < ${s}; 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 = ${s} - 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 TD={kernelName:Ze,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,dy:a}=t,{strides:i,pad:o,dataFormat:l,dimRoundingMode:u,filterShape:c}=s,h=Ao(l),p=ko(r.shape,c,i,1,o,u,!1,h),d=new kD(p);return n.runWebGLProgram(d,[r,a],"float32")}};const CD={kernelName:Je,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{dy:r,filter:a}=t,{inputShape:i,strides:o,pad:l,dataFormat:u,dimRoundingMode:c}=s,h=Ao(u),p=ko(i,a.shape,o,1,l,c,!1,h),d=new ID(p);return n.runWebGLProgram(d,[r,a],"float32")}};const $D={kernelName:Qe,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a}=t,{strides:i,pad:o,dilations:l}=s,u=Io(r.shape,a.shape,i,l,o),c=new mD(u);return n.runWebGLProgram(c,[r,a],"float32")}};const ED={kernelName:et,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,dy:a}=t,{strides:i,pad:o,filterShape:l}=s,u=Io(r.shape,l,i,1,o),c=new ND(u);return n.runWebGLProgram(c,[r,a],"float32")}};const RD={kernelName:tt,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{dy:r,filter:a}=t,{pad:i,strides:o,inputShape:l}=s,u=Io(l,a.shape,o,1,i),c=new SD(u);return n.runWebGLProgram(c,[r,a],"float32")}},AD=SF({opSnippet:NF+"\n return cos(x);\n"}),FD={kernelName:nt,backendName:"webgl",kernelFunc:AD},_D=SF({opSnippet:"\n float e2x = exp(-x);\n return (e2x + 1.0 / e2x) / 2.0;\n"}),DD={kernelName:st,backendName:"webgl",kernelFunc:_D}; +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class OD{constructor(e,t,n,s,r){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"===s?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(${r}));\n return;\n }\n float in_x = ${w};\n if( in_x < 0.0 || in_x > ${f} ) {\n setOutput(float(${r}));\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 `}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +const MD={kernelName:it,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:s}=e,{image:r,boxes:a,boxInd:i}=t,{cropSize:o,method:l,extrapolationValue:u}=s,c=new OD(r.shape,a.shape,o,l,u);return n.runWebGLProgram(c,[r,a,i],"float32")}};var LD;!function(e){e.Prod="*",e.Sum="+"}(LD||(LD={}));class zD{constructor(e,t,n,s){this.op=e,this.outputShape=t,this.variableNames=["x"],this.customUniforms=[{name:"index",type:"float"}];const r=this.outputShape.length,a=this.op===LD.Prod?"1.0":"0.0",i=n?a:`getX(${PD(r,"coords",this.op)})`,o=this.outputShape[this.outputShape.length-1];let l="",u="";n?(l=s?"end != "+(o-1):"end != 0",u=s?"end + 1":"end - 1"):(l=s?`end + pow2 < ${o}`:"end >= pow2",u=s?"end + pow2":"end - pow2"),this.userCode=`\n void main() {\n ${CR(r)} coords = getOutputCoords();\n int end = ${BD(r,"coords",this.op)};\n float val = ${i};\n int pow2 = int(pow(2.0, index));\n if (${l}) {\n int idx = ${u};\n ${BD(r,"coords",this.op)} = idx;\n val ${this.op}= getX(${PD(r,"coords",this.op)});\n }\n setOutput(val);\n }\n `}}function PD(e,t,n){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 new Error(`Cumulative ${n} for rank ${e} is not yet supported`)}function BD(e,t,n){if(1===e)return`${t}`;if(2===e)return`${t}.y`;if(3===e)return`${t}.z`;if(4===e)return`${t}.w`;throw new Error(`Cumulative ${n} for rank ${e} is not yet supported`)} +/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function WD(e,t,n,s,r,a){const i=t.shape.length,o=Ol([s],i);let l=t;null!=o&&(l=HF({inputs:{x:t},backend:n,attrs:{perm:o}}));const u=Ll(1,i)[0];if(u!==i-1)throw new Error(`WebGL cumprod shader expects an inner-most axis=${t.shape.length-1} but got axis=${s}`);const c=l.shape[u];let h=fF({inputs:{x:l},backend:n});for(let t=0;t<=Math.ceil(Math.log2(c))-1;t++){const s=new zD(e,l.shape,!1,a),r=[[t]],i=h;h=n.runWebGLProgram(s,[h],h.dtype,r),n.disposeIntermediateTensorInfo(i)}if(r){const t=new zD(e,l.shape,r,a),s=h;h=n.runWebGLProgram(t,[h],h.dtype),n.disposeIntermediateTensorInfo(s)}if(null!=o){const e=HF({inputs:{x:h},backend:n,attrs:{perm:Ml(o)}});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(l),e}return h}const VD={kernelName:rt,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,exclusive:i,reverse:o}=s;return WD(LD.Prod,r,n,a,i,o)}};const UD={kernelName:at,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,exclusive:i,reverse:o}=s;return WD(LD.Sum,r,n,a,i,o)}};const GD={kernelName:ot,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,weights:a}=t,{size:i,binaryOutput:o}=s;if(1===r.shape.length){const e=n.readSync(r.dataId),t=n.readSync(a.dataId),s=QR(e,t,a.dtype,a.shape,i);return n.makeTensorInfo([i],a.dtype,s)}if(2===r.shape.length){const e=n.bufferSync(r),t=n.bufferSync(a),s=eA(e,t,i,o);return n.makeTensorInfo(s.shape,a.dtype,s.values)}throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${r.shape.length}.`)}}; +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class HD{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 jD={kernelName:lt,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{blockSize:a,dataFormat:i}=s,o=r.shape[0],l=("NHWC"===i?r.shape[1]:r.shape[2])*a,u=("NHWC"===i?r.shape[2]:r.shape[3])*a,c=("NHWC"===i?r.shape[3]:r.shape[1])/(a*a),h=new HD("NHWC"===i?[o,l,u,c]:[o,c,l,u],a,i);return n.runWebGLProgram(h,[r],r.dtype)}}; +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class qD{constructor(e,t=!1,n=null,s=!1,r=!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=DR(this.outputShape.length);const a=e.filterHeight,i=e.filterWidth,o=e.outChannels/e.inChannels;let l="",u="";n&&(l=s?`float activation(float a) {\n float b = getPreluActivationWeightsAtOutCoords();\n ${n}\n }`:r?`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"),s&&this.variableNames.push("preluActivationWeights"),r&&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 `}} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class KD{constructor(e,t=!1,n=null,s=!1,r=!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=DR(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 `,p+=l>1?`\n xCOffset -= 2;\n if (xCOffset >= 0 && xCOffset < inDims[1]) {\n previous = getX(batch, xR, xCOffset, d1);\n xC${t+1} = vec4(previous.zw, xTexelC${t+1}.xy);\n } else {\n xC${t+1} = vec4(0.0, 0.0, xTexelC${t+1}.xy);\n }\n `:`\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=ko(r.shape,a.shape,i,c,o,u,!0);let p;p=ye().getBool("WEBGL_PACK_DEPTHWISECONV")&&h.strideWidth<=2&&h.outChannels/h.inChannels==1?new KD(h):new qD(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,[r,a],"float32",d)}}; +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class YD{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;const t=e.strideHeight,n=e.strideWidth,s=e.padInfo.top,r=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} - ${s};\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} - ${r};\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 ZD{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterHeight,n=e.filterWidth,s=e.strideHeight,r=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) / ${s}.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) / ${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 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 JD={kernelName:ct,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,dy:a}=t,{strides:i,dilations:o,pad:l,dimRoundingMode:u,filterShape:c}=s,h=ko(r.shape,c,i,o,l,u,!0),p=new YD(h);return n.runWebGLProgram(p,[r,a],"float32")}};const QD={kernelName:ht,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{dy:r,filter:a}=t,{strides:i,dilations:o,pad:l,dimRoundingMode:u,inputShape:c}=s,h=ko(c,a.shape,i,o,l,u,!0),p=new ZD(h);return n.runWebGLProgram(p,[r,a],"float32")}}; +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class eO{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 tO={kernelName:pt,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n}=e,{x:s}=t,r=[...s.shape,...s.shape],a=P(s.shape),i=OF({inputs:{x:s},backend:n,attrs:{shape:[a]}}),o=new eO(a),l=n.runWebGLProgram(o,[i],i.dtype),u=OF({inputs:{x:l},backend:n,attrs:{shape:r}});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(l),u}}; +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class nO{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;const{inHeight:t,inWidth:n,padInfo:s,strideHeight:r,strideWidth:a,filterHeight:i,filterWidth:o,dilationHeight:l,dilationWidth:u}=e,{top:c,left:h}=s;this.userCode=`\n const ivec2 strides = ivec2(${r}, ${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 sO={kernelName:dt,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a}=t,{strides:i,pad:o,dilations:l}=s,u=xo(r.shape,a.shape,i,o,"NHWC",l);let c;const h=new nO(u);c=n.runWebGLProgram(h,[r,a],"float32");const p=OF({inputs:{x:c},backend:n,attrs:{shape:u.outShape}});return n.disposeIntermediateTensorInfo(c),p}};const rO={kernelName:yt,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{equation:r}=s,a=t,{allDims:i,summedDims:o,idDims:l}=kd(r,a.length);Nd(i.length,l,a);const{path:u,steps:c}=Sd(o,l),h=c.length;let p=null,d=i.length;const f=[];for(let e=0;e=0&&(p=UF({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}},aO=SF({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"}),iO={kernelName:bt,backendName:"webgl",kernelFunc:aO},oO={kernelName:xt,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n}=e,{dy:s,y:r}=t,a=ye().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new dF("\n vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));\n return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));\n",s.shape,r.shape):new hF("return (b >= 1.0) ? a : a * (b + 1.0);",s.shape,r.shape);return n.runWebGLProgram(a,[s,r],s.dtype)}},lO=TF({opSnippet:"return float(a == b);",packedOpSnippet:"\n return vec4(equal(a, b));\n",dtype:"bool",cpuKernelImpl:rA}),uO={kernelName:vt,backendName:"webgl",kernelFunc:lO},cO=SF({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 = ${rd};\n float a1 = ${ad};\n float a2 = ${id};\n float a3 = ${od};\n float a4 = ${ld};\n float a5 = ${ud};\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`}),hO={kernelName:wt,backendName:"webgl",kernelFunc:cO},pO=SF({opSnippet:NF+"\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:aA,dtype:"float32"}),dO={kernelName:kt,backendName:"webgl",kernelFunc:pO}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function fO(e){const{inputs:t,attrs:n,backend:s}=e,{dim:r}=n,{input:a}=t,i=a.shape.length,o=a.shape.slice();let l=r;return r<0&&(O(-(i+1)<=r,(()=>`Axis must be in the interval [${-(i+1)}, ${i}]`)),l=i+r+1),o.splice(l,0,1),OF({inputs:{x:a},backend:s,attrs:{shape:o}})}const mO={kernelName:It,backendName:"webgl",kernelFunc:fO},gO="return exp(x) - 1.0;",yO=SF({opSnippet:gO,packedOpSnippet:gO,cpuKernelImpl:iA}),bO={kernelName:Nt,backendName:"webgl",kernelFunc:yO}; +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class xO{constructor(e,t,n){this.variableNames=["real","imag"];const s=t[1];this.outputShape=t;const r=n?`2.0 * ${Math.PI}`:`-2.0 * ${Math.PI}`,a=n?`${s}.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 = ${r};\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(${s});\n float exponentMultiplierTimesIndexRatio =\n exponentMultiplier * indexRatio;\n\n float result = 0.0;\n\n for (int i = 0; i < ${s}; 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 `}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function wO(e,t,n){const s=n.texData.get(e.dataId),r=P(e.shape),a=e.shape[e.shape.length-1],i=OF({inputs:{x:e},backend:n,attrs:{shape:[r/a,a]}}),o=i.shape,l=new xO("real",o,t),u=new xO("imag",o,t),c=[{dataId:s.complexTensorInfos.real.dataId,dtype:s.complexTensorInfos.real.dtype,shape:o},{dataId:s.complexTensorInfos.imag.dataId,dtype:s.complexTensorInfos.imag.dtype,shape:o}],h=n.runWebGLProgram(l,c,"float32"),p=n.runWebGLProgram(u,c,"float32"),d=gF({inputs:{real:h,imag:p},backend:n});n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(p);const f=OF({inputs:{x:d},backend:n,attrs:{shape:e.shape}});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(d),f}const vO={kernelName:St,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n}=e,{input:s}=t;return wO(s,!1,n)}}; +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class kO{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 "}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function IO(e){const{backend:t,attrs:n}=e,{shape:s,value:r}=n;let{dtype:a}=n;if(a=a||te(r),"string"===a){const e=X(a,P(s));return e.fill(r),t.makeTensorInfo(s,a,e)}{const e=new kO(s,r),n=[[r]];return t.runWebGLProgram(e,[],a,n)}}const NO={kernelName:Tt,backendName:"webgl",kernelFunc:IO}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class SO{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 `}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +const TO={kernelName:Ct,backendName:"webgl",kernelFunc:({inputs:e,backend:t})=>{const{image:n}=e,s=t,r=new SO(n.shape);return s.runWebGLProgram(r,[n],n.dtype)}},CO="return floor(x);",$O=SF({opSnippet:CO,packedOpSnippet:CO,cpuKernelImpl:oA}),EO={kernelName:$t,backendName:"webgl",kernelFunc:$O},RO=TF({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"}),AO={kernelName:Et,backendName:"webgl",kernelFunc:RO}; +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class FO{constructor(e){this.variableNames=["A"];const t=cR(),[n,s]=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(${s}.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 `}} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class _O{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;const t=cR(),[n,s]=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(${s}.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 `}} +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +const DO={kernelName:Ns,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e;let{pixels:r}=t;const{numChannels:a}=s,i="undefined"!=typeof HTMLVideoElement&&r instanceof HTMLVideoElement,o="undefined"!=typeof HTMLImageElement&&r instanceof HTMLImageElement,[l,u]=i?[r.videoWidth,r.videoHeight]:[r.width,r.height],c=[u,l],h=[u,l,a];if(o||i){const e=ye().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");null!=OO&&e===MO||(MO=e,OO=document.createElement("canvas").getContext("2d",{willReadFrequently:MO})),OO.canvas.width=l,OO.canvas.height=u,OO.drawImage(r,0,0,l,u),r=OO.canvas}const p=n.makeTensorInfo(c,"int32");n.texData.get(p.dataId).usage=FE.PIXELS,n.gpgpu.uploadPixelDataToTexture(n.getTexture(p.dataId),r);const d=ye().getBool("WEBGL_PACK")?new _O(h):new FO(h),f=n.runWebGLProgram(d,[p],"int32");return n.disposeData(p.dataId),f}};let OO,MO=ye().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");const LO={kernelName:Cs,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dataFormat:c,dilations:h,dimRoundingMode:p,activation:d,leakyreluAlpha:f}=s,m=Ao(c),g=ko(r.shape,a.shape,l,h,u,p,!1,m);let y;const b=[],x=null!=i,w=null!=o,v="leakyrelu"===d,k=()=>{const e=[r,a],t=(e,t)=>{if("NCHW"===t&&1===e.shape.length&&1!==e.shape[0]){const t=OF({inputs:{x:e},backend:n,attrs:{shape:[e.shape[0],1,1]}});return b.push(t),t}return e};if(x&&e.push(t(i,c)),w&&e.push(t(o,c)),v){const t=n.makeTensorInfo([],"float32",Qs(f,"float32"));e.push(t),b.push(t)}return e};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(g.strideWidth<=2&&"channelsLast"===m&&ye().getBool("WEBGL_EXP_CONV")){const e=d?CF(d,!0):null,t=new gD(g,x,e,w,v),s=[[g.padInfo.top,g.padInfo.left],[g.strideHeight,g.strideWidth],[g.dilationHeight,g.dilationWidth],[g.inHeight,g.inWidth]],r=k();y=n.runWebGLProgram(t,r,"float32",s)}else if(ye().getBool("WEBGL_CONV_IM2COL"))y=wD({x:r,filter:a,convInfo:g,backend:n,bias:i,activation:d,preluActivationWeights:o,leakyreluAlpha:f});else{const e=d?CF(d,!1):null,t=new fD(g,x,e,w,v),s=k();y=n.runWebGLProgram(t,s,"float32")}else y=xD({x:r,filter:a,convInfo:g,backend:n,bias:i,activation:d,preluActivationWeights:o,leakyreluAlpha:f});const I=OF({inputs:{x:y},backend:n,attrs:{shape:g.outShape}});return b.push(y),b.forEach((e=>n.disposeIntermediateTensorInfo(e))),I}};const zO={kernelName:$s,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dilations:c,dimRoundingMode:h,activation:p,leakyreluAlpha:d}=s,f=[];let m=c;null==m&&(m=[1,1]),O(Ro(l,m),(()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${l} and dilations '${m}'`));const g=ko(r.shape,a.shape,l,m,u,h,!0),y=ye().getBool("WEBGL_PACK_DEPTHWISECONV")&&g.strideWidth<=2&&g.outChannels/g.inChannels==1,b=p?CF(p,y):null,x=[r,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",Qs(d,"float32"));x.push(e),f.push(e)}let I;I=y?new KD(g,w,b,v,k):new qD(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 PO{constructor(e,t,n,s){this.sliceDim=e,this.strides=t,this.paramsShape=s,this.variableNames=["x","indices"],this.outputShape=n;const r=CR(n.length);let a="\n int index;";for(let e=0;e= ${this.paramsShape[e]};\n flattenIndex += index * ${this.strides[e]};`;this.userCode=`\n void main() {\n ${r} coords = getOutputCoords();\n int flattenIndex = 0;\n bool out_of_bounds = false;\n\n ${a}\n\n setOutput(out_of_bounds ? 0.0 : getX(flattenIndex, coords[1]));\n }\n `}}const BO={kernelName:Ft,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n}=e,{params:s,indices:r}=t,a=r.shape,i=a[a.length-1],o=P(s.shape),[l,u,c,h]=td(s,r),p=OF({inputs:{x:r},backend:n,attrs:{shape:[u,i]}}),d=OF({inputs:{x:s},backend:n,attrs:{shape:[P(s.shape)/c,c]}});if(n.shouldExecuteOnCPU([s,r])||"string"===s.dtype){const e=n.readSync(r.dataId),t=n.bufferSync(s),a=lA(e,t,s.dtype,u,i,c,h,s.shape,o);return n.makeTensorInfo(l,s.dtype,a.values)}const f=new PO(i,h,[u,c],s.shape),m=n.runWebGLProgram(f,[d,p],d.dtype),g=OF({inputs:{x:m},backend:n,attrs:{shape:l}});return n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(m),g}}; +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class WO{constructor(e,t){this.variableNames=["A","indices"],this.outputShape=t,this.rank=t.length;const n=CR(this.rank),s=function(e){const t=["resRC.x","resRC.y","resRC.z","resRC.w"],n=[];for(let s=0;s= 0) && (index < ${e[2]}) ? 1.0 : 0.0;\n setOutput(inBounds * getA(${s}));\n }\n `}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function VO(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,indices:a}=t,{axis:i,batchDims:o}=s,l=j(i,r.shape)[0];if(ye().get("DEBUG")){const e=n.readSync(a.dataId),t=r.shape[l];for(let n=0;n=0,(()=>`GatherV2: the index value ${s} is not in [0, ${t-1}]`))}}const u=Ud(r,a,l,o),c=P(a.shape),h=[],p=OF({inputs:{x:r},backend:n,attrs:{shape:[u.batchSize,u.outerSize,u.dimSize,u.sliceSize]}}),d=OF({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([r,a])||"string"===r.dtype){const e=n.bufferSync(d),t=n.bufferSync(p),s=uA(t,e,f);return h.forEach((e=>n.disposeIntermediateTensorInfo(e))),n.makeTensorInfo(u.outputShape,s.dtype,s.values)}const m=new WO(p.shape,f),g=n.runWebGLProgram(m,[p,d],p.dtype);h.push(g);const y=OF({inputs:{x:g},backend:n,attrs:{shape:u.outputShape}});return h.forEach((e=>n.disposeIntermediateTensorInfo(e))),y}const UO={kernelName:At,backendName:"webgl",kernelFunc:VO},GO=TF({opSnippet:"return float(a > b);",packedOpSnippet:"\n return vec4(greaterThan(a, b));\n",cpuKernelImpl:cA,dtype:"bool"}),HO={kernelName:_t,backendName:"webgl",kernelFunc:GO},jO=TF({opSnippet:"return float(a >= b);",packedOpSnippet:"\n return vec4(greaterThanEqual(a, b));\n",dtype:"bool",cpuKernelImpl:hA}),qO={kernelName:Dt,backendName:"webgl",kernelFunc:jO};const KO={kernelName:Mt,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n}=e,{input:s}=t;return wO(s,!0,n)}},XO=SF({opSnippet:"return float(!isnan(x) && !isinf(x));",dtype:"bool"}),YO={kernelName:zt,backendName:"webgl",kernelFunc:XO},ZO=SF({opSnippet:"return float(isinf(x));",dtype:"bool"}),JO={kernelName:Pt,backendName:"webgl",kernelFunc:ZO},QO=SF({opSnippet:"return float(isnan(x));",dtype:"bool"}),eM={kernelName:Bt,backendName:"webgl",kernelFunc:QO},tM=TF({opSnippet:"return float(a < b);",packedOpSnippet:"\n return vec4(lessThan(a, b));\n",cpuKernelImpl:pA,dtype:"bool"}),nM={kernelName:Vt,backendName:"webgl",kernelFunc:tM},sM=TF({opSnippet:"return float(a <= b);",packedOpSnippet:"\n return vec4(lessThanEqual(a, b));\n",cpuKernelImpl:dA,dtype:"bool"}),rM={kernelName:Ut,backendName:"webgl",kernelFunc:sM};const aM={kernelName:Gt,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{backend:t,attrs:n}=e,{start:s,stop:r,num:a}=n,i=fA(s,r,a);return t.makeTensorInfo([i.length],"float32",i)}},iM=SF({opSnippet:NF+"\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:mA}),oM={kernelName:Ht,backendName:"webgl",kernelFunc:iM},lM=SF({opSnippet:NF+"\n return log(1.0 + x);\n"}),uM={kernelName:jt,backendName:"webgl",kernelFunc:lM},cM=TF({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"}),hM={kernelName:qt,backendName:"webgl",kernelFunc:cM},pM=SF({opSnippet:"return float(!(x >= 1.0));"}),dM={kernelName:Kt,backendName:"webgl",kernelFunc:pM},fM=TF({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"}),mM={kernelName:Xt,backendName:"webgl",kernelFunc:fM}; +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class gM{constructor(e,t,n,s,r){this.variableNames=["x"],this.outputShape=[];const a=t,i=e[3]-1;let o;this.outputShape=e;const l=`float(${n}) + float(${s}) * sum`;o=.5===r?`inversesqrt(${l})`:1===r?`1.0/(${l})`:`exp(log(${l}) * float(-${r}));`,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 `}} +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class yM{constructor(e,t,n,s,r){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(${s}) * sum`;o=.5===r?`inversesqrt(${l})`:1===r?`1.0/(${l})`:`exp(log(${l}) * float(-${r}));`,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 `}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +const bM={kernelName:Yt,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{depthRadius:a,bias:i,alpha:o,beta:l}=s,u=ye().getBool("WEBGL_PACK_NORMALIZATION")?new yM(r.shape,a,i,o,l):new gM(r.shape,a,i,o,l);return n.runWebGLProgram(u,[r],r.dtype)}}; +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class xM{constructor(e,t,n,s,r){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=e,this.depth=e[3],this.depthRadius=t,this.bias=n,this.alpha=s,this.beta=r,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(${s}) * 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(${s})\n * float(${r})\n * getInputImage(b ,r ,c, k) * getOutputImage(b, r, c, d)\n / norm;\n if (k == d) {\n dyi += pow(norm, -1.0 * ${r});\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 `}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +const wM={kernelName:Zt,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:s}=e,{x:r,y:a,dy:i}=t,{depthRadius:o,bias:l,alpha:u,beta:c}=s,h=new xM(r.shape,o,l,u,c);return n.runWebGLProgram(h,[r,a,i],r.dtype)}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function vM(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{reductionIndices:a,keepDims:i}=s,o=r.shape.length,l=j(a,r.shape);let u=l;const c=Ol(u,o),h=null!=c,p=n.shouldExecuteOnCPU([r]);let d=r;if(h){if(p){const e=n.texData.get(d.dataId).values,t=new Array(o);for(let e=0;e`Error in maxPool: Either strides or dilations must be 1. Got strides ${i} and dilations '1'`));const u=wo(r.shape,a,i,1,o,l);if(1===u.filterWidth&&1===u.filterHeight&&B(u.inShape,u.outShape))return fF({inputs:{x:r},backend:n});const c=new T_(u,"max",!1);return n.runWebGLProgram(c,[r],r.dtype)}};const TM={kernelName:nn,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{filterSize:a,strides:i,pad:o,dataFormat:l,dimRoundingMode:u}=s,c=vo(r.shape,a,i,[1,1,1],o,u,l),h=new C_(c,"max",!1);return n.runWebGLProgram(h,[r],r.dtype)}}; +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class CM{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;const t=e.strideHeight,n=e.strideWidth,s=e.dilationHeight,r=e.effectiveFilterHeight,a=e.effectiveFilterWidth,i=r-1-e.padInfo.top,o=a-1-e.padInfo.left,l=r*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 < ${r};\n wR += ${s}) {\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 $M{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;const t=e.strideDepth,n=e.strideHeight,s=e.strideWidth,r=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 += ${r}) {\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) / ${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(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 EM={kernelName:sn,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{dy:r,input:a}=t,i=a,{filterSize:o,strides:l,pad:u,dimRoundingMode:c}=s,h=vo(i.shape,o,l,[1,1,1],u,c),p=new C_(h,"max",!0),d=n.runWebGLProgram(p,[i],i.dtype),f=new $M(h),m=n.runWebGLProgram(f,[r,d],i.dtype);return n.disposeIntermediateTensorInfo(d),m}};const RM={kernelName:tn,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{dy:r,input:a,output:i}=t,o=a;lR([a,i],"maxPoolGrad");const{filterSize:l,strides:u,pad:c,dimRoundingMode:h}=s,p=wo(o.shape,l,u,1,c,h),d=new T_(p,"max",!0),f=n.runWebGLProgram(d,[o],o.dtype),m=new CM(p),g=n.runWebGLProgram(m,[r,f],o.dtype);return n.disposeIntermediateTensorInfo(f),g}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +const AM={kernelName:rn,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:s}=e,{filterSize:r,strides:a,pad:i,includeBatchInIndex:o}=t,l=n;O(4===s.shape.length,(()=>`Error in maxPool: input must be rank 4 but got rank ${s.shape.length}.`));const u=[1,1];O(Ro(a,u),(()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${u}'`));const c=wo(s.shape,r,a,u,i),[h,p]= +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n,s){let r=new T_(n,"max",!1);const a=s.runWebGLProgram(r,[e],"float32");return r=new T_(n,"max",!0,!0,t),[a,s.runWebGLProgram(r,[e],"float32")]}(s,o,c,l);return[h,p]}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +const FM={kernelName:an,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:s}=e,{keepDims:r,axis:a}=t,i=n,o=s.shape.length,l=j(a,s.shape);let u=l;const c=Ol(u,o),h=null!=c,p=i.shouldExecuteOnCPU([s]),d=[];let f=s;if(h){if(p){const e=i.texData.get(f.dataId).values,t=new Array(o);for(let e=0;et[0]+e[n]+t[1]));const s=e.length,r=CR(s),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,s),l="reflect"===n?0:1;this.userCode=1!==s?`\n ${r} start = ${r}(${a});\n ${r} end = ${r}(${i});\n\n void main() {\n ${r} outC = getOutputCoords();\n for (int i = 0; i < ${s}; 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 ${r} 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 `}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class LM{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 s=e.length,r=CR(s),a=t.map((e=>e[0])).join(","),i=t.map(((t,n)=>t[0]+e[n])).join(","),o=HA("rc",s),l=HA("source",s),u=`${o[s-1]} < ${this.outputShape[s-1]}`,c=1===s?"source":`vec2(${l.slice(-2).join()})`,h="reflect"===n?0:1;let p="";if(1===s){const e=`\n ${r} 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 ${r} rc = outputLoc;\n ${e}\n result[0] = getChannel(getX(${l.join()}), ${c});\n ${o[s-1]} += 1;\n if(${u}) {\n ${e}\n result[1] = getChannel(getX(${l.join()}), ${c});\n }\n `}else{const e=`\n ${r} source = rc;\n ${r} lt = ${r}(lessThan(source, start));\n ${r} gte = ${r}(greaterThanEqual(source, end));\n ${r} 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 ${r} rc = outputLoc;\n ${e}\n result[0] = getChannel(getX(${l.join()}), ${c});\n ${o[s-1]} += 1;\n if(${u}) {\n ${e}\n result[1] = getChannel(getX(${l.join()}), ${c});\n }\n rc = outputLoc;\n ${o[s-2]} += 1;\n if(${o[s-2]} < ${this.outputShape[s-2]}) {\n ${e}\n result[2] = getChannel(getX(${l.join()}), ${c});\n ${o[s-1]} += 1;\n if(${u}) {\n ${e}\n result[3] = getChannel(getX(${l.join()}), ${c});\n }\n }\n `}this.userCode=`\n const ${r} start = ${r}(${a});\n const ${r} end = ${r}(${i});\n\n void main() {\n ${r} outputLoc = getOutputCoords();\n vec4 result = vec4(0.);\n ${p}\n setOutput(result);\n }\n `}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +const zM={kernelName:un,backendName:"webgl",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:s}=e,{paddings:r,mode:a}=n,i=ye().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new LM(s.shape,r,a):new MM(s.shape,r,a);return t.runWebGLProgram(i,[s],s.dtype)}},PM=TF({opSnippet:"if (b == 0.0) return NAN;\n return mod(a, b);",packedOpSnippet:"\n vec4 result = mod(a, b);\n bvec4 isNaN = equal(b, vec4(0.0));\n "+pF+"\n return result;\n"}),BM={kernelName:cn,backendName:"webgl",kernelFunc:PM}; +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class WM{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 `}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +const VM=TF({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}),UM={kernelName:gt,backendName:"webgl",kernelFunc:VM},GM="return a - b;",HM=TF({opSnippet:GM,packedOpSnippet:GM,supportsComplex:!0,cpuKernelImpl:PA}),jM={kernelName:ps,backendName:"webgl",kernelFunc:HM}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function qM(e){const{inputs:t,backend:n,attrs:s}=e,{logits:r}=t,{dim:a}=s,i=j([a],r.shape),o=vM({inputs:{x:r},backend:n,attrs:{reductionIndices:i,keepDims:!1}}),l=_l(o.shape,i),u=OF({inputs:{x:o},backend:n,attrs:{shape:l}}),c=HM({inputs:{a:r,b:u},backend:n}),h=pO({inputs:{x:c},backend:n}),p=UF({inputs:{x:h},backend:n,attrs:{axis:i,keepDims:!1}}),d=OF({inputs:{x:p},backend:n,attrs:{shape:l}}),f=VM({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 KM={kernelName:es,backendName:"webgl",kernelFunc:qM};const XM={kernelName:hn,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{logits:r}=t,{numSamples:a,seed:i,normalized:o}=s,l=o?r:qM({inputs:{logits:r},backend:n,attrs:{dim:r.shape.length-1}}),u=l.shape[0],c=l.shape[1],h=new WM(u,c,a),p=[[i]],d=n.runWebGLProgram(h,[l],"int32",p);return o||n.disposeIntermediateTensorInfo(l),d}},YM=QA+"\n return -x;\n";const ZM={kernelName:dn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:s}=t;if(n.shouldExecuteOnCPU([s])){const e=n.texData.get(s.dataId),[t,r]=wA(e.values,s.shape,s.dtype);return n.makeTensorInfo(r,s.dtype,t)}let r;return r=ye().getBool("WEBGL_PACK_UNARY_OPERATIONS")?new rF(s.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 JA(s.shape,YM),n.runWebGLProgram(r,[s],s.dtype)}},JM=Ph;const QM={kernelName:mn,backendName:"webgl",kernelFunc:function(e){Es("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{inputs:t,backend:n,attrs:s}=e,{boxes:r,scores:a}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l}=s,u=n.readSync(r.dataId),c=n.readSync(a.dataId),{selectedIndices:h}=JM(u,c,i,o,l);return n.makeTensorInfo([h.length],"int32",new Int32Array(h))}},eL=Bh;const tL={kernelName:gn,backendName:"webgl",kernelFunc:function(e){Es("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{inputs:t,backend:n,attrs:s}=e,{boxes:r,scores:a}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,padToMaxOutputSize:u}=s,c=n.readSync(r.dataId),h=n.readSync(a.dataId),{selectedIndices:p,validOutputs:d}=eL(c,h,i,o,l,u);return[n.makeTensorInfo([p.length],"int32",new Int32Array(p)),n.makeTensorInfo([],"int32",new Int32Array([d]))]}},nL=Wh;const sL={kernelName:yn,backendName:"webgl",kernelFunc:function(e){Es("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{inputs:t,backend:n,attrs:s}=e,{boxes:r,scores:a}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,softNmsSigma:u}=s,c=n.readSync(r.dataId),h=n.readSync(a.dataId),p=i,d=o,f=l,m=u,{selectedIndices:g,selectedScores:y}=nL(c,h,p,d,f,m);return[n.makeTensorInfo([g.length],"int32",new Int32Array(g)),n.makeTensorInfo([y.length],"float32",new Float32Array(y))]}}; +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class rL{constructor(e,t,n,s){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(${s}), float(${n}),\n float(index == coords.y)));\n }\n `}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +const aL={kernelName:xn,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:s}=e,{indices:r}=t,{dtype:a,depth:i,onValue:o,offValue:l}=s,u=P(r.shape),c=new rL(u,i,o,l),h=OF({inputs:{x:r},backend:n,attrs:{shape:[u]}}),p=n.runWebGLProgram(c,[h],a);n.disposeIntermediateTensorInfo(h);const d=OF({inputs:{x:p},backend:n,attrs:{shape:[...r.shape,i]}});return n.disposeIntermediateTensorInfo(p),d}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function iL(e){const{inputs:t,backend:n}=e,{x:s}=t;if("complex64"===s.dtype){const e=K_({inputs:{input:s},backend:n}),t=iL({inputs:{x:e},backend:n}),r=uD({inputs:{input:s},backend:n}),a=iL({inputs:{x:r},backend:n}),i=gF({inputs:{real:t,imag:a},backend:n});return n.disposeIntermediateTensorInfo(e),n.disposeIntermediateTensorInfo(t),n.disposeIntermediateTensorInfo(r),n.disposeIntermediateTensorInfo(a),i}return IO({attrs:{shape:s.shape,dtype:s.dtype,value:"string"===s.dtype?"":0},backend:n})}const oL={kernelName:ks,backendName:"webgl",kernelFunc:iL};const lL={kernelName:bn,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function e(t){const{inputs:n,backend:s}=t,{x:r}=n;if("string"===r.dtype)throw new Error("onesLike is not supported under string dtype");if("complex64"===r.dtype){const t=K_({inputs:{input:r},backend:s}),n=e({inputs:{x:t},backend:s}),a=uD({inputs:{input:r},backend:s}),i=iL({inputs:{x:a},backend:s}),o=gF({inputs:{real:n,imag:i},backend:s});return s.disposeIntermediateTensorInfo(t),s.disposeIntermediateTensorInfo(n),s.disposeIntermediateTensorInfo(a),s.disposeIntermediateTensorInfo(i),o}return IO({attrs:{shape:r.shape,dtype:r.dtype,value:1},backend:s})}};const uL={kernelName:wn,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{axis:r}=s;if(1===t.length)return fO({inputs:{input:t[0]},backend:n,attrs:{dim:r}});const a=t[0].shape,i=t[0].dtype;t.forEach((e=>{M(a,e.shape,"All tensors passed to stack must have matching shapes"),O(i===e.dtype,(()=>"All tensors passed to stack must have matching dtypes"))}));const o=[],l=pD({inputs:t.map((e=>{const t=fO({inputs:{input:e},backend:n,attrs:{dim:r}});return o.push(t),t})),backend:n,attrs:{axis:r}});return o.forEach((e=>n.disposeIntermediateTensorInfo(e))),l}}; +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class cL{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 s=e.length,r=CR(s),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,s);this.userCode=1!==s?`\n ${r} start = ${r}(${a});\n ${r} end = ${r}(${i});\n\n void main() {\n ${r} outC = getOutputCoords();\n if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {\n setOutput(value);\n } else {\n ${r} 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 `}} +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class hL{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 s=e.length,r=CR(s),a=t.map((e=>e[0])).join(","),i=t.map(((t,n)=>t[0]+e[n])).join(","),o=HA("rc",s),l=HA("source",s),u=`${o[s-1]} < ${this.outputShape[s-1]}`,c=1===s?"source":`vec2(${l.slice(-2).join()})`,h=[`${r} rc = outputLoc;`,`${o[s-1]} += 1;\n if(${u}) {\n `,1===s?"":`}\n rc = outputLoc;\n ${o[s-2]} += 1;\n if(${o[s-2]} < ${this.outputShape[s-2]}) {`,1===s?"":` ${o[s-1]} += 1;\n if(${u}) {`],p=1===s?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))";let d="";for(let e=0,t=1===s?2:4;e{const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{paddings:a,constantValue:i}=s;if(0===P(r.shape)){const e=a.map(((e,t)=>e[0]+r.shape[t]+e[1]));return IO({backend:n,attrs:{shape:e,value:i,dtype:r.dtype}})}const o=ye().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new hL(r.shape,a,i):new cL(r.shape,a,i),l=[[i]];return n.runWebGLProgram(o,[r],r.dtype,l)},dL={kernelName:vn,backendName:"webgl",kernelFunc:pL},fL=TF({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 bvec4 isNaN1 = lessThan(a, vec4(0.0));\n bvec4 isNaN2 = lessThan(floor(b), b);\n bvec4 isNaN = bvec4(isNaN1.x && isNaN2.x, isNaN1.y && isNaN2.y, isNaN1.z && isNaN2.z, isNaN1.w && isNaN2.w);\n "+pF+"\n return result;\n"}),mL={kernelName:kn,backendName:"webgl",kernelFunc:fL};const gL={kernelName:Nn,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:i}=s,o=r.shape.length,l=[],u=j(a,r.shape);let c=u;const h=Ol(c,o);let p,d=r;if(null!=h&&(d=HF({inputs:{x:r},backend:n,attrs:{perm:h}}),c=Ll(c.length,o),l.push(d)),Dl("prod",c,o),n.shouldExecuteOnCPU([d])){const e=n.texData.get(d.dataId).values,{outVals:t,outShape:s,outDtype:r}=kA(d.shape,d.dtype,e,c);p=n.makeTensorInfo(s,r,t)}else{const[e,t]=Fl(d.shape,c),s=P(t),a=OF({inputs:{x:d},backend:n,attrs:{shape:[-1,s]}}),i=PF(a,Tr(r.dtype),"prod",n);p=OF({inputs:{x:i},backend:n,attrs:{shape:e}}),l.push(a),l.push(i)}if(i){l.push(p);const e=_l(p.shape,u);p=OF({inputs:{x:p},backend:n,attrs:{shape:e}})}return l.forEach((e=>n.disposeIntermediateTensorInfo(e))),p}};const yL={kernelName:Sn,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{paramsNestedSplits:r,paramsDenseValues:a,indices:i}=t,{outputRaggedRank:o}=s,l=r.map((e=>n.readSync(e.dataId))),u=r.map((e=>e.shape)),c=n.readSync(a.dataId),h=n.readSync(i.dataId),[p,d,f]=IA(l,u,c,a.shape,a.dtype,h,i.shape,o),m=p.map((e=>n.makeTensorInfo([e.length],"int32",e))),g=n.makeTensorInfo(f,a.dtype,d);return m.concat([g])}};const bL={kernelName:Tn,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{shape:r,values:a,defaultValue:i,rowPartitionTensors:o}=t,{rowPartitionTypes:l}=s,u=n.readSync(r.dataId),c=n.readSync(a.dataId),h=n.readSync(i.dataId),p=o.map((e=>n.readSync(e.dataId))),d=o.map((e=>e.shape)),[f,m]=NA(u,r.shape,c,a.shape,a.dtype,h,i.shape,p,d,l);return n.makeTensorInfo(f,a.dtype,m)}},xL=e=>{const{backend:t,attrs:n}=e,{start:s,stop:r,step:a,dtype:i}=n,o=SA(s,r,a,i);return t.makeTensorInfo([o.length],i,o)},wL={kernelName:Cn,backendName:"webgl",kernelFunc:xL},vL=SF({opSnippet:"return 1.0 / x;"}),kL={kernelName:En,backendName:"webgl",kernelFunc:vL},IL=SF({opSnippet:QA+"\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"}),NL={kernelName:Rn,backendName:"webgl",kernelFunc:IL},SL=SF({opSnippet:QA+"\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"}),TL={kernelName:Mn,backendName:"webgl",kernelFunc:SL}; +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class CL{constructor(e,t,n,s,r){this.variableNames=["A"],this.outputShape=[];const[a,i,o,l]=e;this.outputShape=[a,t,n,l];const u=[s&&t>1?i-1:i,s&&n>1?o-1:o],c=[s&&t>1?t-1:t,s&&n>1?n-1:n];let h;h=r?"(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 `}} +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class $L{constructor(e,t,n,s,r){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=[s&&t>1?i-1:i,s&&n>1?o-1:o],c=[s&&t>1?t-1:t,s&&n>1?n-1:n];let h;h=r?"(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 EL={kernelName:Dn,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{images:r}=t,{alignCorners:a,halfPixelCenters:i,size:o}=s,[l,u]=o,c=ye().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new $L(r.shape,l,u,a,i):new CL(r.shape,l,u,a,i);return n.runWebGLProgram(c,[r],"float32")}}; +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class RL{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;const[,s,r]=t,[,a,i]=e,o=[n&&a>1?s-1:s,n&&i>1?r-1:r],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), ${s-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), ${r-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 AL={kernelName:On,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{images:r,dy:a}=t,{alignCorners:i}=s,o=new RL(a.shape,r.shape,i);return n.runWebGLProgram(o,[a],a.dtype)}}; +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class FL{constructor(e,t,n,s,r){this.variableNames=["A"],this.outputShape=[];const[a,i,o,l]=e;this.outputShape=[a,t,n,l];const u=[s&&t>1?i-1:i,s&&n>1?o-1:o],c=[s&&t>1?t-1:t,s&&n>1?n-1:n],h=s?"0.5":"0.0";let p;p=r?"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 `}} +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class _L{constructor(e,t,n,s,r){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=[s&&t>1?i-1:i,s&&n>1?o-1:o],c=[s&&t>1?t-1:t,s&&n>1?n-1:n],h=s?"0.5":"0.0";let p;p=r?"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 DL={kernelName:Fn,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{images:r}=t,{alignCorners:a,halfPixelCenters:i,size:o}=s,[l,u]=o,c=ye().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new _L(r.shape,l,u,a,i):new FL(r.shape,l,u,a,i);return n.runWebGLProgram(c,[r],r.dtype)}}; +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class OL{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;const[,s,r]=t,[,a,i]=e,o=[n&&a>1?s-1:s,n&&i>1?r-1:r],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(${s}) - 1),\n ${n} ? float(round(sourceFracRow)) :\n float(floor(sourceFracRow))));\n\n int sourceNearestCol = int(min(\n float(int(${r}) - 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 ML={kernelName:_n,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{images:r,dy:a}=t,{alignCorners:i}=s,o=new OL(a.shape,r.shape,i);return n.runWebGLProgram(o,[a],a.dtype)}}; +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class LL{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 s=e.map(((n,s)=>(n=>-1!==t.indexOf(n)&&1!==e[n]?`${e[n]} - coords[${n}] - 1`:`coords[${n}]`)(s))).join(","),r=CR(n);this.userCode=`\n void main() {\n ${r} coords = getOutputCoords();\n setOutput(getX(${s}));\n }\n `}} +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class zL{constructor(e,t){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;const n=e.length;if(n>4)throw new Error(`WebGL backend: Reverse of rank-${n} tensor is not yet supported`);this.outputShape=e;const s=HA("rc",n),r=`${s[n-1]} + 1 < ${this.outputShape[n-1]}`,a=`${s[n-2]} + 1 < ${this.outputShape[n-2]}`,i=CR(n);function o(n){const s=e.map(((s,r)=>function(n,s){return-1!==t.indexOf(n)&&1!==e[n]?`${e[n]} - ${s[n]} - 1`:`${s[n]}`}(r,n)));return`getChannel(getX(${s.join(",")}), vec2(${s.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(${r}){\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)}(s.slice())};\n if(${r}){\n result.g = ${function(e){return e[n-1]="("+e[n-1]+" + 1)",o(e)}(s.slice())};\n }\n if(${a}) {\n result.b = ${function(e){return e[n-2]="("+e[n-2]+" + 1)",o(e)}(s.slice())};\n if(${r}) {\n result.a = ${function(e){return e[n-1]="("+e[n-1]+" + 1)",e[n-2]="("+e[n-2]+" + 1)",o(e)}(s.slice())};\n }\n }\n setOutput(result);\n }\n `}}const PL={kernelName:Ln,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{dims:a}=s,i=r.shape.length,o=j(a,r.shape);if(0===i)return fF({inputs:{x:r},backend:n});const l=ye().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new zL(r.shape,o):new LL(r.shape,o);return n.runWebGLProgram(l,[r],r.dtype)}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class BL{constructor(e,t){this.variableNames=["Image"],this.outputShape=[],this.customUniforms=[{name:"params",type:"vec4"}];const n=e[1],s=e[2];this.outputShape=e;let r="";r="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 ${r}\n if(coordX >= 0 && coordX < ${s} && coordY >= 0 && coordY < ${n}) {\n outputValue = getImage(coords[0], coordY, coordX, coords[3]);\n }\n setOutput(outputValue);\n }\n `}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +const WL={kernelName:Ss,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{image:s}=e,{radians:r,fillValue:a,center:i}=t,o=n,l=new BL(s.shape,a),[u,c]=Xp(i,s.shape[1],s.shape[2]),h=[[u,c,Math.sin(r),Math.cos(r)]];return o.runWebGLProgram(l,[s],s.dtype,h)}},VL=SF({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"}),UL={kernelName:zn,backendName:"webgl",kernelFunc:VL},GL=SF({opSnippet:"return inversesqrt(x);",cpuKernelImpl:TA}),HL={kernelName:Pn,backendName:"webgl",kernelFunc:GL}; +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class jL{constructor(e,t,n,s,r,a,i=!0){this.variableNames=["updates","indices","defaultValue"],this.outputShape=a;const o=CR(r.length),l=CR(a.length);let u="";1===n?u="i":2===n&&(u="i, j");const c=`getIndices(${u})`;let h="";1===s?h="i":2===s&&(h="i, coords[1]");const p=`getUpdates(${h})`,d=t>1?"strides[j]":"strides";this.userCode=`\n ${o} strides = ${o}(${r});\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 qL={kernelName:Bn,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{indices:r,updates:a}=t,{shape:i}=s,{sliceRank:o,numUpdates:l,sliceSize:u,strides:c,outputSize:h}=uh(0,r,i),p=[h/u,u];if(0===h)return n.makeTensorInfo(i,r.dtype);const d=OF({inputs:{x:r},backend:n,attrs:{shape:[l,o]}}),f=OF({inputs:{x:a},backend:n,attrs:{shape:[l,u]}}),m=n.makeTensorInfo([],"float32",new Float32Array([0])),g=new jL(l,o,d.shape.length,f.shape.length,c,p),y=n.runWebGLProgram(g,[f,d,m],f.dtype),b=OF({inputs:{x:y},backend:n,attrs:{shape:i}});return n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(y),n.disposeIntermediateTensorInfo(m),b}}; +/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class KL{constructor(e,t,n,s){this.variableNames=["sortedSequence","values"],this.customUniforms=[{name:"numInputs",type:"int"}],this.outputShape=[e,n];const r=`for (int i = 0; i < ${Math.ceil(Math.log2(t+1))}; ++i) { if (left >= right) break;`,a=2===ye().getNumber("WEBGL_VERSION")?"while (left < right) {":r,i="left"===s?"<":"<=";this.userCode=`\n int findBound(int batch, float value) {\n int left = 0;\n int right = numInputs;\n int mid;\n ${a}\n mid = (left + right) / 2;\n if (getSortedSequence(batch, mid) ${i} value) {\n left = mid + 1;\n } else {\n right = mid;\n }\n }\n return right;\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int valueIndex = coords[1];\n\n float value = getValues(batch, valueIndex);\n\n setOutput(float(findBound(batch, value)));\n }\n `}}const XL={kernelName:Wn,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{sortedSequence:r,values:a}=t,{side:i}=s,o=new KL(r.shape[0],r.shape[1],a.shape[1],i),l=[[r.shape[1]]];return n.runWebGLProgram(o,[r,a],"int32",l)}}; +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class YL{constructor(e,t,n){let s,r;if(this.variableNames=["c","a","b"],this.outputShape=t,n>4)throw Error(`Where for rank ${n} is not yet supported`);if(1===n)r="resRC",s="resRC";else{const n=["resRC.x","resRC.y","resRC.z","resRC.w"],a=[],i=[];for(let s=0;s= 1.0) {\n setOutput(getA(${r}));\n } else {\n setOutput(getB(${r}));\n }\n }\n `}}const ZL={kernelName:Vn,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n}=e,{condition:s,t:r,e:a}=t,i=new YL(s.shape.length,r.shape,r.shape.length);return n.runWebGLProgram(i,[s,r,a],Sr(r.dtype,a.dtype))}},JL=SF({opSnippet:`\n // Stable and Attracting Fixed Point (0, 1) for Normalized Weights.\n // see: https://arxiv.org/abs/1706.02515\n float scaleAlpha = ${nd};\n float scale = ${sd};\n return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);\n`}),QL={kernelName:Un,backendName:"webgl",kernelFunc:JL},ez=SF({opSnippet:NF+"\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:$A}),tz={kernelName:Kn,backendName:"webgl",kernelFunc:ez},nz=SF({opSnippet:"\n if (isnan(x)) { return 0.0; }\n return sign(x);\n"}),sz={kernelName:qn,backendName:"webgl",kernelFunc:nz},rz=SF({opSnippet:NF+"\n return sin(x);\n"}),az={kernelName:Hn,backendName:"webgl",kernelFunc:rz},iz=SF({opSnippet:"\n float e2x = exp(x);\n return (e2x - 1.0 / e2x) / 2.0;\n"}),oz={kernelName:jn,backendName:"webgl",kernelFunc:iz},lz=SF({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"}),uz={kernelName:Xn,backendName:"webgl",kernelFunc:lz},cz={kernelName:Jn,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{blockShape:a,paddings:i}=s;O(r.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}};const hz={kernelName:ts,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n}=e,{indices:s,values:r,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!==s.shape.length)throw new Error(`Indices must be a matrix, saw:\n ${s.shape}`);if(1!==r.shape.length)throw new Error(`Values must be a vector, saw:\n ${r.shape}`);if(0!==i.shape.length)throw new Error(`Default value must be a scalar, saw:\n ${i.shape}`);const o=n.readSync(s.dataId),l=n.readSync(r.dataId),u=n.readSync(a.dataId),c=n.readSync(i.dataId)[0],[h,p,d,f,m]=AA(o,s.shape,s.dtype,l,r.dtype,u,c);return[n.makeTensorInfo(p,s.dtype,h),n.makeTensorInfo([p[0]],r.dtype,d),n.makeTensorInfo([f.length],"bool",new Uint8Array(f.map((e=>Number(e))))),n.makeTensorInfo([m.length],s.dtype,new Int32Array(m))]}};const pz={kernelName:ns,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n}=e,{inputIndices:s,inputShape:r,newShape:a}=t;if(2!==s.shape.length)throw new Error(`Input indices should be a matrix but received shape ${s.shape}`);if(1!==r.shape.length)throw new Error(`Input shape should be a vector but received shape ${r.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(r.dataId)),o=n.readSync(s.dataId),l=Array.from(n.readSync(a.dataId)),[u,c,h]=FA(o,s.shape,s.dtype,i,l);return[n.makeTensorInfo(c,s.dtype,u),n.makeTensorInfo([h.length],a.dtype,new Int32Array(h))]}};const dz={kernelName:ss,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n}=e,{data:s,indices:r,segmentIds:a}=t;if(s.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(1!==r.shape.length)throw new Error(`Indices should be a vector but received shape\n ${r.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(s.dataId),o=n.readSync(r.dataId),l=n.readSync(a.dataId),[u,c]=_A(i,s.shape,s.dtype,o,l,!0);return n.makeTensorInfo(c,s.dtype,u)}};const fz={kernelName:rs,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n}=e,{data:s,indices:r,segmentIds:a}=t;if(s.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(1!==r.shape.length)throw new Error(`Indices should be a vector but received shape\n ${r.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(s.dataId),o=n.readSync(r.dataId),l=n.readSync(a.dataId),[u,c]=_A(i,s.shape,s.dtype,o,l);return n.makeTensorInfo(c,s.dtype,u)}};const mz={kernelName:as,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{sparseIndices:r,sparseValues:a,defaultValue:i}=t,{outputShape:o}=s,{sliceRank:l,numUpdates:u,sliceSize:c,strides:h,outputSize:p}=uh(0,r,o),d=!1;if("string"===a.dtype){const e=n.bufferSync(r),t=n.bufferSync(a),s=sr(n.readSync(i.dataId)[0]),f=CA(e,t,o,p,c,u,l,h,s,d);return n.makeTensorInfo(o,f.dtype,f.values)}const f=new jL(u,l,r.shape.length,a.shape.length,h,[p,1],d),m=n.runWebGLProgram(f,[a,r,i],a.dtype),g=OF({inputs:{x:m},backend:n,attrs:{shape:o}});return n.disposeIntermediateTensorInfo(m),g}};const gz={kernelName:Qn,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{numOrSizeSplits:a,axis:i}=s,o=j(i,r.shape)[0],l=$d(r,a,o),u=r.shape.length,c=new Array(u).fill(0),h=r.shape.slice();return l.map((e=>{const t=[...h];t[o]=e;const s=W_({inputs:{x:r},backend:n,attrs:{begin:c,size:t}});return c[o]+=e,s}))}},yz="return sqrt(x);",bz=SF({opSnippet:yz,packedOpSnippet:yz,cpuKernelImpl:DA}),xz={kernelName:Yn,backendName:"webgl",kernelFunc:bz},wz={kernelName:os,backendName:"webgl",kernelFunc:SF({opSnippet:"return x * x;"})},vz="return (a - b) * (a - b);",kz=TF({opSnippet:vz,packedOpSnippet:vz}),Iz={kernelName:is,backendName:"webgl",kernelFunc:kz};const Nz={kernelName:Is,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function({inputs:e,attrs:t,backend:n}){const{x:s}=e,r=QA+`\n return x > 0.0 ? 1.0 : float(${t.alpha});\n `,a=new JA(s.shape,r);return n.runWebGLProgram(a,[s],s.dtype)}}; +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class Sz{constructor(e,t,n){this.variableNames=["x"],this.outputShape=n;const s=n.length,r=CR(n.length),a=CR(n.length);let i="";if(1===s)i="coords * strides + begin";else{let e=0;i=n.map(((t,s)=>(e++,1===n.length?`coords * strides[${s}] + begin[${s}]`:`coords[${e-1}] * strides[${s}] + begin[${s}]`))).join(",")}this.userCode=`\n ${r} begin = ${r}(${e});\n ${r} strides = ${r}(${t});\n\n void main() {\n ${a} coords = getOutputCoords();\n setOutput(getX(${i}));\n }\n `}}const Tz={kernelName:ls,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{begin:a,end:i,strides:o,beginMask:l,endMask:u,ellipsisMask:c,newAxisMask:h,shrinkAxisMask:p}=s,{finalShapeSparse:d,finalShape:f,isIdentity:m,sliceDim0:g,isSimpleSlice:y,begin:b,end:x,strides:w}=Gi(r.shape,a,i,o,l,u,c,h,p);let v;if(m)v=OF({inputs:{x:r},backend:n,attrs:{shape:f}});else if(g||y){O(r.shape.length>=1,(()=>`Input must have rank at least 1, got: ${r.shape.length}`));const e=Ai(b,x,w),t=W_({inputs:{x:r},backend:n,attrs:{begin:b,size:e}});v=OF({inputs:{x:t},backend:n,attrs:{shape:f}}),n.disposeIntermediateTensorInfo(t)}else{if(n.shouldExecuteOnCPU([r])){const e=n.readSync(r.dataId),t=Ya(r.shape,r.dtype,e),s=OA(d,t,w,b);v=n.makeTensorInfo(f,r.dtype,s.values)}else{const e=new Sz(b,w,d);v=n.runWebGLProgram(e,[r],r.dtype)}}const k=OF({inputs:{x:v},backend:n,attrs:{shape:f}});return n.disposeIntermediateTensorInfo(v),k}};const Cz={kernelName:us,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{separator:r,nGramWidths:a,leftPad:i,rightPad:o,padWidth:l,preserveShortSequences:u}=s,{data:c,dataSplits:h}=t,p=n.readSync(c.dataId),d=n.readSync(h.dataId),[f,m]=MA(p,d,r,a,i,o,l,u);return[n.makeTensorInfo([f.length],"string",f),n.makeTensorInfo(h.shape,"int32",m)]}};const $z={kernelName:cs,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{skipEmpty:r}=s,{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]=LA(o,l,r),p=c.length;return[n.makeTensorInfo([p,2],"int32",u),n.makeTensorInfo([p],"string",c),n.makeTensorInfo([2],"int32",new Int32Array(h))]}};const Ez={kernelName:hs,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{numBuckets:r}=s,{input:a}=t;if("string"!==a.dtype)throw new Error("Input must be of datatype string");if(r<=0)throw new Error("Number of buckets must be at least 1");const i=n.readSync(a.dataId),o=zA(i,r);return n.makeTensorInfo(a.shape,"int32",o)}},Rz=SF({opSnippet:"return tan(x);"}),Az={kernelName:ds,backendName:"webgl",kernelFunc:Rz},Fz=SF({opSnippet:"\n float e2x = exp(-2.0 * abs(x));\n return sign(x) * (1.0 - e2x) / (1.0 + e2x);\n"}),_z={kernelName:fs,backendName:"webgl",kernelFunc:Fz}; +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class Dz{constructor(e,t){this.variableNames=["A"];const n=new Array(e.length);for(let s=0;s5)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"],s=[];for(let t=0;t5){const e=n.readSync(r.dataId),t="string"===r.dtype?e.map((e=>sr(e))):e,s=Ya(r.shape,r.dtype,t),i=BA(s,a);return n.makeTensorInfo(i.shape,i.dtype,i.values)}const i=new Dz(r.shape,a);return n.runWebGLProgram(i,[r],r.dtype)}const Mz={kernelName:ms,backendName:"webgl",kernelFunc:Oz};class Lz{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 zz{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 "}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function Pz(e,t){null!==t&&e.disposeIntermediateTensorInfo(t)}function Bz(e){let t=1;for(;tl){const e=n.readSync(r.dataId),[t,s]=WA(e,u,r.dtype,a,i);return[n.makeTensorInfo(t.shape,t.dtype,t.values),n.makeTensorInfo(s.shape,s.dtype,s.values)]}if(0===a)return u[u.length-1]=0,[n.makeTensorInfo(u,r.dtype,[]),n.makeTensorInfo(u,"int32",[])];if(1===c)return[r,IO({attrs:{shape:u,dtype:"int32",value:0},backend:n})];const h=n.texData.get(r.dataId),p=null!==h&&h.isPacked,d=p?n.unpackTensor(r):r,f=P(u)/c,m=OF({inputs:{x:d},attrs:{shape:[f,c]},backend:n});p&&Pz(n,d);const g=Bz(a),y=Bz(c);let b=null;const x=()=>null===b?[m,m]:[m,b],w=(e,t,s)=>{const r=x(),a=new Lz(s),i=[[c],[null===b?1:0],[Number.NEGATIVE_INFINITY],[e],[t]],o=b;b=n.runWebGLProgram(a,r,"int32",i),Pz(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(),s=new zz([f,e/2]),r=[[c],[null===b?1:0],[g]],a=b;b=n.runWebGLProgram(s,t,"int32",r),Pz(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=W_({inputs:{x:b},backend:n,attrs:{begin:0,size:[f,a]}}),Pz(n,v);let k=VO({inputs:{x:m,indices:b},backend:n,attrs:{axis:1,batchDims:1}});Pz(n,m);const I=u.slice(0,-1);I.push(a),v=b,b=OF({inputs:{x:b},attrs:{shape:I},backend:n}),Pz(n,v);const N=k;return k=OF({inputs:{x:k},attrs:{shape:I},backend:n}),Pz(n,N),[k,b]}}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class Vz{constructor(e,t,n,s,r,a){this.variableNames=["Image","Transforms"],this.outputShape=a;const i="nearest"===n?1:2;let o;switch(s){case"constant":default:o=1;break;case"reflect":o=2;break;case"wrap":o=3;break;case"nearest":o=4}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(${r});\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(${r});\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 Uz={kernelName:ys,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{image:r,transforms:a}=t,{interpolation:i,fillMode:o,fillValue:l,outputShape:u}=s,[c,h,p,d]=r.shape,[f,m]=null!=u?u:[h,p],g=new Vz(h,p,i,o,l,[c,f,m,d]);return n.runWebGLProgram(g,[r,a],"float32")}};const Gz={kernelName:xs,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,attrs:n,backend:s}=e,{axis:r}=n,{x:a}=t;lR(a,"unique"),console.warn("WARNING: ","UI might be locked temporarily as data is being downloaded");const i=s.readSync(a.dataId),{outputValues:o,outputShape:l,indices:u}=UA(i,r,a.shape,a.dtype);return[s.makeTensorInfo(l,a.dtype,o),s.makeTensorInfo([u.length],"int32",u)]}};const Hz={kernelName:ws,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{value:r}=t;let{axis:a}=s;a<0&&(a+=r.shape.length);const i=r,o=i.shape.length,l=r.shape[a],u=new Array(o-1);let c=0;for(let e=0;en.disposeIntermediateTensorInfo(e))),f}}; +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class jz{constructor(e,t){this.variableNames=["x","segmentIds"];const n=e.windowSize,s=e.batchSize,r=e.inSize,a=e.numSegments,i=a*Math.ceil(r/n);this.outputShape=[s,i];const o=4*Math.floor(n/4),l=n%4,u="\n sumValue += dot(values, segFilter);\n ";let c="";r%n>0&&(c=`\n if (inIdx < 0 || inIdx >= ${r}) {\n return initializationValue;\n }\n `);let h="";r%n>0&&(h=`\n if (inIdx < 0 || inIdx >= ${r}) {\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 qz={kernelName:vs,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,segmentIds:a}=t,{numSegments:i}=s,o=r.shape.length,l=[];let u=0;const c=Ol([u],o);let h=r;null!=c&&(h=HF({inputs:{x:r},backend:n,attrs:{perm:c}}),l.push(h),u=Ll(1,o)[0]);const p=Vd(h.shape,u,i),d=P([h.shape[u]]),f=OF({inputs:{x:h},backend:n,attrs:{shape:[-1,d]}});l.push(f);const m=Tr(r.dtype),g=(e,t,s,r,a)=>{const i=e.shape[0],o=e.shape[1],u=Wd(o,a),c=new jz({windowSize:u,inSize:o,batchSize:i,numSegments:a},t),h=n.compileAndRun(c,[e,s],r);if(l.push(h),h.shape[1]===a)return h;const p=xL({backend:n,attrs:{start:0,stop:a,step:1,dtype:"float32"}}),d=Oz({inputs:{x:p},backend:n,attrs:{reps:[o/u]}});l.push(p),l.push(d);return g(h,t,d,r,a)},y=OF({inputs:{x:g(f,"unsortedSegmentSum",a,m,i)},backend:n,attrs:{shape:p}});let b=y;if(null!=c){l.push(y);const e=Ml(c);b=HF({inputs:{x:b},backend:n,attrs:{perm:e}})}return l.forEach((e=>n.disposeIntermediateTensorInfo(e))),b}},Kz=[KF,YF,JF,e_,s_,i_,o_,l_,f_,m_,y_,x_,v_,I_,S_,$_,E_,F_,__,D_,L_,U_,G_,H_,Y_,Q_,nD,yF,aD,dD,vD,TD,CD,$D,ED,RD,FD,DD,MD,VD,UD,GD,jD,XD,JD,QD,tO,sO,rO,iO,oO,uO,hO,dO,mO,bO,vO,NO,TO,EO,AO,DO,LO,zO,BO,UO,HO,qO,mF,KO,cD,YO,JO,eM,wF,nM,rM,aM,oM,uM,hM,dM,mM,bM,wM,kM,NM,SM,TM,EM,RM,AM,FM,_M,OM,zM,BM,XM,DF,ZM,QM,tL,sL,q_,aL,lL,uL,dL,mL,IF,gL,yL,bL,wL,X_,UM,kL,NL,TL,MF,EL,AL,DL,ML,PL,WL,UL,HL,qL,XL,ZL,QL,tz,sz,az,oz,V_,KM,uz,cz,hz,pz,dz,fz,mz,gz,xz,wz,Iz,Nz,Tz,Cz,$z,Ez,jM,GF,Az,_z,Mz,Wz,Uz,jF,Gz,Hz,qz,oL];for(const e of Kz)Ms(e);n(312);const Xz={moveTickSize:50,videoContainerId:"webgazerVideoContainer",videoElementId:"webgazerVideoFeed",videoElementCanvasId:"webgazerVideoCanvas",faceOverlayId:"webgazerFaceOverlay",faceFeedbackBoxId:"webgazerFaceFeedbackBox",gazeDotId:"webgazerGazeDot",videoViewerWidth:320,videoViewerHeight:240,faceFeedbackBoxRatio:.66,showVideo:!0,mirrorVideo:!0,showFaceOverlay:!0,showFaceFeedbackBox:!0,showGazeDot:!0,camConstraints:{video:{width:{min:320,ideal:640,max:1920},height:{min:240,ideal:480,max:1080},facingMode:"user"}},dataTimestep:50,showVideoPreview:!0,applyKalmanFilter:!0,saveDataAcrossSessions:!0,storingPoints:!1,trackEye:"both"};n(190);var Yz=n(790),Zz=n.n(Yz),Jz=function(){return(Jz=Object.assign||function(e){for(var t,n=1,s=arguments.length;n0&&r[r.length-1])||6!==a[0]&&2!==a[0])){i=0;continue}if(3===a[0]&&(!r||a[1]>r[0]&&a[1]0&&r[r.length-1])&&(6===a[0]||2===a[0])){i=0;continue}if(3===a[0]&&(!r||a[1]>r[0]&&a[1]=468,o=wP[0],l=wP[1];!1===a&&(o=vP[0],l=vP[1]),r=function(e,t){var n;return(n=Math.PI/2-Math.atan2(-(t[1]-e[1]),t[0]-e[0]))-2*Math.PI*Math.floor((n+Math.PI)/(2*Math.PI))}(n.landmarks[o],n.landmarks[l]);var u=hP({startPoint:n.startPoint,endPoint:n.endPoint}),c=[u[0]/e.shape[2],u[1]/e.shape[1]],h=e,p=fP;0!==r&&(h=Np.rotateWithOffset(e,r,0,c),p=xP(-r,u));var d={startPoint:n.startPoint,endPoint:n.endPoint},f=vl(function(e,t,n){var s=t.shape[1],r=t.shape[2],a=[[e.startPoint[1]/s,e.startPoint[0]/r,e.endPoint[1]/s,e.endPoint[0]/r]];return Np.cropAndResize(t,a,[0],n,"bilinear",0)}(d,h,[i.meshHeight,i.meshWidth]),255),m=i.meshDetector.predict(f),g=m[1],y=m[2],b=_o(y,[-1,3]).arraySync();if(t){var x=i.getEyeBox(b,f,IP[0],IP[1],!0),w=x.box,v=x.boxSize,k=x.crop,I=i.getEyeBox(b,f,SP[0],SP[1]),N=I.box,S=I.boxSize,T=I.crop,C=i.irisModel.predict(Mo([k,T])).dataSync(),$=C.slice(0,228),E=i.getEyeCoords($,w,v,!0),R=E.rawCoords,A=E.iris,F=C.slice(228),_=i.getEyeCoords(F,N,S),D=_.rawCoords,O=_.iris,M=i.getLeftToRightEyeDepthDifference(b);Math.abs(M)<30?(CP(b,R,"left"),CP(b,D,"right")):M<1?CP(b,R,"left",["EyeUpper0","EyeLower0"]):CP(b,D,"right",["EyeUpper0","EyeLower0"]);var L=i.getAdjustedIrisCoords(b,A,"left"),z=i.getAdjustedIrisCoords(b,O,"right");b=b.concat(L).concat(z)}var P=i.transformRawCoords(b,n,r,p),B=Hc(P),W=pP(i.calculateLandmarksBoundingBox(P)),V=dP(W);return i.regionsOfInterest[s]=Jz({},V,{landmarks:B.arraySync()}),{coords:Hc(b,[b.length,3]),scaledCoords:B,box:W,flag:Pc(g)}}))}))]}}))}))},e.prototype.updateRegionsOfInterest=function(e){for(var t=0;t=this.maxContinuousChecks},e.prototype.calculateLandmarksBoundingBox=function(e){var t=e.map((function(e){return e[0]})),n=e.map((function(e){return e[1]}));return{startPoint:[Math.min.apply(Math,t),Math.min.apply(Math,n)],endPoint:[Math.max.apply(Math,t),Math.max.apply(Math,n)]}},e}(),EP=[[.499976992607117,.652534008026123],[.500025987625122,.547487020492554],[.499974012374878,.602371990680695],[.482113003730774,.471979022026062],[.500150978565216,.527155995368958],[.499909996986389,.498252987861633],[.499523013830185,.40106201171875],[.289712011814117,.380764007568359],[.499954998493195,.312398016452789],[.499987006187439,.269918978214264],[.500023007392883,.107050001621246],[.500023007392883,.666234016418457],[.5000159740448,.679224014282227],[.500023007392883,.692348003387451],[.499976992607117,.695277988910675],[.499976992607117,.70593398809433],[.499976992607117,.719385027885437],[.499976992607117,.737019002437592],[.499967992305756,.781370997428894],[.499816000461578,.562981009483337],[.473773002624512,.573909997940063],[.104906998574734,.254140973091125],[.365929991006851,.409575998783112],[.338757991790771,.41302502155304],[.311120003461838,.409460008144379],[.274657994508743,.389131009578705],[.393361985683441,.403706014156342],[.345234006643295,.344011008739471],[.370094001293182,.346076011657715],[.319321990013123,.347265005111694],[.297903001308441,.353591024875641],[.24779200553894,.410809993743896],[.396889001131058,.842755019664764],[.280097991228104,.375599980354309],[.106310002505779,.399955987930298],[.2099249958992,.391353011131287],[.355807989835739,.534406006336212],[.471751004457474,.65040397644043],[.474155008792877,.680191993713379],[.439785003662109,.657229006290436],[.414617002010345,.66654098033905],[.450374007225037,.680860996246338],[.428770989179611,.682690978050232],[.374971002340317,.727805018424988],[.486716985702515,.547628998756409],[.485300987958908,.527395009994507],[.257764995098114,.314490020275116],[.401223003864288,.455172002315521],[.429818987846375,.548614978790283],[.421351999044418,.533740997314453],[.276895999908447,.532056987285614],[.483370006084442,.499586999416351],[.33721199631691,.282882988452911],[.296391993761063,.293242990970612],[.169294998049736,.193813979625702],[.447580009698868,.302609980106354],[.392390012741089,.353887975215912],[.354490011930466,.696784019470215],[.067304998636246,.730105042457581],[.442739009857178,.572826027870178],[.457098007202148,.584792017936707],[.381974011659622,.694710969924927],[.392388999462128,.694203019142151],[.277076005935669,.271932005882263],[.422551989555359,.563233017921448],[.385919004678726,.281364023685455],[.383103013038635,.255840003490448],[.331431001424789,.119714021682739],[.229923993349075,.232002973556519],[.364500999450684,.189113974571228],[.229622006416321,.299540996551514],[.173287004232407,.278747975826263],[.472878992557526,.666198015213013],[.446828007698059,.668527007102966],[.422762006521225,.673889994621277],[.445307999849319,.580065965652466],[.388103008270264,.693961024284363],[.403039008378983,.706539988517761],[.403629004955292,.693953037261963],[.460041999816895,.557139039039612],[.431158006191254,.692366003990173],[.452181994915009,.692366003990173],[.475387006998062,.692366003990173],[.465828001499176,.779190003871918],[.472328990697861,.736225962638855],[.473087012767792,.717857003211975],[.473122000694275,.704625964164734],[.473033010959625,.695277988910675],[.427942007780075,.695277988910675],[.426479011774063,.703539967536926],[.423162013292313,.711845993995667],[.4183090031147,.720062971115112],[.390094995498657,.639572978019714],[.013953999616206,.560034036636353],[.499913990497589,.58014702796936],[.413199990987778,.69539999961853],[.409626007080078,.701822996139526],[.468080013990402,.601534962654114],[.422728985548019,.585985004901886],[.463079988956451,.593783974647522],[.37211999297142,.47341400384903],[.334562003612518,.496073007583618],[.411671012639999,.546965003013611],[.242175996303558,.14767599105835],[.290776997804642,.201445996761322],[.327338010072708,.256527006626129],[.399509996175766,.748921036720276],[.441727995872498,.261676013469696],[.429764986038208,.187834024429321],[.412198007106781,.108901023864746],[.288955003023148,.398952007293701],[.218936994671822,.435410976409912],[.41278201341629,.398970007896423],[.257135003805161,.355440020561218],[.427684992551804,.437960982322693],[.448339998722076,.536936044692993],[.178560003638268,.45755398273468],[.247308000922203,.457193970680237],[.286267012357712,.467674970626831],[.332827985286713,.460712015628815],[.368755996227264,.447206974029541],[.398963987827301,.432654976844788],[.476410001516342,.405806005001068],[.189241006970406,.523923993110657],[.228962004184723,.348950982093811],[.490725994110107,.562400996685028],[.404670000076294,.485132992267609],[.019469000399113,.401564002037048],[.426243007183075,.420431017875671],[.396993011236191,.548797011375427],[.266469985246658,.376977026462555],[.439121007919312,.51895797252655],[.032313998788595,.644356966018677],[.419054001569748,.387154996395111],[.462783008813858,.505746960639954],[.238978996872902,.779744982719421],[.198220998048782,.831938028335571],[.107550002634525,.540755033493042],[.183610007166862,.740257024765015],[.134409993886948,.333683013916016],[.385764002799988,.883153975009918],[.490967005491257,.579378008842468],[.382384985685349,.508572995662689],[.174399003386497,.397670984268188],[.318785011768341,.39623498916626],[.343364000320435,.400596976280212],[.396100014448166,.710216999053955],[.187885001301765,.588537991046906],[.430987000465393,.944064974784851],[.318993002176285,.898285031318665],[.266247987747192,.869701027870178],[.500023007392883,.190576016902924],[.499976992607117,.954452991485596],[.366169989109039,.398822009563446],[.393207013607025,.39553701877594],[.410373002290726,.391080021858215],[.194993004202843,.342101991176605],[.388664990663528,.362284004688263],[.365961998701096,.355970978736877],[.343364000320435,.355356991291046],[.318785011768341,.35834002494812],[.301414996385574,.363156020641327],[.058132998645306,.319076001644135],[.301414996385574,.387449026107788],[.499987989664078,.618434011936188],[.415838003158569,.624195992946625],[.445681989192963,.566076993942261],[.465844005346298,.620640993118286],[.49992299079895,.351523995399475],[.288718998432159,.819945991039276],[.335278987884521,.852819979190826],[.440512001514435,.902418971061707],[.128294005990028,.791940987110138],[.408771991729736,.373893976211548],[.455606997013092,.451801002025604],[.499877005815506,.908990025520325],[.375436991453171,.924192011356354],[.11421000212431,.615022003650665],[.448662012815475,.695277988910675],[.4480200111866,.704632043838501],[.447111994028091,.715808033943176],[.444831997156143,.730794012546539],[.430011987686157,.766808986663818],[.406787008047104,.685672998428345],[.400738000869751,.681069016456604],[.392399996519089,.677703022956848],[.367855995893478,.663918972015381],[.247923001646996,.601333022117615],[.452769994735718,.420849978923798],[.43639200925827,.359887003898621],[.416164010763168,.368713974952698],[.413385987281799,.692366003990173],[.228018000721931,.683571994304657],[.468268007040024,.352671027183533],[.411361992359161,.804327011108398],[.499989002943039,.469825029373169],[.479153990745544,.442654013633728],[.499974012374878,.439637005329132],[.432112008333206,.493588984012604],[.499886006116867,.866917014122009],[.49991300702095,.821729004383087],[.456548988819122,.819200992584229],[.344549000263214,.745438992977142],[.37890899181366,.574010014533997],[.374292999505997,.780184984207153],[.319687992334366,.570737957954407],[.357154995203018,.604269981384277],[.295284003019333,.621580958366394],[.447750002145767,.862477004528046],[.410986006259918,.508723020553589],[.31395098567009,.775308012962341],[.354128003120422,.812552988529205],[.324548006057739,.703992962837219],[.189096003770828,.646299958229065],[.279776990413666,.71465802192688],[.1338230073452,.682700991630554],[.336768001317978,.644733011722565],[.429883986711502,.466521978378296],[.455527991056442,.548622965812683],[.437114000320435,.558896005153656],[.467287987470627,.529924988746643],[.414712011814117,.335219979286194],[.37704598903656,.322777986526489],[.344107985496521,.320150971412659],[.312875986099243,.32233202457428],[.283526003360748,.333190023899078],[.241245999932289,.382785975933075],[.102986000478268,.468762993812561],[.267612010240555,.424560010433197],[.297879010438919,.433175981044769],[.333433985710144,.433878004550934],[.366427004337311,.426115989685059],[.396012008190155,.416696012020111],[.420121014118195,.41022801399231],[.007561000064015,.480777025222778],[.432949006557465,.569517970085144],[.458638995885849,.479089021682739],[.473466008901596,.545744001865387],[.476087987422943,.563830018043518],[.468472003936768,.555056989192963],[.433990985155106,.582361996173859],[.483518004417419,.562983989715576],[.482482999563217,.57784903049469],[.42645001411438,.389798998832703],[.438998997211456,.39649498462677],[.450067013502121,.400434017181396],[.289712011814117,.368252992630005],[.276670008897781,.363372981548309],[.517862021923065,.471948027610779],[.710287988185883,.380764007568359],[.526226997375488,.573909997940063],[.895093023777008,.254140973091125],[.634069979190826,.409575998783112],[.661242008209229,.41302502155304],[.688880026340485,.409460008144379],[.725341975688934,.389131009578705],[.606630027294159,.40370500087738],[.654766023159027,.344011008739471],[.629905998706818,.346076011657715],[.680678009986877,.347265005111694],[.702096998691559,.353591024875641],[.75221198797226,.410804986953735],[.602918028831482,.842862963676453],[.719901978969574,.375599980354309],[.893692970275879,.399959981441498],[.790081977844238,.391354024410248],[.643998026847839,.534487962722778],[.528249025344849,.65040397644043],[.525849997997284,.680191040039062],[.560214996337891,.657229006290436],[.585384011268616,.66654098033905],[.549625992774963,.680860996246338],[.57122802734375,.682691991329193],[.624852001667023,.72809898853302],[.513050019741058,.547281980514526],[.51509702205658,.527251958847046],[.742246985435486,.314507007598877],[.598631024360657,.454979002475739],[.570338010787964,.548575043678284],[.578631997108459,.533622980117798],[.723087012767792,.532054007053375],[.516445994377136,.499638974666595],[.662801027297974,.282917976379395],[.70362401008606,.293271005153656],[.830704987049103,.193813979625702],[.552385985851288,.302568018436432],[.607609987258911,.353887975215912],[.645429015159607,.696707010269165],[.932694971561432,.730105042457581],[.557260990142822,.572826027870178],[.542901992797852,.584792017936707],[.6180260181427,.694710969924927],[.607590973377228,.694203019142151],[.722943007946014,.271963000297546],[.577413976192474,.563166975975037],[.614082992076874,.281386971473694],[.616907000541687,.255886018276215],[.668509006500244,.119913995265961],[.770092010498047,.232020974159241],[.635536015033722,.189248979091644],[.77039098739624,.299556016921997],[.826722025871277,.278755009174347],[.527121007442474,.666198015213013],[.553171992301941,.668527007102966],[.577238023281097,.673889994621277],[.554691970348358,.580065965652466],[.611896991729736,.693961024284363],[.59696102142334,.706539988517761],[.596370995044708,.693953037261963],[.539958000183105,.557139039039612],[.568841993808746,.692366003990173],[.547818005084991,.692366003990173],[.52461302280426,.692366003990173],[.534089982509613,.779141008853912],[.527670979499817,.736225962638855],[.526912987232208,.717857003211975],[.526877999305725,.704625964164734],[.526966989040375,.695277988910675],[.572058022022247,.695277988910675],[.573521018028259,.703539967536926],[.57683801651001,.711845993995667],[.581691026687622,.720062971115112],[.609944999217987,.639909982681274],[.986046016216278,.560034036636353],[.5867999792099,.69539999961853],[.590372025966644,.701822996139526],[.531915009021759,.601536989212036],[.577268004417419,.585934996604919],[.536915004253387,.593786001205444],[.627542972564697,.473352015018463],[.665585994720459,.495950996875763],[.588353991508484,.546862006187439],[.757824003696442,.14767599105835],[.709249973297119,.201507985591888],[.672684013843536,.256581008434296],[.600408971309662,.74900496006012],[.55826598405838,.261672019958496],[.570303976535797,.187870979309082],[.588165998458862,.109044015407562],[.711045026779175,.398952007293701],[.781069993972778,.435405015945435],[.587247014045715,.398931980133057],[.742869973182678,.355445981025696],[.572156012058258,.437651991844177],[.55186802148819,.536570012569427],[.821442008018494,.457556009292603],[.752701997756958,.457181990146637],[.71375697851181,.467626988887787],[.66711300611496,.460672974586487],[.631101012229919,.447153985500336],[.6008620262146,.432473003864288],[.523481011390686,.405627012252808],[.810747981071472,.523926019668579],[.771045982837677,.348959028720856],[.509127020835876,.562718033790588],[.595292985439301,.485023975372314],[.980530977249146,.401564002037048],[.573499977588654,.420000016689301],[.602994978427887,.548687994480133],[.733529984951019,.376977026462555],[.560611009597778,.519016981124878],[.967685997486115,.644356966018677],[.580985009670258,.387160003185272],[.537728011608124,.505385041236877],[.760966002941132,.779752969741821],[.801778972148895,.831938028335571],[.892440974712372,.54076099395752],[.816350996494293,.740260004997253],[.865594983100891,.333687007427216],[.614073991775513,.883246004581451],[.508952975273132,.579437971115112],[.617941975593567,.508316040039062],[.825608015060425,.397674977779388],[.681214988231659,.39623498916626],[.656635999679565,.400596976280212],[.603900015354156,.710216999053955],[.81208598613739,.588539004325867],[.56801301240921,.944564998149872],[.681007981300354,.898285031318665],[.733752012252808,.869701027870178],[.633830010890961,.398822009563446],[.606792986392975,.39553701877594],[.589659988880157,.391062021255493],[.805015981197357,.342108011245728],[.611334979534149,.362284004688263],[.634037971496582,.355970978736877],[.656635999679565,.355356991291046],[.681214988231659,.35834002494812],[.698584973812103,.363156020641327],[.941866993904114,.319076001644135],[.698584973812103,.387449026107788],[.584177017211914,.624107003211975],[.554318010807037,.566076993942261],[.534153997898102,.62064003944397],[.711217999458313,.819975018501282],[.664629995822906,.852871000766754],[.559099972248077,.902631998062134],[.871706008911133,.791940987110138],[.591234028339386,.373893976211548],[.544341027736664,.451583981513977],[.624562978744507,.924192011356354],[.88577002286911,.615028977394104],[.551338016986847,.695277988910675],[.551980018615723,.704632043838501],[.552887976169586,.715808033943176],[.555167973041534,.730794012546539],[.569944024085999,.767035007476807],[.593203008174896,.685675978660583],[.599261999130249,.681069016456604],[.607599973678589,.677703022956848],[.631937980651855,.663500010967255],[.752032995223999,.601315021514893],[.547226011753082,.420395016670227],[.563543975353241,.359827995300293],[.583841025829315,.368713974952698],[.586614012718201,.692366003990173],[.771915018558502,.683578014373779],[.531597018241882,.352482974529266],[.588370978832245,.804440975189209],[.52079701423645,.442565023899078],[.567984998226166,.493479013442993],[.543282985687256,.819254994392395],[.655317008495331,.745514988899231],[.621008992195129,.574018001556396],[.625559985637665,.78031200170517],[.680198013782501,.570719003677368],[.64276397228241,.604337990283966],[.704662978649139,.621529996395111],[.552012026309967,.862591981887817],[.589071989059448,.508637011051178],[.685944974422455,.775357007980347],[.645735025405884,.812640011310577],[.675342977046967,.703978002071381],[.810858011245728,.646304965019226],[.72012197971344,.714666962623596],[.866151988506317,.682704985141754],[.663187026977539,.644596993923187],[.570082008838654,.466325998306274],[.544561982154846,.548375964164734],[.562758982181549,.558784961700439],[.531987011432648,.530140042304993],[.585271000862122,.335177004337311],[.622952997684479,.32277899980545],[.655896008014679,.320163011550903],[.687132000923157,.322345972061157],[.716481983661652,.333200991153717],[.758756995201111,.382786989212036],[.897013008594513,.468769013881683],[.732392013072968,.424547016620636],[.70211398601532,.433162987232208],[.66652500629425,.433866024017334],[.633504986763,.426087975502014],[.603875994682312,.416586995124817],[.579657971858978,.409945011138916],[.992439985275269,.480777025222778],[.567192018032074,.569419980049133],[.54136598110199,.478899002075195],[.526564002037048,.546118021011353],[.523913025856018,.563830018043518],[.531529009342194,.555056989192963],[.566035985946655,.582329034805298],[.51631098985672,.563053965568542],[.5174720287323,.577877044677734],[.573594987392426,.389806985855103],[.560697972774506,.395331978797913],[.549755990505219,.399751007556915],[.710287988185883,.368252992630005],[.723330020904541,.363372981548309]];function RP(e){return Qz(this,void 0,void 0,(function(){var t,n,s,r,a,i,o,l,u,c,h,p,d,f,m,g;return eP(this,(function(y){switch(y.label){case 0:return t=e.maxContinuousChecks,n=void 0===t?5:t,s=e.detectionConfidence,r=void 0===s?.9:s,a=e.maxFaces,i=void 0===a?10:a,o=e.iouThreshold,l=void 0===o?.3:o,u=e.scoreThreshold,c=void 0===u?.75:u,h=e.shouldLoadIrisModel,p=void 0===h||h,d=e.modelUrl,f=e.detectorModelUrl,m=e.irisModelUrl,p?[4,Promise.all([AP(f,i,l,c),FP(d),_P(m)])]:[3,2];case 1:return g=y.sent(),[3,4];case 2:return[4,Promise.all([AP(f,i,l,c),FP(d)])];case 3:g=y.sent(),y.label=4;case 4:return[2,new MP(g[0],g[1],n,r,i,p?g[2]:null)]}}))}))}function AP(e,t,n,s){return Qz(this,void 0,void 0,(function(){return eP(this,(function(r){return[2,lP({modelUrl:e,maxFaces:t,iouThreshold:n,scoreThreshold:s})]}))}))}function FP(e){return Qz(this,void 0,void 0,(function(){return eP(this,(function(t){return null!=e?[2,Ck(e)]:[2,Ck("https://tfhub.dev/mediapipe/tfjs-model/facemesh/1/default/1",{fromTFHub:!0})]}))}))}function _P(e){return Qz(this,void 0,void 0,(function(){return eP(this,(function(t){return null!=e?[2,Ck(e)]:[2,Ck("https://tfhub.dev/mediapipe/tfjs-model/iris/1/default/2",{fromTFHub:!0})]}))}))}function DP(e,t){if(e.mesh instanceof gr){var n=Zi((function(){var n=Gc([t-1,0,0]),s=Gc([1,-1,1]);return Zi((function(){return[Mo([gu(t-1,Bo(e.boundingBox.topLeft,0,1)),Bo(e.boundingBox.topLeft,1,1)]),Mo([gu(t-1,Bo(e.boundingBox.bottomRight,0,1)),Bo(e.boundingBox.bottomRight,1,1)]),zo(gu(n,e.mesh),s),zo(gu(n,e.scaledMesh),s)]}))})),s=n[0],r=n[1],a=n[2],i=n[3];return Object.assign({},e,{boundingBox:{topLeft:s,bottomRight:r},mesh:a,scaledMesh:i})}return Object.assign({},e,{boundingBox:{topLeft:[t-1-e.boundingBox.topLeft[0],e.boundingBox.topLeft[1]],bottomRight:[t-1-e.boundingBox.bottomRight[0],e.boundingBox.bottomRight[1]]},mesh:e.mesh.map((function(e){var n=e.slice(0);return n[0]=t-1-e[0],n})),scaledMesh:e.scaledMesh.map((function(e){var n=e.slice(0);return n[0]=t-1-e[0],n}))})}var OP,MP=function(){function e(e,t,n,s,r,a){this.kind="MediaPipeFaceMesh",this.pipeline=new $P(e,t,192,192,n,r,a),this.detectionConfidence=s}return e.getAnnotations=function(){return uP},e.getUVCoords=function(){return EP},e.prototype.estimateFaces=function(e){return Qz(this,void 0,void 0,(function(){var t,n,s,r,a,i,o,l,u,c,h,p,d=this;return eP(this,(function(f){switch(f.label){case 0:if(t=e.returnTensors,n=void 0!==t&&t,s=e.flipHorizontal,r=void 0!==s&&s,a=e.predictIrises,i=void 0===a||a,o=e.input,i&&null==this.pipeline.irisModel)throw new Error("The iris model was not loaded as part of facemesh. Please initialize the model with facemesh.load({shouldLoadIrisModel: true}).");return l=function(e){return e instanceof gr?[e.shape[0],e.shape[1]]:[e.height,e.width]}(o),u=l[1],c=Zi((function(){return o instanceof gr||(o=Ti(o)),Kl(Za(o,"float32"),0)})),"webgl"!==Or.backendName?[3,2]:(p=ye().get("WEBGL_PACK_DEPTHWISECONV"),ye().set("WEBGL_PACK_DEPTHWISECONV",!0),[4,this.pipeline.predict(c,i)]);case 1:return h=f.sent(),ye().set("WEBGL_PACK_DEPTHWISECONV",p),[3,4];case 2:return[4,this.pipeline.predict(c,i)];case 3:h=f.sent(),f.label=4;case 4:return c.dispose(),null!=h&&h.length>0?[2,Promise.all(h.map((function(e,t){return Qz(d,void 0,void 0,(function(){var s,a,o,l,c,h,p,d,f,m,g,y,b,x,w=this;return eP(this,(function(v){switch(v.label){case 0:return s=e.coords,a=e.scaledCoords,o=e.box,l=e.flag,c=[l],n||(c=c.concat([s,a])),[4,Promise.all(c.map((function(e){return Qz(w,void 0,void 0,(function(){return eP(this,(function(t){return[2,e.array()]}))}))})))];case 1:if(h=v.sent(),p=h[0],l.dispose(),p{const n={x:Math.round(Math.min(...e.map((e=>e[0])))),y:Math.round(Math.min(...e.map((e=>e[1]))))},s=Math.round(Math.max(...t.map((e=>e[0])))),r=Math.round(Math.max(...t.map((e=>e[1]))));return{origin:n,width:s-n.x,height:r-n.y}}));var c=l.origin.x,h=l.origin.y,p=l.width,d=l.height,f=u.origin.x,m=u.origin.y,g=u.width,y=u.height;if(0===p||0===g)return console.log("an eye patch had zero width"),null;if(0===d||0===y)return console.log("an eye patch had zero height"),null;var b={},x=t.getContext("2d",{willReadFrequently:!0}).getImageData(c,h,p,d);b.left={patch:x,imagex:c,imagey:h,width:p,height:d};var w=t.getContext("2d",{willReadFrequently:!0}).getImageData(f,m,g,y);return b.right={patch:w,imagex:f,imagey:m,width:g,height:y},this.predictionReady=!0,b},LP.prototype.getPositions=function(){return this.positionsArray},LP.prototype.reset=function(){console.log("Unimplemented; Tracking.js has no obvious reset function")},LP.prototype.drawFaceOverlay=function(e,t){if(t){e.fillStyle="#32EEDB",e.strokeStyle="#32EEDB",e.lineWidth=.5;for(let n=0;nPP(e,t,((e,t)=>e+t)),sub:(e,t)=>PP(e,t,((e,t)=>e-t)),inv:e=>BP.solve(e,BP.identity(e.length,e[0].length)),identity(e,t=e){const n=new Array(e);for(let s=0;se.length===e[0].length?BP.LUDecomposition(e,t):BP.QRDecomposition(e,t),LUDecomposition(e,t){for(var n=new Array(e.length),s=0;sMath.abs(c[f])&&(f=s);if(f!=r){for(d=0;d=0;d--){for(r=0;r=0;u--){for(r=0;r{let t=this.resizeEye(e,10,6),n=this.grayscale(t.data,t.width,t.height),s=[];return this.equalizeHistogram(n,5,s),s};return"left"==Xz.trackEye?t(e.left):"right"==Xz.trackEye?t(e.right):[].concat(t(e.left),t(e.right))},VP.DataWindow=function(e,t){this.data=[],this.windowSize=e,this.index=0,this.length=0,t&&(this.data=t.slice(t.length-e,t.length),this.length=this.data.length)},VP.DataWindow.prototype.push=function(e){return this.data.length>2),r=0,a=0,i=0;it?255:0;return e},VP.correlation=function(e,t){const n=Math.min(e.length,t.length);let s=0;for(let r=0;rt&&(e.x=t),e.y>n&&(e.y=n),e},VP.DebugBox=function(e){var t;this.para=document.createElement("p"),this.div=document.createElement("div"),this.div.appendChild(this.para),document.body.appendChild(this.div),this.buttons={},this.canvas={},this.stats={},t=this,setInterval((function(){!function(e,t){var n="";for(var s in t)n+=s+": "+t[s]+"\n";e.innerText=n}(t.para,t.stats)}),e||300)},VP.DebugBox.prototype.set=function(e,t){this.stats[e]=t},VP.DebugBox.prototype.inc=function(e,t,n){this.stats[e]||(this.stats[e]=n||0),this.stats[e]+=t||1},VP.DebugBox.prototype.addButton=function(e,t){this.buttons[e]||(this.buttons[e]=document.createElement("button"),this.div.appendChild(this.buttons[e]));var n=this.buttons[e];this.buttons[e]=n,n.addEventListener("click",t),n.innerText=e},VP.DebugBox.prototype.show=function(e,t){this.canvas[e]||(this.canvas[e]=document.createElement("canvas"),this.div.appendChild(this.canvas[e]));var n=this.canvas[e];n.getContext("2d").clearRect(0,0,n.width,n.height),t(n)};const UP=VP,GP={InitRegression:function(){var e=50;this.ridgeParameter=Math.pow(10,-5),this.errorXArray=new UP.DataWindow(e),this.errorYArray=new UP.DataWindow(e),this.screenXClicksArray=new UP.DataWindow(e),this.screenYClicksArray=new UP.DataWindow(e),this.eyeFeaturesClicks=new UP.DataWindow(e),this.trailTime=1e3,this.trailDataWindow=this.trailTime/Xz.moveTickSize,this.screenXTrailArray=new UP.DataWindow(10),this.screenYTrailArray=new UP.DataWindow(10),this.eyeFeaturesTrail=new UP.DataWindow(10),this.trailTimes=new UP.DataWindow(10),this.dataClicks=new UP.DataWindow(e),this.dataTrail=new UP.DataWindow(10);var t=[[1/4,0,.5,0],[0,1/4,0,.5],[.5,0,1,0],[0,.5,0,1]];t=WP.multScalar(t,.1);var n=WP.multScalar(WP.identity(2),47),s=WP.multScalar(WP.identity(4),1e-4);this.kalman=new GP.KalmanFilter([[1,0,1,0],[0,1,0,1],[0,0,1,0],[0,0,0,1]],[[1,0,0,0],[0,1,0,0]],t,n,s,[[500],[500],[0],[0]])},KalmanFilter:function(e,t,n,s,r,a){this.F=e,this.Q=n,this.H=t,this.R=s,this.P=r,this.X=a}};GP.KalmanFilter.prototype.update=function(e){for(var{add:t,sub:n,mult:s,inv:r,identity:a,transpose:i}=WP,o=s(this.F,this.X),l=t(s(s(this.F,this.P),i(this.F)),this.Q),u=n(e=i([e]),s(this.H,o)),c=t(s(s(this.H,l),i(this.H)),this.R),h=s(l,s(i(this.H),r(c))),p=0;p=0;n--){var s=this.screenXTrailArray.get(n),r=this.screenYTrailArray.get(n);if(Math.sqrt(Math.pow(s-e,2)+Math.pow(r-t,2))>72)return n+1}return n},GP.addData=function(e,t,n){e&&("click"===n?(this.screenXClicksArray.push([t[0]]),this.screenYClicksArray.push([t[1]]),this.eyeFeaturesClicks.push(UP.getEyeFeats(e)),this.dataClicks.push({eyes:e,screenPos:t,type:n})):"move"===n&&(this.screenXTrailArray.push([t[0]]),this.screenYTrailArray.push([t[1]]),this.eyeFeaturesTrail.push(UP.getEyeFeats(e)),this.trailTimes.push(performance.now()),this.dataTrail.push({eyes:e,screenPos:t,type:n})))};const HP=GP,jP={RidgeReg:function(){this.init()}};jP.RidgeReg.prototype.init=HP.InitRegression,jP.RidgeReg.prototype.addData=HP.addData,jP.RidgeReg.prototype.predict=function(e){if(!e||0===this.eyeFeaturesClicks.length)return null;for(var t=performance.now()-this.trailTime,n=[],s=[],r=[],a=0;at&&(n.push(this.screenXTrailArray.get(a)),s.push(this.screenYTrailArray.get(a)),r.push(this.eyeFeaturesTrail.get(a)));var i=this.screenXClicksArray.data.concat(n),o=this.screenYClicksArray.data.concat(s),l=this.eyeFeaturesClicks.data.concat(r),u=HP.ridge(i,l,this.ridgeParameter),c=HP.ridge(o,l,this.ridgeParameter),h=UP.getEyeFeats(e),p=0;for(a=0;at&&(n.push(this.screenXTrailArray.get(a)),s.push(this.screenYTrailArray.get(a)),r.push(this.eyeFeaturesTrail.get(a)));var i=this.eyeFeaturesClicks.data.length,o=Array(i),l=Array(i),u=Array(i);for(a=0;ar&&o+hB.left.widthr&&u+hB.right.widths&&l+hB.left.heights&&c+hB.right.height{nB.addEventListener("loadeddata",(function t(n){LB(nB.videoWidth,nB.videoHeight),QP.setVideoViewerSize(QP.params.videoViewerWidth,QP.params.videoViewerHeight),tB.appendChild(sB),tB.appendChild(rB),tB.appendChild(aB),document.body.appendChild(iB),n.target.removeEventListener(n.type,t),e()}))}));DB(),dB=!1,cB=performance.now(),await t,await RB()}function MB(e){navigator.vendor&&navigator.vendor.indexOf("Apple")>-1||navigator.userAgent&&navigator.userAgent.search("Firefox")>-1?(e.style.opacity=QP.params.showVideo?"1":"0",e.style.display="block"):e.style.display=QP.params.showVideo?"block":"none"}function LB(e,t){sB&&(sB.width=e,sB.height=t),rB&&(rB.width=e,rB.height=t)}QP.begin=function(e){return"https:"!==window.location.protocol&&"localhost"!==window.location.hostname&&window.chrome&&alert("WebGazer works only over https. If you are doing local development, you need to run a local server."),QP.params.saveDataAcrossSessions&&async function(){NB=(NB=await Zz().getItem(IB))||TB;var e=await Zz().getItem(kB);for(var t in SB=e=e||TB,xB)xB[t].setData(e);console.log("loaded stored data into regression model")}(),e=e||function(){console.log("No stream")},oB?(OB(oB),QP):(void 0===navigator.mediaDevices&&(navigator.mediaDevices={}),void 0===navigator.mediaDevices.getUserMedia&&(navigator.mediaDevices.getUserMedia=function(e){var t=navigator.webkitGetUserMedia||navigator.mozGetUserMedia;return t?new Promise((function(n,s){t.call(navigator,e,n,s)})):Promise.reject(new Error("Unfortunately, your browser does not support access to the webcam through the getUserMedia API. Try to use the latest version of Google Chrome, Mozilla Firefox, Opera, or Microsoft Edge instead."))}),new Promise((async(t,n)=>{let s;try{s=await navigator.mediaDevices.getUserMedia(QP.params.camConstraints),await OB(s),t(QP)}catch(t){e(),nB=null,s=null,n(t)}})))},QP.isReady=function(){return null!==sB&&sB.width>0},QP.pause=function(){return dB=!0,QP},QP.resume=async function(){return dB?(dB=!1,await RB(),QP):QP},QP.end=function(){return dB=!0,tB.remove(),iB.remove(),QP},QP.stopVideo=function(){return eB.getTracks()[0].stop(),tB.removeChild(rB),tB.removeChild(aB),QP},QP.detectCompatibility=function(){return void 0!==(navigator.mediaDevices.getUserMedia||navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia)},QP.showVideoPreview=function(e){return QP.params.showVideoPreview=e,QP.showVideo(e&&QP.params.showVideo),QP.showFaceOverlay(e&&QP.params.showFaceOverlay),QP.showFaceFeedbackBox(e&&QP.params.showFaceFeedbackBox),QP},QP.showVideo=function(e){return QP.params.showVideo=e,nB&&MB(nB),tB&&MB(tB),QP},QP.showFaceOverlay=function(e){return QP.params.showFaceOverlay=e,rB&&(rB.style.display=e?"block":"none"),QP},QP.showFaceFeedbackBox=function(e){return QP.params.showFaceFeedbackBox=e,aB&&(aB.style.display=e?"block":"none"),QP},QP.showPredictionPoints=function(e){return QP.params.showGazeDot=e,iB&&(iB.style.display=e?"block":"none"),QP},QP.saveDataAcrossSessions=function(e){return QP.params.saveDataAcrossSessions=e,QP},QP.applyKalmanFilter=function(e){return QP.params.applyKalmanFilter=e,QP},QP.setCameraConstraints=async function(e){var t,n;if(QP.params.camConstraints=e,eB){QP.pause(),t=eB.getVideoTracks()[0];try{await t.applyConstraints(QP.params.camConstraints),LB((n=t.getSettings()).width,n.height)}catch(e){return void console.log(e)}QP.setVideoViewerSize(QP.params.videoViewerWidth,QP.params.videoViewerHeight),QP.getTracker().reset(),await QP.resume()}},QP.setStaticVideo=function(e){return oB=e,QP},QP.setVideoViewerSize=function(e,t){QP.params.videoViewerWidth=e,QP.params.videoViewerHeight=t,nB.style.width=e+"px",nB.style.height=t+"px",tB.style.width=e+"px",tB.style.height=t+"px",rB.style.width=e+"px",rB.style.height=t+"px";var n=QP.computeValidationBoxSize();aB.style.top=n[0]+"px",aB.style.left=n[1]+"px",aB.style.width=n[2]+"px",aB.style.height=n[3]+"px"},QP.addMouseEventListeners=function(){return DB(),QP},QP.removeMouseEventListeners=function(){return document.removeEventListener("click",FB,!0),document.removeEventListener("mousemove",_B,!0),QP},QP.recordScreenPosition=function(e,t,n){return AB(e,t,n||gB[0]),QP},QP.storePoints=function(e,t,n){lB[n]=e,uB[n]=t},QP.setTracker=function(e){if(void 0===wB[e]){for(var t in console.log("Invalid tracker selection"),console.log("Options are: "),wB)console.log(t);return QP}return bB=wB[e](),QP},QP.setRegression=function(e){if(void 0===vB[e]){for(var t in console.log("Invalid regression selection"),console.log("Options are: "),vB)console.log(t);return QP}return SB=xB[0].getData(),(xB=[vB[e]()])[0].setData(SB),QP},QP.addTrackerModule=function(e,t){wB[e]=function(){return new t}},QP.addRegressionModule=function(e,t){vB[e]=function(){return new t}},QP.addRegression=function(e){var t=vB[e]();return SB=xB[0].getData(),t.setData(SB),xB.push(t),QP},QP.setGazeListener=function(e){return mB=e,QP},QP.clearGazeListener=function(){return mB=fB,QP},QP.setVideoElementCanvas=function(e){return sB=e},QP.clearData=async function(){!function(){for(var e in Zz().clear(),xB)xB[e].init()}()},QP.getTracker=function(){return bB},QP.getRegression=function(){return xB},QP.getCurrentPrediction=function(e){return CB(e)},QP.params.getEventTypes=function(){return gB.slice()},QP.getVideoElementCanvas=function(){return sB},QP.getVideoPreviewToCameraResolutionRatio=function(){return[QP.params.videoViewerWidth/nB.videoWidth,QP.params.videoViewerHeight/nB.videoHeight]},QP.getStoredPoints=function(){return[lB,uB]};const zB=QP})(),webgazer=s.default})(); +//# sourceMappingURL=webgazer.js.map \ No newline at end of file diff --git a/src/styles/styles.css b/src/styles/styles.css index fb010e8..a7ada2f 100644 --- a/src/styles/styles.css +++ b/src/styles/styles.css @@ -373,28 +373,47 @@ body { .hero-features { display: grid; - grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); - gap: var(--space-lg); + grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)); + gap: var(--space-xl); margin: var(--space-xl) 0; } .hero-feature { - background: var(--bg-primary-overlay-10); - border: 2px solid; - border-image: linear-gradient(45deg, var(--color-primary), var(--color-secondary)) 1; - padding: 25px; + background: linear-gradient(135deg, rgba(138, 43, 226, 0.15), rgba(218, 112, 214, 0.15)); + border: 2px solid var(--color-primary); + border-radius: 12px; + padding: 10px 12px; text-align: center; - transition: all 0.3s ease; + transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275); position: relative; - clip-path: polygon(0 0, calc(100% - 15px) 0, 100% 15px, 100% 100%, 15px 100%, 0 calc(100% - 15px)); + overflow: hidden; +} + +.hero-feature::before { + content: ''; + position: absolute; + top: -2px; + left: -2px; + right: -2px; + bottom: -2px; + background: linear-gradient(45deg, var(--color-primary), var(--color-secondary), var(--color-primary)); + border-radius: 12px; + z-index: -1; + opacity: 0; + transition: opacity 0.4s ease; } .hero-feature:hover { - transform: translateY(-5px) scale(1.02); - border-image: linear-gradient(45deg, var(--color-primary), var(--color-secondary), var(--color-primary)) 1; + transform: translateY(-8px); box-shadow: - var(--shadow-glow-primary), - inset 0 1px 0 rgba(255, 255, 255, 0.2); + 0 0 30px rgba(138, 43, 226, 0.8), + 0 0 60px rgba(138, 43, 226, 0.4), + inset 0 0 20px rgba(138, 43, 226, 0.2); + border-color: var(--color-secondary); +} + +.hero-feature:hover::before { + opacity: 0.3; } .feature-icon { @@ -403,12 +422,13 @@ body { align-items: center; justify-content: center; min-width: 32px; + margin-bottom: 4px; } .cassie-icon { display: inline-block; - width: 2.5rem; - height: 2.5rem; + width: 1.8rem; + height: 1.8rem; background-image: url('../../assets/cassie.png'); background-size: contain; background-repeat: no-repeat;