webpackJsonp([0],{"++K3":function(t,e){var n,i,r,o,s,a,l,u,c,h,p,d,f,g,m,v=!1;function _(){if(!v){v=!0;var t=navigator.userAgent,e=/(?:MSIE.(\d+\.\d+))|(?:(?:Firefox|GranParadiso|Iceweasel).(\d+\.\d+))|(?:Opera(?:.+Version.|.)(\d+\.\d+))|(?:AppleWebKit.(\d+(?:\.\d+)?))|(?:Trident\/\d+\.\d+.*rv:(\d+\.\d+))/.exec(t),_=/(Mac OS X)|(Windows)|(Linux)/.exec(t);if(d=/\b(iPhone|iP[ao]d)/.exec(t),f=/\b(iP[ao]d)/.exec(t),h=/Android/i.exec(t),g=/FBAN\/\w+;/i.exec(t),m=/Mobile/i.exec(t),p=!!/Win64/.exec(t),e){(n=e[1]?parseFloat(e[1]):e[5]?parseFloat(e[5]):NaN)&&document&&document.documentMode&&(n=document.documentMode);var y=/(?:Trident\/(\d+.\d+))/.exec(t);a=y?parseFloat(y[1])+4:n,i=e[2]?parseFloat(e[2]):NaN,r=e[3]?parseFloat(e[3]):NaN,(o=e[4]?parseFloat(e[4]):NaN)?(e=/(?:Chrome\/(\d+\.\d+))/.exec(t),s=e&&e[1]?parseFloat(e[1]):NaN):s=NaN}else n=i=r=s=o=NaN;if(_){if(_[1]){var b=/(?:Mac OS X (\d+(?:[._]\d+)?))/.exec(t);l=!b||parseFloat(b[1].replace("_","."))}else l=!1;u=!!_[2],c=!!_[3]}else l=u=c=!1}}var y={ie:function(){return _()||n},ieCompatibilityMode:function(){return _()||a>n},ie64:function(){return y.ie()&&p},firefox:function(){return _()||i},opera:function(){return _()||r},webkit:function(){return _()||o},safari:function(){return y.webkit()},chrome:function(){return _()||s},windows:function(){return _()||u},osx:function(){return _()||l},linux:function(){return _()||c},iphone:function(){return _()||d},mobile:function(){return _()||d||f||h||m},nativeApp:function(){return _()||g},android:function(){return _()||h},ipad:function(){return _()||f}};t.exports=y},"+E39":function(t,e,n){t.exports=!n("S82l")(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})},"+ZMJ":function(t,e,n){var i=n("lOnJ");t.exports=function(t,e,n){if(i(t),void 0===e)return t;switch(n){case 1:return function(n){return t.call(e,n)};case 2:return function(n,i){return t.call(e,n,i)};case 3:return function(n,i,r){return t.call(e,n,i,r)}}return function(){return t.apply(e,arguments)}}},"+tPU":function(t,e,n){n("xGkn");for(var i=n("7KvD"),r=n("hJx8"),o=n("/bQp"),s=n("dSzd")("toStringTag"),a="CSSRuleList,CSSStyleDeclaration,CSSValueList,ClientRectList,DOMRectList,DOMStringList,DOMTokenList,DataTransferItemList,FileList,HTMLAllCollection,HTMLCollection,HTMLFormElement,HTMLSelectElement,MediaList,MimeTypeArray,NamedNodeMap,NodeList,PaintRequestList,Plugin,PluginArray,SVGLengthList,SVGNumberList,SVGPathSegList,SVGPointList,SVGStringList,SVGTransformList,SourceBufferList,StyleSheetList,TextTrackCueList,TextTrackList,TouchList".split(","),l=0;l=0&&(e=t.slice(i),t=t.slice(0,i));var r=t.indexOf("?");return r>=0&&(n=t.slice(r+1),t=t.slice(0,r)),{path:t,query:n,hash:e}}(o.path||""),p=e&&e.path||"/",d=u.path?C(u.path,p,n||o.append):p,f=function(t,e,n){void 0===e&&(e={});var i,r=n||h;try{i=r(t||"")}catch(t){i={}}for(var o in e){var s=e[o];i[o]=Array.isArray(s)?s.map(c):c(s)}return i}(u.query,o.query,i&&i.options.parseQuery),g=o.hash||u.hash;return g&&"#"!==g.charAt(0)&&(g="#"+g),{_normalized:!0,path:d,query:f,hash:g}}var j,z=[String,Object],$=[String,Array],X=function(){},Y={name:"RouterLink",props:{to:{type:z,required:!0},tag:{type:String,default:"a"},custom:Boolean,exact:Boolean,exactPath:Boolean,append:Boolean,replace:Boolean,activeClass:String,exactActiveClass:String,ariaCurrentValue:{type:String,default:"page"},event:{type:$,default:"click"}},render:function(t){var e=this,n=this.$router,i=this.$route,o=n.resolve(this.to,i,this.append),s=o.location,a=o.route,l=o.href,u={},c=n.options.linkActiveClass,h=n.options.linkExactActiveClass,p=null==c?"router-link-active":c,g=null==h?"router-link-exact-active":h,m=null==this.activeClass?p:this.activeClass,v=null==this.exactActiveClass?g:this.exactActiveClass,y=a.redirectedFrom?f(null,G(a.redirectedFrom),null,n):a;u[v]=_(i,y,this.exactPath),u[m]=this.exact||this.exactPath?u[v]:function(t,e){return 0===t.path.replace(d,"/").indexOf(e.path.replace(d,"/"))&&(!e.hash||t.hash===e.hash)&&function(t,e){for(var n in e)if(!(n in t))return!1;return!0}(t.query,e.query)}(i,y);var b=u[v]?this.ariaCurrentValue:null,T=function(t){K(t)&&(e.replace?n.replace(s,X):n.push(s,X))},E={click:K};Array.isArray(this.event)?this.event.forEach(function(t){E[t]=T}):E[this.event]=T;var C={class:u},S=!this.$scopedSlots.$hasNormal&&this.$scopedSlots.default&&this.$scopedSlots.default({href:l,route:a,navigate:T,isActive:u[m],isExactActive:u[v]});if(S){if(1===S.length)return S[0];if(S.length>1||!S.length)return 0===S.length?t():t("span",{},S)}if("a"===this.tag)C.on=E,C.attrs={href:l,"aria-current":b};else{var w=function t(e){if(e)for(var n,i=0;i-1&&(a.params[p]=n.params[p]);return a.path=W(c.path,a.params),l(c,a,s)}if(a.path){a.params={};for(var d=0;d=t.length?n():t[r]?e(t[r],function(){i(r+1)}):i(r+1)};i(0)}var Tt={redirected:2,aborted:4,cancelled:8,duplicated:16};function Et(t,e){return St(t,e,Tt.redirected,'Redirected when going from "'+t.fullPath+'" to "'+function(t){if("string"==typeof t)return t;if("path"in t)return t.path;var e={};return wt.forEach(function(n){n in t&&(e[n]=t[n])}),JSON.stringify(e,null,2)}(e)+'" via a navigation guard.')}function Ct(t,e){return St(t,e,Tt.cancelled,'Navigation cancelled from "'+t.fullPath+'" to "'+e.fullPath+'" with a new navigation.')}function St(t,e,n,i){var r=new Error(i);return r._isRouter=!0,r.from=t,r.to=e,r.type=n,r}var wt=["params","query","hash"];function kt(t){return Object.prototype.toString.call(t).indexOf("Error")>-1}function xt(t,e){return kt(t)&&t._isRouter&&(null==e||t.type===e)}function It(t){return function(e,n,i){var r=!1,o=0,s=null;Rt(t,function(t,e,n,a){if("function"==typeof t&&void 0===t.cid){r=!0,o++;var l,u=At(function(e){var r;((r=e).__esModule||Dt&&"Module"===r[Symbol.toStringTag])&&(e=e.default),t.resolved="function"==typeof e?e:j.extend(e),n.components[a]=e,--o<=0&&i()}),c=At(function(t){var e="Failed to resolve async component "+a+": "+t;s||(s=kt(t)?t:new Error(e),i(s))});try{l=t(u,c)}catch(t){c(t)}if(l)if("function"==typeof l.then)l.then(u,c);else{var h=l.component;h&&"function"==typeof h.then&&h.then(u,c)}}}),r||i()}}function Rt(t,e){return Ot(t.map(function(t){return Object.keys(t.components).map(function(n){return e(t.components[n],t.instances[n],t,n)})}))}function Ot(t){return Array.prototype.concat.apply([],t)}var Dt="function"==typeof Symbol&&"symbol"==typeof Symbol.toStringTag;function At(t){var e=!1;return function(){for(var n=[],i=arguments.length;i--;)n[i]=arguments[i];if(!e)return e=!0,t.apply(this,n)}}var Mt=function(t,e){this.router=t,this.base=function(t){if(!t)if(q){var e=document.querySelector("base");t=(t=e&&e.getAttribute("href")||"/").replace(/^https?:\/\/[^\/]+/,"")}else t="/";"/"!==t.charAt(0)&&(t="/"+t);return t.replace(/\/$/,"")}(e),this.current=m,this.pending=null,this.ready=!1,this.readyCbs=[],this.readyErrorCbs=[],this.errorCbs=[],this.listeners=[]};function Nt(t,e,n,i){var r=Rt(t,function(t,i,r,o){var s=function(t,e){"function"!=typeof t&&(t=j.extend(t));return t.options[e]}(t,e);if(s)return Array.isArray(s)?s.map(function(t){return n(t,i,r,o)}):n(s,i,r,o)});return Ot(i?r.reverse():r)}function Lt(t,e){if(e)return function(){return t.apply(e,arguments)}}Mt.prototype.listen=function(t){this.cb=t},Mt.prototype.onReady=function(t,e){this.ready?t():(this.readyCbs.push(t),e&&this.readyErrorCbs.push(e))},Mt.prototype.onError=function(t){this.errorCbs.push(t)},Mt.prototype.transitionTo=function(t,e,n){var i,r=this;try{i=this.router.match(t,this.current)}catch(t){throw this.errorCbs.forEach(function(e){e(t)}),t}var o=this.current;this.confirmTransition(i,function(){r.updateRoute(i),e&&e(i),r.ensureURL(),r.router.afterHooks.forEach(function(t){t&&t(i,o)}),r.ready||(r.ready=!0,r.readyCbs.forEach(function(t){t(i)}))},function(t){n&&n(t),t&&!r.ready&&(xt(t,Tt.redirected)&&o===m||(r.ready=!0,r.readyErrorCbs.forEach(function(e){e(t)})))})},Mt.prototype.confirmTransition=function(t,e,n){var r=this,o=this.current;this.pending=t;var s,a,l=function(t){!xt(t)&&kt(t)&&(r.errorCbs.length?r.errorCbs.forEach(function(e){e(t)}):(i(),console.error(t))),n&&n(t)},u=t.matched.length-1,c=o.matched.length-1;if(_(t,o)&&u===c&&t.matched[u]===o.matched[c])return this.ensureURL(),l(((a=St(s=o,t,Tt.duplicated,'Avoided redundant navigation to current location: "'+s.fullPath+'".')).name="NavigationDuplicated",a));var h=function(t,e){var n,i=Math.max(t.length,e.length);for(n=0;n0)){var e=this.router,n=e.options.scrollBehavior,i=vt&&n;i&&this.listeners.push(at());var r=function(){var n=t.current,r=Bt(t.base);t.current===m&&r===t._startLocation||t.transitionTo(r,function(t){i&<(e,t,n,!0)})};window.addEventListener("popstate",r),this.listeners.push(function(){window.removeEventListener("popstate",r)})}},e.prototype.go=function(t){window.history.go(t)},e.prototype.push=function(t,e,n){var i=this,r=this.current;this.transitionTo(t,function(t){_t(S(i.base+t.fullPath)),lt(i.router,t,r,!1),e&&e(t)},n)},e.prototype.replace=function(t,e,n){var i=this,r=this.current;this.transitionTo(t,function(t){yt(S(i.base+t.fullPath)),lt(i.router,t,r,!1),e&&e(t)},n)},e.prototype.ensureURL=function(t){if(Bt(this.base)!==this.current.fullPath){var e=S(this.base+this.current.fullPath);t?_t(e):yt(e)}},e.prototype.getCurrentLocation=function(){return Bt(this.base)},e}(Mt);function Bt(t){var e=window.location.pathname,n=e.toLowerCase(),i=t.toLowerCase();return!t||n!==i&&0!==n.indexOf(S(i+"/"))||(e=e.slice(t.length)),(e||"/")+window.location.search+window.location.hash}var Ft=function(t){function e(e,n,i){t.call(this,e,n),i&&function(t){var e=Bt(t);if(!/^\/#/.test(e))return window.location.replace(S(t+"/#"+e)),!0}(this.base)||Ut()}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.setupListeners=function(){var t=this;if(!(this.listeners.length>0)){var e=this.router.options.scrollBehavior,n=vt&&e;n&&this.listeners.push(at());var i=function(){var e=t.current;Ut()&&t.transitionTo(Vt(),function(i){n&<(t.router,i,e,!0),vt||Gt(i.fullPath)})},r=vt?"popstate":"hashchange";window.addEventListener(r,i),this.listeners.push(function(){window.removeEventListener(r,i)})}},e.prototype.push=function(t,e,n){var i=this,r=this.current;this.transitionTo(t,function(t){Wt(t.fullPath),lt(i.router,t,r,!1),e&&e(t)},n)},e.prototype.replace=function(t,e,n){var i=this,r=this.current;this.transitionTo(t,function(t){Gt(t.fullPath),lt(i.router,t,r,!1),e&&e(t)},n)},e.prototype.go=function(t){window.history.go(t)},e.prototype.ensureURL=function(t){var e=this.current.fullPath;Vt()!==e&&(t?Wt(e):Gt(e))},e.prototype.getCurrentLocation=function(){return Vt()},e}(Mt);function Ut(){var t=Vt();return"/"===t.charAt(0)||(Gt("/"+t),!1)}function Vt(){var t=window.location.href,e=t.indexOf("#");return e<0?"":t=t.slice(e+1)}function Ht(t){var e=window.location.href,n=e.indexOf("#");return(n>=0?e.slice(0,n):e)+"#"+t}function Wt(t){vt?_t(Ht(t)):window.location.hash=t}function Gt(t){vt?yt(Ht(t)):window.location.replace(Ht(t))}var jt=function(t){function e(e,n){t.call(this,e,n),this.stack=[],this.index=-1}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.push=function(t,e,n){var i=this;this.transitionTo(t,function(t){i.stack=i.stack.slice(0,i.index+1).concat(t),i.index++,e&&e(t)},n)},e.prototype.replace=function(t,e,n){var i=this;this.transitionTo(t,function(t){i.stack=i.stack.slice(0,i.index).concat(t),e&&e(t)},n)},e.prototype.go=function(t){var e=this,n=this.index+t;if(!(n<0||n>=this.stack.length)){var i=this.stack[n];this.confirmTransition(i,function(){var t=e.current;e.index=n,e.updateRoute(i),e.router.afterHooks.forEach(function(e){e&&e(i,t)})},function(t){xt(t,Tt.duplicated)&&(e.index=n)})}},e.prototype.getCurrentLocation=function(){var t=this.stack[this.stack.length-1];return t?t.fullPath:"/"},e.prototype.ensureURL=function(){},e}(Mt),zt=function(t){void 0===t&&(t={}),this.app=null,this.apps=[],this.options=t,this.beforeHooks=[],this.resolveHooks=[],this.afterHooks=[],this.matcher=Q(t.routes||[],this);var e=t.mode||"hash";switch(this.fallback="history"===e&&!vt&&!1!==t.fallback,this.fallback&&(e="hash"),q||(e="abstract"),this.mode=e,e){case"history":this.history=new Pt(this,t.base);break;case"hash":this.history=new Ft(this,t.base,this.fallback);break;case"abstract":this.history=new jt(this,t.base);break;default:0}},$t={currentRoute:{configurable:!0}};function Xt(t,e){return t.push(e),function(){var n=t.indexOf(e);n>-1&&t.splice(n,1)}}zt.prototype.match=function(t,e,n){return this.matcher.match(t,e,n)},$t.currentRoute.get=function(){return this.history&&this.history.current},zt.prototype.init=function(t){var e=this;if(this.apps.push(t),t.$once("hook:destroyed",function(){var n=e.apps.indexOf(t);n>-1&&e.apps.splice(n,1),e.app===t&&(e.app=e.apps[0]||null),e.app||e.history.teardown()}),!this.app){this.app=t;var n=this.history;if(n instanceof Pt||n instanceof Ft){var i=function(t){n.setupListeners(),function(t){var i=n.current,r=e.options.scrollBehavior;vt&&r&&"fullPath"in t&<(e,t,i,!1)}(t)};n.transitionTo(n.getCurrentLocation(),i,i)}n.listen(function(t){e.apps.forEach(function(e){e._route=t})})}},zt.prototype.beforeEach=function(t){return Xt(this.beforeHooks,t)},zt.prototype.beforeResolve=function(t){return Xt(this.resolveHooks,t)},zt.prototype.afterEach=function(t){return Xt(this.afterHooks,t)},zt.prototype.onReady=function(t,e){this.history.onReady(t,e)},zt.prototype.onError=function(t){this.history.onError(t)},zt.prototype.push=function(t,e,n){var i=this;if(!e&&!n&&"undefined"!=typeof Promise)return new Promise(function(e,n){i.history.push(t,e,n)});this.history.push(t,e,n)},zt.prototype.replace=function(t,e,n){var i=this;if(!e&&!n&&"undefined"!=typeof Promise)return new Promise(function(e,n){i.history.replace(t,e,n)});this.history.replace(t,e,n)},zt.prototype.go=function(t){this.history.go(t)},zt.prototype.back=function(){this.go(-1)},zt.prototype.forward=function(){this.go(1)},zt.prototype.getMatchedComponents=function(t){var e=t?t.matched?t:this.resolve(t).route:this.currentRoute;return e?[].concat.apply([],e.matched.map(function(t){return Object.keys(t.components).map(function(e){return t.components[e]})})):[]},zt.prototype.resolve=function(t,e,n){var i=G(t,e=e||this.history.current,n,this),r=this.match(i,e),o=r.redirectedFrom||r.fullPath;return{location:i,route:r,href:function(t,e,n){var i="hash"===n?"#"+e:e;return t?S(t+"/"+i):i}(this.history.base,o,this.mode),normalizedTo:i,resolved:r}},zt.prototype.getRoutes=function(){return this.matcher.getRoutes()},zt.prototype.addRoute=function(t,e){this.matcher.addRoute(t,e),this.history.current!==m&&this.history.transitionTo(this.history.getCurrentLocation())},zt.prototype.addRoutes=function(t){this.matcher.addRoutes(t),this.history.current!==m&&this.history.transitionTo(this.history.getCurrentLocation())},Object.defineProperties(zt.prototype,$t),zt.install=J,zt.version="3.5.2",zt.isNavigationFailure=xt,zt.NavigationFailureType=Tt,zt.START_LOCATION=m,q&&window.Vue&&window.Vue.use(zt),e.a=zt},"02w1":function(t,e,n){"use strict";e.__esModule=!0,e.removeResizeListener=e.addResizeListener=void 0;var i,r=n("z+gd"),o=(i=r)&&i.__esModule?i:{default:i};var s="undefined"==typeof window,a=function(t){var e=t,n=Array.isArray(e),i=0;for(e=n?e:e[Symbol.iterator]();;){var r;if(n){if(i>=e.length)break;r=e[i++]}else{if((i=e.next()).done)break;r=i.value}var o=r.target.__resizeListeners__||[];o.length&&o.forEach(function(t){t()})}};e.addResizeListener=function(t,e){s||(t.__resizeListeners__||(t.__resizeListeners__=[],t.__ro__=new o.default(a),t.__ro__.observe(t)),t.__resizeListeners__.push(e))},e.removeResizeListener=function(t,e){t&&t.__resizeListeners__&&(t.__resizeListeners__.splice(t.__resizeListeners__.indexOf(e),1),t.__resizeListeners__.length||t.__ro__.disconnect())}},"06OY":function(t,e,n){var i=n("3Eo+")("meta"),r=n("EqjI"),o=n("D2L2"),s=n("evD5").f,a=0,l=Object.isExtensible||function(){return!0},u=!n("S82l")(function(){return l(Object.preventExtensions({}))}),c=function(t){s(t,i,{value:{i:"O"+ ++a,w:{}}})},h=t.exports={KEY:i,NEED:!1,fastKey:function(t,e){if(!r(t))return"symbol"==typeof t?t:("string"==typeof t?"S":"P")+t;if(!o(t,i)){if(!l(t))return"F";if(!e)return"E";c(t)}return t[i].i},getWeak:function(t,e){if(!o(t,i)){if(!l(t))return!0;if(!e)return!1;c(t)}return t[i].w},onFreeze:function(t){return u&&h.NEED&&l(t)&&!o(t,i)&&c(t),t}}},"0kY3":function(t,e,n){t.exports=function(t){var e={};function n(i){if(e[i])return e[i].exports;var r=e[i]={i:i,l:!1,exports:{}};return t[i].call(r.exports,r,r.exports,n),r.l=!0,r.exports}return n.m=t,n.c=e,n.d=function(t,e,i){n.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:i})},n.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},n.t=function(t,e){if(1&e&&(t=n(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var i=Object.create(null);if(n.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var r in t)n.d(i,r,function(e){return t[e]}.bind(null,r));return i},n.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return n.d(e,"a",e),e},n.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},n.p="/dist/",n(n.s=102)}({0:function(t,e,n){"use strict";function i(t,e,n,i,r,o,s,a){var l,u="function"==typeof t?t.options:t;if(e&&(u.render=e,u.staticRenderFns=n,u._compiled=!0),i&&(u.functional=!0),o&&(u._scopeId="data-v-"+o),s?(l=function(t){(t=t||this.$vnode&&this.$vnode.ssrContext||this.parent&&this.parent.$vnode&&this.parent.$vnode.ssrContext)||"undefined"==typeof __VUE_SSR_CONTEXT__||(t=__VUE_SSR_CONTEXT__),r&&r.call(this,t),t&&t._registeredComponents&&t._registeredComponents.add(s)},u._ssrRegister=l):r&&(l=a?function(){r.call(this,this.$root.$options.shadowRoot)}:r),l)if(u.functional){u._injectStyles=l;var c=u.render;u.render=function(t,e){return l.call(e),c(t,e)}}else{var h=u.beforeCreate;u.beforeCreate=h?[].concat(h,l):[l]}return{exports:t,options:u}}n.d(e,"a",function(){return i})},10:function(t,e){t.exports=n("HJMx")},102:function(t,e,n){"use strict";n.r(e);var i=function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("div",{class:["el-input-number",t.inputNumberSize?"el-input-number--"+t.inputNumberSize:"",{"is-disabled":t.inputNumberDisabled},{"is-without-controls":!t.controls},{"is-controls-right":t.controlsAtRight}],on:{dragstart:function(t){t.preventDefault()}}},[t.controls?n("span",{directives:[{name:"repeat-click",rawName:"v-repeat-click",value:t.decrease,expression:"decrease"}],staticClass:"el-input-number__decrease",class:{"is-disabled":t.minDisabled},attrs:{role:"button"},on:{keydown:function(e){return"button"in e||!t._k(e.keyCode,"enter",13,e.key,"Enter")?t.decrease(e):null}}},[n("i",{class:"el-icon-"+(t.controlsAtRight?"arrow-down":"minus")})]):t._e(),t.controls?n("span",{directives:[{name:"repeat-click",rawName:"v-repeat-click",value:t.increase,expression:"increase"}],staticClass:"el-input-number__increase",class:{"is-disabled":t.maxDisabled},attrs:{role:"button"},on:{keydown:function(e){return"button"in e||!t._k(e.keyCode,"enter",13,e.key,"Enter")?t.increase(e):null}}},[n("i",{class:"el-icon-"+(t.controlsAtRight?"arrow-up":"plus")})]):t._e(),n("el-input",{ref:"input",attrs:{value:t.displayValue,placeholder:t.placeholder,disabled:t.inputNumberDisabled,size:t.inputNumberSize,max:t.max,min:t.min,name:t.name,label:t.label},on:{blur:t.handleBlur,focus:t.handleFocus,input:t.handleInput,change:t.handleInputChange},nativeOn:{keydown:[function(e){return"button"in e||!t._k(e.keyCode,"up",38,e.key,["Up","ArrowUp"])?(e.preventDefault(),t.increase(e)):null},function(e){return"button"in e||!t._k(e.keyCode,"down",40,e.key,["Down","ArrowDown"])?(e.preventDefault(),t.decrease(e)):null}]}})],1)};i._withStripped=!0;var r=n(10),o=n.n(r),s=n(22),a=n.n(s),l=n(30),u={name:"ElInputNumber",mixins:[a()("input")],inject:{elForm:{default:""},elFormItem:{default:""}},directives:{repeatClick:l.a},components:{ElInput:o.a},props:{step:{type:Number,default:1},stepStrictly:{type:Boolean,default:!1},max:{type:Number,default:1/0},min:{type:Number,default:-1/0},value:{},disabled:Boolean,size:String,controls:{type:Boolean,default:!0},controlsPosition:{type:String,default:""},name:String,label:String,placeholder:String,precision:{type:Number,validator:function(t){return t>=0&&t===parseInt(t,10)}}},data:function(){return{currentValue:0,userInput:null}},watch:{value:{immediate:!0,handler:function(t){var e=void 0===t?t:Number(t);if(void 0!==e){if(isNaN(e))return;if(this.stepStrictly){var n=this.getPrecision(this.step),i=Math.pow(10,n);e=Math.round(e/this.step)*i*this.step/i}void 0!==this.precision&&(e=this.toPrecision(e,this.precision))}e>=this.max&&(e=this.max),e<=this.min&&(e=this.min),this.currentValue=e,this.userInput=null,this.$emit("input",e)}}},computed:{minDisabled:function(){return this._decrease(this.value,this.step)this.max},numPrecision:function(){var t=this.value,e=this.step,n=this.getPrecision,i=this.precision,r=n(e);return void 0!==i?(r>i&&console.warn("[Element Warn][InputNumber]precision should not be less than the decimal places of step"),i):Math.max(n(t),r)},controlsAtRight:function(){return this.controls&&"right"===this.controlsPosition},_elFormItemSize:function(){return(this.elFormItem||{}).elFormItemSize},inputNumberSize:function(){return this.size||this._elFormItemSize||(this.$ELEMENT||{}).size},inputNumberDisabled:function(){return this.disabled||!!(this.elForm||{}).disabled},displayValue:function(){if(null!==this.userInput)return this.userInput;var t=this.currentValue;if("number"==typeof t){if(this.stepStrictly){var e=this.getPrecision(this.step),n=Math.pow(10,e);t=Math.round(t/this.step)*n*this.step/n}void 0!==this.precision&&(t=t.toFixed(this.precision))}return t}},methods:{toPrecision:function(t,e){return void 0===e&&(e=this.numPrecision),parseFloat(Math.round(t*Math.pow(10,e))/Math.pow(10,e))},getPrecision:function(t){if(void 0===t)return 0;var e=t.toString(),n=e.indexOf("."),i=0;return-1!==n&&(i=e.length-n-1),i},_increase:function(t,e){if("number"!=typeof t&&void 0!==t)return this.currentValue;var n=Math.pow(10,this.numPrecision);return this.toPrecision((n*t+n*e)/n)},_decrease:function(t,e){if("number"!=typeof t&&void 0!==t)return this.currentValue;var n=Math.pow(10,this.numPrecision);return this.toPrecision((n*t-n*e)/n)},increase:function(){if(!this.inputNumberDisabled&&!this.maxDisabled){var t=this.value||0,e=this._increase(t,this.step);this.setCurrentValue(e)}},decrease:function(){if(!this.inputNumberDisabled&&!this.minDisabled){var t=this.value||0,e=this._decrease(t,this.step);this.setCurrentValue(e)}},handleBlur:function(t){this.$emit("blur",t)},handleFocus:function(t){this.$emit("focus",t)},setCurrentValue:function(t){var e=this.currentValue;"number"==typeof t&&void 0!==this.precision&&(t=this.toPrecision(t,this.precision)),t>=this.max&&(t=this.max),t<=this.min&&(t=this.min),e!==t&&(this.userInput=null,this.$emit("input",t),this.$emit("change",t,e),this.currentValue=t)},handleInput:function(t){this.userInput=t},handleInputChange:function(t){var e=""===t?void 0:Number(t);isNaN(e)&&""!==t||this.setCurrentValue(e),this.userInput=null},select:function(){this.$refs.input.select()}},mounted:function(){var t=this.$refs.input.$refs.input;t.setAttribute("role","spinbutton"),t.setAttribute("aria-valuemax",this.max),t.setAttribute("aria-valuemin",this.min),t.setAttribute("aria-valuenow",this.currentValue),t.setAttribute("aria-disabled",this.inputNumberDisabled)},updated:function(){this.$refs&&this.$refs.input&&this.$refs.input.$refs.input.setAttribute("aria-valuenow",this.currentValue)}},c=n(0),h=Object(c.a)(u,i,[],!1,null,null,null);h.options.__file="packages/input-number/src/input-number.vue";var p=h.exports;p.install=function(t){t.component(p.name,p)};e.default=p},2:function(t,e){t.exports=n("2kvA")},22:function(t,e){t.exports=n("1oZe")},30:function(t,e,n){"use strict";var i=n(2);e.a={bind:function(t,e,n){var r=null,o=void 0,s=function(){return n.context[e.expression].apply()},a=function(){Date.now()-o<100&&s(),clearInterval(r),r=null};Object(i.on)(t,"mousedown",function(t){0===t.button&&(o=Date.now(),Object(i.once)(document,"mouseup",a),clearInterval(r),r=setInterval(s,100))})}}}})},"1kS7":function(t,e){e.f=Object.getOwnPropertySymbols},"1oZe":function(t,e,n){"use strict";e.__esModule=!0,e.default=function(t){return{methods:{focus:function(){this.$refs[t].focus()}}}}},"21It":function(t,e,n){"use strict";var i=n("FtD3");t.exports=function(t,e,n){var r=n.config.validateStatus;n.status&&r&&!r(n.status)?e(i("Request failed with status code "+n.status,n.config,null,n.request,n)):t(n)}},"2KxR":function(t,e){t.exports=function(t,e,n,i){if(!(t instanceof e)||void 0!==i&&i in t)throw TypeError(n+": incorrect invocation!");return t}},"2kvA":function(t,e,n){"use strict";e.__esModule=!0,e.isInContainer=e.getScrollContainer=e.isScroll=e.getStyle=e.once=e.off=e.on=void 0;var i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t};e.hasClass=f,e.addClass=function(t,e){if(!t)return;for(var n=t.className,i=(e||"").split(" "),r=0,o=i.length;r-1}var g=e.getStyle=u<9?function(t,e){if(!s){if(!t||!e)return null;"float"===(e=h(e))&&(e="styleFloat");try{switch(e){case"opacity":try{return t.filters.item("alpha").opacity/100}catch(t){return 1}default:return t.style[e]||t.currentStyle?t.currentStyle[e]:null}}catch(n){return t.style[e]}}}:function(t,e){if(!s){if(!t||!e)return null;"float"===(e=h(e))&&(e="cssFloat");try{var n=document.defaultView.getComputedStyle(t,"");return t.style[e]||n?n[e]:null}catch(n){return t.style[e]}}};var m=e.isScroll=function(t,e){if(!s)return g(t,null!==e&&void 0!==e?e?"overflow-y":"overflow-x":"overflow").match(/(scroll|auto)/)};e.getScrollContainer=function(t,e){if(!s){for(var n=t;n;){if([window,document,document.documentElement].includes(n))return window;if(m(n,e))return n;n=n.parentNode}return n}},e.isInContainer=function(t,e){if(s||!t||!e)return!1;var n=t.getBoundingClientRect(),i=void 0;return i=[window,document,document.documentElement,null,void 0].includes(e)?{top:0,right:window.innerWidth,bottom:window.innerHeight,left:0}:e.getBoundingClientRect(),n.topi.top&&n.right>i.left&&n.left0&&r[r.length-1])&&(6===o[0]||2===o[0])){s=0;continue}if(3===o[0]&&(!r||o[1]>r[0]&&o[1]0;)i=Math.random()*e|0,n=t[--e],t[e]=t[i],t[i]=n}function b(t,e,n){return Math.max(t,Math.min(e,n))}function T(t){return t%2==0?t:t+1}function E(t){for(var e=0,n=0;n=n?r():setTimeout(s,a)}};s()})}function N(t,e){for(var n=1,i=-1,r=0;r=0)n*=t[r];else if(-1===t[r]){if(-1!==i)throw Error("Shapes can only have 1 implicit size. Found -1 at dim "+i+" and dim "+r);i=r}else if(t[r]<0)throw Error("Shapes can not be < 0. Found "+t[r]+" at dim "+r);if(-1===i){if(e>0&&e!==n)throw Error("Size("+e+") must match the product of shape "+t);return t}if(0===n)throw Error("Cannot infer the missing size in ["+t+"] when there are 0 elements");if(e%n!=0)throw Error("The implicit shape can't be a fractional number. Got "+e+" / "+n);var o=t.slice();return o[i]=e/n,o}function L(t,e){var n=e.length;return C((t=null==t?e.map(function(t,e){return e}):[].concat(t)).every(function(t){return t>=-n&&ta)&&1===t[a]&&(n.push(t[a]),i.push(a)),o[s]<=a&&s++}1!==t[a]&&(n.push(t[a]),i.push(a))}return{newShape:n,keptDims:i}}function B(t,e){var n=null;if(null==t||"float32"===t)n=new Float32Array(e);else if("int32"===t)n=new Int32Array(e);else{if("bool"!==t)throw new Error("Unknown data type "+t);n=new Uint8Array(e)}return n}function F(t,e){var n=null;if(null==t||"float32"===t)n=new Float32Array(e);else if("int32"===t)n=new Int32Array(e);else if("bool"===t)n=new Uint8Array(e);else{if("string"!==t)throw new Error("Unknown data type "+t);n=new Array(e)}return n}function U(t,e){for(var n=0;n=0;--i)n[i]=n[i+1]*t[i+1];return n}function Z(t,e,n){if("string"===e)throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(t)&&(t=k(t)),n&&U(t,e),function(t,e){return t instanceof Float32Array&&"float32"===e||t instanceof Int32Array&&"int32"===e||t instanceof Uint8Array&&"bool"===e}(t,e))return t;if(null==e||"float32"===e||"complex64"===e)return new Float32Array(t);if("int32"===e)return new Int32Array(t);if("bool"===e){for(var i=new Uint8Array(t.length),r=0;r=0,function(){return"Tensor must have a shape comprised of positive integers but got shape ["+t+"]."})})}function rt(t,e){return void 0===e&&(e="utf-8"),e=e||"utf-8",c().platform.encode(t,e)}function ot(t,e){return void 0===e&&(e="utf-8"),e=e||"utf-8",c().platform.decode(t,e)}function st(t,e,n){if(0===e)return 0;if(1===e)return t[0];for(var i=t[t.length-1],r=0;r0?d:"")+" "}console.log("%c"+a+"\t%c"+s+"\t%c"+l+"D "+c+"\t%c"+u+"\t%c"+h+"\t%c"+o,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")},t}(),ct=20,ht=3,pt=7;function dt(t,e,n){return A(Array.isArray(t)?parseFloat(t[0].toFixed(pt))+" + "+parseFloat(t[1].toFixed(pt))+"j":z(t)?"'"+t+"'":"bool"===n?ft(t):parseFloat(t.toFixed(pt)).toString(),e)}function ft(t){return 0===t?"false":"true"}function gt(t){for(var e=[],n=0;n=this.shape[n]){var s="Requested out of range element at "+t+". Buffer shape="+this.shape;throw new Error(s)}n++}for(var a=t[t.length-1],l=0;l1)for(var u=0;uct){var c=ht*a,h=Array.from(e.slice(0,c)),p=Array.from(e.slice((l-ht)*a,l*a));return"complex64"===i&&(h=gt(h),p=gt(p)),["["+h.map(function(t,e){return dt(t,o[e],i)}).join(", ")+", ..., "+p.map(function(t,e){return dt(t,o[l-ht+e],i)}).join(", ")+"]"]}return["["+("complex64"===i?gt(e):Array.from(e)).map(function(t,e){return dt(t,o[e],i)}).join(", ")+"]"]}var d=n.slice(1),f=r.slice(1),g=r[0]*a,m=[];if(l>ct){for(var v=0;v0)throw new Error("Backend '"+this.backendName+"' has an internal memory leak ("+s+" data ids) after running '"+t+"'")},t.prototype.runKernelFunc=function(t,e,n,i,r,o,s){var a,l=this;void 0===o&&(o=[]),void 0===s&&(s=[]);var u=[],c=this.isTapeOn();null==i&&(i=null!=this.state.activeScope?this.state.activeScope.name:"");var h,p=function(t){c&&(u=t.map(function(t){return l.keep(l.clone(t))}))},d=this.state.numBytes,g=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);var m,v=f(i,this.backendName);return h=null!=v?function(){var t=l.backend.numDataIds();m=v.kernelFunc({inputs:e,attrs:r,backend:l.backend});var n=Array.isArray(m)?m:[m];l.shouldCheckForMemLeaks()&&l.checkKernelForMemLeak(i,t,n);var a=n.map(function(t){var e=t.dataId,n=t.shape,i=t.dtype;return l.makeTensorFromDataId(e,n,i)}),u=a.filter(function(t,e){return s[e]});return p((o||[]).slice().concat(u)),a}:function(){var e=l.backend.numDataIds();m=l.tidy(function(){return t(l.backend,p)});var n=Array.isArray(m)?m:[m];return l.shouldCheckForMemLeaks()&&l.checkKernelForMemLeak(i,e,n),n},this.scopedRun(function(){return l.state.kernelDepth++},function(){return l.state.kernelDepth--},function(){a=l.ENV.getBool("DEBUG")?l.profiler.profileKernel(i,e,function(){return h()}):h()}),c&&this.addTapeNode(i,e,a,n,u),this.state.profiling&&this.state.activeProfile.kernels.push({name:i,bytesAdded:this.state.numBytes-d,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-g,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(e).map(function(t){return e[t].shape}),outputShapes:a.map(function(t){return t.shape})}),Array.isArray(m)?a:a[0]},t.prototype.makeTensor=function(t,e,n,i){if(null==t)throw new Error("Values passed to engine.makeTensor() are null");n=n||"float32",i=i||this.backend;var r=t;"string"===n&&z(t[0])&&(r=t.map(function(t){return rt(t)}));var o=i.write(r,e,n),s=new bt(e,n,o,this.nextTensorId());if(this.incRef(s,i),"string"===n){var a=this.state.tensorInfo.get(o),l=j(r);this.state.numBytes+=l-a.bytes,a.bytes=l}return s},t.prototype.makeTensorFromDataId=function(t,e,n,i){var r=new bt(e,n=n||"float32",t,this.nextTensorId());return this.incRef(r,i),r},t.prototype.makeVariable=function(t,e,n,i){void 0===e&&(e=!0),n=n||this.nextVariableId().toString(),null!=i&&i!==t.dtype&&(t=t.asType(i));var r=new kt(t,e,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},t.prototype.incRef=function(t,e){var n=this.state.tensorInfo.has(t.dataId)?this.state.tensorInfo.get(t.dataId).refCount:0;if(this.state.numTensors++,"string"===t.dtype&&this.state.numStringTensors++,0===n){this.state.numDataBuffers++;var i=0;"complex64"!==t.dtype&&"string"!==t.dtype&&(i=t.size*G(t.dtype)),this.state.tensorInfo.set(t.dataId,{backend:e||this.backend,dtype:t.dtype,shape:t.shape,bytes:i,refCount:0}),this.state.numBytes+=i}this.state.tensorInfo.get(t.dataId).refCount++,t instanceof kt||this.track(t)},t.prototype.disposeTensor=function(t){if(this.state.tensorInfo.has(t.dataId)){this.state.numTensors--,"string"===t.dtype&&this.state.numStringTensors--;var e=this.state.tensorInfo.get(t.dataId);e.refCount<=1?("complex64"!==t.dtype&&(this.state.numBytes-=e.bytes),this.state.numDataBuffers--,e.backend.disposeData(t.dataId),this.state.tensorInfo.delete(t.dataId)):this.state.tensorInfo.get(t.dataId).refCount--}},t.prototype.disposeVariables=function(){for(var t in this.state.registeredVariables){var e=this.state.registeredVariables[t];this.disposeVariable(e)}},t.prototype.disposeVariable=function(t){this.disposeTensor(t),null!=this.state.registeredVariables[t.name]&&delete this.state.registeredVariables[t.name]},t.prototype.memory=function(){var t=this.backend.memory();return t.numTensors=this.state.numTensors,t.numDataBuffers=this.state.numDataBuffers,t.numBytes=this.state.numBytes,this.state.numStringTensors>0&&(t.unreliable=!0,null==t.reasons&&(t.reasons=[]),t.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),t},t.prototype.profile=function(t){return a(this,void 0,void 0,function(){var e,n;return l(this,function(i){return this.state.profiling=!0,e=this.state.numBytes,n=this.state.numTensors,this.state.activeProfile.kernels=[],this.state.activeProfile.result=t(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max.apply(Math,this.state.activeProfile.kernels.map(function(t){return t.totalBytesSnapshot})),this.state.activeProfile.newBytes=this.state.numBytes-e,this.state.activeProfile.newTensors=this.state.numTensors-n,[2,this.state.activeProfile]})})},t.prototype.isTapeOn=function(){return this.state.gradientDepth>0&&0===this.state.kernelDepth},t.prototype.addTapeNode=function(t,e,n,i,r){var o=this,s={id:this.state.nextTapeNodeId++,kernelName:t,inputs:e,outputs:n,saved:r},a=function(t){return d.get(t)}(t);null!=a&&(i=a.gradFunc),null!=i&&(s.gradient=function(t){return t=t.map(function(t,e){if(null==t){var i=n[e],r=et(i.size,i.dtype);return o.makeTensor(r,i.shape,i.dtype)}return t}),i(t.length>1?t:t[0],r)}),this.state.activeTape.push(s)},t.prototype.keep=function(t){return t.kept=!0,t},t.prototype.startTape=function(){0===this.state.gradientDepth&&(this.state.activeTape=[]),this.state.gradientDepth++},t.prototype.endTape=function(){this.state.gradientDepth--},t.prototype.startScope=function(t){var e={track:[],name:"unnamed scope",id:this.state.nextScopeId++};t&&(e.name=t),this.state.scopeStack.push(e),this.state.activeScope=e},t.prototype.endScope=function(t){for(var e=this,n=At(t),i=new Set(n.map(function(t){return t.id})),r=0;r0,function(){return"gradients() received an empty list of xs."}),null!=n&&"float32"!==n.dtype)throw new Error("dy must have 'float32' dtype, but has '"+n.dtype+"'");var o=this.scopedRun(function(){return r.startTape()},function(){return r.endTape()},function(){return r.tidy("forward",t)});C(o instanceof bt,function(){return"The result y returned by f() must be a tensor."});var s=function(t,e,n){for(var i={},r={},o=0;o=0;o--)for(s=(f=t[o]).inputs,c=0;c0)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",function(){var t,i,a={};a[o.id]=null==n?(i=tt(x(t=o.shape),"float32"),Pt.makeTensor(i,t,"float32")):n,function(t,e,n){for(var i=function(i){var r=e[i],o=[];if(r.outputs.forEach(function(e){var n=t[e.id];null!=n?o.push(n):o.push(null)}),null==r.gradient)throw new Error("Cannot compute gradient: gradient function not found for "+r.kernelName+".");var s=r.gradient(o),a=function(e){if(!(e in s))throw new Error("Cannot backprop through input "+e+". Available gradients found: "+Object.keys(s)+".");var i=n(function(){return s[e]()});if("float32"!==i.dtype)throw new Error("Error in gradient for op "+r.kernelName+". The gradient of input "+e+" must have 'float32' dtype, but has '"+i.dtype+"'");var o=r.inputs[e];if(!I(i.shape,o.shape))throw new Error("Error in gradient for op "+r.kernelName+". The gradient of input '"+e+"' has shape '"+i.shape+"', which does not match the shape of the input '"+o.shape+"'");if(null==t[o.id])t[o.id]=i;else{var a=t[o.id];t[o.id]=a.add(i),a.dispose()}};for(var l in r.inputs)a(l)},r=e.length-1;r>=0;r--)i(r)}(a,s,function(t){return r.tidy(t)});var l=e.map(function(t){return a[t.id]});return 0===r.state.gradientDepth&&(r.state.activeTape.forEach(function(t){for(var e=0,n=t.saved;en||e>n)throw i="["+t+"x"+e+"]",new Error("Requested texture size "+i+" greater than WebGL maximum on this browser / GPU ["+n+"x"+n+"].")}function fe(t,e){return Se(t,e,function(){return t.createFramebuffer()},"Unable to create WebGLFramebuffer.")}function ge(t,e,n,i,r,o,s,a){var l=t.getAttribLocation(n,i);return-1!==l&&(Jt(t,e,function(){return t.bindBuffer(t.ARRAY_BUFFER,r)}),Jt(t,e,function(){return t.vertexAttribPointer(l,o,t.FLOAT,!1,s,a)}),Jt(t,e,function(){return t.enableVertexAttribArray(l)}),!0)}function me(t,e,n,i){we(t,i),Jt(t,e,function(){return t.activeTexture(t.TEXTURE0+i)}),Jt(t,e,function(){return t.bindTexture(t.TEXTURE_2D,n)})}function ve(t,e,n,i){return Se(t,e,function(){return t.getUniformLocation(n,i)},'uniform "'+i+'" not present in program.')}function _e(t,e,n){return t.getUniformLocation(e,n)}function ye(t,e,n,i,r,o){Jt(t,e,function(){return me(t,e,i,o)}),Jt(t,e,function(){return t.uniform1i(r,o)})}function be(t,e,n,i){Jt(t,e,function(){return t.bindFramebuffer(t.FRAMEBUFFER,i)}),Jt(t,e,function(){return t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,n,0)})}function Te(t,e,n){Jt(t,e,function(){return t.bindFramebuffer(t.FRAMEBUFFER,n)}),Jt(t,e,function(){return t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,null,0)})}function Ee(t){var e=t.checkFramebufferStatus(t.FRAMEBUFFER);if(e!==t.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+Ce(t,e))}function Ce(t,e){switch(e){case t.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case t.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case t.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return"FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case t.FRAMEBUFFER_UNSUPPORTED:return"FRAMEBUFFER_UNSUPPORTED";default:return"unknown error "+e}}function Se(t,e,n,i){var r=Jt(t,e,function(){return n()});if(null==r)throw new Error(i);return r}function we(t,e){var n=t.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,i=e+t.TEXTURE0;if(in)throw new Error("textureUnit must be in [gl.TEXTURE0, gl.TEXTURE"+n+"].")}function ke(t,e){return void 0===e&&(e=2),x(t.slice(0,t.length-e))}function xe(t){if(0===t.length)throw Error("Cannot get rows and columns of an empty shape array.");return[t.length>1?t[t.length-2]:1,t[t.length-1]]}function Ie(t){var e=[1,1,1];return 0===t.length||1===t.length&&1===t[0]||(e=[ke(t)].concat(xe(t))),e}function Re(t,e){var n;void 0===e&&(e=!1);var i=c().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(e&&(i*=2,1===(t=t.map(function(e,n){return n>=t.length-2?T(t[n]):t[n]})).length&&(t=[2,t[0]])),2!==t.length){var r=P(t);t=r.newShape}var o=x(t);if(t.length<=1&&o<=i)return[1,o];if(2===t.length&&t[0]<=i&&t[1]<=i)return t;if(3===t.length&&t[0]*t[1]<=i&&t[2]<=i)return[t[0]*t[1],t[2]];if(3===t.length&&t[0]<=i&&t[1]*t[2]<=i)return[t[0],t[1]*t[2]];if(4===t.length&&t[0]*t[1]*t[2]<=i&&t[3]<=i)return[t[0]*t[1]*t[2],t[3]];if(4===t.length&&t[0]<=i&&t[1]*t[2]*t[3]<=i)return[t[0],t[1]*t[2]*t[3]];if(e){var s=ke(t),a=2,l=2;return t.length&&(a=(n=xe(t))[0],l=n[1]),D(o=s*(a/2)*(l/2)).map(function(t){return 2*t})}return D(o)}function Oe(t){return t%2==0}function De(t,e){if(I(t=t.slice(-2),e=e.slice(-2)))return!0;if(!t.length||!e.length)return!0;if(0===t[0]||0===t[1]||0===e[0]||0===e[1])return!0;if(t.length!==e.length){var n=t.slice(-1)[0],i=e.slice(-1)[0];if(n===i)return!0;if(Oe(n)&&Oe(i)&&(1===t[0]||1===e[0]))return!0}return t[1]===e[1]&&Oe(t[0])&&Oe(e[0])}function Ae(t){if(null==re){var e=zt(t);re=e.getParameter(e.MAX_TEXTURE_SIZE)}return re}function Me(t){if(null==oe){var e=zt(t);oe=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,oe)}function Ne(t){if(0===t)return 0;var e=zt(t);return Le(e,"EXT_disjoint_timer_query_webgl2")&&2===t?2:Le(e,"EXT_disjoint_timer_query")?1:0}function Le(t,e){return null!=t.getExtension(e)}function Pe(t){try{if(null!=zt(t))return!0}catch(t){return!1}return!1}function Be(t){if(0===t)return!1;var e=zt(t);if(1===t){if(!Le(e,"OES_texture_float"))return!1}else if(!Le(e,"EXT_color_buffer_float"))return!1;return Ue(e)}function Fe(t){if(0===t)return!1;var e=zt(t);return 1!==t?Le(e,"EXT_color_buffer_float")?Ue(e):!!Le(e,"EXT_color_buffer_half_float")&&function(t,e){var n=Kt(t,e),i=t.createTexture();t.bindTexture(t.TEXTURE_2D,i),t.texImage2D(t.TEXTURE_2D,0,n.internalFormatHalfFloat,1,1,0,n.textureFormatFloat,n.textureTypeHalfFloat,null);var r=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,r),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,i,0);var o=t.checkFramebufferStatus(t.FRAMEBUFFER)===t.FRAMEBUFFER_COMPLETE;return t.bindTexture(t.TEXTURE_2D,null),t.bindFramebuffer(t.FRAMEBUFFER,null),t.deleteTexture(i),t.deleteFramebuffer(r),o}(e,e.getExtension("EXT_color_buffer_half_float")):!!Le(e,"OES_texture_float")&&!!Le(e,"WEBGL_color_buffer_float")&&Ue(e)}function Ue(t){var e=Kt(t),n=t.createTexture();t.bindTexture(t.TEXTURE_2D,n),t.texImage2D(t.TEXTURE_2D,0,e.internalFormatFloat,1,1,0,e.textureFormatFloat,e.textureTypeFloat,null);var i=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,i),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,n,0);var r=t.checkFramebufferStatus(t.FRAMEBUFFER)===t.FRAMEBUFFER_COMPLETE;return t.bindTexture(t.TEXTURE_2D,null),t.bindFramebuffer(t.FRAMEBUFFER,null),t.deleteTexture(n),t.deleteFramebuffer(i),r}function Ve(t){return 2===t&&null!=zt(t).fenceSync}var He=Object.freeze({callAndCheck:Jt,canBeRepresented:Qt,getWebGLErrorMessage:te,getExtensionOrThrow:ee,createVertexShader:ne,createFragmentShader:ie,createProgram:ae,linkProgram:le,validateProgram:ue,createStaticVertexBuffer:ce,createStaticIndexBuffer:he,getNumChannels:function(){return 2===c().getNumber("WEBGL_VERSION")?1:4},createTexture:pe,validateTextureSize:de,createFramebuffer:fe,bindVertexBufferToProgramAttribute:ge,bindTextureUnit:me,unbindTextureUnit:function(t,e,n){we(t,n),Jt(t,e,function(){return t.activeTexture(t.TEXTURE0+n)}),Jt(t,e,function(){return t.bindTexture(t.TEXTURE_2D,null)})},getProgramUniformLocationOrThrow:ve,getProgramUniformLocation:_e,bindTextureToProgramUniformSampler:ye,bindCanvasToFramebuffer:function(t,e){Jt(t,e,function(){return t.bindFramebuffer(t.FRAMEBUFFER,null)}),Jt(t,e,function(){return t.viewport(0,0,t.canvas.width,t.canvas.height)}),Jt(t,e,function(){return t.scissor(0,0,t.canvas.width,t.canvas.height)})},bindColorTextureToFramebuffer:be,unbindColorTextureFromFramebuffer:Te,validateFramebuffer:Ee,getFramebufferErrorMessage:Ce,getBatchDim:ke,getRowsCols:xe,getShapeAs3D:Ie,getTextureShapeFromLogicalShape:Re,isReshapeFree:De,getWebGLMaxTextureSize:Ae,resetMaxTextureSize:function(){re=null},resetMaxTexturesInShader:function(){oe=null},getMaxTexturesInShader:Me,getWebGLDisjointQueryTimerVersion:Ne,hasExtension:Le,isWebGLVersionEnabled:Pe,isCapableOfRenderingToFloatTexture:Be,isDownloadFloatTextureEnabled:Fe,isWebGLFenceEnabled:Ve}),We=c();function Ge(t){c().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(t+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}function je(t,e){return Pt.tidy(t,e)}function ze(t){At(t).forEach(function(t){return t.dispose()})}function $e(){for(var t=[],e=0;e0,function(){return"Element arr["+i.join("][")+"] should be a primitive, but is an array of "+e.length+" elements"}),C(e.length===n[0],function(){return"Element arr["+i.join("][")+"] should have "+n[0]+" elements, but has "+e.length+" elements"});for(var r=n.slice(1),o=0;o=0&&(r=i),Ye(i,r,e,n),null==t||!W(t)&&!Array.isArray(t)&&"number"!=typeof t&&"boolean"!=typeof t&&"string"!=typeof t){var o=null==t?"null":t.constructor.name;throw new Error("Argument '"+e+"' passed to '"+n+"' must be a Tensor or TensorLike, but got '"+o+"'")}var s=Xe(t,r);W(t)||Array.isArray(t)||(t=[t]);var a="string"!==r?Z(t,r,c().getBool("DEBUG")):k(t,[],!0);return Pt.makeTensor(a,s,r)}function Je(t,e,n,i){if(void 0===i&&(i="numeric"),!Array.isArray(t))throw new Error("Argument "+e+" passed to "+n+" must be a `Tensor[]` or `TensorLike[]`");return t.map(function(t,i){return Ke(t,e+"["+i+"]",n)},i)}function qe(t,e){for(var n=0;n=0&&e0}),We.registerFlag("WEBGL_VERSION",function(){return Pe(2)?2:Pe(1)?1:0}),We.registerFlag("WEBGL_BUFFER_SUPPORTED",function(){return 2===We.get("WEBGL_VERSION")}),We.registerFlag("WEBGL_CPU_FORWARD",function(){return!0}),We.registerFlag("WEBGL_FORCE_F16_TEXTURES",function(){return!1}),We.registerFlag("WEBGL_PACK",function(){return We.getBool("HAS_WEBGL")}),We.registerFlag("WEBGL_PACK_NORMALIZATION",function(){return We.getBool("WEBGL_PACK")}),We.registerFlag("WEBGL_PACK_CLIP",function(){return We.getBool("WEBGL_PACK")}),We.registerFlag("WEBGL_PACK_DEPTHWISECONV",function(){return!1}),We.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",function(){return We.getBool("WEBGL_PACK")}),We.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",function(){return We.getBool("WEBGL_PACK")}),We.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",function(){return We.getBool("WEBGL_PACK")}),We.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",function(){return We.getBool("WEBGL_PACK")}),We.registerFlag("WEBGL_PACK_REDUCE",function(){return We.getBool("WEBGL_PACK")}),We.registerFlag("WEBGL_LAZILY_UNPACK",function(){return We.getBool("WEBGL_PACK")}),We.registerFlag("WEBGL_CONV_IM2COL",function(){return We.getBool("WEBGL_PACK")}),We.registerFlag("WEBGL_MAX_TEXTURE_SIZE",function(){return Ae(We.getNumber("WEBGL_VERSION"))}),We.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",function(){return Me(We.getNumber("WEBGL_VERSION"))}),We.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",function(){var t=We.getNumber("WEBGL_VERSION");return 0===t?0:Ne(t)}),We.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",function(){return We.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&(t=navigator.userAgent||navigator.vendor||window.opera,!(/(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))));var t}),We.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",function(){return Be(We.getNumber("WEBGL_VERSION"))}),We.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",function(){return!We.getBool("WEBGL_FORCE_F16_TEXTURES")&&We.getBool("WEBGL_RENDER_FLOAT32_CAPABLE")}),We.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",function(){return Fe(We.getNumber("WEBGL_VERSION"))}),We.registerFlag("WEBGL_FENCE_API_ENABLED",function(){return Ve(We.getNumber("WEBGL_VERSION"))}),We.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",function(){return We.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0}),yt=Ge;var un=ln({complex_:function(t,e){var n=Ke(t,"real","complex"),i=Ke(e,"imag","complex");return S(n.shape,i.shape,"real and imag shapes, "+n.shape+" and "+i.shape+", must match in call to tf.complex()."),Pt.runKernelFunc(function(t){return t.complex(n,i)},{$real:n,$imag:i})}}),cn=ln({real_:function(t){var e=Ke(t,"input","real");return Pt.runKernelFunc(function(t){return t.real(e)},{$input:e})}}),hn=ln({imag_:function(t){var e=Ke(t,"input","imag");return Pt.runKernelFunc(function(t){return t.imag(e)},{$input:e})}});function pn(t,e,n){return dn(t,e,Xe(t,n),n)}function dn(t,e,n,i){if(null==i&&(i=Y(t)),"complex64"===i)throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!W(t)&&!Array.isArray(t)&&"number"!=typeof t&&"boolean"!=typeof t&&"string"!=typeof t)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!=e){it(e);var r=x(e),o=x(n);C(r===o,function(){return"Based on the provided shape, ["+e+"], the tensor should have "+r+" values but has "+o});for(var s=0;s1)return bn([0],i);var r=et(Math.abs(Math.ceil((e-t)/n)),i);e=1,function(){return"Pass at least one tensor to concat"});var n=Je(t,"tensors","concat");"complex64"===n[0].dtype&&n.forEach(function(t){if("complex64"!==t.dtype)throw new Error("Cannot concatenate complex64 tensors with a tensor\n with dtype "+t.dtype+". ")}),e=L(e,n[0].shape)[0];var i=an(n.map(function(t){return t.shape}),e);if(0===x(i))return pn([],i);if(1===(n=n.filter(function(t){return t.size>0})).length)return n[0];var r=n.map(function(t){return t.shape});sn(r,e);var o=n,s={axis:e};return Pt.runKernelFunc(function(t){return t.concat(n,e)},o,function(t){var n=r.map(function(t){return t[e]});return On(t,n,e).map(function(t){return function(){return t}})},"Concat",s)}}),kn=ln({concat1d_:function(t){return wn(t,0)}}),xn=ln({concat2d_:function(t,e){return wn(t,e)}}),In=ln({concat3d_:function(t,e){return wn(t,e)}}),Rn=ln({concat4d_:function(t,e){return wn(t,e)}}),On=ln({split_:function(t,e,n){void 0===n&&(n=0);var i,r=Ke(t,"x","split");return n=L(n,r.shape)[0],"number"==typeof e?(C(r.shape[n]%e==0,function(){return"Number of splits must evenly divide the axis."}),i=new Array(e).fill(r.shape[n]/e)):(C(r.shape[n]===e.reduce(function(t,e){return t+e}),function(){return"The sum of sizes must match the size of the axis dimension."}),i=e),Pt.runKernelFunc(function(t){return t.split(r,i,n)},{$x:r},function(t){return{$x:function(){return wn(t,n)}}})}});function Dn(t,e){return t(e={exports:{}},e.exports),e.exports}"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==t||"undefined"!=typeof self&&self;var An=Dn(function(t){!function(t,e,n){function i(t,e){return e.c=t.c,e.s0=t.s0,e.s1=t.s1,e.s2=t.s2,e}function r(t,e){var n=new function(t){var e,n=this,i=(e=4022871197,function(t){t=t.toString();for(var n=0;n>>0,e=(i*=e)>>>0,e+=4294967296*(i-=e)}return 2.3283064365386963e-10*(e>>>0)});n.next=function(){var t=2091639*n.s0+2.3283064365386963e-10*n.c;return n.s0=n.s1,n.s1=n.s2,n.s2=t-(n.c=0|t)},n.c=1,n.s0=i(" "),n.s1=i(" "),n.s2=i(" "),n.s0-=i(t),n.s0<0&&(n.s0+=1),n.s1-=i(t),n.s1<0&&(n.s1+=1),n.s2-=i(t),n.s2<0&&(n.s2+=1),i=null}(t),r=e&&e.state,o=n.next;return o.int32=function(){return 4294967296*n.next()|0},o.double=function(){return o()+1.1102230246251565e-16*(2097152*o()|0)},o.quick=o,r&&("object"==typeof r&&i(r,n),o.state=function(){return i(n,{})}),o}e&&e.exports?e.exports=r:this.alea=r}(0,t)}),Mn=Dn(function(t){!function(t,e,n){function i(t,e){return e.x=t.x,e.y=t.y,e.z=t.z,e.w=t.w,e}function r(t,e){var n=new function(t){var e=this,n="";e.x=0,e.y=0,e.z=0,e.w=0,e.next=function(){var t=e.x^e.x<<11;return e.x=e.y,e.y=e.z,e.z=e.w,e.w^=e.w>>>19^t^t>>>8},t===(0|t)?e.x=t:n+=t;for(var i=0;i>>0)/4294967296};return o.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},o.int32=n.next,o.quick=o,r&&("object"==typeof r&&i(r,n),o.state=function(){return i(n,{})}),o}e&&e.exports?e.exports=r:this.xor128=r}(0,t)}),Nn=Dn(function(t){!function(t,e,n){function i(t,e){return e.x=t.x,e.y=t.y,e.z=t.z,e.w=t.w,e.v=t.v,e.d=t.d,e}function r(t,e){var n=new function(t){var e=this,n="";e.next=function(){var t=e.x^e.x>>>2;return e.x=e.y,e.y=e.z,e.z=e.w,e.w=e.v,(e.d=e.d+362437|0)+(e.v=e.v^e.v<<4^t^t<<1)|0},e.x=0,e.y=0,e.z=0,e.w=0,e.v=0,t===(0|t)?e.x=t:n+=t;for(var i=0;i>>4),e.next()}(t),r=e&&e.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},o.int32=n.next,o.quick=o,r&&("object"==typeof r&&i(r,n),o.state=function(){return i(n,{})}),o}e&&e.exports?e.exports=r:this.xorwow=r}(0,t)}),Ln=Dn(function(t){!function(t,e,n){function i(t,e){return e.x=t.x.slice(),e.i=t.i,e}function r(t,e){null==t&&(t=+new Date);var n=new function(t){var e=this;e.next=function(){var t,n,i=e.x,r=e.i;return t=i[r],n=(t^=t>>>7)^t<<24,n^=(t=i[r+1&7])^t>>>10,n^=(t=i[r+3&7])^t>>>3,n^=(t=i[r+4&7])^t<<7,t=i[r+7&7],n^=(t^=t<<13)^t<<9,i[r]=n,e.i=r+1&7,n},function(t,e){var n,i=[];if(e===(0|e))i[0]=e;else for(e=""+e,n=0;n0;--n)t.next()}(e,t)}(t),r=e&&e.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},o.int32=n.next,o.quick=o,r&&(r.x&&i(r,n),o.state=function(){return i(n,{})}),o}e&&e.exports?e.exports=r:this.xorshift7=r}(0,t)}),Pn=Dn(function(t){!function(t,e,n){function i(t,e){return e.i=t.i,e.w=t.w,e.X=t.X.slice(),e}function r(t,e){null==t&&(t=+new Date);var n=new function(t){var e=this;e.next=function(){var t,n,i=e.w,r=e.X,o=e.i;return e.w=i=i+1640531527|0,n=r[o+34&127],t=r[o=o+1&127],n^=n<<13,t^=t<<17,n^=n>>>15,t^=t>>>12,n=r[o]=n^t,e.i=o,n+(i^i>>>16)|0},function(t,e){var n,i,r,o,s,a=[],l=128;for(e===(0|e)?(i=e,e=null):(e+="\0",i=0,l=Math.max(l,e.length)),r=0,o=-32;o>>15,i^=i<<4,i^=i>>>13,o>=0&&(s=s+1640531527|0,r=0==(n=a[127&o]^=i+s)?r+1:0);for(r>=128&&(a[127&(e&&e.length||0)]=-1),r=127,o=512;o>0;--o)i=a[r+34&127],n=a[r=r+1&127],i^=i<<13,n^=n<<17,i^=i>>>15,n^=n>>>12,a[r]=i^n;t.w=s,t.X=a,t.i=r}(e,t)}(t),r=e&&e.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},o.int32=n.next,o.quick=o,r&&(r.X&&i(r,n),o.state=function(){return i(n,{})}),o}e&&e.exports?e.exports=r:this.xor4096=r}(0,t)}),Bn=Dn(function(t){!function(t,e,n){function i(t,e){return e.a=t.a,e.b=t.b,e.c=t.c,e.d=t.d,e}function r(t,e){var n=new function(t){var e=this,n="";e.next=function(){var t=e.b,n=e.c,i=e.d,r=e.a;return t=t<<25^t>>>7^n,n=n-i|0,i=i<<24^i>>>8^r,r=r-t|0,e.b=t=t<<20^t>>>12^n,e.c=n=n-i|0,e.d=i<<16^n>>>16^r,e.a=r-t|0},e.a=0,e.b=0,e.c=-1640531527,e.d=1367130551,t===Math.floor(t)?(e.a=t/4294967296|0,e.b=0|t):n+=t;for(var i=0;i>>0)/4294967296};return o.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},o.int32=n.next,o.quick=o,r&&("object"==typeof r&&i(r,n),o.state=function(){return i(n,{})}),o}e&&e.exports?e.exports=r:this.tychei=r}(0,t)}),Fn=Dn(function(t){!function(e,i){var r,o=this,s=256,a=6,l="random",u=i.pow(s,a),c=i.pow(2,52),h=2*c,p=s-1;function d(t,n,p){var d=[],_=m(function t(e,n){var i,r=[],o=typeof e;if(n&&"object"==o)for(i in e)try{r.push(t(e[i],n-1))}catch(t){}return r.length?r:"string"==o?e:e+"\0"}((n=1==n?{entropy:!0}:n||{}).entropy?[t,v(e)]:null==t?function(){try{var t;return r&&(t=r.randomBytes)?t=t(s):(t=new Uint8Array(s),(o.crypto||o.msCrypto).getRandomValues(t)),v(t)}catch(t){var n=o.navigator,i=n&&n.plugins;return[+new Date,o,i,o.screen,v(e)]}}():t,3),d),y=new f(d),b=function(){for(var t=y.g(a),e=u,n=0;t=h;)t/=2,e/=2,n>>>=1;return(t+n)/e};return b.int32=function(){return 0|y.g(4)},b.quick=function(){return y.g(4)/4294967296},b.double=b,m(v(y.S),e),(n.pass||p||function(t,e,n,r){return r&&(r.S&&g(r,y),t.state=function(){return g(y,{})}),n?(i[l]=t,e):t})(b,_,"global"in n?n.global:this==i,n.state)}function f(t){var e,n=t.length,i=this,r=0,o=i.i=i.j=0,a=i.S=[];for(n||(t=[n++]);r=1||0===s);var a=Math.sqrt(-2*Math.log(s)/s);e=this.mean+this.stdDev*r*a,n=this.mean+this.stdDev*o*a,this.truncated&&!this.isValidTruncated(e)||(i=!0)}return this.truncated&&!this.isValidTruncated(n)||(this.nextVal=this.convertValue(n)),this.convertValue(e)},t.prototype.convertValue=function(t){return null==this.dtype||"float32"===this.dtype?t:Math.round(t)},t.prototype.isValidTruncated=function(t){return t<=this.upper&&t>=this.lower},t}(),Hn=function(){function t(t,e,n,i){this.alpha=t,this.beta=1/e,this.dtype=n;var r=i||Math.random();this.randu=Un(r.toString()),this.randn=new Vn(0,1,n,!1,this.randu()),this.d=t<1?t+2/3:t-1/3,this.c=1/Math.sqrt(9*this.d)}return t.prototype.nextValue=function(){for(var t,e,n,i,r,o;;){do{i=this.randn.nextValue(),o=1+this.c*i}while(o<=0);if(o*=o*o,e=1-.331*(t=i*i)*t,n=.5*t+this.d*(1-o+Math.log(o)),(r=this.randu())=1+e.length,function(){return"input rank is "+i.rank+" but should be > than blockShape.length "+e.length}),C(n.length===e.length,function(){return"crops.length is "+n.length+" but should be equal to blockShape.length "+e.length}),C(i.shape[0]%r==0,function(){return"input tensor batch is "+i.shape[0]+" but is not divisible by the product of the elements of blockShape "+e.join(" * ")+" === "+r}),Pt.runKernelFunc(function(t){return t.batchToSpaceND(i,e,n)},{$x:i},function(t){return{$x:function(){return t.spaceToBatchND(e,n)}}})}}),zn=ln({broadcastTo_:function(t,e){var n=Ke(t,"broadcastTo","x"),i=n.shape;if(e.some(function(t){return!(t>0)||t%1!=0}))throw new Error("broadcastTo(): Invalid broadcast shape ["+e+"].");if(e.lengthn.rank){for(var r=n.shape.slice();r.length=0;s--)if(n.shape[s]===e[s])o[s]=1;else if(1!==n.shape[s])throw new Error("broadcastTo(): ["+i+"] cannot be broadcast to ["+e+"].");var a=o.map(function(t,e){return t>1?e:-1}).filter(function(t){return t>=0});return 0===a.length?n.clone():Pt.runKernelFunc(function(t){return t.tile(n,o)},{input:n},function(t){return{input:function(){return t.sum(a,!0)}}})}}),$n=ln({cast_:function(t,e){var n=Ke(t,"x","cast");if(!V(e))throw new Error("Failed to cast to unknown dtype "+e);if("string"===e&&"string"!==n.dtype||"string"!==e&&"string"===n.dtype)throw new Error("Only strings can be casted to strings");var i={dtype:e};return Pt.runKernelFunc(function(t){return t.cast(n,e)},{x:n},function(t){return{x:function(){return t.clone()}}},"Cast",i)}}),Xn=ln({clone_:function(t){var e=Ke(t,"x","clone",null);return Pt.runKernelFunc(function(){return Pt.makeTensorFromDataId(e.dataId,e.shape,e.dtype)},{$x:e},function(t){return{$x:function(){return t.toFloat()}}})}}),Yn=ln({cumsum_:function(t,e,n,i){void 0===e&&(e=0),void 0===n&&(n=!1),void 0===i&&(i=!1);var r=Ke(t,"x","cumsum"),o=nn([e|=0],r.rank),s=r;null!=o&&(s=r.transpose(o));var a=on(1,r.rank)[0],l=Pt.runKernelFunc(function(t){return t.cumsum(s,a,n,i)},{permutedX:s},function(t){return{permutedX:function(){return t.cumsum(e,n,!i)}}});return null!=o&&(l=l.transpose(o)),l}}),Kn=ln({depthToSpace_:function(t,e,n){void 0===n&&(n="NHWC");var i=Ke(t,"x","depthToSpace"),r="NHWC"===n?i.shape[1]:i.shape[2],o="NHWC"===n?i.shape[2]:i.shape[3],s="NHWC"===n?i.shape[3]:i.shape[1];return C(r*e>=0,function(){return"Negative dimension size caused by overflow when multiplying\n "+r+" and "+e+" for depthToSpace with input shape\n "+i.shape}),C(o*e>=0,function(){return"Negative dimension size caused by overflow when multiplying\n "+o+" and "+e+" for depthToSpace with input shape\n "+i.shape}),C(s%(e*e)==0,function(){return"Dimension size must be evenly divisible by "+e*e+" but is "+s+" for depthToSpace with input shape "+i.shape}),Pt.runKernelFunc(function(t){return t.depthToSpace(i,e,n)},{$x:i})}}),Jn=ln({expandDims_:function(t,e){void 0===e&&(e=0);var n=Ke(t,"x","expandDims",null);C(e<=n.rank,function(){return"Axis must be <= rank of the tensor"});var i=n.shape.slice();return e<0&&(C(-(n.rank+1)<=e,function(){return"Axis must be in the interval ["+-(n.rank+1)+", "+n.rank+"]"}),e=n.rank+e+1),i.splice(e,0,1),ui(n,i)}}),qn=ln({eye_:function(t,e,n,i){void 0===i&&(i="float32"),null==e&&(e=t);for(var r=Gn([t,e],i),o=t<=e?t:e,s=0;s2)throw new Error("Rank of probabilities must be 1 or 2, but is "+s);n=n||Math.random();var a=1===s?r.as2D(1,-1):r,l=Pt.runKernelFunc(function(t){return t.multinomial(a,i,e,n)},{logits2D:a});return 1===s?l.as1D():l}}),Qn=ln({oneHot_:function(t,e,n,i){if(void 0===n&&(n=1),void 0===i&&(i=0),e<2)throw new Error("Error in oneHot: depth must be >=2, but it is "+e);var r=Ke(t,"indices","oneHot","int32"),o=r.shape.concat([e]);return r=r.flatten(),Pt.runKernelFunc(function(t){return t.oneHot(r,e,n,i)},{$indices:r},function(t){return{$indices:function(){return bn(r.shape,"float32")}}}).reshape(o)}}),ti=ln({pad_:function(t,e,n){void 0===n&&(n=0);var i=Ke(t,"x","pad");if(0===i.rank)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");var r={paddings:e,constantValue:n};return Pt.runKernelFunc(function(t){return t.pad(i,e,n)},{x:i},function(t){var n=e.map(function(t){return t[0]});return{x:function(){return t.slice(n,i.shape)}}},"PadV2",r)}}),ei=ln({pad1d_:function(t,e,n){return void 0===n&&(n=0),C(2===e.length,function(){return"Invalid number of paddings. Must be length of 2."}),ti(t,[e],n)}}),ni=ln({pad2d_:function(t,e,n){return void 0===n&&(n=0),C(2===e.length&&2===e[0].length&&2===e[1].length,function(){return"Invalid number of paddings. Must be length of 2 each."}),ti(t,e,n)}}),ii=ln({pad3d_:function(t,e,n){return void 0===n&&(n=0),C(3===e.length&&2===e[0].length&&2===e[1].length&&2===e[2].length,function(){return"Invalid number of paddings. Must be length of 2 each."}),ti(t,e,n)}}),ri=ln({pad4d_:function(t,e,n){return void 0===n&&(n=0),C(4===e.length&&2===e[0].length&&2===e[1].length&&2===e[2].length&&2===e[3].length,function(){return"Invalid number of paddings. Must be length of 2 each."}),ti(t,e,n)}}),oi=ln({rand_:function(t,e,n){var i=x(t),r=null;if(null==n||"float32"===n)r=new Float32Array(i);else if("int32"===n)r=new Int32Array(i);else{if("bool"!==n)throw new Error("Unknown data type "+n);r=new Uint8Array(i)}for(var o=0;o=1+e.length,function(){return"input rank "+i.rank+" should be > than [blockShape] "+e.length}),C(n.length===e.length,function(){return"paddings.shape[0] "+n.length+" must be equal to [blockShape] "+e.length}),C(i.shape.reduce(function(t,i,r){return r>0&&r<=e.length?t&&(i+n[r-1][0]+n[r-1][1])%e[r-1]==0:t},!0),function(){return"input spatial dimensions "+i.shape.slice(1)+" with paddings "+n.toString()+" must be divisible by blockShapes "+e.toString()}),Pt.runKernelFunc(function(t){return t.spaceToBatchND(i,e,n)},{$x:i},function(t){return{$x:function(){return t.batchToSpaceND(e,n)}}})}}),hi=ln({squeeze_:function(t,e){var n=Ke(t,"x","squeeze");return ui(n,P(n.shape,e).newShape)}}),pi=ln({stack_:function(t,e){void 0===e&&(e=0);var n=Je(t,"tensors","stack");if(C(n.length>=1,function(){return"Pass at least one tensor to tf.stack"}),1===n.length)return n[0].expandDims(e);var i=n[0].rank,r=n[0].shape,o=n[0].dtype;C(e<=i,function(){return"Axis must be <= rank of the tensor"}),n.forEach(function(t){S(r,t.shape,"All tensors passed to stack must have matching shapes")}),n.forEach(function(t){C(o===t.dtype,function(){return"All tensors passed to stack must have matching dtypes"})});var s=n.map(function(t){return t.expandDims(e)});return wn(s,e)}}),di=ln({tile_:function(t,e){var n=Ke(t,"x","tile",null);C(n.rank===e.length,function(){return"Error in transpose: rank of input "+n.rank+" must match length of reps "+e+"."});var i=[n],r={reps:e};return Pt.runKernelFunc(function(t,i){var r=t.tile(n,e);return i([n]),r},{x:n},function(t,n){var i=n[0];return{x:function(){var n=Sn(i);if(1===i.rank)for(var r=0;r=-n.shape.length&&e=2*e+1||r%2==1?s.push(r):o.push(r);i.push.apply(i,o),i.push(0),i.push.apply(i,s)}return i}function _i(t,e,n,i){void 0===i&&(i=!0);var r=[];i?r.push(t[0]/n):r.push(t[0]*n);for(var o=1;ot.rank)throw new Error("index innermost dimension length must be <= tensor rank; saw: "+e.shape[e.rank-1]+" vs. "+t.rank);if(0===t.size)throw new Error("Requested more than 0 entries, but input is empty. Input shape: "+t.shape+".");for(var n=e.shape,i=n[n.length-1],r=1,o=0;o1?e.shape[e.rank-1]:1,r=e.rank>1?e.rank-1:1,o="Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: "+n.shape+", indices.shape: "+e.shape+", shape: "+t+", sliceDim: "+i+", and batchDim: "+r+".";if(n.rank1?e.shape[i-1]:1,o=n.length,s=1,a=r;a0;)1&t&&e.push(n),t/=2,n++;return e}function Ri(t,e,n){for(var i=[],r=0;r0?Number.MIN_SAFE_INTEGER:Number.MAX_SAFE_INTEGER);var a=i[r];return o<0&&(o+=a),b(0,o,a-1)}function Di(t,e,n,i,r){var o=e[r],s=n[r]||1;(t&1<0?Number.MAX_SAFE_INTEGER:Number.MIN_SAFE_INTEGER);var a=i[r];return o<0&&(o+=a),s>0?b(0,o,a):b(-1,o,a-1)}function Ai(t,e,n){for(var i=n.length,r=0;r1){i=r;break}for(r=i+1;r0||n[r]!==t[r])return!1;return!0}function Mi(t,e){for(var n=t.length>0?t[t.length-1]:1,i=0;i1&&1===s&&i.unshift(o)}return i}function Hi(t,e){for(var n=[],i=0;i1)&&n.unshift(o)}return n}function Wi(t,e){for(var n=[],i=Math.max(t.length,e.length),r=0;r>>1)]);a>0?i=o+1:(r=o,s=!a)}return s?i:-i-1}(t,e,n||ur)}(t,e,n),r=i<0?-(i+1):i;t.splice(r,0,e)}function ur(t,e){return t>e?1:tr}).sort(gr),u=o>0?-.5/o:0,c=[],h=[];c.length0;){var p=l.pop(),d=p.score,f=p.boxIndex,g=p.suppressBeginIndex;if(d=g;--v){var _=dr(t,f,c[v]);if(_>=i){m=!0;break}if(p.score=p.score*fr(i,u,_),p.score<=r)break}p.suppressBeginIndex=c.length,m||(p.score===d?(c.push(f),h.push(p.score)):p.score>r&&lr(l,p,gr))}var y=c.length;return a&&(c.fill(0,y),h.fill(0,y)),{selectedIndices:gn(c,"int32"),selectedScores:gn(h,"float32"),numValidOutputs:fn(y,"int32")}}function dr(t,e,n){var i=t.subarray(4*e,4*e+4),r=t.subarray(4*n,4*n+4),o=Math.min(i[0],i[2]),s=Math.min(i[1],i[3]),a=Math.max(i[0],i[2]),l=Math.max(i[1],i[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=(a-o)*(l-s),f=(h-u)*(p-c);if(d<=0||f<=0)return 0;var g=Math.max(o,u),m=Math.max(s,c),v=Math.min(a,h),_=Math.min(l,p),y=Math.max(v-g,0)*Math.max(_-m,0);return y/(d+f-y)}function fr(t,e,n){var i=Math.exp(e*n*n);return n<=t?i:0}function gr(t,e){return t.score-e.score||t.score===e.score&&e.boxIndex-t.boxIndex}function mr(t,e,n){var i=new Array(t.rank).fill(0),r=t.shape.slice();return e.map(function(e){r[n]=e;var o=t.slice(i,r);return i[n]+=e,o})}function vr(t,e){for(var n=new Array(t.rank),i=0;i1?"["+e+"]":"")+";"):(r.push("uniform sampler2D "+t.name+";"),r.push("uniform int offset"+t.name+";"))});var o,s,a=r.join("\n"),l=t.map(function(t){return function(t,e,n){void 0===n&&(n=!1);var i="";i+=n?function t(e){var n,i,r;switch(e.shapeInfo.logicalShape.length){case 0:return n=e.name,i="get"+n.charAt(0).toUpperCase()+n.slice(1),r=Er(),"\n vec4 "+i+"() {\n return "+r.texture2D+"("+n+", halfCR);\n }\n ";case 1:return function(t){var e=t.name,n="get"+e.charAt(0).toUpperCase()+e.slice(1),i=t.shapeInfo.texShape,r=[Math.ceil(i[0]/2),Math.ceil(i[1]/2)],o=Er();return"\n vec4 "+n+"(int index) {\n vec2 uv = packedUVfrom1D(\n "+r[0]+", "+r[1]+", index);\n return "+o.texture2D+"("+e+", uv);\n }\n "}(e);case 2:return function(t){var e=t.shapeInfo.logicalShape,n=t.name,i="get"+n.charAt(0).toUpperCase()+n.slice(1),r=t.shapeInfo.texShape,o=r[0],s=r[1],a=Er();if(null!=r&&I(e,r))return"\n vec4 "+i+"(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2("+s+".0, "+o+".0);\n\n return "+a.texture2D+"("+n+", uv);\n }\n ";var l=[Math.ceil(r[0]/2),Math.ceil(r[1]/2)],u=Math.ceil(e[1]/2);return"\n vec4 "+i+"(int row, int col) {\n vec2 uv = packedUVfrom2D("+u+", "+l[0]+", "+l[1]+", row, col);\n return "+a.texture2D+"("+n+", uv);\n }\n "}(e);case 3:return function(e){var n=e.shapeInfo.logicalShape,i=e.name,r="get"+i.charAt(0).toUpperCase()+i.slice(1),o=e.shapeInfo.texShape,s=[Math.ceil(o[0]/2),Math.ceil(o[1]/2)];if(1===n[0]){var a=n.slice(1),l=Nr(e,a);return"\n "+t(l)+"\n vec4 "+r+"(int b, int row, int col) {\n return "+r+"("+Lr(["b","row","col"],[1,2])+");\n }\n "}var u=s[0],c=s[1],h=Math.ceil(n[2]/2),p=h*Math.ceil(n[1]/2),d=Er();return"\n vec4 "+r+"(int b, int row, int col) {\n vec2 uv = packedUVfrom3D(\n "+u+", "+c+", "+p+", "+h+", b, row, col);\n return "+d.texture2D+"("+i+", uv);\n }\n "}(e);default:return function(t){for(var e=t.shapeInfo.logicalShape,n=e.length,i=t.name,r="get"+i.charAt(0).toUpperCase()+i.slice(1),o=t.shapeInfo.texShape,s=[Math.ceil(o[0]/2),Math.ceil(o[1]/2)],a=s[0],l=s[1],u=Math.ceil(e[n-1]/2),c=u*Math.ceil(e[n-2]/2),h="int b, int row, int col",p="b * "+c+" + (row / 2) * "+u+" + (col / 2)",d=2;d=1?"coords = 0;":l.map(function(t){return"coords."+h[t+c]+" = 0;"}).join("\n");var p;p=a<2&&s>0?"coords":t.shapeInfo.logicalShape.map(function(t,e){return"coords."+h[e+c]}).join(", ");var d="return outputValue;",f=1===x(t.shapeInfo.logicalShape),g=1===x(e.logicalShape);if(1!==s||f||g){if(f&&!g)d=1===a?"\n return vec4(outputValue.x, outputValue.x, 0., 0.);\n ":"\n return vec4(outputValue.x);\n ";else if(l.length){var m=s-2,v=s-1;l.indexOf(m)>-1&&l.indexOf(v)>-1?d="return vec4(outputValue.x);":l.indexOf(m)>-1?d="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":l.indexOf(v)>-1&&(d="return vec4(outputValue.xx, outputValue.zz);")}}else d="\n return vec4(outputValue.xy, outputValue.xy);\n ";return"\n vec4 "+o+"() {\n "+u+" coords = getOutputCoords();\n "+n+"\n vec4 outputValue = get"+r+"("+p+");\n "+d+"\n }\n "}(t,e):function(t,e){var n=t.name,i=n.charAt(0).toUpperCase()+n.slice(1),r="get"+i+"AtOutCoords",o=e.texShape,s=t.shapeInfo.texShape,a=t.shapeInfo.logicalShape.length,l=e.logicalShape.length;if(!t.shapeInfo.isUniform&&a===l&&null==t.shapeInfo.flatOffset&&I(s,o))return"\n float "+r+"() {\n return sampleTexture("+n+", resultUV);\n }\n ";var u=Mr(l),c=Vi(t.shapeInfo.logicalShape,e.logicalShape),h=l-a,p=["x","y","z","w","u","v"];return"\n float "+r+"() {\n "+u+" coords = getOutputCoords();\n "+(0===a?"":l<2&&c.length>=1?"coords = 0;":c.map(function(t){return"coords."+p[t+h]+" = 0;"}).join("\n"))+"\n return get"+i+"("+(l<2&&a>0?"coords":t.shapeInfo.logicalShape.map(function(t,e){return"coords."+p[e+h]}).join(", "))+");\n }\n "}(t,e)),i}(t,e,i)}).join("\n"),u=e.texShape,c=Er(),h="\n float sampleTexture(sampler2D textureSampler, vec2 uv) {\n return "+c.texture2D+"(textureSampler, uv).r;\n }\n ",p=function(t){return t.version+"\n precision highp float;\n precision highp int;\n precision highp sampler2D;\n "+t.varyingFs+" vec2 resultUV;\n "+t.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 "+t.defineSpecialNaN+"\n "+t.defineSpecialInf+"\n "+t.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 "+xr+"\n "+Ir+"\n "+Rr+"\n "}(c);return e.isPacked?(o=function(t,e){switch(t.length){case 0:return"\n int getOutputCoords() {\n return 0;\n }\n ";case 1:return function(t,e){var n=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)];return 1===n[0]?"\n int getOutputCoords() {\n return 2 * int(resultUV.x * "+n[1]+".0);\n }\n ":1===n[1]?"\n int getOutputCoords() {\n return 2 * int(resultUV.y * "+n[0]+".0);\n }\n ":"\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+n[0]+", "+n[1]+"));\n return 2 * (resTexRC.x * "+n[1]+" + resTexRC.y);\n }\n "}(0,e);case 2:return function(t,e){var n=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)];if(I(t,e))return"\n ivec2 getOutputCoords() {\n return 2 * ivec2(resultUV.yx * vec2("+n[0]+", "+n[1]+"));\n }\n ";var i=Math.ceil(t[1]/2);return"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+n[0]+", "+n[1]+"));\n\n int index = resTexRC.x * "+n[1]+" + resTexRC.y;\n int r = 2 * (index / "+i+");\n int c = imod(index, "+i+") * 2;\n\n return ivec2(r, c);\n }\n "}(t,e);case 3:return n=t,i=e,r=[Math.ceil(i[0]/2),Math.ceil(i[1]/2)],s=(o=Math.ceil(n[2]/2))*Math.ceil(n[1]/2),"\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+r[0]+", "+r[1]+"));\n int index = resTexRC.x * "+r[1]+" + resTexRC.y;\n\n int b = index / "+s+";\n index -= b * "+s+";\n\n int r = 2 * (index / "+o+");\n int c = imod(index, "+o+") * 2;\n\n return ivec3(b, r, c);\n }\n ";default:return function(t,e){for(var n=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)],i=Math.ceil(t[t.length-1]/2),r=i*Math.ceil(t[t.length-2]/2),o=r,s="",a="b, r, c",l=2;l= "+this.outputShape[0]+" ? 0. : result.y;\n result.z = 0.;\n result.w = 0.;\n ";else{var s=Tr("coords",r);o+="\n bool nextRowOutOfBounds =\n ("+s[r-2]+" + 1) >= "+this.outputShape[r-2]+";\n bool nextColOutOfBounds =\n ("+s[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 "+t+"\n }\n\n void main() {\n vec4 a = getAAtOutCoords();\n vec4 b = getBAtOutCoords();\n\n vec4 result = binaryOperation(a, b);\n "+o+"\n\n setOutput(result);\n }\n "},jr=function(){function t(t){this.variableNames=["A"],this.outputShape=t,this.userCode="\n uniform float minVal;\n uniform float maxVal;\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 "}return t.prototype.getCustomSetupFunc=function(t,e){var n=this;return function(i,r){null==n.minLoc&&(n.minLoc=i.getUniformLocationNoThrow(r,"minVal"),n.maxLoc=i.getUniformLocationNoThrow(r,"maxVal")),i.gl.uniform1f(n.minLoc,t),i.gl.uniform1f(n.maxLoc,e)}},t}(),zr=function(){function t(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,this.userCode="\n uniform float minVal;\n uniform float maxVal;\n\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 "}return t.prototype.getCustomSetupFunc=function(t,e){var n=this;return function(i,r){null==n.minLoc&&(n.minLoc=i.getUniformLocationNoThrow(r,"minVal"),n.maxLoc=i.getUniformLocationNoThrow(r,"maxVal")),i.gl.uniform1f(n.minLoc,t),i.gl.uniform1f(n.maxLoc,e)}},t}();function $r(t,e,n){var i=t.indexOf(e);return t.map(function(t,e){return e===i?t+" - "+n:t}).join()}var Xr=function(t,e,n,i){void 0===e&&(e=!1),void 0===n&&(n=null),void 0===i&&(i=!1),this.variableNames=["x","W"],this.outputShape=t.outShape;var r=t.padInfo.top,o=t.padInfo.left,s=t.strideHeight,a=t.strideWidth,l=t.dilationHeight,u=t.dilationWidth,c=t.filterHeight,h=t.filterWidth,p=4*Math.floor(t.inChannels/4),d=t.inChannels%4,f="channelsLast"===t.dataFormat,g=f?1:2,m=f?2:3,v=f?3:1,_="",y="";n&&(_=i?"float activation(float a) {\n float b = getPreluActivationWeightsAtOutCoords();\n "+n+"\n }":"\n float activation(float x) {\n "+n+"\n }\n ",y="result = activation(result);");var b=e?"result += getBiasAtOutCoords();":"";e&&this.variableNames.push("bias"),i&&this.variableNames.push("preluActivationWeights"),this.userCode="\n "+_+"\n\n const ivec2 strides = ivec2("+s+", "+a+");\n const ivec2 pads = ivec2("+r+", "+o+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d2 = coords["+v+"];\n\n ivec2 xRCCorner =\n ivec2(coords["+g+"], coords["+m+"]) * 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 < "+c+"; wR++) {\n int xR = xRCorner + wR * "+l+";\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+h+"; wC++) {\n int xC = xCCorner + wC * "+u+";\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n for (int d1 = 0; d1 < "+p+"; 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 ("+f+") {\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===d)+") {\n\n if ("+f+") {\n dotProd +=\n getX(batch, xR, xC, "+p+") *\n getW(wR, wC, "+p+", d2);\n } else {\n dotProd +=\n getX(batch, "+p+", xR, xC) *\n getW(wR, wC, "+p+", d2);\n }\n\n } else if ("+(2===d)+") {\n vec2 wValues = vec2(\n getW(wR, wC, "+p+", d2),\n getW(wR, wC, "+p+" + 1, d2)\n );\n\n if ("+f+") {\n vec2 xValues = vec2(\n getX(batch, xR, xC, "+p+"),\n getX(batch, xR, xC, "+p+" + 1)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec2 xValues = vec2(\n getX(batch, "+p+", xR, xC),\n getX(batch, "+p+" + 1, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n\n } else if ("+(3===d)+") {\n vec3 wValues = vec3(\n getW(wR, wC, "+p+", d2),\n getW(wR, wC, "+p+" + 1, d2),\n getW(wR, wC, "+p+" + 2, d2)\n );\n\n if ("+f+") {\n vec3 xValues = vec3(\n getX(batch, xR, xC, "+p+"),\n getX(batch, xR, xC, "+p+" + 1),\n getX(batch, xR, xC, "+p+" + 2)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec3 xValues = vec3(\n getX(batch, "+p+", xR, xC),\n getX(batch, "+p+" + 1, xR, xC),\n getX(batch, "+p+" + 2, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n\n }\n }\n }\n\n float result = dotProd;\n "+b+"\n "+y+"\n setOutput(result);\n }\n "},Yr=function(t,e,n,i){void 0===e&&(e=!1),void 0===n&&(n=null),void 0===i&&(i=!1),this.variableNames=["x","W"],this.outputShape=t.outShape;var r=t.inHeight,o=t.inWidth,s=t.padInfo.top,a=t.padInfo.left,l=t.strideHeight,u=t.strideWidth,c=t.dilationHeight,h=t.dilationWidth,p=t.filterHeight,d=t.filterWidth,f=t.outChannels/t.inChannels,g="",m="";n&&(g=i?"float activation(float a) {\n float b = getPreluActivationWeightsAtOutCoords();\n "+n+"\n }":"\n float activation(float x) {\n "+n+"\n }\n ",m="result = activation(result);");var v=e?"result += getBiasAtOutCoords();":"";e&&this.variableNames.push("bias"),i&&this.variableNames.push("preluActivationWeights"),this.userCode="\n "+g+"\n\n const ivec2 strides = ivec2("+l+", "+u+");\n const ivec2 pads = ivec2("+s+", "+a+");\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 / "+f+";\n int q = d2 - d1 * "+f+";\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 < "+p+"; wR++) {\n int xR = xRCorner + wR * "+c+";\n\n if (xR < 0 || xR >= "+r+") {\n continue;\n }\n\n for (int wC = 0; wC < "+d+"; wC++) {\n int xC = xCCorner + wC * "+h+";\n\n if (xC < 0 || xC >= "+o+") {\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 "+v+"\n "+m+"\n setOutput(result);\n }\n "},Kr=function(t,e,n,i){void 0===e&&(e=!1),void 0===n&&(n=null),void 0===i&&(i=!1),this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.outShape;for(var r=t.inHeight,o=t.inWidth,s=t.padInfo.top,a=t.padInfo.left,l=t.strideHeight,u=t.strideWidth,c=t.dilationHeight,h=t.dilationWidth,p=t.filterHeight,d=t.filterWidth,f=d,g="int xR; int xC; int xCOffset;",m=0;m= 0 && xR < "+r+" && xCOffset >= 0 && xCOffset < "+o+") {\n xTexelR"+m+"C"+v+" = 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 >= "+o+") {\n xTexelR"+m+"C"+v+".zw = vec2(0.);\n }\n } else {\n xTexelR"+m+"C"+v+" = vec4(0.);\n }\n\n xCOffset = xC + 1 - 2;\n if(xR >= 0 && xR < "+r+" && xCOffset >= 0 && xCOffset < "+o+") {\n vec4 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 >= "+o+") {\n previous.zw = vec2(0.);\n }\n\n xR"+m+"C"+v+" = vec4(previous.zw, xTexelR"+m+"C"+v+".xy);\n } else {\n xR"+m+"C"+v+" = vec4(0, 0, xTexelR"+m+"C"+v+".xy);\n }\n ":"\n if(xR >= 0 && xR < "+r+" && xC >= 0 && xC < "+o+") {\n xTexelR"+m+"C"+v+" = getX(batch, xR, xC, d1);\n } else {\n xTexelR"+m+"C"+v+" = vec4(0.);\n }\n\n xR"+m+"C"+v+" = xTexelR"+m+"C"+v+";\n ",v+1= 0 && xR < "+r+" &&\n xCOffset >= 0 && xCOffset < "+o+") {\n xTexelR"+m+"C"+(v+2)+" = getX(batch, xR, xCOffset, d1);\n }\n ",h>1&&(g+="\n xCOffset -= 2;\n if(xR >= 0 && xR < "+r+" &&\n xCOffset >= 0 && xCOffset < "+o+") {\n xTexelR"+m+"C"+v+" = getX(batch, xR, xCOffset, d1);\n } else {\n xTexelR"+m+"C"+v+" = vec4(0.);\n }\n "),g+="\n xR"+m+"C"+(v+1)+" = vec4(\n xTexelR"+m+"C"+v+".zw, xTexelR"+m+"C"+(v+2)+".xy);\n "):g+="\n xCOffset = xC + "+y+";\n\n if(xR >= 0 && xR < "+r+" &&\n xCOffset >= 0 && xCOffset < "+o+") {\n xTexelR"+m+"C"+(v+2)+" = getX(batch, xR, xCOffset, d1);\n }\n\n xR"+m+"C"+(v+1)+" = xTexelR"+m+"C"+(v+2)+";\n "}}else v= 0 && xR < "+r+") {\n ",a%2==1?(g+="\n xCOffset = xC + 1 - "+u+";\n if(xCOffset >= 0 && xCOffset < "+o+") {\n xTexelR"+m+"C"+v+" = getX(batch, xR, xCOffset, d1);\n } else {\n xTexelR"+m+"C"+v+" = vec4(0.);\n }\n\n if(xC + 1 >= 0 && xC + 1 < "+o+") {\n xTexelR"+m+"C"+(v+2)+" = getX(batch, xR, xC + 1, d1);\n } else {\n xTexelR"+m+"C"+(v+2)+" = vec4(0.);\n }\n\n xR"+m+"C"+v+" = vec4(\n xTexelR"+m+"C"+v+".zw, xTexelR"+m+"C"+(v+2)+".zw);\n ",v+1= 0 && xCOffset < "+o+") {\n final = getX(batch, xR, xCOffset, d1);\n }\n xR"+m+"C"+(v+1)+" = vec4(xTexelR"+m+"C"+(v+2)+".xy, final.xy);\n ")):(g+="\n if(xC >= 0 && xC < "+o+") {\n xTexelR"+m+"C"+v+" = getX(batch, xR, xC, d1);\n } else {\n xTexelR"+m+"C"+v+" = vec4(0.);\n }\n\n xCOffset = xC + "+u+";\n if(xCOffset >= 0 && xCOffset < "+o+") {\n xTexelR"+m+"C"+(v+2)+" = getX(batch, xR, xCOffset, d1);\n } else {\n xTexelR"+m+"C"+(v+2)+" = vec4(0.);\n }\n\n xR"+m+"C"+v+" = vec4(\n xTexelR"+m+"C"+v+".xy, xTexelR"+m+"C"+(v+2)+".xy);\n ",v+10?(e=this.beginQuery(),this.endQuery(),n=function(){return i.isQueryAvailable(e,c().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}):n=function(){return!0};return{query:e,isFencePassed:n}},t.prototype.downloadMatrixFromPackedTexture=function(t,e,n){var i=this;return this.downloadMatrixDriver(t,function(){return vo(i.gl,i.debug,e,n)})},t.prototype.createProgram=function(t){this.throwIfDisposed();var e=this.gl,n=ie(e,this.debug,t),i=to(e,this.debug),r=ae(e,this.debug);return Jt(e,this.debug,function(){return e.attachShader(r,i)}),Jt(e,this.debug,function(){return e.attachShader(r,n)}),le(e,this.debug,r),this.debug&&ue(e,this.debug,r),this.vertexAttrsAreBound||(this.setProgram(r),this.vertexAttrsAreBound=uo(e,this.debug,this.program,this.vertexBuffer)),r},t.prototype.deleteProgram=function(t){var e=this;this.throwIfDisposed(),t===this.program&&(this.program=null),null!=t&&Jt(this.gl,this.debug,function(){return e.gl.deleteProgram(t)})},t.prototype.setProgram=function(t){var e=this;this.throwIfDisposed(),this.program=t,null!=this.program&&this.debug&&ue(this.gl,this.debug,this.program),Jt(this.gl,this.debug,function(){return e.gl.useProgram(t)})},t.prototype.getUniformLocation=function(t,e,n){return void 0===n&&(n=!0),this.throwIfDisposed(),n?ve(this.gl,this.debug,t,e):_e(this.gl,t,e)},t.prototype.getAttributeLocation=function(t,e){var n=this;return this.throwIfDisposed(),Jt(this.gl,this.debug,function(){return n.gl.getAttribLocation(t,e)})},t.prototype.getUniformLocationNoThrow=function(t,e){return this.throwIfDisposed(),this.gl.getUniformLocation(t,e)},t.prototype.setInputMatrixTexture=function(t,e,n){this.throwIfDisposed(),this.throwIfNoProgram(),ye(this.gl,this.debug,this.program,t,e,n)},t.prototype.setOutputMatrixTexture=function(t,e,n){this.setOutputMatrixTextureDriver(t,n,e)},t.prototype.setOutputPackedMatrixTexture=function(t,e,n){this.throwIfDisposed();var i=Yt(e,n),r=i[0],o=i[1];this.setOutputMatrixTextureDriver(t,r,o)},t.prototype.setOutputMatrixWriteRegion=function(t,e,n,i){this.setOutputMatrixWriteRegionDriver(n,t,i,e)},t.prototype.setOutputPackedMatrixWriteRegion=function(t,e,n,i){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")},t.prototype.debugValidate=function(){null!=this.program&&ue(this.gl,this.debug,this.program),Ee(this.gl)},t.prototype.executeProgram=function(){this.throwIfDisposed(),this.throwIfNoProgram();var t=this.gl;this.debug&&this.debugValidate(),Jt(t,this.debug,function(){return t.drawElements(t.TRIANGLES,6,t.UNSIGNED_SHORT,0)})},t.prototype.blockUntilAllProgramsCompleted=function(){var t=this;this.throwIfDisposed(),Jt(this.gl,this.debug,function(){return t.gl.finish()})},t.prototype.getQueryTimerExtension=function(){return null==this.disjointQueryTimerExtension&&(this.disjointQueryTimerExtension=ee(this.gl,this.debug,2===c().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")?"EXT_disjoint_timer_query_webgl2":"EXT_disjoint_timer_query")),this.disjointQueryTimerExtension},t.prototype.getQueryTimerExtensionWebGL2=function(){return this.getQueryTimerExtension()},t.prototype.getQueryTimerExtensionWebGL1=function(){return this.getQueryTimerExtension()},t.prototype.beginQuery=function(){if(2===c().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){var t=this.gl,e=this.getQueryTimerExtensionWebGL2(),n=t.createQuery();return t.beginQuery(e.TIME_ELAPSED_EXT,n),n}var i=this.getQueryTimerExtensionWebGL1(),r=i.createQueryEXT();return i.beginQueryEXT(i.TIME_ELAPSED_EXT,r),r},t.prototype.endQuery=function(){if(2!==c().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){var t=this.getQueryTimerExtensionWebGL1();t.endQueryEXT(t.TIME_ELAPSED_EXT)}else{var e=this.gl,n=this.getQueryTimerExtensionWebGL2();e.endQuery(n.TIME_ELAPSED_EXT)}},t.prototype.waitForQueryAndGetTime=function(t){return a(this,void 0,void 0,function(){var e=this;return l(this,function(n){switch(n.label){case 0:return[4,M(function(){return e.disposed||e.isQueryAvailable(t,c().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))})];case 1:return n.sent(),[2,this.getQueryTime(t,c().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))]}})})},t.prototype.getQueryTime=function(t,e){if(0===e)return null;if(2===e){var n=this.gl;return n.getQueryParameter(t,n.QUERY_RESULT)/1e6}var i=this.getQueryTimerExtensionWebGL1();return i.getQueryObjectEXT(t,i.QUERY_RESULT_EXT)/1e6},t.prototype.isQueryAvailable=function(t,e){if(0===e)return!0;if(2===e){var n=this.gl,i=this.getQueryTimerExtensionWebGL2(),r=n.getQueryParameter(t,n.QUERY_RESULT_AVAILABLE);return null==this.disjoint&&(this.disjoint=this.gl.getParameter(i.GPU_DISJOINT_EXT)),r&&!this.disjoint}return r=(i=this.getQueryTimerExtensionWebGL1()).getQueryObjectEXT(t,i.QUERY_RESULT_AVAILABLE_EXT),null==this.disjoint&&(this.disjoint=this.gl.getParameter(i.GPU_DISJOINT_EXT)),r&&!this.disjoint},t.prototype.pollFence=function(t){var e=this;return new Promise(function(n){e.addItemToPoll(function(){return t.isFencePassed()},function(){return n()})})},t.prototype.pollItems=function(){for(var t=function(t){for(var e=0;e1||M(function(){return n.pollItems(),0===n.itemsToPoll.length})},t.prototype.bindTextureToFrameBuffer=function(t){this.throwIfDisposed(),be(this.gl,this.debug,t,this.framebuffer),this.debug&&Ee(this.gl)},t.prototype.unbindTextureToFrameBuffer=function(){null!=this.outputTexture?(be(this.gl,this.debug,this.outputTexture,this.framebuffer),this.debug&&Ee(this.gl)):Te(this.gl,this.debug,this.framebuffer)},t.prototype.downloadMatrixDriver=function(t,e){this.bindTextureToFrameBuffer(t);var n=e();return this.unbindTextureToFrameBuffer(),n},t.prototype.setOutputMatrixTextureDriver=function(t,e,n){this.throwIfDisposed();var i=this.gl;be(i,this.debug,t,this.framebuffer),this.debug&&Ee(i),this.outputTexture=t,Jt(i,this.debug,function(){return i.viewport(0,0,e,n)}),Jt(i,this.debug,function(){return i.scissor(0,0,e,n)})},t.prototype.setOutputMatrixWriteRegionDriver=function(t,e,n,i){var r=this;this.throwIfDisposed(),Jt(this.gl,this.debug,function(){return r.gl.scissor(t,e,n,i)})},t.prototype.throwIfDisposed=function(){if(this.disposed)throw new Error("Attempted to use disposed GPGPUContext.")},t.prototype.throwIfNoProgram=function(){if(null==this.program)throw new Error("No GPU program is currently set.")},t}();function bo(t,e){if(t.length!==e.length)throw Error("Binary was compiled with "+t.length+" inputs, but was executed with "+e.length+" inputs");t.forEach(function(t,n){var i=t.logicalShape,r=e[n],o=r.shape;if(!I(i,o))throw Error("Binary was compiled with different shapes than the current args. Shapes "+i+" and "+o+" must match");if(!t.isUniform||!r.isUniform){var s=t.texShape,a=r.isUniform?null:r.texData.texShape;if(!I(s,a))throw Error("Binary was compiled with different texture shapes than the current args. Shape "+s+" and "+a+" must match")}})}var To=function(t,e,n,i,r,o,s){void 0===n&&(n=!1),void 0===i&&(i=!1),void 0===r&&(r=!1),void 0===o&&(o=null),void 0===s&&(s=!1),this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e;var a=n?t[1]:t[2],l=Math.ceil(a/2),u=n?"i * 2, rc.y":"rc.y, i * 2",c=i?"rc.z, i * 2":"i * 2, rc.z",h=n?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],p=i?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"],d="",f="";o&&(d=s?"vec4 activation(vec4 a) {\n vec4 b = getPreluActivationWeightsAtOutCoords();\n "+o+"\n }":"vec4 activation(vec4 x) {\n "+o+"\n }",f="result = activation(result);");var g=r?"result += getBiasAtOutCoords();":"";r&&this.variableNames.push("bias"),s&&this.variableNames.push("preluActivationWeights"),this.userCode="\n "+d+"\n\n const float sharedDimension = "+l+".0;\n\n vec4 dot2x2ARowBCol(ivec3 rc) {\n vec4 result = vec4(0);\n for (int i = 0; i < "+l+"; i++) {\n vec4 a = getMatrixA(rc.x, "+u+");\n vec4 b = getMatrixB(rc.x, "+c+");\n\n // These swizzled products need to be separately added.\n // See: https://github.com/tensorflow/tfjs/issues/1735\n result += ("+h[0]+" * "+p[0]+");\n result += ("+h[1]+" * "+p[1]+");\n }\n return result;\n }\n\n void main() {\n ivec3 rc = getOutputCoords();\n vec4 result = dot2x2ARowBCol(rc);\n\n "+g+"\n\n "+f+"\n\n setOutput(result);\n }\n "},Eo=function(){function t(t,e,n){this.variableNames=["probs"],this.outputShape=[t,n],this.userCode="\n uniform float seed;\n\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 < "+(e-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("+(e-1)+"));\n }\n "}return t.prototype.getCustomSetupFunc=function(t){var e=this;return function(n,i){null==e.seedLoc&&(e.seedLoc=n.getUniformLocation(i,"seed")),n.gl.uniform1f(e.seedLoc,t)}},t}(),Co=function(t,e,n){if(this.variableNames=["x"],"avg"===e&&n)throw new Error("Cannot compute positions for average pool.");var i=t.filterWidth,r=t.strideHeight,o=t.strideWidth,s=t.dilationHeight,a=t.dilationWidth,l=t.effectiveFilterHeight,u=t.effectiveFilterWidth,c=t.padInfo.top,h=t.padInfo.left;this.outputShape=t.outShape;var p="avg"===e,d="0.0";if(p||(d="-1.0 / 1e-20"),n)this.userCode="\n const ivec2 strides = ivec2("+r+", "+o+");\n const ivec2 pads = ivec2("+c+", "+h+");\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 < "+l+";\n wR += "+s+") {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+u+";\n wC += "+a+") {\n int xC = xCCorner + wC;\n\n if (xC < 0 || xC >= "+t.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 >= currMinMaxValue) {\n minMaxValue = value;\n minMaxValueFound = 1.0;\n minMaxPosition = wR * "+u+" + wC;\n }\n }\n }\n setOutput(float(minMaxPosition));\n }\n ";else{var f=e+"("+e+"("+e+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"avg"===e&&(f="avgValue / count");var g=4*Math.floor(i/4),m=i%4,v="\n if ("+p+") {\n avgValue += dot(values, ones);\n } else {\n minMaxValue = max(values, minMaxValue);\n }\n ";this.userCode="\n const ivec2 strides = ivec2("+r+", "+o+");\n const ivec2 pads = ivec2("+c+", "+h+");\n const float initializationValue = "+d+";\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 >= "+t.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("+d+");\n float avgValue = 0.0;\n count = 0.0;\n\n for (int wR = 0; wR < "+l+";\n wR += "+s+") {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+g+"; wC += 4) {\n int xC = xCCorner + wC * "+a+";\n\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + "+a+", d),\n getValue(batch, xR, xC + 2 * "+a+", d),\n getValue(batch, xR, xC + 3 * "+a+", d)\n );\n\n "+v+"\n }\n\n int xC = xCCorner + "+g+";\n if ("+(1===m)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n "+v+"\n } else if ("+(2===m)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + "+a+", d),\n initializationValue,\n initializationValue\n );\n\n "+v+"\n } else if ("+(3===m)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + "+a+", d),\n getValue(batch, xR, xC + 2 * "+a+", d),\n initializationValue\n );\n\n "+v+"\n }\n }\n setOutput("+f+");\n }\n "}},So=function(t,e,n){if(this.variableNames=["x"],"avg"===e&&n)throw new Error("Cannot compute positions for average pool.");var i=t.filterWidth,r=t.strideDepth,o=t.strideHeight,s=t.strideWidth,a=t.dilationDepth,l=t.dilationHeight,u=t.dilationWidth,c=t.effectiveFilterDepth,h=t.effectiveFilterHeight,p=t.effectiveFilterWidth,d=t.padInfo.front,f=t.padInfo.top,g=t.padInfo.left;this.outputShape=t.outShape;var m="avg"===e,v="0.0";if(m||(v="-1.0 / 1e-20"),n)this.userCode="\n const ivec3 strides =\n ivec3("+r+", "+o+", "+s+");\n const ivec3 pads = ivec3("+d+", "+f+", "+g+");\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 < "+c+";\n wD += "+a+") {\n int xD = xDCorner + wD;\n\n if (xD < 0 || xD >= "+t.inDepth+") {\n continue;\n }\n\n for (int wR = 0; wR < "+h+";\n wR += "+l+") {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+p+";\n wC += "+u+") {\n int xC = xCCorner + wC;\n\n if (xC < 0 || xC >= "+t.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 >= currMinMaxValue) {\n minMaxValue = value;\n minMaxValueFound = 1.0;\n minMaxPosition =\n wD * "+h+" * "+p+" +\n wR * "+p+" + wC;;\n }\n }\n }\n }\n setOutput(float(minMaxPosition));\n }\n ";else{var _=e+"("+e+"("+e+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"avg"===e&&(_="avgValue / count");var y=4*Math.floor(i/4),b=i%4,T="\n if ("+m+") {\n avgValue += dot(values, ones);\n } else {\n minMaxValue = max(values, minMaxValue);\n }\n ";this.userCode="\n const ivec3 strides =\n ivec3("+r+", "+o+", "+s+");\n const ivec3 pads = ivec3("+d+", "+f+", "+g+");\n const float initializationValue = "+v+";\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 >= "+t.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("+v+");\n float avgValue = 0.0;\n count = 0.0;\n\n for (int wD = 0; wD < "+c+";\n wD += "+a+") {\n int xD = xDCorner + wD;\n\n if (xD < 0 || xD >= "+t.inDepth+") {\n continue;\n }\n\n for (int wR = 0; wR < "+h+";\n wR += "+l+") {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+y+"; wC += 4) {\n int xC = xCCorner + wC * "+u+";\n\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + "+u+", ch),\n getValue(batch, xD, xR, xC + 2 * "+u+", ch),\n getValue(batch, xD, xR, xC + 3 * "+u+", ch)\n );\n\n "+T+"\n }\n\n int xC = xCCorner + "+y+";\n if ("+(1===b)+") {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n "+T+"\n } else if ("+(2===b)+") {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + "+u+", ch),\n initializationValue,\n initializationValue\n );\n\n "+T+"\n } else if ("+(3===b)+") {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + "+u+", ch),\n getValue(batch, xD, xR, xC + 2 * "+u+", ch),\n initializationValue\n );\n\n "+T+"\n }\n }\n setOutput("+_+");\n }\n }\n "}},wo=function(t,e,n,i,r,o,s){void 0===s&&(s=!0),this.variableNames=["updates","indices","defaultValue"],this.outputShape=o;var a=Mr(r.length),l=Mr(o.length),u="";1===n?u="i":2===n&&(u="i, j");var c="getIndices("+u+")",h="";1===i?h="i":2===i&&(h="i, coords[1]");var p="getUpdates("+h+")",d=e>1?"strides[j]":"strides";this.userCode="\n "+a+" strides = "+a+"("+r+");\n\n void main() {\n "+l+" coords = getOutputCoords();\n float sum = 0.0;\n bool found = false;\n for (int i = 0; i < "+t+"; i++) {\n int flattenedIndex = 0;\n for (int j = 0; j < "+e+"; 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 "},ko=function(){function t(t){this.variableNames=["source"],this.outputShape=t,this.rank=t.length;var e,n=Mr(this.rank),i="uniform int start["+this.rank+"];",r=function(t){if(1===t)return"sourceLoc";if(t<=6)return xo.slice(0,t).map(function(t){return"sourceLoc."+t}).join(",");throw Error("Slicing for rank "+t+" is not yet supported")}(this.rank);e="\n "+n+" sourceLoc;\n "+n+" coords = getOutputCoords();\n "+t.map(function(t,e){return"sourceLoc."+xo[e]+" = start["+e+"] + coords."+xo[e]+";"}).join("\n")+"\n ",this.userCode="\n "+i+"\n void main() {\n "+e+"\n setOutput(getSource("+r+"));\n }\n "}return t.prototype.getCustomSetupFunc=function(t){var e=this;if(t.length!==this.rank)throw Error("The rank ("+this.rank+") of the program must match the length of start ("+t.length+")");return function(n,i){null==e.startLoc&&(e.startLoc=n.getUniformLocationNoThrow(i,"start"),null==e.startLoc)||n.gl.uniform1iv(e.startLoc,t)}},t}(),xo=["x","y","z","w","u","v"],Io=function(){function t(t){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,this.rank=t.length;var e=Mr(this.rank),n=Tr("coords",this.rank),i=Tr("sourceLoc",this.rank),r=1===this.rank?"sourceLoc":"vec2("+i.slice(-2).join()+")",o="getChannel(getSource("+i.join()+"), "+r+")",s="\n result.x = "+o+";\n if (++"+n[this.rank-1]+" < "+t[this.rank-1]+") {\n ++"+i[this.rank-1]+";\n result.y = "+o+";\n --"+i[this.rank-1]+";\n }\n ",a=1===this.rank?"":"\n --"+n[this.rank-1]+";\n if (++"+n[this.rank-2]+" < "+t[this.rank-2]+") {\n ++"+i[this.rank-2]+";\n result.z = "+o+";\n if (++"+n[this.rank-1]+" < "+t[this.rank-1]+") {\n ++"+i[this.rank-1]+";\n result.w = "+o+";\n }\n }\n ",l=this.rank<=4?"sourceLoc = coords +\n "+e+"("+t.map(function(t,e){return"start["+e+"]"}).join()+");":t.map(function(t,e){return i[e]+" = "+n[e]+" + start["+e+"];"}).join("\n");this.userCode="\n uniform int start["+this.rank+"];\n void main() {\n "+e+" coords = getOutputCoords();\n "+e+" sourceLoc;\n "+l+"\n vec4 result = vec4(0.);\n "+s+"\n "+a+"\n setOutput(result);\n }\n "}return t.prototype.getCustomSetupFunc=function(t){var e=this;if(t.length!==this.rank)throw Error("The rank ("+this.rank+") of the program must match the length of start ("+t.length+")");return function(n,i){null==e.startLoc&&(e.startLoc=n.getUniformLocationNoThrow(i,"start"),null==e.startLoc)||n.gl.uniform1iv(e.startLoc,t)}},t}(),Ro=function(){function t(t){this.gpgpu=t,this.numUsedTextures=0,this.numFreeTextures=0,this.freeTextures={},this.logEnabled=!1,this.usedTextures={}}return t.prototype.acquireTexture=function(t,e,n){var i,r=Oo(e,n),o=Do(t,r,n);if(o in this.freeTextures||(this.freeTextures[o]=[]),o in this.usedTextures||(this.usedTextures[o]=[]),this.freeTextures[o].length>0){this.numFreeTextures--,this.numUsedTextures++,this.log();var s=this.freeTextures[o].shift();return this.usedTextures[o].push(s),s}return this.numUsedTextures++,this.log(),r===Ht.PACKED_2X2_FLOAT32?i=this.gpgpu.createPackedMatrixTexture(t[0],t[1]):r===Ht.PACKED_2X2_FLOAT16?i=this.gpgpu.createFloat16PackedMatrixTexture(t[0],t[1]):r===Ht.UNPACKED_FLOAT32?i=this.gpgpu.createFloat32MatrixTexture(t[0],t[1]):r===Ht.UNPACKED_FLOAT16?i=this.gpgpu.createFloat16MatrixTexture(t[0],t[1]):r===Ht.PACKED_4X1_UNSIGNED_BYTE&&(i=this.gpgpu.createUnsignedBytesMatrixTexture(t[0],t[1])),this.usedTextures[o].push(i),i},t.prototype.releaseTexture=function(t,e,n,i){if(null!=this.freeTextures){var r=Do(e,Oo(n,i),i);r in this.freeTextures||(this.freeTextures[r]=[]),this.freeTextures[r].push(t),this.numFreeTextures++,this.numUsedTextures--;var o=this.usedTextures[r],s=o.indexOf(t);if(s<0)throw new Error("Cannot release a texture that was never provided by this texture manager");o.splice(s,1),this.log()}},t.prototype.log=function(){if(this.logEnabled){var t=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",this.numFreeTextures+" / "+this.numUsedTextures,"("+t+")")}},t.prototype.getNumUsedTextures=function(){return this.numUsedTextures},t.prototype.getNumFreeTextures=function(){return this.numFreeTextures},t.prototype.dispose=function(){var t=this;if(null!=this.freeTextures){for(var e in this.freeTextures)this.freeTextures[e].forEach(function(e){t.gpgpu.deleteMatrixTexture(e)});for(var e in this.usedTextures)this.usedTextures[e].forEach(function(e){t.gpgpu.deleteMatrixTexture(e)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0}},t}();function Oo(t,e){if(t===Vt.UPLOAD)return Ht.PACKED_2X2_FLOAT32;if(t===Vt.RENDER||null==t)return function(t){return c().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?t?Ht.PACKED_2X2_FLOAT32:Ht.UNPACKED_FLOAT32:t?Ht.PACKED_2X2_FLOAT16:Ht.UNPACKED_FLOAT16}(e);if(t===Vt.DOWNLOAD||t===Vt.PIXELS)return Ht.PACKED_4X1_UNSIGNED_BYTE;throw new Error("Unknown logical texture type "+t)}function Do(t,e,n){return t[0]+"_"+t[1]+"_"+e+"_"+n}var Ao=1.7580993408473768,Mo=1.0507009873554805,No=function(t,e){this.variableNames=["A"],this.outputShape=t,this.userCode="\n float unaryOperation(float x) {\n "+e+"\n }\n\n void main() {\n float x = getAAtOutCoords();\n float y = unaryOperation(x);\n\n setOutput(y);\n }\n "},Lo="if (isnan(x)) return x;",Po="return x;",Bo="return abs(x);",Fo=Lo+"\n return (x < 0.0) ? 0.0 : x;\n",Uo=Lo+"\n return (x < 0.0) ? 0.0 : min(6.0, x);\n",Vo="return (x >= 0.0) ? x : (exp(x) - 1.0);",Ho="return -x;",Wo="return ceil(x);",Go="return floor(x);",jo="return exp(x);",zo="return exp(x) - 1.0;",$o="return x;",Xo="return x;",Yo="\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",Ko="\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",Jo="\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",qo=function(t,e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,this.userCode="\n vec4 unaryOperation(vec4 x) {\n "+e+"\n }\n\n void main() {\n vec4 x = getAAtOutCoords();\n vec4 y = unaryOperation(x);\n\n setOutput(y);\n }\n "},Zo={};function Qo(t,e){if(void 0===e&&(e=!1),"linear"===t)return e?Xo:Po;if("relu"===t)return e?Yo:Fo;if("elu"===t)return e?Jo:Vo;if("relu6"===t)return e?Ko:Uo;if("prelu"===t)return e?Wr:Vr;throw new Error("Activation "+t+" has not been implemented for the WebGL backend.")}var ts=600,es=function(t){function e(e){var n,i=t.call(this)||this;if(i.pendingRead=new WeakMap,i.pendingDisposal=new WeakSet,i.dataRefCount=new WeakMap,i.numBytesInGPU=0,i.uploadWaitMs=0,i.downloadWaitMs=0,i.warnedAboutMemory=!1,i.pendingDeletes=0,i.disposed=!1,!c().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");if(null==e){var r=zt(c().getNumber("WEBGL_VERSION"));i.binaryCache=(n=c().getNumber("WEBGL_VERSION"))in Zo?Zo[n]:(Zo[n]={},Zo[n]),i.gpgpu=new yo(r),i.canvas=r.canvas,i.gpgpuCreatedLocally=!0}else i.gpgpu=e,i.binaryCache={},i.gpgpuCreatedLocally=!1,i.canvas=e.gl.canvas;return i.textureManager=new Ro(i.gpgpu),i.numMBBeforeWarning=null==c().global.screen?1024:c().global.screen.height*c().global.screen.width*window.devicePixelRatio*ts/1024/1024,i.texData=new Bi(i,Pt),i}return s(e,t),e.prototype.numDataIds=function(){return this.texData.numDataIds()+(this.cpuBackend?this.cpuBackend.numDataIds():0)-this.pendingDeletes},e.prototype.write=function(t,e,n){if(c().getBool("DEBUG")&&this.checkNumericalProblems(t),"complex64"===n&&null!=t)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");var i={};return this.texData.set(i,{shape:e,dtype:n,values:t,usage:Vt.UPLOAD}),i},e.prototype.move=function(t,e,n,i){if(c().getBool("DEBUG")&&this.checkNumericalProblems(e),"complex64"===i)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(t,{shape:n,dtype:i,values:e,usage:Vt.UPLOAD})},e.prototype.readSync=function(t){var e=this.texData.get(t),n=e.values,i=e.dtype,r=e.complexTensors,o=e.slice,s=e.shape,a=e.isPacked;if(null!=o){var l;l=a?new qo(s,$o):new No(s,$o);var u=this.runWebGLProgram(l,[{dataId:t,shape:s,dtype:i}],i),c=this.readSync(u.dataId);return this.disposeData(u.dataId),c}if(null!=n)return this.convertAndCacheOnCPU(t);if("string"===i)return n;var h,p,d=null!=this.activeTimers;return d&&(h=nt()),p="complex64"===i?rr(r.real.dataSync(),r.imag.dataSync()):this.getValuesFromTexture(t),d&&(this.downloadWaitMs+=nt()-h),this.convertAndCacheOnCPU(t,p)},e.prototype.read=function(t){return a(this,void 0,void 0,function(){var e,n,i,r,o,s,a,u,h,p,d,f,g,m,v,_,y,b,T,E,C,S;return l(this,function(l){switch(l.label){case 0:if(this.pendingRead.has(t))return e=this.pendingRead.get(t),[2,new Promise(function(t){return e.push(t)})];if(n=this.texData.get(t),i=n.values,r=n.shape,o=n.slice,s=n.dtype,a=n.complexTensors,u=n.isPacked,null!=o)return h=void 0,h=u?new qo(r,$o):new No(r,$o),p=this.runWebGLProgram(h,[{dataId:t,shape:r,dtype:s}],s),d=this.read(p.dataId),this.disposeData(p.dataId),[2,d];if(null!=i)return[2,this.convertAndCacheOnCPU(t)];if(!c().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&2===c().getNumber("WEBGL_VERSION"))throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");return f=null,"complex64"!==s&&c().get("WEBGL_BUFFER_SUPPORTED")&&(g=this.decode(t),m=this.texData.get(g.dataId),f=(S=this.gpgpu).createBufferFromTexture.apply(S,[m.texture].concat(Xt(r)))),this.pendingRead.set(t,[]),"complex64"===s?[3,2]:[4,this.gpgpu.createAndWaitForFence()];case 1:l.sent(),l.label=2;case 2:return"complex64"!==s?[3,4]:[4,Promise.all([a.real.data(),a.imag.data()])];case 3:return _=l.sent(),y=_[0],b=_[1],v=rr(y,b),[3,5];case 4:null==f?v=this.getValuesFromTexture(t):(T=x(r),v=this.gpgpu.downloadFloat32MatrixFromBuffer(f,T)),l.label=5;case 5:return null!=g&&this.disposeData(g.dataId),E=this.convertAndCacheOnCPU(t,v),C=this.pendingRead.get(t),this.pendingRead.delete(t),C.forEach(function(t){return t(E)}),this.pendingDisposal.has(t)&&(this.pendingDisposal.delete(t),this.disposeData(t),this.pendingDeletes--),[2,E]}})})},e.prototype.checkNumericalProblems=function(t){if(null!=t)for(var e=0;e0?[4,Promise.all(r)]:[3,2];case 1:return a=l.sent(),s.kernelMs=E(a),s.getExtraProfileInfo=function(){return a.map(function(t,e){return{name:o[e],ms:t}}).map(function(t){return t.name+": "+t.ms}).join(", ")},[3,3];case 2:s.kernelMs={error:"WebGL query timers are not supported in this environment."},l.label=3;case 3:return this.uploadWaitMs=0,this.downloadWaitMs=0,[2,s]}})})},e.prototype.memory=function(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU}},e.prototype.startTimer=function(){return c().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:nt(),endMs:null}},e.prototype.endTimer=function(t){return c().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),t):(t.endMs=nt(),t)},e.prototype.getQueryTime=function(t){return a(this,void 0,void 0,function(){var e;return l(this,function(n){return c().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?[2,this.gpgpu.waitForQueryAndGetTime(t)]:[2,(e=t).endMs-e.startMs]})})},e.prototype.disposeData=function(t){if(!this.pendingDisposal.has(t)){if(this.pendingRead.has(t))return this.pendingDisposal.add(t),void this.pendingDeletes++;if(this.texData.has(t)){this.releaseGPUData(t);var e=this.texData.get(t).complexTensors;null!=e&&(e.real.dispose(),e.imag.dispose()),this.texData.delete(t)}}},e.prototype.releaseGPUData=function(t){var e=this.texData.get(t),n=e.texture,i=e.dtype,r=e.texShape,o=e.usage,s=e.isPacked,a=e.slice,l=a&&a.origDataId||t,u=this.dataRefCount.get(l);u>1?this.dataRefCount.set(l,u-1):(this.dataRefCount.delete(l),null!=n&&(this.numBytesInGPU-=this.computeBytes(r,i),this.textureManager.releaseTexture(n,r,o,s)));var c=this.texData.get(t);c.texture=null,c.texShape=null,c.isPacked=!1,c.slice=null},e.prototype.getTexture=function(t){return this.uploadToGPU(t),this.texData.get(t).texture},e.prototype.getDataInfo=function(t){return this.texData.get(t)},e.prototype.getCPUBackend=function(){return c().getBool("WEBGL_CPU_FORWARD")?(null==this.cpuBackend&&(this.cpuBackend=Pt.findBackend("cpu")),this.cpuBackend):null},e.prototype.shouldExecuteOnCPU=function(t,e){var n=this;return void 0===e&&(e=128),null!=this.getCPUBackend()&&t.every(function(t){return null==n.texData.get(t.dataId).texture&&t.size4)throw new Error("WebGL backend: Reverse of rank-"+n+" tensor is not yet supported");this.outputShape=t;var i=Tr("rc",n),r=i[n-1]+" + 1 < "+this.outputShape[n-1],o=i[n-2]+" + 1 < "+this.outputShape[n-2],s=Mr(n);function a(n){var i=t.map(function(i,r){return function(n,i){return-1!==e.indexOf(n)&&1!==t[n]?t[n]+" - "+i[n]+" - 1":""+i[n]}(r,n)});return"getChannel(getX("+i.join(",")+"), vec2("+i.slice(-2).join(",")+"))"}this.userCode=1===n?"\n void main(){\n int rc = getOutputCoords();\n vec4 result = vec4(0.);\n result.r = getChannel(getX("+t[0]+" - rc - 1),\n "+t[0]+" - rc - 1);\n if("+r+"){\n result.g = getChannel(getX("+t[0]+" - (rc + 1) - 1),\n "+t[0]+" - (rc + 1) - 1);\n }\n setOutput(result);\n }\n ":"\n void main() {\n "+s+" rc = getOutputCoords();\n vec4 result = vec4(0.);\n result.r = "+a(i.slice())+";\n if("+r+"){\n result.g = "+function(t){return t[n-1]="("+t[n-1]+" + 1)",a(t)}(i.slice())+";\n }\n if("+o+") {\n result.b = "+function(t){return t[n-2]="("+t[n-2]+" + 1)",a(t)}(i.slice())+";\n if("+r+") {\n result.a = "+function(t){return t[n-1]="("+t[n-1]+" + 1)",t[n-2]="("+t[n-2]+" + 1)",a(t)}(i.slice())+";\n }\n }\n setOutput(result);\n }\n "}(t.shape,e):new function(t,e){this.variableNames=["x"];var n=t.length;if(n>4)throw new Error("WebGL backend: Reverse of rank-"+n+" tensor is not yet supported");if(this.outputShape=t,1!==n){var i=t.map(function(n,i){return function(n){return-1!==e.indexOf(n)&&1!==t[n]?t[n]+" - coords["+n+"] - 1":"coords["+n+"]"}(i)}).join(","),r=Mr(n);this.userCode="\n void main() {\n "+r+" coords = getOutputCoords();\n setOutput(getX("+i+"));\n }\n "}else this.userCode="\n void main() {\n int coord = getOutputCoords();\n setOutput(getX("+t[0]+" - coord - 1));\n }\n "}(t.shape,e);return this.compileAndRun(n,[t])},e.prototype.concat=function(t,e){if("complex64"===t[0].dtype){var n=t.map(function(t){return cn(t)}),i=t.map(function(t){return hn(t)});return un(this.concat(n,e),this.concat(i,e))}if(this.shouldExecuteOnCPU(t))return this.cpuBackend.concat(t,e);if(1===t.length)return t[0];if(t.length>c().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){var r=Math.floor(t.length/2),o=this.concat(t.slice(0,r),e),s=this.concat(t.slice(r),e);return this.concat([o,s],e)}if(c().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&t[0].rank>1){var a=new function(t,e){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=an(t,e);var n=this.outputShape,i=n.length,r=Mr(i),o=Tr("coords",i),s=["x","y","z","w","u","v"].slice(0,i);this.variableNames=t.map(function(t,e){return"T"+e});var a=new Array(t.length-1);a[0]=t[0][e];for(var l=1;l= "+a[l-1]+") {\n return getChannel(\n getT"+l+"("+$r(s,u,d)+"),\n vec2("+$r(c,u,d)+"));\n }"}var f=a.length,g=a[a.length-1];p+="\n return getChannel(\n getT"+f+"("+$r(s,u,g)+"),\n vec2("+$r(c,u,g)+"));",this.userCode="\n float getValue("+s.map(function(t){return"int "+t})+") {\n "+p+"\n }\n\n void main() {\n "+r+" coords = getOutputCoords();\n vec4 result = vec4(getValue("+o+"), 0., 0., 0.);\n\n "+o[i-1]+" = "+o[i-1]+" + 1;\n if ("+o[i-1]+" < "+n[i-1]+") {\n result.g = getValue("+o+");\n }\n\n "+o[i-2]+" = "+o[i-2]+" + 1;\n if ("+o[i-2]+" < "+n[i-2]+") {\n result.a = getValue("+o+");\n }\n\n "+o[i-1]+" = "+o[i-1]+" - 1;\n if ("+o[i-2]+" < "+n[i-2]+" &&\n "+o[i-1]+" < "+n[i-1]+") {\n result.b = getValue("+o+");\n }\n setOutput(result);\n }\n "}(t.map(function(t){return t.shape}),e);return this.compileAndRun(a,t)}var l=an(t.map(function(t){return t.shape}),e),u=t.map(function(t){return t.as2D(-1,x(t.shape.slice(e)))}),h=new function(t){this.outputShape=[],this.outputShape=an(t,1),this.variableNames=t.map(function(t,e){return"T"+e});var e=new Array(t.length-1);e[0]=t[0][1];for(var n=1;n1e3){n&&(t=t.transpose([0,2,1])),i&&(e=e.transpose([0,2,1]));var l=1===o?t:t.as3D(a,s,1),u=1===o?2:1,c=1===o?e.as3D(a,1,s):e;return this.multiply(l,c).sum(u,!0)}var h=It(t.dtype,e.dtype),p=new To(t.shape,[a,r,o],n,i);return this.compileAndRun(p,[t,e],h)},e.prototype.fusedBatchMatMul=function(t){var e=t.a,n=t.b,i=t.transposeA,r=t.transposeB,o=t.bias,s=t.activation,a=t.preluActivationWeights,l=i?e.shape[2]:e.shape[1],u=r?n.shape[1]:n.shape[2],c=e.shape[0],h=It(e.dtype,n.dtype),p=null!=o,d=null!=a,f=s?Qo(s,!0):null,g=new To(e.shape,[c,l,u],i,r,p,f,d),m=[e,n];return o&&m.push(o),a&&m.push(a),this.compileAndRun(g,m,h)},e.prototype.multiply=function(t,e){if("complex64"===t.dtype){var n=this.texData.get(t.dataId),i=this.texData.get(e.dataId),r=new Pr("return areal * breal - aimag * bimag;",t.shape,e.shape),o=new Pr("return areal * bimag + aimag * breal;",t.shape,e.shape),s=[this.makeComplexComponentTensorInfo(t,n.complexTensors.real),this.makeComplexComponentTensorInfo(t,n.complexTensors.imag),this.makeComplexComponentTensorInfo(e,i.complexTensors.real),this.makeComplexComponentTensorInfo(e,i.complexTensors.imag)],a=this.compileAndRun(r,s),l=this.compileAndRun(o,s),u=this.complex(a,l);return a.dispose(),l.dispose(),u}if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.multiply(t,e);if(c().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,Ur,t.dtype);var h=new Hr(Ur,t.shape,e.shape);return this.compileAndRun(h,[t,e],t.dtype)},e.prototype.batchNormalization=function(t,e,n,i,r,o){var s=[t,e,n],a=null;null!=o&&(a=o.shape,s.push(o));var l=null;if(null!=r&&(l=r.shape,s.push(r)),c().getBool("WEBGL_PACK_NORMALIZATION")){var u=new function(t,e,n,i,r,o){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],Wi(t,e),Wi(t,n);var s="vec4(0.0)";null!=i&&(Wi(t,i),this.variableNames.push("offset"),s="getOffsetAtOutCoords()");var a="vec4(1.0)";null!=r&&(Wi(t,r),this.variableNames.push("scale"),a="getScaleAtOutCoords()"),this.outputShape=t,this.userCode="\n void main() {\n vec4 offset = "+s+";\n vec4 scale = "+a+";\n\n vec4 x = getXAtOutCoords();\n vec4 mean = getMeanAtOutCoords();\n vec4 variance = getVarianceAtOutCoords();\n\n vec4 inv = scale * inversesqrt(variance + vec4("+o+"));\n\n setOutput((x - mean) * inv + offset);\n }\n "}(t.shape,e.shape,n.shape,a,l,i);return this.compileAndRun(u,s)}var h=new function(t,e,n,i,r,o){this.outputShape=[],this.variableNames=["x","mean","variance"],Wi(t,e),Wi(t,n);var s="0.0";null!=i&&(Wi(t,i),this.variableNames.push("offset"),s="getOffsetAtOutCoords()");var a="1.0";null!=r&&(Wi(t,r),this.variableNames.push("scale"),a="getScaleAtOutCoords()"),this.outputShape=t,this.userCode="\n void main() {\n float x = getXAtOutCoords();\n float mean = getMeanAtOutCoords();\n float variance = getVarianceAtOutCoords();\n float offset = "+s+";\n float scale = "+a+";\n float inv = scale * inversesqrt(variance + float("+o+"));\n setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));\n }\n "}(t.shape,e.shape,n.shape,a,l,i);return this.compileAndRun(h,s)},e.prototype.localResponseNormalization4D=function(t,e,n,i,r){var o=c().getBool("WEBGL_PACK_NORMALIZATION")?new function(t,e,n,i,r){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;var o,s=e,a=t[3]-1;this.outputShape=t;var l="float("+n+") + float("+i+") * 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 - "+s+";\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 = - "+s+"; j <= "+s+"; j++) {\n ivec2 idx = depth + j;\n bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));\n bvec2 belowUpperBound = lessThanEqual(idx, ivec2("+a+"));\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 "}(t.shape,e,n,i,r):new function(t,e,n,i,r){this.variableNames=["x"],this.outputShape=[];var o,s=e,a=t[3]-1;this.outputShape=t;var l="float("+n+") + float("+i+") * 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 = -"+s+"; j <= "+s+"; j++) {\n int idx = d + j;\n if (idx >= 0 && idx <= "+a+") {\n float z = getX(b, r, c, idx);\n sum += z * z;\n }\n }\n float val = x * "+o+";\n setOutput(val);\n }\n "}(t.shape,e,n,i,r);return this.compileAndRun(o,[t])},e.prototype.LRNGrad=function(t,e,n,i,r,o,s){var a=new function(t,e,n,i,r){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=t,this.depth=t[3],this.depthRadius=e,this.bias=n,this.alpha=i,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 - "+e+")));\n int depthEnd = int(min(float("+this.depth+"),\n float(d + "+e+" + 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("+i+") * 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("+i+")\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 "}(e.shape,i,r,o,s);return this.compileAndRun(a,[e,n,t])},e.prototype.tile=function(t,e){if("string"===t.dtype){var n=this.readSync(t.dataId).map(function(t){return ot(t)});return vr(Gn(t.shape,t.dtype,n),e)}var i=new function(t,e){this.variableNames=["A"];for(var n=new Array(t.length),i=0;i5)throw Error("Tile for rank "+e+" is not yet supported");if(1===e)return"imod(resRC, "+t[0]+")";for(var n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],i=[],r=0;r= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))",d="",f=0,g=1===i?2:4;f= end) {\n setOutput(float("+n+"));\n } else {\n setOutput(getX(outC - start));\n }\n }\n "}(t.shape,e,n);return this.compileAndRun(i,[t])},e.prototype.transpose=function(t,e){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.transpose(t,e);var n=c().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new function(t,e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0;for(var n=new Array(t.length),i=0;i6)throw Error("Packed transpose for rank "+this.rank+" is not yet supported.");var r=Mr(this.rank),o=br("rc",this.rank),s=new Array(this.rank);for(i=0;i6)throw Error("Transpose for rank "+e+" is not yet supported");for(var n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],i=new Array(e),r=0;r4)throw Error("Gather for rank "+n+" is not yet supported");if(1===n)return"int(getIndices(resRC))";for(var i=["resRC.x","resRC.y","resRC.z","resRC.w"],r=[],o=0;o 4 with a WebGL backend not implemented yet"});var i=e.reduce(function(t,e){return t*e}),r=mi(t.shape,e,i),o=vi(r.length,e.length),s=_i(t.shape,e,i),a=yi(n,e.length),l=bi(s,n,e.length);return t.reshape(r).transpose(o).reshape(s).slice(a,l)},e.prototype.spaceToBatchND=function(t,e,n){C(t.rank<=4,function(){return"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet"});var i=e.reduce(function(t,e){return t*e}),r=[[0,0]];r.push.apply(r,n);for(var o=1+e.length;o= 1.0 && floatedReducedAllValue >= 1.0);\n ",p="bvec4"):"any"===e&&(s="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");var d="";r%n>0&&(d="\n if (inIdx < 0 || inIdx >= "+r+") {\n return initializationValue;\n }\n "),this.userCode="\n const float initializationValue = "+s+";\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("+s+");\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 "}({windowSize:Ci(r),inSize:r,batchSize:i},e),s=this.compileAndRun(o,[t],n);return 1===s.shape[1]?s:this.reduce(s,e,n)},e.prototype.argReduce=function(t,e,n){void 0===n&&(n=null);var i=t.shape[0],r=t.shape[1];null!=n&&(i=n.shape[0],r=n.shape[1]);var o=new function(t,e,n){this.variableNames=["A"];var i=t.windowSize,r=t.batchSize,o=t.inSize,s=Math.ceil(o/i);n||this.variableNames.push("bestIndicesA"),this.outputShape=[r,s];var a="max"===e?">":"<",l=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 * "+i+";\n\n int bestIndex = inOffset;\n float bestValue = getA(batch, bestIndex);\n\n for (int i = 0; i < "+i+"; i++) {\n int inIdx = "+l+";\n float candidate = getA(batch, inIdx);\n if (candidate "+a+" bestValue) {\n bestValue = candidate;\n bestIndex = inIdx;\n }\n }\n setOutput(float(bestIndex));\n }\n "}({windowSize:Ci(r),inSize:r,batchSize:i},e,null==n),s=[t];null!=n&&s.push(n);var a=this.compileAndRun(o,s,"int32");return 1===a.shape[1]?a:this.argReduce(t,e,a)},e.prototype.argReducePacked=function(t,e,n){void 0===n&&(n=null);var i=null!=n?n.shape:t.shape,r=new function(t,e,n,i){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,C(t.length>2,function(){return"Packed arg"+(n.charAt(0).toUpperCase()+n.slice(1))+" supports only inputs with rank above 2."});var r=t[t.length-1],o=Math.ceil(r/e);this.outputShape=t.slice(0,-1),o>1&&this.outputShape.push(o),i||this.variableNames.push("bestIndicesA");var s,a,l=this.outputShape,u=l.length,c=Mr(u),h=Tr("coords",u);if(1===o){var p=Mr(a=u+1);s="\n "+p+" sourceLocR = "+p+"("+h.join()+", 0);\n ++"+h[u-1]+";\n "+p+" sourceLocG = "+p+"("+h.join()+", 0);\n ++"+h[u-2]+";\n "+p+" sourceLocA = "+p+"("+h.join()+", 0);\n --"+h[u-1]+";\n "+p+" sourceLocB = "+p+"("+h.join()+", 0);\n --"+h[u-2]+";"}else a=u,s="\n "+c+" sourceLocR = coords;\n ++"+h[u-1]+";\n "+c+" sourceLocG = coords;\n ++"+h[u-2]+";\n "+c+" sourceLocA = coords;\n --"+h[u-1]+";\n "+c+" sourceLocB = coords;\n --"+h[u-2]+";";var d=["x","y","z","w","u","v"].slice(0,a),f="."+d[a-1],g=d.map(function(t){return"int "+t}),m=Tr("sourceLocR",a-1).concat("inIdx.r"),v=Tr("sourceLocG",a-1).concat("inIdx.g"),_=Tr("sourceLocB",a-1).concat("inIdx.b"),y=Tr("sourceLocA",a-1).concat("inIdx.a"),b="max"===n?"greaterThan":"lessThan",T=i?"":"\n inIdx = round(vec4(getBestIndicesAChannel("+m.join()+"),\n getBestIndicesAChannel("+v.join()+"),\n getBestIndicesAChannel("+_.join()+"),\n getBestIndicesAChannel("+y.join()+")));",E="vec4(\n getAChannel("+m.join()+"),\n hasNextCol ? getAChannel("+v.join()+") : 0.,\n hasNextRow ? getAChannel("+_.join()+") : 0.,\n hasNextRow && hasNextCol ? getAChannel("+y.join()+") : 0.)",S=i?"":"\n float getBestIndicesAChannel("+g.join()+") {\n return getChannel(getBestIndicesA("+d.join()+"),\n vec2("+d.slice(-2).join()+"));\n }";this.userCode="\n float getAChannel("+g.join()+") {\n return getChannel(getA("+d.join()+"),\n vec2("+d.slice(-2).join()+"));\n }\n "+S+"\n void main() {\n "+c+" coords = getOutputCoords();\n bool hasNextCol = "+h[u-1]+" < "+(l[u-1]-1)+";\n bool hasNextRow = "+h[u-2]+" < "+(l[u-2]-1)+";\n "+s+"\n ivec4 srcIdx = ivec4(sourceLocR"+f+", sourceLocG"+f+",\n sourceLocB"+f+", sourceLocA"+f+") * "+e+";\n ivec4 inIdx = srcIdx;\n vec4 bestIndex = vec4(inIdx);\n vec4 bestValue = "+E+";\n\n for (int i = 0; i < "+e+"; i++) {\n inIdx = srcIdx;\n "+T+"\n vec4 candidate = "+E+";\n bvec4 nan = isnan(candidate);\n bvec4 replace = bvec4(\n vec4("+b+"(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 "}(i,Ci(i[i.length-1]),e,null==n),o=null==n?[t]:[t,n],s=this.compileAndRun(r,o,"int32");return s.rank===t.rank?this.argReducePacked(t,e,s):s},e.prototype.sum=function(t,e){en("sum",e,t.rank);var n=Qe(t.shape,e),i=n[0],r=x(n[1]),o=t.as2D(-1,r),s=Rt(t.dtype);return this.reduce(o,"sum",s).reshape(i)},e.prototype.prod=function(t,e){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.prod(t,e);var n=Qe(t.shape,e),i=n[0],r=x(n[1]),o=t.as2D(-1,r),s=Rt(t.dtype);return this.reduce(o,"prod",s).reshape(i)},e.prototype.unsortedSegmentSum=function(t,e,n){var i=0,r=nn([i],t.rank),o=t;null!=r&&(o=t.transpose(r),i=on(1,t.rank)[0]);var s=function(t,e,n){for(var i=[],r=t.length,o=0;oe||n===t?i=!0:n=J(t,n+1);return n}(s,r),l=new function(t,e){this.variableNames=["x","segmentIds"];var n=t.windowSize,i=t.batchSize,r=t.inSize,o=t.numSegments,s=o*Math.ceil(r/n);this.outputShape=[i,s];var a=4*Math.floor(n/4),l=n%4,u="\n sumValue += dot(values, segFilter);\n ",c="";r%n>0&&(c="\n if (inIdx < 0 || inIdx >= "+r+") {\n return initializationValue;\n }\n ");var 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 "+o+")) * float("+n+"));\n int currentSeg = int(mod(float(outIdx), float("+o+")));\n\n float sumValue = 0.0;\n\n for (int i = 0; i < "+a+"; 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 + "+a+";\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 "}({windowSize:a,inSize:s,batchSize:o,numSegments:r},e),u=this.compileAndRun(l,[t,n],i);return u.shape[1]===r?u:(n=En(0,r).tile([s/a]),this.segOpCompute(u,e,n,i,r))},e.prototype.argMinMaxReduce=function(t,e,n){var i=[e];if(en("arg"+n.charAt(0).toUpperCase()+n.slice(1),i,t.rank),!c().getBool("WEBGL_PACK_REDUCE")||t.rank<=2){var r=Qe(t.shape,i),o=r[0],s=x(r[1]),a=t.as2D(-1,s);return this.argReduce(a,n).reshape(o)}return this.argReducePacked(t,n)},e.prototype.argMin=function(t,e){return this.argMinMaxReduce(t,e,"min")},e.prototype.argMax=function(t,e){return this.argMinMaxReduce(t,e,"max")},e.prototype.cumsum=function(t,e,n,i){if(e!==t.rank-1)throw new Error("WebGL cumsum shader expects an inner-most axis="+(t.rank-1)+" but got axis="+e);var r=new function(t,e,n){this.variableNames=["x"],this.outputShape=t;var i=t.length,r=t[t.length-1],o=n?"<":">";this.userCode="\n int getIndex(int i) {\n "+(n?"return "+r+" -i - 1;":"return i;")+"\n }\n\n void main() {\n "+Mr(i)+" coords = getOutputCoords();\n int end = "+Jr(i,"coords")+";\n float val = 0.0;\n for (int i = "+r+" - 1; i >= 0; i -= 1) {\n int idx = getIndex(i);\n if (idx "+o+" end) {\n continue;\n }\n if (idx == end && "+e+") {\n continue;\n }\n "+Jr(i,"coords")+" = idx;\n val += getX("+function(t,e){if(1===t)return""+e;if(2===t)return e+".x, "+e+".y";if(3===t)return e+".x, "+e+".y, "+e+".z";if(4===t)return e+".x, "+e+".y, "+e+".z, "+e+".w";throw Error("Cumulative sum for rank "+t+" is not yet supported")}(i,"coords")+");\n }\n setOutput(val);\n }\n "}(t.shape,n,i);return this.compileAndRun(r,[t])},e.prototype.equal=function(t,e){if(c().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(equal(a, b));\n","bool");var n=new Hr("return float(a == b);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},e.prototype.notEqual=function(t,e){if(c().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(notEqual(a, b));\n","bool");var n=new Hr("return float(a != b);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},e.prototype.less=function(t,e){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.less(t,e);if(c().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(lessThan(a, b));\n","bool");var n=new Hr("return float(a < b);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},e.prototype.lessEqual=function(t,e){if(c().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(lessThanEqual(a, b));\n","bool");var n=new Hr("return float(a <= b);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},e.prototype.greater=function(t,e){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.greater(t,e);if(c().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(greaterThan(a, b));\n","bool");var n=new Hr("return float(a > b);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},e.prototype.greaterEqual=function(t,e){if(c().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(greaterThanEqual(a, b));\n","bool");var n=new Hr("return float(a >= b);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},e.prototype.logicalNot=function(t){var e=new No(t.shape,"return float(!(x >= 1.0));");return this.compileAndRun(e,[t])},e.prototype.logicalAnd=function(t,e){if(c().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(\n vec4(greaterThanEqual(a, vec4(1.0))) *\n vec4(greaterThanEqual(b, vec4(1.0))));\n","bool");var n=new Hr("return float(a >= 1.0 && b >= 1.0);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},e.prototype.logicalOr=function(t,e){if(c().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return min(\n vec4(greaterThanEqual(a, vec4(1.0))) +\n vec4(greaterThanEqual(b, vec4(1.0))),\n vec4(1.0));\n","bool");var n=new Hr("return float(a >= 1.0 || b >= 1.0);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},e.prototype.select=function(t,e,n){var i=new function(t,e,n){var i,r;if(this.variableNames=["c","a","b"],this.outputShape=e,n>4)throw Error("Where for rank "+n+" is not yet supported");if(1===n)r="resRC",i="resRC";else{for(var o=["resRC.x","resRC.y","resRC.z","resRC.w"],s=[],a=[],l=0;l= 1.0) {\n setOutput(getA("+r+"));\n } else {\n setOutput(getB("+r+"));\n }\n }\n "}(t.rank,e.shape,e.rank);return this.compileAndRun(i,[t,e,n],It(e.dtype,n.dtype))},e.prototype.where=function(t){$e("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");var e=t.dataSync();return yr(t.shape,e)},e.prototype.topk=function(t,e,n){return _r(t.dataSync(),t.shape,t.dtype,e)},e.prototype.min=function(t,e){en("min",e,t.rank);var n=Qe(t.shape,e),i=n[0],r=x(n[1]),o=t.as2D(-1,r);return this.reduce(o,"min",o.dtype).reshape(i)},e.prototype.minimum=function(t,e){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.minimum(t,e);var n=c().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Gr("\n vec4 result = vec4(min(a, b));\n vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n",t.shape,e.shape):new Hr("\n if (isnan(a)) return a;\n if (isnan(b)) return b;\n\n return min(a, b);\n",t.shape,e.shape);return this.compileAndRun(n,[t,e])},e.prototype.mod=function(t,e){var n=c().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Gr("\n vec4 result = mod(a, b);\n vec4 isNaN = vec4(equal(b, vec4(0.0)));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n",t.shape,e.shape):new Hr("if (b == 0.0) return NAN;\n return mod(a, b);",t.shape,e.shape);return this.compileAndRun(n,[t,e])},e.prototype.max=function(t,e){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.max(t,e);en("max",e,t.rank);var n=Qe(t.shape,e),i=n[0],r=x(n[1]),o=t.as2D(-1,r);return this.reduce(o,"max",o.dtype).reshape(i)},e.prototype.maximum=function(t,e){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.maximum(t,e);var n=c().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Gr("\n vec4 result = vec4(max(a, b));\n vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n",t.shape,e.shape):new Hr("\n if (isnan(a)) return a;\n if (isnan(b)) return b;\n\n return max(a, b);\n",t.shape,e.shape);return this.compileAndRun(n,[t,e])},e.prototype.all=function(t,e){en("all",e,t.rank);var n=Qe(t.shape,e),i=n[0],r=x(n[1]),o=t.as2D(-1,r);return this.reduce(o,"all",o.dtype).reshape(i)},e.prototype.any=function(t,e){en("any",e,t.rank);var n=Qe(t.shape,e),i=n[0],r=x(n[1]),o=t.as2D(-1,r);return this.reduce(o,"any",o.dtype).reshape(i)},e.prototype.realDivide=function(t,e){if(c().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\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","float32",!0);var n=new Hr("\nif (a == b) {\n return 1.0;\n};\nreturn a / b;",t.shape,e.shape);return this.compileAndRun(n,[t,e],"float32")},e.prototype.floorDiv=function(t,e){if(c().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\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","int32");var n=new Hr("\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",t.shape,e.shape);return this.compileAndRun(n,[t,e],"int32")},e.prototype.add=function(t,e){if("complex64"===t.dtype&&"complex64"===e.dtype)return this.complexSeparableBinaryOp(t,e,Br);if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.add(t,e);var n=It(t.dtype,e.dtype);if(c().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,Br,n);var i=new Hr(Br,t.shape,e.shape);return this.compileAndRun(i,[t,e],n)},e.prototype.packedUnaryOp=function(t,e,n){var i=new qo(t.shape,e);return this.compileAndRun(i,[t],n)},e.prototype.packedBinaryOp=function(t,e,n,i,r){void 0===r&&(r=!1);var o=new Gr(n,t.shape,e.shape,r);return this.compileAndRun(o,[t,e],i)},e.prototype.complexSeparableBinaryOp=function(t,e,n){var i=this,r=this.texData.get(t.dataId),o=this.texData.get(e.dataId),s=[[r.complexTensors.real,o.complexTensors.real],[r.complexTensors.imag,o.complexTensors.imag]].map(function(r){var o=r[0],s=r[1],a=i.makeComplexComponentTensorInfo(t,o),l=i.makeComplexComponentTensorInfo(e,s),u=new Hr(n,t.shape,e.shape);return i.compileAndRun(u,[a,l],It(o.dtype,s.dtype))}),a=s[0],l=s[1],u=this.complex(a,l);return a.dispose(),l.dispose(),u},e.prototype.makeComplexComponentTensorInfo=function(t,e){return{dataId:e.dataId,dtype:e.dtype,shape:t.shape}},e.prototype.addN=function(t){if(1===t.length)return t[0];if(t.length>c().get("WEBGL_MAX_TEXTURES_IN_SHADER")){var e=Math.floor(t.length/2),n=this.addN(t.slice(0,e)),i=this.addN(t.slice(e));return this.addN([n,i])}var r=t.map(function(t){return t.dtype}).reduce(function(t,e){return It(t,e)}),o=t.map(function(t){return t.shape}),s=c().getBool("WEBGL_PACK")?new function(t,e){this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,this.variableNames=e.map(function(t,e){return"T"+e});var n=[];this.variableNames.forEach(function(t){n.push("vec4 v"+t+" = get"+t+"AtOutCoords();")});var i=this.variableNames.map(function(t){return"v"+t}).join(" + ");this.userCode="\n void main() {\n "+n.join("\n ")+"\n\n vec4 result = "+i+";\n setOutput(result);\n }\n "}(t[0].shape,o):new function(t,e){this.outputShape=[],this.outputShape=t,this.variableNames=e.map(function(t,e){return"T"+e});var n=[];this.variableNames.forEach(function(t){n.push("float v"+t+" = get"+t+"AtOutCoords();")});var i=this.variableNames.map(function(t){return"v"+t}).join(" + ");this.userCode="\n void main() {\n "+n.join("\n ")+"\n\n float result = "+i+";\n setOutput(result);\n }\n "}(t[0].shape,o);return this.compileAndRun(s,t,r)},e.prototype.subtract=function(t,e){if("complex64"===t.dtype&&"complex64"===e.dtype)return this.complexSeparableBinaryOp(t,e,Fr);if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.subtract(t,e);var n=It(t.dtype,e.dtype);if(c().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,Fr,t.dtype);var i=new Hr(Fr,t.shape,e.shape);return this.compileAndRun(i,[t,e],n)},e.prototype.pow=function(t,e){var n=c().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Gr("\n // isModRound1 has 1 for components with round(mod(b, 2.0)) == 1, 0 otherwise.\n vec4 isModRound1 = vec4(equal(round(mod(b, 2.0)), ivec4(1)));\n vec4 multiplier = sign(a) * isModRound1 + (vec4(1.0) - isModRound1);\n vec4 result = multiplier * pow(abs(a), b);\n\n // Ensure that a^0 = 1, including 0^0 = 1 as this correspond to TF and JS\n bvec4 isExpZero = equal(b, vec4(0.0));\n result.r = isExpZero.r ? 1.0 : result.r;\n result.g = isExpZero.g ? 1.0 : result.g;\n result.b = isExpZero.b ? 1.0 : result.b;\n result.a = isExpZero.a ? 1.0 : result.a;\n\n vec4 isNaN = vec4(lessThan(a, vec4(0.0))) * vec4(lessThan(floor(b), b));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n",t.shape,e.shape):new Hr("\nif(a < 0.0 && floor(b) < b){\n return NAN;\n}\nif (b == 0.0) {\n return 1.0;\n}\nreturn (round(mod(b, 2.0)) != 1) ?\n pow(abs(a), b) : sign(a) * pow(abs(a), b);\n",t.shape,e.shape),i=It(t.dtype,e.dtype);return this.compileAndRun(n,[t,e],i)},e.prototype.ceil=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.ceil(t);if(c().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,Wo,t.dtype);var e=new No(t.shape,Wo);return this.compileAndRun(e,[t])},e.prototype.floor=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.floor(t);if(c().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,Go,t.dtype);var e=new No(t.shape,Go);return this.compileAndRun(e,[t])},e.prototype.sign=function(t){var e=new No(t.shape,"\n if (isnan(x)) { return 0.0; }\n return sign(x);\n");return this.compileAndRun(e,[t])},e.prototype.isNaN=function(t){var e=new No(t.shape,"return float(isnan(x));");return this.compileAndRun(e,[t],"bool")},e.prototype.isInf=function(t){var e=new No(t.shape,"return float(isinf(x));");return this.compileAndRun(e,[t],"bool")},e.prototype.isFinite=function(t){var e=new No(t.shape,"return float(!isnan(x) && !isinf(x));");return this.compileAndRun(e,[t],"bool")},e.prototype.round=function(t){var e=new No(t.shape,"\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");return this.compileAndRun(e,[t])},e.prototype.exp=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.exp(t);if(c().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,jo,t.dtype);var e=new No(t.shape,jo);return this.compileAndRun(e,[t])},e.prototype.expm1=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.expm1(t);if(c().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,zo,t.dtype);var e=new No(t.shape,zo);return this.compileAndRun(e,[t])},e.prototype.softmax=function(t,e){var n=L([e],t.shape),i=this.max(t,n),r=tn(i.shape,n),o=this.subtract(t,i.reshape(r)),s=this.exp(o),a=this.sum(s,n).reshape(r);return this.realDivide(s,a)},e.prototype.log=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.log(t);if(c().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,"\n vec4 result = log(x);\n vec4 isNaN = vec4(lessThan(x, vec4(0.0)));\n result.r = isNaN.r == 1.0 ? NAN : result.r;\n result.g = isNaN.g == 1.0 ? NAN : result.g;\n result.b = isNaN.b == 1.0 ? NAN : result.b;\n result.a = isNaN.a == 1.0 ? NAN : result.a;\n\n return result;\n",t.dtype);var e=new No(t.shape,"if (x < 0.0) return NAN;\n return log(x);");return this.compileAndRun(e,[t])},e.prototype.log1p=function(t){var e=new No(t.shape,"return log(1.0 + x);");return this.compileAndRun(e,[t])},e.prototype.sqrt=function(t){var e=new No(t.shape,"return sqrt(x);");return this.compileAndRun(e,[t])},e.prototype.rsqrt=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.rsqrt(t);var e=new No(t.shape,"return inversesqrt(x);");return this.compileAndRun(e,[t])},e.prototype.reciprocal=function(t){var e=new No(t.shape,"return 1.0 / x;");return this.compileAndRun(e,[t])},e.prototype.relu=function(t){var e;return e=c().getBool("WEBGL_PACK")?new qo(t.shape,Yo):new No(t.shape,Fo),this.compileAndRun(e,[t])},e.prototype.relu6=function(t){var e;return e=c().getBool("WEBGL_PACK")?new qo(t.shape,Ko):new No(t.shape,Uo),this.compileAndRun(e,[t])},e.prototype.prelu=function(t,e){var n=c().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Gr(Wr,t.shape,e.shape):new Hr(Vr,t.shape,e.shape);return this.compileAndRun(n,[t,e])},e.prototype.elu=function(t){if(c().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,Jo,t.dtype);var e=new No(t.shape,Vo);return this.compileAndRun(e,[t])},e.prototype.eluDer=function(t,e){var n=c().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Gr("\n vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));\n return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));\n",t.shape,e.shape):new Hr("return (b >= 1.0) ? a : a * (b + 1.0);",t.shape,e.shape);return this.compileAndRun(n,[t,e])},e.prototype.selu=function(t){var e=new No(t.shape,"\n // Stable and Attracting Fixed Point (0, 1) for Normalized Weights.\n // see: https://arxiv.org/abs/1706.02515\n float scaleAlpha = 1.7580993408473768;\n float scale = 1.0507009873554805;\n return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);\n");return this.compileAndRun(e,[t])},e.prototype.int=function(t){var e=new No(t.shape,"return float(int(x));");return this.compileAndRun(e,[t],"int32")},e.prototype.clip=function(t,e,n){var i,r=(i=c().getBool("WEBGL_PACK_CLIP")?new zr(t.shape):new jr(t.shape)).getCustomSetupFunc(e,n);return this.compileAndRun(i,[t],null,r)},e.prototype.abs=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.abs(t);if(c().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,Bo,t.dtype);var e=new No(t.shape,Bo);return this.compileAndRun(e,[t])},e.prototype.complexAbs=function(t){var e=this.texData.get(t.dataId),n=new function(t){this.variableNames=["real","imag"],this.outputShape=t,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 "}(t.shape),i=[this.makeComplexComponentTensorInfo(t,e.complexTensors.real),this.makeComplexComponentTensorInfo(t,e.complexTensors.imag)];return this.compileAndRun(n,i)},e.prototype.sigmoid=function(t){var e=new No(t.shape,"return 1.0 / (1.0 + exp(-1.0 * x));");return this.compileAndRun(e,[t])},e.prototype.softplus=function(t){var e=new No(t.shape,"\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");return this.compileAndRun(e,[t])},e.prototype.sin=function(t){var e=new No(t.shape,"if (isnan(x)) return x;\n return sin(x);\n");return this.compileAndRun(e,[t])},e.prototype.cos=function(t){var e=new No(t.shape,"if (isnan(x)) return x;\n return cos(x);\n");return this.compileAndRun(e,[t])},e.prototype.tan=function(t){var e=new No(t.shape,"return tan(x);");return this.compileAndRun(e,[t])},e.prototype.asin=function(t){var e=new No(t.shape,"if (isnan(x)) return x;\n if (abs(x) > 1.) {\n return NAN;\n }\n return asin(x);\n");return this.compileAndRun(e,[t])},e.prototype.acos=function(t){var e=new No(t.shape,"if (isnan(x)) return x;\n if (abs(x) > 1.) {\n return NAN;\n }\n return acos(x);\n");return this.compileAndRun(e,[t])},e.prototype.atan=function(t){var e=new No(t.shape,"if (isnan(x)) return x;\n return atan(x);\n");return this.compileAndRun(e,[t])},e.prototype.atan2=function(t,e){var n=c().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Gr("\n vec4 result = atan(a, b);\n vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n",t.shape,e.shape):new Hr("\n if (isnan(a)) return a;\n if (isnan(b)) return b;\n\n return atan(a, b);\n",t.shape,e.shape);return this.compileAndRun(n,[t,e])},e.prototype.sinh=function(t){var e=new No(t.shape,"\n float e2x = exp(x);\n return (e2x - 1.0 / e2x) / 2.0;\n");return this.compileAndRun(e,[t])},e.prototype.cosh=function(t){var e=new No(t.shape,"\n float e2x = exp(-x);\n return (e2x + 1.0 / e2x) / 2.0;\n");return this.compileAndRun(e,[t])},e.prototype.tanh=function(t){var e=new No(t.shape,"\n float e2x = exp(-2.0 * abs(x));\n return sign(x) * (1.0 - e2x) / (1.0 + e2x);\n");return this.compileAndRun(e,[t])},e.prototype.asinh=function(t){var e=new No(t.shape,"if (isnan(x)) return x;return log(x + sqrt(x * x + 1.0));");return this.compileAndRun(e,[t])},e.prototype.acosh=function(t){var e=new No(t.shape,"if (isnan(x)) return x;\n if (x < 1.0) return NAN;\n return log(x + sqrt(x * x - 1.0));");return this.compileAndRun(e,[t])},e.prototype.atanh=function(t){var e=new No(t.shape,"if (isnan(x)) return x;\n if ((x < -1.0) || (x > 1.0)) return NAN;\n return (log(1.0 + x) - log(1.0 - x)) / 2.0;");return this.compileAndRun(e,[t])},e.prototype.erf=function(t){var e=new No(t.shape,'\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 = 0.3275911;\n float a1 = 0.254829592;\n float a2 = -0.284496736;\n float a3 = 1.421413741;\n float a4 = -1.453152027;\n float a5 = 1.061405429;\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');return this.compileAndRun(e,[t])},e.prototype.step=function(t,e){var n=new No(t.shape,function(t){return void 0===t&&(t=0),Lo+"\n return x > 0.0 ? 1.0 : float("+t+");\n "}(e));return this.compileAndRun(n,[t])},e.prototype.conv2dByMatMul=function(t,e,n,i,r,o){var s=t.shape,a=this.texData.get(t.dataId),l=n.inChannels,u=s[0]*s[1]*s[2],h=n.outChannels,p="channelsLast"===n.dataFormat,d=(1===u||1===h)&&l>1e3,f=s[2]%2!=0&&!!a.isPacked;if(d||!c().getBool("WEBGL_LAZILY_UNPACK")||!c().getBool("WEBGL_PACK_BINARY_OPERATIONS")||!f){var g=p?s[0]*s[1]*s[2]:s[0]*s[2]*s[3],m=this.reshape(t,[1,g,n.inChannels]),v=this.reshape(e,[1,n.inChannels,n.outChannels]);return this.reshape(this.fusedBatchMatMul({a:m,b:v,transposeA:!1,transposeB:!1,bias:i,activation:r,preluActivationWeights:o}),n.outShape)}var _=p?s[0]*s[1]*(s[2]+1):s[0]*s[2]*(s[3]+1),y={dataId:t.dataId,shape:[1,_,n.inChannels],dtype:t.dtype},b=a.shape;a.shape=a.shape.slice(),a.shape[a.shape.length-2]++,C(De(a.shape,y.shape),function(){return"packed reshape "+a.shape+" to "+y.shape+" isn't free"});var T=this.reshape(e,[1,n.inChannels,n.outChannels]),E=this.fusedBatchMatMul({a:y,b:T,transposeA:!1,transposeB:!1,bias:i,activation:r,preluActivationWeights:o}),S=this.texData.get(E.dataId);return C(S.isPacked,function(){return"batchMatMul result is expected to be packed"}),a.shape=b,S.shape=n.outShape,Pt.makeTensorFromDataId(E.dataId,n.outShape,E.dtype)},e.prototype.conv2dWithIm2Row=function(t,e,n,i,r,o){var s=n.filterWidth,a=n.filterHeight,l=n.inChannels,u=n.outWidth,c=n.outHeight,h="channelsLast"===n.dataFormat,p=s*a*l,d=c*u,f=[p,d],g=t.squeeze([0]),m=e.reshape([1,p,-1]),v=new function(t,e,n){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t;for(var i=n.filterWidth,r=n.inChannels,o=n.strideWidth,s=n.strideHeight,a=n.padInfo,l=n.outWidth,u=n.dilationWidth,c=n.dilationHeight,h=n.dataFormat,p=a.left,d=a.top,f=r*i,g=Er(),m="channelsLast"===h,v=m?0:1,_=m?1:2,y="",b=0;b<=1;b++)for(var T=0;T<=1;T++)y+="\n blockIndex = rc.y + "+T+";\n pos = rc.x + "+b+";\n\n if(blockIndex < "+t[1]+" && pos < "+t[0]+") {\n offsetY = int(blockIndex / ("+l+")) * "+s+" - "+d+";\n d0 = offsetY + "+c+" * (pos / "+f+");\n\n if(d0 < "+e[v]+" && d0 >= 0) {\n\n offsetX = int(mod(float(blockIndex), "+l+".) * "+o+". - "+p+".);\n d1 = offsetX + "+u+" * (int(mod(float(pos), "+f+".) / "+r+".));\n\n if(d1 < "+e[_]+" && d1 >= 0) {\n\n ch = int(mod(float(pos), "+r+".));\n\n if ("+m+") {\n innerDims = vec2(d1, ch);\n result["+(2*b+T)+"] = getChannel(\n getA(d0, int(innerDims.x),\n int(innerDims.y)), innerDims);\n } else {\n innerDims = vec2(d0, d1);\n result["+(2*b+T)+"] = getChannel(\n getA(ch, int(innerDims.x),\n int(innerDims.y)), innerDims);\n }\n }\n }\n }\n ";this.userCode="\n void main() {\n ivec2 rc = getOutputCoords();\n\n vec4 result = vec4(0);\n\n int blockIndex, pos, offsetY, d0, offsetX, d1, ch;\n vec2 innerDims;\n\n "+y+"\n\n "+g.output+" = result;\n }\n "}(f,g.shape,n),_=this.compileAndRun(v,[g]).reshape([1,f[0],f[1]]),y=null!=i,b=null!=o,T=r?Qo(r,!0):null,E=new To(_.shape,[1,d,n.outChannels],!0,!1,y,T,b),C=[_,m];i&&C.push(i),b&&C.push(o);var S=this.compileAndRun(E,C);return h?S.reshape([1,c,u,n.outChannels]):S.reshape([1,n.outChannels,c,u])},e.prototype.fusedConv2d=function(t){var e=t.input,n=t.filter,i=t.convInfo,r=t.bias,o=t.activation,s=t.preluActivationWeights;if(1===i.filterHeight&&1===i.filterWidth&&1===i.dilationHeight&&1===i.dilationWidth&&1===i.strideHeight&&1===i.strideWidth&&("SAME"===i.padInfo.type||"VALID"===i.padInfo.type))return this.conv2dByMatMul(e,n,i,r,o,s);if(c().getBool("WEBGL_CONV_IM2COL")&&1===e.shape[0])return this.conv2dWithIm2Row(e,n,i,r,o,s);var a=null!=r,l=null!=s,u=o?Qo(o,!1):null,h=new Xr(i,a,u,l),p=[e,n];return r&&p.push(r),s&&p.push(s),this.compileAndRun(h,p)},e.prototype.conv2d=function(t,e,n){if(1===n.filterHeight&&1===n.filterWidth&&1===n.dilationHeight&&1===n.dilationWidth&&1===n.strideHeight&&1===n.strideWidth&&("SAME"===n.padInfo.type||"VALID"===n.padInfo.type))return this.conv2dByMatMul(t,e,n);if(c().getBool("WEBGL_CONV_IM2COL")&&1===t.shape[0])return this.conv2dWithIm2Row(t,e,n);var i=new Xr(n);return this.compileAndRun(i,[t,e])},e.prototype.conv2dDerInput=function(t,e,n){var i=new function(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterHeight,n=t.filterWidth,i=t.strideHeight,r=t.strideWidth,o="channelsLast"===t.dataFormat,s=e-1-t.padInfo.top,a=n-1-t.padInfo.left,l=o?1:2,u=o?2:3,c=o?3:1;this.userCode="\n const ivec2 pads = ivec2("+s+", "+a+");\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 < "+e+"; wR++) {\n float dyR = float(dyRCorner + wR) / "+i+".0;\n\n if (dyR < 0.0 || dyR >= "+t.outHeight+".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = "+e+" - 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 >= "+t.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 < "+t.outChannels+"; d2++) {\n\n if ("+o+") {\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 "}(n);return this.compileAndRun(i,[t,e])},e.prototype.conv2dDerFilter=function(t,e,n){var i=new function(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;var e=t.strideHeight,n=t.strideWidth,i=t.padInfo.top,r=t.padInfo.left,o="channelsLast"===t.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 < "+t.batchSize+"; b++) {\n for (int yR = 0; yR < "+t.outHeight+"; yR++) {\n int xR = wR + yR * "+e+" - "+i+";\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int yC = 0; yC < "+t.outWidth+"; yC++) {\n int xC = wC + yC * "+n+" - "+r+";\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n if ("+o+") {\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 "}(n);return this.compileAndRun(i,[t,e])},e.prototype.fusedDepthwiseConv2D=function(t){var e,n=t.input,i=t.filter,r=t.convInfo,o=t.bias,s=t.activation,a=t.preluActivationWeights,l=c().getBool("WEBGL_PACK_DEPTHWISECONV")&&r.strideWidth<=2&&r.outChannels/r.inChannels==1,u=s?Qo(s,l):null,h=[n,i],p=null!=o,d=null!=a;return p&&h.push(o),d&&h.push(a),l?(e=new Kr(r,p,u,d),this.compileAndRun(e,h)):(e=new Yr(r,p,u,d),this.compileAndRun(e,h))},e.prototype.depthwiseConv2D=function(t,e,n){var i;return c().getBool("WEBGL_PACK_DEPTHWISECONV")&&n.strideWidth<=2&&n.outChannels/n.inChannels==1?(i=new Kr(n),this.compileAndRun(i,[t,e])):(i=new Yr(n),this.compileAndRun(i,[t,e]))},e.prototype.depthwiseConv2DDerInput=function(t,e,n){var i=new function(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterHeight,n=t.filterWidth,i=t.strideHeight,r=t.strideWidth,o=e-1-t.padInfo.top,s=n-1-t.padInfo.left,a=t.outChannels/t.inChannels;this.userCode="\n const ivec2 pads = ivec2("+o+", "+s+");\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 < "+e+"; wR++) {\n float dyR = float(dyRCorner + wR) / "+i+".0;\n\n if (dyR < 0.0 || dyR >= "+t.outHeight+".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = "+e+" - 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 >= "+t.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 < "+a+"; dm++) {\n int d2 = d1 * "+a+" + 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 "}(n);return this.compileAndRun(i,[t,e])},e.prototype.depthwiseConv2DDerFilter=function(t,e,n){var i=new function(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;var e=t.strideHeight,n=t.strideWidth,i=t.padInfo.top,r=t.padInfo.left,o=t.outChannels/t.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 * "+o+" + dm;\n\n float dotProd = 0.0;\n\n // TO DO: Vec4 over the batch size\n for (int b = 0; b < "+t.batchSize+"; b++) {\n for (int yR = 0; yR < "+t.outHeight+"; yR++) {\n int xR = wR + yR * "+e+" - "+i+";\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int yC = 0; yC < "+t.outWidth+"; yC++) {\n int xC = wC + yC * "+n+" - "+r+";\n\n if (xC < 0 || xC >= "+t.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 "}(n);return this.compileAndRun(i,[t,e])},e.prototype.conv3d=function(t,e,n){var i=new function(t){this.variableNames=["x","W"],this.outputShape=t.outShape;var e=t.padInfo.front,n=t.padInfo.top,i=t.padInfo.left,r=t.strideDepth,o=t.strideHeight,s=t.strideWidth,a=t.dilationDepth,l=t.dilationHeight,u=t.dilationWidth,c=t.filterDepth,h=t.filterHeight,p=t.filterWidth,d=4*Math.floor(t.inChannels/4),f=t.inChannels%4;this.userCode="\n const ivec3 strides = ivec3("+r+", "+o+", "+s+");\n const ivec3 pads = ivec3("+e+", "+n+", "+i+");\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 * "+a+";\n\n if (xF < 0 || xF >= "+t.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 >= "+t.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 >= "+t.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 "}(n);return this.compileAndRun(i,[t,e])},e.prototype.conv3dDerInput=function(t,e,n){var i=new function(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterDepth,n=t.filterHeight,i=t.filterWidth,r=t.strideDepth,o=t.strideHeight,s=t.strideWidth,a=e-1-t.padInfo.front,l=n-1-t.padInfo.top,u=i-1-t.padInfo.left;this.userCode="\n const ivec3 pads = ivec3("+a+", "+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 < "+e+"; wF++) {\n float dyF = float(dyFCorner + wF) / "+r+".0;\n\n if (dyF < 0.0 || dyF >= "+t.outDepth+".0 || fract(dyF) > 0.0) {\n continue;\n }\n int idyF = int(dyF);\n\n int wFPerm = "+e+" - 1 - wF;\n\n for (int wR = 0; wR < "+n+"; wR++) {\n float dyR = float(dyRCorner + wR) / "+o+".0;\n\n if (dyR < 0.0 || dyR >= "+t.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 < "+i+"; wC++) {\n float dyC = float(dyCCorner + wC) / "+s+".0;\n\n if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = "+i+" - 1 - wC;\n\n for (int d2 = 0; d2 < "+t.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 "}(n);return this.compileAndRun(i,[t,e])},e.prototype.conv3dDerFilter=function(t,e,n){var i=new function(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;var e=t.strideDepth,n=t.strideHeight,i=t.strideWidth,r=t.padInfo.front,o=t.padInfo.top,s=t.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 < "+t.batchSize+"; b++) {\n for (int yF = 0; yF < "+t.outDepth+"; yF++) {\n int xF = wF + yF * "+e+" - "+r+";\n\n if (xF < 0 || xF >= "+t.inDepth+") {\n continue;\n }\n\n for (int yR = 0; yR < "+t.outHeight+"; yR++) {\n int xR = wR + yR * "+n+" - "+o+";\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int yC = 0; yC < "+t.outWidth+"; yC++) {\n int xC = wC + yC * "+i+" - "+s+";\n\n if (xC < 0 || xC >= "+t.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 "}(n);return this.compileAndRun(i,[t,e])},e.prototype.maxPool=function(t,e){var n=new Co(e,"max",!1);return this.compileAndRun(n,[t])},e.prototype.avgPool=function(t,e){var n=new Co(e,"avg",!1);return this.compileAndRun(n,[t],"float32")},e.prototype.maxPoolBackprop=function(t,e,n,i){var r=new Co(i,"max",!0),o=this.compileAndRun(r,[e]),s=new function(t){this.variableNames=["dy","maxPos"],this.outputShape=t.inShape;var e=t.strideHeight,n=t.strideWidth,i=t.dilationHeight,r=t.effectiveFilterHeight,o=t.effectiveFilterWidth,s=r-1-t.padInfo.top,a=o-1-t.padInfo.left,l=r*o-1;this.userCode="\n const ivec2 pads = ivec2("+s+", "+a+");\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 += "+i+") {\n float dyR = float(dyRCorner + wR) / "+e+".0;\n\n if (dyR < 0.0 || dyR >= "+t.outHeight+".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < "+o+"; wC++) {\n float dyC = float(dyCCorner + wC) / "+n+".0;\n\n if (dyC < 0.0 || dyC >= "+t.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 * "+o+" + wC;\n float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n dotProd += dyValue * mask;\n }\n }\n setOutput(dotProd);\n }\n "}(i),a=this.compileAndRun(s,[t,o],e.dtype);return o.dispose(),a},e.prototype.avgPoolBackprop=function(t,e,n){var i=new function(t){this.variableNames=["dy"],this.outputShape=t.inShape;var e=t.filterHeight,n=t.filterWidth,i=t.strideHeight,r=t.strideWidth,o=t.dilationHeight,s=t.dilationWidth,a=t.effectiveFilterHeight,l=t.effectiveFilterWidth,u=a-1-t.padInfo.top,c=l-1-t.padInfo.left,h=1/(e*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 < "+a+";\n wR += "+o+") {\n float dyR = float(dyRCorner + wR) / "+i+".0;\n\n if (dyR < 0.0 || dyR >= "+t.outHeight+".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < "+l+";\n wC+= "+s+") {\n float dyC = float(dyCCorner + wC) / "+r+".0;\n\n if (dyC < 0.0 || dyC >= "+t.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 "}(n);return this.compileAndRun(i,[t],e.dtype)},e.prototype.cast=function(t,e){return er(t,e,this)},e.prototype.unstack=function(t,e){for(var n=t.shape[e],i=new Array(t.rank-1),r=0,o=0;o= "+t.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) / "+o+".0;\n\n if (dyR < 0.0 || dyR >= "+t.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) / "+s+".0;\n\n if (dyC < 0.0 || dyC >= "+t.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 "}(n);return this.compileAndRun(i,[t],e.dtype)},e.prototype.maxPool3d=function(t,e){var n=new So(e,"max",!1);return this.compileAndRun(n,[t],"float32")},e.prototype.maxPool3dBackprop=function(t,e,n,i){var r=new So(i,"max",!0),o=this.compileAndRun(r,[e]),s=new function(t){this.variableNames=["dy","maxPos"],this.outputShape=t.inShape;var e=t.strideDepth,n=t.strideHeight,i=t.strideWidth,r=t.dilationDepth,o=t.dilationHeight,s=t.dilationWidth,a=t.effectiveFilterDepth,l=t.effectiveFilterHeight,u=t.effectiveFilterWidth,c=a-1-t.padInfo.front,h=l-1-t.padInfo.top,p=u-1-t.padInfo.left,d=a*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 < "+a+";\n wD += "+r+") {\n float dyD = float(dyDCorner + wD) / "+e+".0;\n\n if (dyD < 0.0 || dyD >= "+t.outDepth+".0 || fract(dyD) > 0.0) {\n continue;\n }\n int idyD = int(dyD);\n\n for (int wR = 0; wR < "+l+";\n wR += "+o+") {\n float dyR = float(dyRCorner + wR) / "+n+".0;\n\n if (dyR < 0.0 || dyR >= "+t.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 += "+s+") {\n float dyC = float(dyCCorner + wC) / "+i+".0;\n\n if (dyC < 0.0 || dyC >= "+t.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 "}(i),a=this.compileAndRun(s,[t,o],e.dtype);return o.dispose(),a},e.prototype.reshape=function(t,e){var n=this.texData.get(t.dataId);if(n.isPacked&&!De(t.shape,e)&&(null===n.texture||!De(n.shape,e))){var i=this.packedReshape(t,e);return Pt.makeTensorFromDataId(i.dataId,i.shape,i.dtype)}return nr(t,e)},e.prototype.resizeBilinear=function(t,e,n,i){var r=c().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new function(t,e,n,i){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];var r=t[0],o=t[1],s=t[2],a=t[3];this.outputShape=[r,e,n,a];var l=[i&&e>1?o-1:o,i&&n>1?s-1:s],u=[i&&e>1?e-1:e,i&&n>1?n-1:n];this.userCode="\n const vec3 effectiveInputOverOutputRatioRC = vec3(\n "+l[0]/u[0]+",\n "+l[1]/u[1]+",\n "+l[1]/u[1]+");\n const vec3 inputShapeRC = vec3("+o+".0, "+s+".0,\n "+s+".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 = vec3(yRC) * effectiveInputOverOutputRatioRC;\n\n // Compute the four integer indices.\n ivec3 sourceFloorRC = ivec3(sourceFracIndexRC);\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 < "+(a-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 "}(t.shape,e,n,i):new function(t,e,n,i){this.variableNames=["A"],this.outputShape=[];var r=t[0],o=t[1],s=t[2],a=t[3];this.outputShape=[r,e,n,a];var l=[i&&e>1?o-1:o,i&&n>1?s-1:s],u=[i&&e>1?e-1:e,i&&n>1?n-1:n];this.userCode="\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n "+l[0]/u[0]+",\n "+l[1]/u[1]+");\n const vec2 inputShapeRC = vec2("+o+".0, "+s+".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 = vec2(yRC) * effectiveInputOverOutputRatioRC;\n\n // Compute the four integer indices.\n ivec2 sourceFloorRC = ivec2(sourceFracIndexRC);\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 "}(t.shape,e,n,i);return this.compileAndRun(r,[t],"float32")},e.prototype.resizeBilinearBackprop=function(t,e,n){var i=new function(t,e,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=e.shape;var i=e.shape,r=i[1],o=i[2],s=t.shape,a=s[1],l=s[2],u=[n&&a>1?r-1:r,n&&l>1?o-1:o],c=[n&&a>1?a-1:a,n&&l>1?l-1:l],h=u[0]/c[0],p=u[1]/c[1],d=1/h,f=1/p,g=2*Math.ceil(d)+2,m=2*Math.ceil(f)+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("+h+");\n const float widthScale = float("+p+");\n\n const float invHeightScale = float("+d+");\n const float invWidthScale = float("+f+");\n\n const int winHeight = int("+g+");\n const int winWidth = int("+m+");\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 >= "+l+") {\n continue;\n }\n\n float dxR = float(dyR) * heightScale;\n int topDxRIndex = int(floor(dxR));\n int bottomDxRIndex = int(min(ceil(dxR), "+(r-1)+".0));\n float dxRLerp = dxR - float(topDxRIndex);\n float inverseDxRLerp = 1.0 - dxRLerp;\n\n float dxC = float(dyC) * widthScale;\n int leftDxCIndex = int(floor(dxC));\n int rightDxCIndex = int(min(ceil(dxC), "+(o-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 "}(t,e,n);return this.compileAndRun(i,[t])},e.prototype.resizeNearestNeighbor=function(t,e,n,i){var r=new function(t,e,n,i){this.variableNames=["A"],this.outputShape=[];var r=t[0],o=t[1],s=t[2],a=t[3];this.outputShape=[r,e,n,a];var l=[i&&e>1?o-1:o,i&&n>1?s-1:s],u=[i&&e>1?e-1:e,i&&n>1?n-1:n],c=i?"0.5":"0.0";this.userCode="\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n "+l[0]/u[0]+",\n "+l[1]/u[1]+");\n const vec2 inputShapeRC = vec2("+o+".0, "+s+".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 = vec2(yRC) * effectiveInputOverOutputRatioRC;\n\n // Compute the coordinators of nearest neighbor point.\n ivec2 sourceNearestRC = ivec2(\n min(inputShapeRC - 1.0, floor(sourceFracIndexRC + "+c+")));\n\n float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);\n\n setOutput(newValue);\n }\n "}(t.shape,e,n,i);return this.compileAndRun(r,[t])},e.prototype.resizeNearestNeighborBackprop=function(t,e,n){var i=new function(t,e,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=e.shape;var i=e.shape,r=i[1],o=i[2],s=t.shape,a=s[1],l=s[2],u=[n&&a>1?r-1:r,n&&l>1?o-1:o],c=[n&&a>1?a-1:a,n&&l>1?l-1:l],h=u[0]/c[0],p=u[1]/c[1],d=1/h,f=1/p,g=2*Math.ceil(d)+2,m=2*Math.ceil(f)+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("+h+");\n const float widthScale = float("+p+");\n\n const float invHeightScale = float("+d+");\n const float invWidthScale = float("+f+");\n\n const int winHeight = int("+g+");\n const int winWidth = int("+m+");\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 >= "+l+") {\n continue;\n }\n\n float sourceFracRow =\n float("+u[0]+") *\n (float(dyR) / float("+c[0]+"));\n\n float sourceFracCol =\n float("+u[1]+") *\n (float(dyC) / float("+c[1]+"));\n\n int sourceNearestRow = int(min(\n float(int("+r+") - 1),\n "+n+" ? float(round(sourceFracRow)) :\n float(floor(sourceFracRow))));\n\n int sourceNearestCol = int(min(\n float(int("+o+") - 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 "}(t,e,n);return this.compileAndRun(i,[t])},e.prototype.multinomial=function(t,e,n,i){var r=e?t:Li(t),o=r.shape[0],s=r.shape[1],a=new Eo(o,s,n),l=a.getCustomSetupFunc(i);return this.compileAndRun(a,[r],"int32",l)},e.prototype.oneHot=function(t,e,n,i){var r=new function(t,e,n,i){this.variableNames=["indices"],this.outputShape=[t,e],this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n int index = round(getIndices(coords.x));\n setOutput(mix(float("+i+"), float("+n+"),\n float(index == coords.y)));\n }\n "}(t.size,e,n,i);return this.compileAndRun(r,[t])},e.prototype.diag=function(t){var e=new function(t){this.variableNames=["X"],this.outputShape=[t,t],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 "}(t.size);return this.compileAndRun(e,[t])},e.prototype.nonMaxSuppression=function(t,e,n,i,r){return $e("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead"),cr(t.dataSync(),e.dataSync(),n,i,r)},e.prototype.cropAndResize=function(t,e,n,i,r,o){var s=new function(t,e,n,i,r){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];var o=t[0],s=t[1],a=t[2],l=t[3],u=e[0],c=n[0],h=n[1];this.outputShape=[u,c,h,l];var p="bilinear"===i?1:0,d=[s-1+".0",a-1+".0"],f=d[0],g=d[1],m=c>1?[""+(s-1)/(c-1),"(y2-y1) * height_ratio","y1*"+f+" + float(y)*(height_scale)"]:["0.0","0.0","0.5 * (y1+y2) * "+f],v=m[0],_=m[1],y=m[2],b=h>1?[""+(a-1)/(h-1),"(x2-x1) * width_ratio","x1*"+g+" + float(x)*(width_scale)"]:["0.0","0.0","0.5 * (x1+x2) * "+g],T=b[0],E=b[1],C=b[2];this.userCode="\n const float height_ratio = float("+v+");\n const float width_ratio = float("+T+");\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 >= "+o+") {\n return;\n }\n\n float height_scale = "+_+";\n float width_scale = "+E+";\n\n float in_y = "+y+";\n if( in_y < 0.0 || in_y > "+f+" ) {\n setOutput(float("+r+"));\n return;\n }\n float in_x = "+C+";\n if( in_x < 0.0 || in_x > "+g+" ) {\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 "}(t.shape,e.shape,i,r,o);return this.compileAndRun(s,[t,e,n],"float32")},e.prototype.depthToSpace=function(t,e,n){C(e>1,function(){return"blockSize should be > 1 for depthToSpace, but was: "+e});var i=t.shape[0],r="NHWC"===n?t.shape[1]:t.shape[2],o="NHWC"===n?t.shape[2]:t.shape[3],s="NHWC"===n?t.shape[3]:t.shape[1],a=r*e,l=o*e,u=s/(e*e),c=new qr("NHWC"===n?[i,a,l,u]:[i,u,a,l],e,n);return this.compileAndRun(c,[t])},e.prototype.split=function(t,e,n){return mr(t,e,n)},e.prototype.scatterND=function(t,e,n){var i=ki(0,t,n),r=i.sliceRank,o=i.numUpdates,s=i.sliceSize,a=i.strides,l=i.outputSize,u=[l/s,s],c=t.reshape([o,r]),h=e.reshape([o,s]);if(0===l)return nr(pn([]),n);var p=fn(0),d=new wo(o,r,c.rank,h.rank,a,u);return this.compileAndRun(d,[h,c,p]).reshape(n)},e.prototype.sparseToDense=function(t,e,n,i){var r=ki(0,t,n),o=r.sliceRank,s=r.numUpdates,a=r.strides,l=r.outputSize,u=new wo(s,o,t.rank,e.rank,a,[l,1],!1);return this.compileAndRun(u,[e,t,i]).reshape(n)},e.prototype.fft=function(t){return this.fftImpl(t,!1)},e.prototype.ifft=function(t){return this.fftImpl(t,!0)},e.prototype.fftImpl=function(t,e){var n=this.texData.get(t.dataId),i=new Zr("return real * expR - imag * expI;",t.shape,e),r=new Zr("return real * expI + imag * expR;",t.shape,e),o=[this.makeComplexComponentTensorInfo(t,n.complexTensors.real),this.makeComplexComponentTensorInfo(t,n.complexTensors.imag)],s=this.compileAndRun(i,o),a=this.compileAndRun(r,o),l=this.complex(s,a).as2D(t.shape[0],t.shape[1]);return s.dispose(),a.dispose(),l},e.prototype.gatherND=function(t,e){var n=e.shape,i=n[n.length-1],r=Ti(t,e),o=r[0],s=r[1],a=r[2],l=r[3],u=e.reshape([s,i]),c=t.reshape([t.size/a,a]),h=new function(t,e,n){this.sliceDim=t,this.strides=e,this.variableNames=["x","indices"],this.outputShape=n;var i=Mr(e.length),r=Mr(n.length),o=this.sliceDim>1?"strides[j]":"strides";this.userCode="\n "+i+" strides = "+i+"("+this.strides+");\n void main() {\n "+r+" coords = getOutputCoords();\n int flattenIndex = 0;\n for (int j = 0; j < "+this.sliceDim+"; j++) {\n int index = round(getIndices(coords[0], j));\n flattenIndex += index * "+o+";\n }\n setOutput(getX(flattenIndex, coords[1]));\n }\n "}(i,l,[s,a]);return this.compileAndRun(h,[c,u]).reshape(o)},e.prototype.fill=function(t,e,n){if("string"===(n=n||Y(e))){var i=F(n,x(t));return i.fill(e),Pt.makeTensor(i,t,n,this)}var r=new Qr(t,e),o=r.getCustomSetupFunc(e);return this.compileAndRun(r,[],n,o)},e.prototype.onesLike=function(t){if("string"===t.dtype)throw new Error("onesLike is not supported under string dtype");return this.fill(t.shape,1,t.dtype)},e.prototype.zerosLike=function(t){return this.fill(t.shape,"string"===t.dtype?"":0,t.dtype)},e.prototype.linspace=function(t,e,n){return ir(t,e,n)},e.prototype.makeTensorInfo=function(t,e){var n=this.write(null,t,e);return this.texData.get(n).usage=null,{dataId:n,shape:t,dtype:e}},e.prototype.makeOutput=function(t,e){var n=this.makeTensorInfo(t,e).dataId;return Pt.makeTensorFromDataId(n,t,e,this)},e.prototype.unpackTensor=function(t){var e=new function(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=t;var e=t.length,n=Tr("rc",e),i=Mr(e),r=function(t,e){if(1===t)return"rc";for(var n="",i=0;i "+e[0];for(var i="",r=t-2;r= "+e[r],r= "+e+";\n bool rEdge = rp1 >= "+n+";\n "}(e,t[t.length-1],t[t.length-2],n),s=function(t,e){var n=t.length,i=function(t,e){for(var n=[],i=0;i<=1;i++)for(var r=0;r<=1;r++){for(var o=(0===i?"r":"rp1")+", "+(0===r?"c":"cp1"),s=2;s= "+t[0]+" ? 0. : getA(rc + 1),\n 0, 0":"getA("+i[0]+"),\n cEdge ? 0. : getA("+i[1]+"),\n rEdge ? 0. : getA("+i[2]+"),\n rEdge || cEdge ? 0. : getA("+i[3]+")"}(t,n);this.userCode="\n void main() {\n "+i+" rc = getOutputCoords();\n\n if("+r+") {\n setOutput(vec4(0));\n } else {\n "+o+"\n\n setOutput(vec4("+s+"));\n }\n }\n "}}(t.shape);return this.runWebGLProgram(e,[t],t.dtype,null,!0)},e.prototype.packedReshape=function(t,e){var n=[ke(t.shape)].concat(xe(t.shape)),i={dtype:t.dtype,shape:n,dataId:t.dataId},r=new function(t,e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t;for(var n="",i=0;i<4;i++){var r="thisRC = rc;";i%2==1&&(r+="thisRC.z += 1;"),i>1&&(r+="thisRC.y += 1;"),n+="\n "+r+"\n "+(i>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["+i+"] =\n getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);\n "+(i>0?"}":"")+"\n "}this.userCode="\n \n ivec3 inputCoordsFromReshapedOutCoords(int index) {\n "+Cr(["r","c","d"],e)+"\n return ivec3(r, c, d);\n }\n \n "+Sr(t)+"\n\n void main() {\n ivec3 rc = getOutputCoords();\n\n vec4 result = vec4(0.);\n\n ivec3 thisRC;\n int rows = "+t[1]+";\n int cols = "+t[2]+";\n\n "+n+"\n\n setOutput(result);\n }\n "}([ke(e)].concat(xe(e)),n),o=this.runWebGLProgram(r,[i],t.dtype,null,!0);return{dataId:o.dataId,shape:e,dtype:o.dtype}},e.prototype.decode=function(t){var e,n=this.texData.get(t),i=n.isPacked,r=n.shape,o=n.dtype,s=Ie(r);return e=i?new function(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=Ut.DENSE;var e=Xt(t),n=Er();this.outputShape=t,this.userCode="\n ivec3 outCoordsFromFlatIndex(int index) {\n "+Cr(["r","c","d"],t)+"\n return ivec3(r, c, d);\n }\n\n void main() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+e[0]+", "+e[1]+"));\n int index = 4 * (resTexRC.x * "+e[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 "+n.output+" = result;\n }\n "}(s):new function(t){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=Ut.DENSE;var e=Xt(t),n=Er();this.outputShape=t,this.userCode="\n ivec3 outCoordsFromFlatIndex(int index) {\n "+Cr(["r","c","d"],t)+"\n return ivec3(r, c, d);\n }\n\n void main() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+e[0]+", "+e[1]+"));\n int index = 4 * (resTexRC.x * "+e[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 "+n.output+" = result;\n }\n "}(s),{dtype:o,shape:r,dataId:this.runWebGLProgram(e,[{shape:s,dtype:o,dataId:t}],o,null,!0).dataId}},e.prototype.runWebGLProgram=function(t,e,n,i,r){var o=this;void 0===r&&(r=!1);var s=this.makeTensorInfo(t.outputShape,n),a=this.texData.get(s.dataId);if(t.packedOutput&&(a.isPacked=!0),t.outPackingScheme===Ut.DENSE){var l=Xt(t.outputShape);a.texShape=l.map(function(t){return 2*t})}if(null!=t.outTexUsage&&(a.usage=t.outTexUsage),0===x(s.shape))return a.values=B(s.dtype,0),s;var u=[],h=e.map(function(e){if("complex64"===e.dtype)throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");var n=o.texData.get(e.dataId);if(null==n.texture){if(!t.packedInputs&&x(e.shape)<=c().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:e.shape,texData:null,isUniform:!0,uniformValues:n.values};t.packedInputs&&(n.isPacked=!0,n.shape=e.shape)}else if(!!n.isPacked!=!!t.packedInputs)e=n.isPacked?o.unpackTensor(e):o.packTensor(e),u.push(e),n=o.texData.get(e.dataId);else if(n.isPacked&&!De(n.shape,e.shape)){var i=e,r=e.shape;e.shape=n.shape,e=o.packedReshape(e,r),u.push(e),n=o.texData.get(e.dataId),i.shape=r}return o.uploadToGPU(e.dataId),{shape:e.shape,texData:n,isUniform:!1}});this.uploadToGPU(s.dataId);var p,d={shape:s.shape,texData:a,isUniform:!1},f=function(t,e,n){var i="";h.concat(n).forEach(function(t){var e=null!=t.texData&&null!=t.texData.slice&&t.texData.slice.flatOffset>0,n=t.isUniform?"uniform":t.texData.texShape;i+=t.shape+"_"+n+"_"+e});var r=t.userCode;return t.constructor.name+"_"+i+"_"+r}(t,0,d),g=this.getAndSaveBinary(f,function(){return function(t,e,n,i){var r=e.userCode,o=n.map(function(t,n){var i={logicalShape:t.shape,texShape:t.isUniform?null:t.texData.texShape,isUniform:t.isUniform,isPacked:!t.isUniform&&t.texData.isPacked,flatOffset:null};return null!=t.texData&&null!=t.texData.slice&&t.texData.slice.flatOffset>0&&(i.flatOffset=t.texData.slice.flatOffset),{name:e.variableNames[n],shapeInfo:i}}),s=o.map(function(t){return t.shapeInfo}),a={logicalShape:i.shape,texShape:i.texData.texShape,isUniform:!1,isPacked:i.texData.isPacked,flatOffset:null},l=kr(o,a,r,e.packedInputs),u=t.createProgram(l),h=null,p=t.getUniformLocation(u,"NAN",!1);1===c().getNumber("WEBGL_VERSION")&&(h=t.getUniformLocation(u,"INFINITY",!1));for(var d={},f=0;f0)return 32}return 16})),this.floatPrecisionValue},e.prototype.epsilon=function(){return 32===this.floatPrecision()?1e-7:1e-4},e.prototype.uploadToGPU=function(t){var e,n=this.texData.get(t),i=n.shape,r=n.dtype,o=n.values,s=n.texture,a=n.usage,l=n.isPacked;if(null==s){var u,c=null!=this.activeTimers;c&&(u=nt());var h=n.texShape;if(null==h&&(h=Re(i,l),n.texShape=h),null!=o){var p=Ie(i),d=void 0,f=h[1],g=h[0],m=o instanceof Uint8Array;l?(f=(e=Yt(h[0],h[1]))[0],d=new function(t,e,n){void 0===n&&(n=!1),this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;var i=Er(),r=e[0],o=e[1];this.outputShape=t;var s="",a="result";n&&(a="floor(result * 255. + 0.5)");for(var l=0;l<=1;l++)for(var u=0;u<=1;u++){var c=2*l+u;s+="\n localCoords = coords;\n if(localCoords[2] + "+u+" < "+t[2]+") {\n localCoords[2] += "+u+";\n if(localCoords[1] + "+l+" < "+t[1]+") {\n localCoords[1] += "+l+";\n\n flatIndex = getFlatIndex(localCoords);\n offset = imod(flatIndex, 4);\n\n flatIndex = idiv(flatIndex, 4, 1.);\n\n r = flatIndex / "+o+";\n c = imod(flatIndex, "+o+");\n uv = (vec2(c, r) + halfCR) / vec2("+o+".0, "+r+".0);\n values = "+i.texture2D+"(A, uv);\n\n if(offset == 0) {\n result["+c+"] = values[0];\n } else if(offset == 1) {\n result["+c+"] = values[1];\n } else if(offset == 2) {\n result["+c+"] = values[2];\n } else {\n result["+c+"] = values[3];\n }\n }\n }\n "}this.userCode="\n "+Sr(t)+"\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 "+i.output+" = "+a+";\n }\n "}(p,[g=e[1],f],m)):d=new function(t,e,n){void 0===n&&(n=!1),this.variableNames=["A"];var i=Er(),r=e[0],o=e[1];this.outputShape=t;var s="result";n&&(s="floor(result * 255. + 0.5)"),this.userCode="\n "+Sr(t)+"\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 / "+o+";\n int c = imod(flatIndex, "+o+");\n vec2 uv = (vec2(c, r) + halfCR) / vec2("+o+".0, "+r+".0);\n vec4 values = "+i.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 "+i.output+" = vec4("+s+", 0., 0., 0.);\n }\n "}(p,[g,f],m);var v=this.makeTensorInfo([g,f],r);this.texData.get(v.dataId).usage=m?Vt.PIXELS:Vt.UPLOAD,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(v.dataId),f,g,o);var _=this.runWebGLProgram(d,[v],r,null,!0),y=this.texData.get(_.dataId);n.texture=y.texture,n.texShape=y.texShape,n.isPacked=y.isPacked,n.usage=y.usage,this.disposeData(v.dataId),this.texData.delete(_.dataId),n.values=null,c&&(this.uploadWaitMs+=nt()-u)}else{var b=this.acquireTexture(h,a,r,l);n.texture=b}}},e.prototype.convertAndCacheOnCPU=function(t,e){var n=this.texData.get(t),i=n.dtype;return this.releaseGPUData(t),null!=e&&(n.values=function(t,e){if("float32"===e||"complex64"===e)return t;if("int32"===e||"bool"===e){for(var n="int32"===e?new Int32Array(t.length):new Uint8Array(t.length),i=0;i1024*this.numMBBeforeWarning*1024){var r=(this.numBytesInGPU/1024/1024).toFixed(2);this.warnedAboutMemory=!0,console.warn("High memory usage in GPU: "+r+" MB, most likely due to a memory leak")}return this.textureManager.acquireTexture(t,e,i)},e.prototype.computeBytes=function(t,e){return t[0]*t[1]*G(e)},e}(Fi);Bt()&&Pt.registerBackend("webgl",function(){return new es},2);var ns=ln({square_:function(t){var e=Ke(t,"x","square"),n=[e];return Pt.runKernelFunc(function(t,n){return n([e]),t.square(e)},{x:e},null,"Square",{},n,[])}}),is="SquaredDifference",rs=ln({squaredDifference_:function(t,e){var n,i=Ke(t,"a","squaredDifference"),r=Ke(e,"b","squaredDifference");n=Ot(i,r),i=n[0],r=n[1],Wi(i.shape,r.shape);var o={a:i,b:r},s=[i,r];return Pt.runKernelFunc(function(t,e){var n=t.squaredDifference(i,r);return e([i,r]),n},o,function(t,e){var n=e[0],i=e[1],r=fn(2);return{a:function(){return t.mul(n.sub(i).mul(r))},b:function(){return t.mul(i.sub(n).mul(r))}}},is,{},s,[])}}),os=ln({abs_:function(t){var e=Ke(t,"x","abs");return"complex64"===e.dtype?Pt.runKernelFunc(function(t){return t.complexAbs(e)},{$x:e}):Pt.runKernelFunc(function(t,n){var i=t.abs(e);return n([e]),i},{x:e},function(t,e){var n=e[0];return{x:function(){return t.mul(n.toFloat().step(-1))}}},"Abs")}}),ss=ln({acos_:function(t){var e=Ke(t,"x","acos");return Pt.runKernelFunc(function(t,n){var i=t.acos(e);return n([e]),i},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.divStrict(fn(1).sub(n.toFloat().square()).sqrt()).neg()}}})}}),as=ln({acosh_:function(t){var e=Ke(t,"x","acosh");return Pt.runKernelFunc(function(t,n){var i=t.acosh(e);return n([e]),i},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.divStrict(n.toFloat().square().sub(1).sqrt())}}})}}),ls=ln({asin_:function(t){var e=Ke(t,"x","asin");return Pt.runKernelFunc(function(t,n){var i=t.asin(e);return n([e]),i},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.divStrict(fn(1).sub(n.toFloat().square()).sqrt())}}})}}),us=ln({asinh_:function(t){var e=Ke(t,"x","asinh");return Pt.runKernelFunc(function(t,n){var i=t.asinh(e);return n([e]),i},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.divStrict(fn(1).add(n.toFloat().square()).sqrt())}}})}}),cs=ln({atan_:function(t){var e=Ke(t,"x","atan");return Pt.runKernelFunc(function(t,n){var i=t.atan(e);return n([e]),i},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.div(n.toFloat().square().add(1))}}})}}),hs=ln({atanh_:function(t){var e=Ke(t,"x","atanh");return Pt.runKernelFunc(function(t,n){var i=t.atanh(e);return n([e]),i},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.div(fn(1).sub(n.toFloat().square()))}}})}}),ps=ln({ceil_:function(t){var e=Ke(t,"x","ceil");return Pt.runKernelFunc(function(t){return t.ceil(e)},{$x:e},function(t){return{$x:function(){return Sn(t)}}})}}),ds=ln({clipByValue_:function(t,e,n){var i=Ke(t,"x","clipByValue");C(e<=n,function(){return"Error in clip: min ("+e+") must be less than or equal to max ("+n+")."});var r=[i],o={min:e,max:n};return Pt.runKernelFunc(function(t,r){var o=t.clip(i,e,n);return r([i]),o},{x:i},function(t,i){var r=i[0];return{x:function(){return t.where(r.greaterEqual(e).logicalAnd(r.lessEqual(n)),Sn(t))}}},"ClipByValue",o,r)}}),fs=ln({cos_:function(t){var e=Ke(t,"x","cos"),n=[e];return Pt.runKernelFunc(function(t,n){var i=t.cos(e);return n([e]),i},{x:e},function(t,e){var n=e[0];return{x:function(){return n.toFloat().sin().neg().mul(t)}}},"Cos",{},n)}}),gs=ln({cosh_:function(t){var e=Ke(t,"x","cosh");return Pt.runKernelFunc(function(t,n){var i=t.cosh(e);return n([e]),i},{$x:e},function(t,e){var n=e[0];return{$x:function(){return n.toFloat().sinh().mulStrict(t)}}})}}),ms=ln({erf_:function(t){var e=Ke(t,"x","erf");return C("int32"===e.dtype||"float32"===e.dtype,function(){return"Input dtype must be `int32` or `float32`."}),"int32"===e.dtype&&(e=e.toFloat()),Pt.runKernelFunc(function(t,n){var i=t.erf(e);return n([e]),i},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.mul(n.square().neg().exp().mul(2/Math.sqrt(Math.PI)))}}})}}),vs=ln({exp_:function(t){var e=Ke(t,"x","exp");return Pt.runKernelFunc(function(t,n){var i=t.exp(e);return n([i]),i},{x:e},function(t,e){return{x:function(){return t.mulStrict(e[0])}}},"Exp",{},[],[!0])}}),_s=ln({expm1_:function(t){var e=Ke(t,"x","expm1");return Pt.runKernelFunc(function(t,n){var i=t.expm1(e);return n([e]),i},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.mul(n.exp())}}})}}),ys=ln({floor_:function(t){var e=Ke(t,"x","floor");return Pt.runKernelFunc(function(t){return t.floor(e)},{$x:e},function(t){return{$x:function(){return Sn(t)}}})}}),bs=ln({log_:function(t){var e=Ke(t,"x","log"),n=[e];return Pt.runKernelFunc(function(t,n){var i=t.log(e);return n([e]),i},{x:e},function(t,e){var n=e[0];return{x:function(){return t.div(n.toFloat())}}},"Log",{},n)}}),Ts=ln({log1p_:function(t){var e=Ke(t,"x","log1p");return Pt.runKernelFunc(function(t,n){var i=t.log1p(e);return n([e]),i},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.div(n.add(1))}}})}}),Es=ln({logSigmoid_:function(t){var e=Ke(t,"x","logSigmoid");return Pt.runKernelFunc(function(t,n){var i=t.softplus(e.neg()).neg();return n([e]),i},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.mul(n.neg().sigmoid())}}})}}),Cs=ln({neg_:function(t){var e=Ke(t,"x","neg"),n=[e];return Pt.runKernelFunc(function(t){return t.neg(e)},{x:e},function(t){return{x:function(){return t.neg()}}},"Neg",{},n)}}),Ss=ln({reciprocal_:function(t){var e=Ke(t,"x","reciprocal");return Pt.runKernelFunc(function(t,n){var i=t.reciprocal(e);return n([e]),i},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.div(n.square().neg())}}})}}),ws=ln({round_:function(t){var e=Ke(t,"x","round");return Pt.runKernelFunc(function(t){return t.round(e)},{$x:e},function(t){return{$x:function(){return Sn(t)}}})}}),ks=ln({rsqrt_:function(t){var e=Ke(t,"x","rsqrt"),n=[e];return Pt.runKernelFunc(function(t,n){var i=t.rsqrt(e);return n([e]),i},{x:e},function(t,e){var n=e[0];return{x:function(){return t.div(n.pow(1.5).mul(2)).neg()}}},"Rsqrt",{},n)}}),xs=ln({sigmoid_:function(t){var e=Ke(t,"x","sigmoid");return Pt.runKernelFunc(function(t,n){var i=t.sigmoid(e);return n([i]),i},{x:e},function(t,e){var n=e[0];return{x:function(){return t.mul(n.mul(fn(1).sub(n)))}}},"Sigmoid")}}),Is=ln({sign_:function(t){var e=Ke(t,"x","sign");return Pt.runKernelFunc(function(t){return t.sign(e)},{$x:e},function(t){return{$x:function(){return Sn(t)}}})}}),Rs=ln({isNaN_:function(t){var e=Ke(t,"x","isNaN");return Pt.runKernelFunc(function(t){return t.isNaN(e)},{$x:e},function(t){return{$x:function(){return Sn(t)}}})}}),Os=ln({isInf_:function(t){var e=Ke(t,"x","isInf");return Pt.runKernelFunc(function(t){return t.isInf(e)},{$x:e},function(t){return{$x:function(){return Sn(t)}}})}}),Ds=ln({isFinite_:function(t){var e=Ke(t,"x","isFinite");return Pt.runKernelFunc(function(t){return t.isFinite(e)},{$x:e},function(t){return{$x:function(){return Sn(t)}}})}}),As=ln({sin_:function(t){var e=Ke(t,"x","sin"),n=[e];return Pt.runKernelFunc(function(t,n){var i=t.sin(e);return n([e]),i},{x:e},function(t,e){var n=e[0];return{x:function(){return n.toFloat().cos().mul(t)}}},"Sin",{},n)}}),Ms=ln({sinh_:function(t){var e=Ke(t,"x","sinh");return Pt.runKernelFunc(function(t,n){var i=t.sinh(e);return n([e]),i},{$x:e},function(t,e){var n=e[0];return{$x:function(){return n.toFloat().cosh().mulStrict(t)}}})}}),Ns=ln({softplus_:function(t){var e=Ke(t,"x","softplus");return Pt.runKernelFunc(function(t,n){var i=t.softplus(e);return n([e]),i},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.mul(n.sigmoid())}}})}}),Ls=ln({sqrt_:function(t){var e=Ke(t,"x","sqrt");return Pt.runKernelFunc(function(t,n){var i=t.sqrt(e);return n([e]),i},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.div(n.toFloat().sqrt().mul(2))}}})}}),Ps=ln({step_:function(t,e){void 0===e&&(e=0);var n=Ke(t,"x","step");return Pt.runKernelFunc(function(t){return t.step(n,e)},{$x:n},function(t){return{$x:function(){return Sn(t)}}})}}),Bs=ln({tan_:function(t){var e=Ke(t,"x","tan");return Pt.runKernelFunc(function(t,n){var i=t.tan(e);return n([e]),i},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.div(n.cos().square())}}})}}),Fs=ln({tanh_:function(t){var e=Ke(t,"x","tanh");return Pt.runKernelFunc(function(t,n){var i=t.tanh(e);return n([i]),i},{x:e},function(t,e){var n=e[0];return{x:function(){return fn(1).sub(n.square()).mulStrict(t)}}},"Tanh",{},null,[!0])}});function Us(t,e,n,i,r,o){var s,a,l=Ke(t,"x","batchNorm"),u=Ke(e,"mean","batchNorm"),c=Ke(n,"variance","batchNorm");return null!=r&&(s=Ke(r,"scale","batchNorm")),null!=i&&(a=Ke(i,"offset","batchNorm")),C(2===l.rank,function(){return"Error in batchNorm3D: x must be rank 3 but got rank "+l.rank+"."}),C(2===u.rank||1===u.rank,function(){return"Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank "+u.rank+"."}),C(2===c.rank||1===c.rank,function(){return"Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank "+c.rank+"."}),null!=s&&C(2===s.rank||1===s.rank,function(){return"Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank "+s.rank+"."}),null!=a&&C(2===a.rank||1===a.rank,function(){return"Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank "+a.rank+"."}),Ws(l,u,c,a,s,o)}function Vs(t,e,n,i,r,o){var s,a,l=Ke(t,"x","batchNorm"),u=Ke(e,"mean","batchNorm"),c=Ke(n,"variance","batchNorm");return null!=r&&(s=Ke(r,"scale","batchNorm")),null!=i&&(a=Ke(i,"offset","batchNorm")),C(3===l.rank,function(){return"Error in batchNorm3D: x must be rank 3 but got rank "+l.rank+"."}),C(3===u.rank||1===u.rank,function(){return"Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank "+u.rank+"."}),C(3===c.rank||1===c.rank,function(){return"Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank "+c.rank+"."}),null!=s&&C(3===s.rank||1===s.rank,function(){return"Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank "+s.rank+"."}),null!=a&&C(3===a.rank||1===a.rank,function(){return"Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank "+a.rank+"."}),Ws(l,u,c,a,s,o)}function Hs(t,e,n,i,r,o){var s,a,l=Ke(t,"x","batchNorm"),u=Ke(e,"mean","batchNorm"),c=Ke(n,"variance","batchNorm");return null!=r&&(s=Ke(r,"scale","batchNorm")),null!=i&&(a=Ke(i,"offset","batchNorm")),C(4===l.rank,function(){return"Error in batchNorm4D: x must be rank 4 but got rank "+l.rank+"."}),C(4===u.rank||1===u.rank,function(){return"Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank "+u.rank+"."}),C(4===c.rank||1===c.rank,function(){return"Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank "+c.rank+"."}),null!=s&&C(4===s.rank||1===s.rank,function(){return"Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank "+s.rank+"."}),null!=a&&C(4===a.rank||1===a.rank,function(){return"Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank "+a.rank+"."}),Ws(l,u,c,a,s,o)}function Ws(t,e,n,i,r,o){null==o&&(o=.001);var s,a,l,u=Ke(t,"x","batchNorm"),c=Ke(e,"mean","batchNorm"),h=Ke(n,"variance","batchNorm");null!=r&&(s=Ke(r,"scale","batchNorm")),null!=i&&(a=Ke(i,"offset","batchNorm")),C(c.rank===h.rank,function(){return"Batch normalization gradient requires mean and variance to have equal ranks."}),C(null==a||c.rank===a.rank,function(){return"Batch normalization gradient requires mean and offset to have equal ranks."}),C(null==s||c.rank===s.rank,function(){return"Batch normalization gradient requires mean and scale to have equal ranks."}),l=0===u.rank||1===u.rank?u.as4D(1,1,1,u.size):2===u.rank?u.as4D(1,1,u.shape[0],u.shape[1]):3===u.rank?u.as4D(1,u.shape[0],u.shape[1],u.shape[2]):u;var p=[u,c,h,s];return Pt.runKernelFunc(function(t,e){var n=t.batchNormalization(l,Gs(c),Gs(h),o,Gs(s),Gs(a));return e([u,c,h,s]),n},{x:u,mean:c,variance:h,scale:s,offset:a},function(t,e){var n=e,i=n[0],r=n[1],s=n[2],a=n[3],u=null==a?fn(1):a,c=Hi(r.shape,l.shape),h=[];if(1===r.rank){for(var p=0;p0&&(e=e.sum(n)),e.reshape(i.shape)},b:function(){var e=t,n=Hi(r.shape,o);return n.length>0&&(e=e.sum(n)),e.reshape(r.shape)}}},"Add")}}),sa=ln({addN_:function(t){C(Array.isArray(t),function(){return"The argument passed to tf.addN() must be a list of tensors"}),C(t.length>=1,function(){return"Must pass at least one tensor to tf.addN(), but got "+t.length});var e=t.map(function(t,e){return Ke(t,"tensors"+e,"addN")}),n=e[0];e.forEach(function(t){if(t.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),e.forEach(function(t){if(!I(t.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});var i=e;return Pt.runKernelFunc(function(t){return t.addN(e)},i,function(t){var n={};return e.forEach(function(e,i){n[i]=function(){return t.clone()}}),n},"AddN")}}),aa=ln({addStrict_:function(t,e){var n=Ke(t,"a","addStrict"),i=Ke(e,"b","addStrict");return S(n.shape,i.shape,"Error in addStrict: "),n.add(i)}}),la=ln({atan2_:function(t,e){var n,i=Ke(t,"a","atan2"),r=Ke(e,"b","atan2");n=Ot(i,r),i=n[0],r=n[1];var o=Wi(i.shape,r.shape);return Pt.runKernelFunc(function(t,e){var n=t.atan2(i,r);return e([i,r]),n},{$a:i,$b:r},function(t,e){var n=e[0],i=e[1];return{$a:function(){var e=oa(n.square(),i.square()),r=t.mul(i.div(e)),s=Hi(n.shape,o);return s.length>0&&(r=r.sum(s)),r.reshape(n.shape)},$b:function(){var e=oa(n.square(),i.square()),r=Cs(t.mul(n.div(e))),s=Hi(i.shape,o);return s.length>0&&(r=r.sum(s)),r.reshape(i.shape)}}})}}),ua=ln({div_:function(t,e){var n,i=Ke(t,"a","div"),r=Ke(e,"b","div");if(n=Ot(i,r),i=n[0],r=n[1],"int32"===i.dtype&&"int32"===r.dtype)return pa(i,r);var o=Wi(i.shape,r.shape);return Pt.runKernelFunc(function(t,e){var n=t.realDivide(i,r);return e([i,r]),n},{a:i,b:r},function(t,e){var n=e[0],i=e[1];return{a:function(){var e=t.div(i.toFloat()),r=Hi(n.shape,o);return r.length>0?e.sum(r).reshape(n.shape):e},b:function(){var e=t.mul(n.toFloat()),r=Hi(i.shape,o);r.length>0&&(e=e.sum(r).reshape(i.shape));var s=i.square();return e.div(s.toFloat()).neg()}}},"Div")}}),ca=ln({divNoNan_:function(t,e){var n,i=Ke(t,"a","div"),r=Ke(e,"b","div");i=(n=Ot(i,r))[0],r=n[1];var o=ua(i,r),s=Sn(o),a=r.equal(s);return ia(a,s,o)}}),ha=ln({divStrict_:function(t,e){var n=Ke(t,"a","div"),i=Ke(e,"b","div");return S(n.shape,i.shape,"Error in divideStrict: "),n.div(i)}}),pa=ln({floorDiv_:function(t,e){var n,i=Ke(t,"a","floorDiv"),r=Ke(e,"b","floorDiv");n=Ot(i,r),i=n[0],r=n[1];var o=Wi(i.shape,r.shape);return Pt.runKernelFunc(function(t,e){var n=t.floorDiv(i,r);return e([i,r]),n},{a:i,b:r},function(t,e){var n=e[0],i=e[1];return{a:function(){var e=t.div(i.toFloat()),r=Hi(n.shape,o);return r.length>0?e.sum(r).reshape(n.shape):e},b:function(){var e=t.mul(n.toFloat()),r=Hi(i.shape,o);r.length>0&&(e=e.sum(r).reshape(i.shape));var s=i.square();return e.div(s.toFloat()).neg()}}},"FloorDiv")}}),da=ln({maximum_:function(t,e){var n,i=Ke(t,"a","maximum"),r=Ke(e,"b","maximum");return n=Ot(i,r),i=n[0],r=n[1],"bool"===i.dtype&&(i=i.toInt(),r=r.toInt()),Wi(i.shape,r.shape),Pt.runKernelFunc(function(t,e){var n=t.maximum(i,r);return e([i,r]),n},{a:i,b:r},function(t,e){var n=e[0],i=e[1];return{a:function(){return t.mul(n.greaterEqual(i).toFloat())},b:function(){return t.mul(n.less(i).toFloat())}}},"Maximum")}}),fa=ln({maximumStrict_:function(t,e){var n=Ke(t,"a","maximumStrict"),i=Ke(e,"b","maximumStrict");return S(n.shape,i.shape,"Error in maximumStrict: "),n.maximum(i)}}),ga=ln({minimum_:function(t,e){var n,i=Ke(t,"a","minimum"),r=Ke(e,"b","minimum");return n=Ot(i,r),i=n[0],r=n[1],"bool"===i.dtype&&(i=i.toInt(),r=r.toInt()),Wi(i.shape,r.shape),Pt.runKernelFunc(function(t,e){var n=t.minimum(i,r);return e([i,r]),n},{a:i,b:r},function(t,e){var n=e[0],i=e[1];return{a:function(){return t.mul(n.lessEqual(i).toFloat())},b:function(){return t.mul(n.greater(i).toFloat())}}},"Minimum")}}),ma=ln({minimumStrict_:function(t,e){var n=Ke(t,"a","minimumStrict"),i=Ke(e,"b","minimumStrict");return S(n.shape,i.shape,"Error in minimumStrict: "),n.minimum(i)}}),va=ln({mod_:function(t,e){var n,i=Ke(t,"a","mod"),r=Ke(e,"b","mod");n=Ot(i,r),i=n[0],r=n[1];var o=Wi(i.shape,r.shape);return Pt.runKernelFunc(function(t,e){var n=t.mod(i,r);return e([i,r]),n},{$a:i,$b:r},function(t,e){var n=e[0],i=e[1];return{$a:function(){var e=Hi(n.shape,o);return e.length>0?t.sum(e).reshape(n.shape):t},$b:function(){var e=t.mul(n.div(i).floor().neg()),r=Hi(i.shape,o);return r.length>0?e.sum(r).reshape(i.shape):e}}})}}),_a=ln({modStrict_:function(t,e){var n=Ke(t,"a","modStrict"),i=Ke(e,"b","modStrict");return S(n.shape,i.shape,"Error in modStrict: "),n.mod(i)}}),ya=ln({mul_:function(t,e){var n,i=Ke(t,"a","mul"),r=Ke(e,"b","mul");n=Ot(i,r),i=n[0],r=n[1];var o=Wi(i.shape,r.shape);return Pt.runKernelFunc(function(t,e){var n=t.multiply(i,r);return e([i,r]),n},{a:i,b:r},function(t,e){var n=e[0],i=e[1];return{a:function(){var e=t.mul(i.toFloat()),r=Hi(n.shape,o);return r.length>0?e.sum(r).reshape(n.shape):e},b:function(){var e=t.mul(n.toFloat()),r=Hi(i.shape,o);return r.length>0?e.sum(r).reshape(i.shape):e}}},"Mul")}}),ba=ln({mulStrict_:function(t,e){var n=Ke(t,"a","mul"),i=Ke(e,"b","mul");return S(n.shape,i.shape,"Error in multiplyStrict: "),n.mul(i)}}),Ta=ln({pow_:function(t,e){var n,i=Ke(t,"base","pow"),r=Ke(e,"exp","pow");n=Ot(i,r),i=n[0],r=n[1];var o=Wi(i.shape,r.shape),s=[i,r];return Pt.runKernelFunc(function(t,e){var n=t.pow(i,r);return e([i,r,n]),n},{a:i,b:r},function(t,e){var n=e[0],i=e[1],r=e[2];return{a:function(){var e=i.toFloat(),r=t.mul(e.mul(n.pow(e.sub(fn(1))))),s=Hi(n.shape,o);return s.length>0&&(r=r.sum(s)),r.reshape(n.shape)},b:function(){var e=n.greater(0),s=n.log().where(e,Sn(n)),a=t.mul(r.mul(s)),l=Hi(i.shape,o);return l.length>0&&(a=a.sum(l)),a.reshape(i.shape)}}},"Pow",{},s,[!0])}}),Ea=ln({powStrict_:function(t,e){return S(t.shape,e.shape,"Error in powStrict: "),t.pow(e)}}),Ca=ln({squaredDifferenceStrict_:function(t,e){var n=Ke(t,"a","squaredDifferenceStrict"),i=Ke(e,"b","squaredDifferenceStrict");return S(n.shape,i.shape,"Error in squaredDifferenceStrict: "),n.squaredDifference(i)}}),Sa=ln({sub_:function(t,e){var n,i=Ke(t,"a","sub"),r=Ke(e,"b","sub");n=Ot(i,r),i=n[0],r=n[1];var o=Wi(i.shape,r.shape);return Pt.runKernelFunc(function(t){return t.subtract(i,r)},{a:i,b:r},function(t){return{a:function(){var e=t,n=Hi(i.shape,o);return n.length>0&&(e=e.sum(n)),e.reshape(i.shape)},b:function(){var e=t,n=Hi(r.shape,o);return n.length>0&&(e=e.sum(n)),e.neg().reshape(r.shape)}}},"Sub")}}),wa=ln({subStrict_:function(t,e){var n=Ke(t,"a","subStrict"),i=Ke(e,"b","subStrict");return S(n.shape,i.shape,"Error in subStrict: "),n.sub(i)}}),ka=ln({equal_:function(t,e){var n,i=Ke(t,"a","equal"),r=Ke(e,"b","equal");return n=Ot(i,r),i=n[0],r=n[1],Wi(i.shape,r.shape),Pt.runKernelFunc(function(t){return t.equal(i,r)},{$a:i,$b:r})}}),xa=ln({equalStrict_:function(t,e){var n=Ke(t,"a","equalStrict"),i=Ke(e,"b","equalStrict");return S(n.shape,i.shape,"Error in equalStrict: "),n.equal(i)}}),Ia=ln({greater_:function(t,e){var n,i=Ke(t,"a","greater"),r=Ke(e,"b","greater");return n=Ot(i,r),i=n[0],r=n[1],Wi(i.shape,r.shape),Pt.runKernelFunc(function(t){return t.greater(i,r)},{a:i,b:r},null,"Greater")}}),Ra=ln({greaterEqual_:function(t,e){var n,i=Ke(t,"a","greaterEqual"),r=Ke(e,"b","greaterEqual");return n=Ot(i,r),i=n[0],r=n[1],Wi(i.shape,r.shape),Pt.runKernelFunc(function(t,e){var n=t.greaterEqual(i,r);return e([i,r]),n},{a:i,b:r},function(t,e){var n=e[0],i=e[1];return{a:function(){return Sn(n)},b:function(){return Sn(i)}}},"GreaterEqual")}}),Oa=ln({greaterEqualStrict_:function(t,e){var n=Ke(t,"a","greaterEqualStrict"),i=Ke(e,"b","greaterEqualStrict");return S(n.shape,i.shape,"Error in greaterEqualStrict: "),n.greaterEqual(i)}}),Da=ln({greaterStrict_:function(t,e){var n=Ke(t,"a","greaterStrict"),i=Ke(e,"b","greaterStrict");return S(n.shape,i.shape,"Error in greaterStrict: "),n.greater(i)}}),Aa=ln({less_:function(t,e){var n,i=Ke(t,"a","less"),r=Ke(e,"b","less");return n=Ot(i,r),i=n[0],r=n[1],Wi(i.shape,r.shape),Pt.runKernelFunc(function(t){return t.less(i,r)},{a:i,b:r},null,"Less")}}),Ma=ln({lessEqual_:function(t,e){var n,i=Ke(t,"a","lessEqual"),r=Ke(e,"b","lessEqual");return n=Ot(i,r),i=n[0],r=n[1],Wi(i.shape,r.shape),Pt.runKernelFunc(function(t,e){var n=t.lessEqual(i,r);return e([i,r]),n},{a:i,b:r},null,"LessEqual")}}),Na=ln({lessEqualStrict_:function(t,e){var n=Ke(t,"a","lessEqualStrict"),i=Ke(e,"b","lessEqualStrict");return S(n.shape,i.shape,"Error in lessEqualStrict: "),n.lessEqual(i)}}),La=ln({lessStrict_:function(t,e){var n=Ke(t,"a","lessStrict"),i=Ke(e,"b","lessStrict");return S(n.shape,i.shape,"Error in lessStrict: "),n.less(i)}}),Pa=ln({notEqual_:function(t,e){var n,i=Ke(t,"a","notEqual"),r=Ke(e,"b","notEqual");return n=Ot(i,r),i=n[0],r=n[1],Wi(i.shape,r.shape),Pt.runKernelFunc(function(t){return t.notEqual(i,r)},{a:i,b:r},null,"NotEqual")}}),Ba=ln({notEqualStrict_:function(t,e){var n=Ke(t,"a","notEqualStrict"),i=Ke(e,"b","notEqualStrict");return S(n.shape,i.shape,"Error in notEqualStrict: "),n.notEqual(i)}});function Fa(t,e){for(var n=[],i=t;i=2&&s.rank>=2&&o.rank===s.rank,function(){return"Error in matMul: inputs must have the same rank of at least 2, got ranks "+o.rank+" and "+s.rank+"."}),C(I(h,p),function(){return"Error in matMul: outer dimensions ("+h+") and ("+p+") of Tensors with shapes "+o.shape+" and "+s.shape+" must match."}),C(a===l,function(){return"Error in matMul: inner shapes ("+a+") and ("+l+") of Tensors with shapes "+o.shape+" and "+s.shape+" and transposeA="+n+" and transposeB="+i+" must match."});var g=o.shape.slice(0,-2).concat([u,c]),m=n?o.as3D(d,a,u):o.as3D(d,u,a),v=i?s.as3D(f,c,l):s.as3D(f,l,c),_={transposeA:n,transposeB:i};return Pt.runKernelFunc(function(t,e){var r=t.batchMatMul(m,v,n,i);return e([m,v]),r},{a:m,b:v},function(t,e){var r=e,o=r[0],s=r[1];return n||i?!n&&i?{a:function(){return t.matMul(s,!1,!1)},b:function(){return t.matMul(o,!0,!1)}}:n&&!i?{a:function(){return s.matMul(t,!1,!0)},b:function(){return o.matMul(t,!1,!1)}}:{a:function(){return s.matMul(t,!0,!0)},b:function(){return t.matMul(o,!0,!0)}}:{a:function(){return t.matMul(s,!1,!0)},b:function(){return o.matMul(t,!0,!1)}}},"BatchMatMul",_).reshape(g)}}),il=ln({dot_:function(t,e){var n=Ke(t,"t1","dot"),i=Ke(e,"t2","dot");C(!(1!==n.rank&&2!==n.rank||1!==i.rank&&2!==i.rank),function(){return"Error in dot: inputs must all be rank 1 or 2, but got ranks "+n.rank+" and "+i.rank+"."});var r=1===n.rank?n.size:n.shape[1],o=1===i.rank?i.size:i.shape[0];return C(r===o,function(){return"Error in dot: inner dimensions of inputs must match, but got "+r+" and "+o+"."}),1===n.rank&&1===i.rank?n.as2D(1,-1).matMul(i.as2D(-1,1)).asScalar():1===n.rank&&2===i.rank?n.as2D(1,-1).matMul(i.as2D(i.shape[0],i.shape[1])).as1D():2===n.rank&&1===i.rank?n.matMul(i.as2D(-1,1)).as1D():n.matMul(i.as2D(i.shape[0],i.shape[1]))}}),rl=ln({outerProduct_:function(t,e){var n=Ke(t,"v1","outerProduct"),i=Ke(e,"v2","outerProduct");return C(1===n.rank&&1===i.rank,function(){return"Error in outerProduct: inputs must be rank 1, but got ranks "+n.rank+" and "+i.rank+"."}),n.as2D(-1,1).matMul(i.as2D(1,-1))}}),ol=ln({reverse_:function(t,e){var n=Ke(t,"x","reverse");if(0===n.rank)return n.clone();var i=L(e,n.shape);return Pt.runKernelFunc(function(t){return t.reverse(n,i)},{$x:n},function(t){return{$x:function(){return t.reverse(i)}}}).reshapeAs(n)}}),sl=ln({reverse1d_:function(t){var e=Ke(t,"x","reverse");return C(1===e.rank,function(){return"Error in reverse1D: x must be rank 1 but got rank "+e.rank+"."}),ol(e,0)}}),al=ln({reverse2d_:function(t,e){var n=Ke(t,"x","reverse");return C(2===n.rank,function(){return"Error in reverse2D: x must be rank 2 but got rank "+n.rank+"."}),ol(n,e)}}),ll=ln({reverse3d_:function(t,e){var n=Ke(t,"x","reverse");return C(3===n.rank,function(){return"Error in reverse3D: x must be rank 3 but got rank "+n.rank+"."}),ol(n,e)}}),ul=ln({reverse4d_:function(t,e){var n=Ke(t,"x","reverse");return C(4===n.rank,function(){return"Error in reverse4D: x must be rank 4 but got rank "+n.rank+"."}),ol(n,e)}});function cl(t,e,n,i,r,o){var s=Ke(t,"x","maxPool"),a=s,l=!1;3===s.rank&&(l=!0,a=s.as4D(1,s.shape[0],s.shape[1],s.shape[2])),null==i&&(i=[1,1]),C(4===a.rank,function(){return"Error in maxPool: input must be rank 4 but got rank "+a.rank+"."}),C(Qi(n,i),function(){return"Error in maxPool: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+i+"'"}),null!=o&&C(R(r),function(){return"Error in maxPool: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+r+"."});var u=Gi(a.shape,e,n,i,r,o);if(1===u.filterWidth&&1===u.filterHeight&&I(u.inShape,u.outShape))return s.clone();var c=[a],h=Pt.runKernelFunc(function(t,e){var n=t.maxPool(a,u);return e([a,n]),n},{x:a},function(t,o){var s=o[0],a=o[1];return{x:function(){return function(t,e,n,i,r,o,s,a){var l=Ke(t,"dy","maxPoolBackprop"),u=Ke(e,"input","maxPoolBackprop"),c=Ke(n,"output","maxPoolBackprop");C(u.rank===l.rank,function(){return"Rank of input ("+u.rank+") does not match rank of dy ("+l.rank+")"}),null==o&&(o=[1,1]),C(Qi(r,o),function(){return"Error in maxPoolBackProp: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+o+"'"}),C(4===l.rank,function(){return"Error in maxPoolBackprop: dy must be rank 4 but got rank "+l.rank+"."}),C(4===u.rank,function(){return"Error in maxPoolBackprop: input must be rank 4 but got rank "+u.rank+"."});var h=Gi(u.shape,i,r,o,s,a);return Pt.runKernelFunc(function(t){return t.maxPoolBackprop(l,u,c,h)},{$dy:l,$input:u})}(t,s,a,e,n,i,r)}}},"MaxPool",u,c);return l?h.as3D(h.shape[1],h.shape[2],h.shape[3]):h}function hl(t,e,n,i,r,o){var s=Ke(t,"x","avgPool","float32");null==i&&(i=[1,1]),C(Qi(n,i),function(){return"Error in avgPool: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+i+"'"});var a=s,l=!1;3===s.rank&&(l=!0,a=s.as4D(1,s.shape[0],s.shape[1],s.shape[2])),C(4===a.rank,function(){return"Error in avgPool: x must be rank 4 but got rank "+a.rank+"."}),null!=o&&C(R(r),function(){return"Error in avgPool: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+r+"."});var u=Gi(a.shape,e,n,i,r,o);if(1===u.filterWidth&&1===u.filterHeight&&I(u.inShape,u.outShape))return s.clone();var c=Pt.runKernelFunc(function(t){return t.avgPool(a,u)},{x:a},function(t){return{x:function(){return function(t,e,n,i,r,o){var s=Ke(t,"dy","avgPoolBackprop"),a=Ke(e,"input","avgPoolBackprop");C(a.rank===s.rank,function(){return"Rank of input ("+a.rank+") does not match rank of dy ("+s.rank+")"}),null==r&&(r=[1,1]),C(Qi(i,r),function(){return"Error in avgPoolBackprop: Either strides or dilations must be 1. Got strides "+i+" and dilations '"+r+"'"});var l=a,u=s,c=!1;3===a.rank&&(c=!0,l=a.as4D(1,a.shape[0],a.shape[1],a.shape[2]),u=s.as4D(1,s.shape[0],s.shape[1],s.shape[2])),C(4===u.rank,function(){return"Error in avgPoolBackprop: dy must be rank 4 but got rank "+u.rank+"."}),C(4===l.rank,function(){return"Error in avgPoolBackprop: input must be rank 4 but got rank "+l.rank+"."});var h=Gi(l.shape,n,i,r,o),p=Pt.runKernelFunc(function(t){return t.avgPoolBackprop(u,l,h)},{dy4D:u,input4D:l});return c?p.as3D(p.shape[1],p.shape[2],p.shape[3]):p}(t,a,e,n,i,r)}}},"AvgPool",u);return c=c.cast(s.dtype),l?c.as3D(c.shape[1],c.shape[2],c.shape[3]):c}var pl=ln({maxPool_:function(t,e,n,i,r){return cl(t,e,n,1,i,r)}}),dl=ln({avgPool_:function(t,e,n,i,r){return hl(t,e,n,1,i,r)}}),fl=ln({pool_:function(t,e,n,i,r,o){null==r&&(r=[1,1]),null==o&&(o=1),0===i&&(i="valid");var s=Ke(t,"x","maxPool"),a=s,l=!1;3===s.rank&&(l=!0,a=s.as4D(1,s.shape[0],s.shape[1],s.shape[2])),C(Qi(o,r),function(){return"Error in pool: Either strides or dilations must be 1. Got strides "+o+" and dilations '"+r+"'"});var u,c=Gi(a.shape,e,o,r,i),h=[c.dilationHeight,c.dilationWidth];u="same"===i?function(t,e){var n=t.map(function(t,n){return t+(t-1)*(e[n]-1)}).map(function(t){return t-1}),i=n.map(function(t){return Math.floor(t/2)}),r=n.map(function(t,e){return t-i[e]});return n.map(function(t,e){return[i[e],r[e]]})}([c.filterHeight,c.filterWidth],h):[[0,0],[0,0]];var p=1===h[0]&&1===h[1],d=function(t,e,n){var i=n.map(function(t){return t[0]}),r=n.map(function(t){return t[1]}),o=t.concat(i,r),s=e.map(function(t,e){return(t-o[e]%t)%t}),a=r.map(function(t,e){return t+s[e]});return[e.map(function(t,e){return[i[e],a[e]]}),e.map(function(t,e){return[0,s[e]]})]}([c.inHeight,c.inWidth],h,u),f=d[0],g=d[1],m=p?i:"valid",v=p?a:ci(a,h,f),_=("avg"===n?function(){return hl(v,e,o,1,m)}:function(){return cl(v,e,o,1,m)})(),y=p?_:jn(_,h,g);return l?y.as3D(y.shape[1],y.shape[2],y.shape[3]):y}}),gl=ln({maxPool3d_:function(t,e,n,i,r,o,s){void 0===o&&(o="NDHWC");var a=Ke(t,"x","maxPool3d"),l=a,u=!1;4===a.rank&&(u=!0,l=a.as5D(1,a.shape[0],a.shape[1],a.shape[2],a.shape[3])),null==s&&(s=[1,1,1]),C(5===l.rank,function(){return"Error in maxPool3d: x must be rank 5 but got rank "+l.rank+"."}),C("NDHWC"===o,function(){return"Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of "+o}),C(Qi(n,s),function(){return"Error in maxPool3d: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+s+"'"}),null!=r&&C(R(i),function(){return"Error in maxPool3d: pad must be an integer when using, dimRoundingMode "+r+" but got pad "+i+"."});var c=ji(l.shape,e,n,s,i,r,o),h=Pt.runKernelFunc(function(t,e){var n=t.maxPool3d(l,c);return e([l,n]),n},{x:l},function(t,o){var a=o[0],l=o[1];return{x:function(){return function(t,e,n,i,r,o,s,a){var l=Ke(t,"dy","maxPool3dBackprop"),u=Ke(e,"input","maxPool3dBackprop"),c=Ke(n,"output","maxPool3dBackprop"),h=l,p=u,d=c,f=!1;4===u.rank&&(f=!0,h=l.as5D(1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]),p=u.as5D(1,u.shape[0],u.shape[1],u.shape[2],u.shape[3]),d=c.as5D(1,c.shape[0],c.shape[1],c.shape[2],c.shape[3])),C(5===h.rank,function(){return"Error in maxPool3dBackprop: dy must be rank 5 but got rank "+h.rank+"."}),C(5===p.rank,function(){return"Error in maxPool3dBackprop: input must be rank 5 but got rank "+p.rank+"."}),C(5===d.rank,function(){return"Error in maxPool3dBackprop: output must be rank 5 but got rank "+d.rank+"."}),null==o&&(o=[1,1,1]),C(Qi(r,o),function(){return"Error in maxPool3dBackprop: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+o+"'"}),null!=a&&C(R(s),function(){return"Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode "+a+" but got pad "+s+"."});var g=ji(p.shape,i,r,o,s,a),m=Pt.runKernelFunc(function(t){return t.maxPool3dBackprop(h,p,d,g)},{dy5D:h,input5D:p});return f?m.as4D(m.shape[1],m.shape[2],m.shape[3],m.shape[4]):m}(t,a,l,e,n,s,i,r)}}});return u?h.as4D(h.shape[1],h.shape[2],h.shape[3],h.shape[4]):h}}),ml=ln({avgPool3d_:function(t,e,n,i,r,o,s){void 0===o&&(o="NDHWC");var a=Ke(t,"x","avgPool3d","float32"),l=a,u=!1;4===a.rank&&(u=!0,l=a.as5D(1,a.shape[0],a.shape[1],a.shape[2],a.shape[3])),null==s&&(s=[1,1,1]),C(5===l.rank,function(){return"Error in avgPool3d: x must be rank 5 but got rank "+l.rank+"."}),C("NDHWC"===o,function(){return"Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of "+o}),C(Qi(n,s),function(){return"Error in avgPool3d: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+s+"'"}),null!=r&&C(R(i),function(){return"Error in avgPool3d: pad must be an integer when using, dimRoundingMode "+r+" but got pad "+i+"."});var c=ji(l.shape,e,n,s,i,r,o),h=Pt.runKernelFunc(function(t){return t.avgPool3d(l,c)},{x:l},function(t){return{x:function(){return function(t,e,n,i,r,o,s){var a=Ke(t,"dy","avgPool3dBackprop"),l=Ke(e,"input","avgPool3dBackprop"),u=a,c=l,h=!1;4===l.rank&&(h=!0,u=a.as5D(1,a.shape[0],a.shape[1],a.shape[2],a.shape[3]),c=l.as5D(1,l.shape[0],l.shape[1],l.shape[2],l.shape[3])),C(5===u.rank,function(){return"Error in avgPool3dBackprop: dy must be rank 5 but got rank "+u.rank+"."}),C(5===c.rank,function(){return"Error in avgPool3dBackprop: input must be rank 5 but got rank "+c.rank+"."}),null==r&&(r=[1,1,1]),C(Qi(i,r),function(){return"Error in avgPool3dBackprop: Either strides or dilations must be 1. Got strides "+i+" and dilations '"+r+"'"}),null!=s&&C(R(o),function(){return"Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode "+s+" but got pad "+o+"."});var p=ji(c.shape,n,i,r,o,s),d=Pt.runKernelFunc(function(t){return t.avgPool3dBackprop(u,c,p)},{dy5D:u,input5D:c});return h?d.as4D(d.shape[1],d.shape[2],d.shape[3],d.shape[4]):d}(t,l,e,n,s,i,r)}}});return h=h.cast(l.dtype),u?h.as4D(h.shape[1],h.shape[2],h.shape[3],h.shape[4]):h}}),vl=ln({slice_:function(t,e,n){var i,r,o=Ke(t,"x","slice");if(0===o.rank)throw new Error("Slicing scalar is not possible");(i="number"==typeof e?[e].concat(new Array(o.rank-1).fill(0)):e.length=0?t:(C(-1===t,function(){return"Negative size values should be exactly -1 but got "+t+" for the slice() size at index "+e+"."}),o.shape[e]-i[e])}),xi(o,i,r);var s=o.shape,a={begin:i,size:r};return Pt.runKernelFunc(function(t){return t.slice(o,i,r)},{x:o},function(t){for(var e=[],n=0;n0&&(e=e.sum(o)),e.reshape(i.shape)}}},"Prelu")}}),Bl=ln({relu_:function(t){var e=Ke(t,"x","relu");return"bool"===e.dtype?e.toInt():Pt.runKernelFunc(function(t,n){var i=t.relu(e);return n([e]),i},{x:e},function(t,e){var n=e[0];return{x:function(){return t.mulStrict(n.step().toFloat())}}},"Relu")}}),Fl=ln({relu6_:function(t){var e=Ke(t,"x","relu6");return"bool"===e.dtype?e.toInt():Pt.runKernelFunc(function(t,n){var i=t.relu6(e);return n([e]),i},{x:e},function(t,e){var n=e[0],i=n.lessEqual(6).mul(n.step());return{x:function(){return t.mulStrict(i.toFloat())}}},"Relu6")}}),Ul=ln({selu_:function(t){var e=Ke(t,"x","selu");return Pt.runKernelFunc(function(t,n){var i=t.selu(e);return n([e]),i},{$x:e},function(t,e){var n=e[0];return{$x:function(){var e=n.greater(fn(0)),i=fn(Ao),r=fn(Mo),o=t.mul(r),s=t.mul(i).mul(n.toFloat().exp());return ia(e,o,s)}}})}}),Vl=ln({transpose_:function(t,e){var n=Ke(t,"x","transpose");if(null==e&&(e=n.shape.map(function(t,e){return e}).reverse()),C(n.rank===e.length,function(){return"Error in transpose: rank of input "+n.rank+" must match length of perm "+e+"."}),e.forEach(function(t){C(t>=0&&tr)throw new Error("'k' passed to topk() must be <= the last dimension ("+r+") but got "+e);var o=Pt.runKernelFunc(function(t){return t.topk(i,e,n)},{$x:i});return{values:o[0],indices:o[1]}}}),Yl=ln({scatterND_:function(t,e,n){var i=Ke(t,"indices","scatterND","int32"),r=Ke(e,"updates","scatterND");return wi(r,i,n),Pt.runKernelFunc(function(t){return t.scatterND(i,r,n)},{indices:i,updates:r},null,"ScatterNd",{shape:n})}}),Kl=ln({fft_:function(t){C("complex64"===t.dtype,function(){return"The dtype for tf.spectral.fft() must be complex64 but got "+t.dtype+"."});var e=t.shape[t.shape.length-1],n=t.size/e,i=t.as2D(n,e);return Pt.runKernelFunc(function(t){return t.fft(i)},{input:t}).reshape(t.shape)}}),Jl=ln({ifft_:function(t){C("complex64"===t.dtype,function(){return"The dtype for tf.spectral.ifft() must be complex64 but got "+t.dtype+"."});var e=t.shape[t.shape.length-1],n=t.size/e,i=t.as2D(n,e);return Pt.runKernelFunc(function(t){return t.ifft(i)},{input:t}).reshape(t.shape)}}),ql=ln({rfft_:function(t,e){C("float32"===t.dtype,function(){return"The dtype for rfft() must be real value but got "+t.dtype});var n,i=t.shape[t.shape.length-1],r=t.size/i;if(null!=e&&ei){var a=t.shape.map(function(t){return t});a[t.shape.length-1]=e-i,n=t.concat(bn(a),t.shape.length-1),i=e}else n=t;var l=n.zerosLike(),u=un(n,l).as2D(r,i),c=Kl(u),h=Math.floor(i/2)+1,p=cn(c),d=hn(c),f=p.split([h,i-h],p.shape.length-1),g=d.split([h,i-h],d.shape.length-1),m=n.shape.slice();return m[n.shape.length-1]=h,un(f[0],g[0]).reshape(m)}}),Zl=ln({irfft_:function(t){var e=t.shape[t.shape.length-1],n=t.size/e;if(e<=2){var i=t.as2D(n,e),r=Jl(i);return cn(r)}var o=[n,2*(e-1)],s=cn(t).as2D(n,e),a=hn(t).as2D(n,e),l=s.slice([0,1],[n,e-2]).reverse(1),u=a.slice([0,1],[n,e-2]).reverse(1).mul(fn(-1)),c=s.concat(l,1),h=a.concat(u,1);return i=un(c,h).as2D(o[0],o[1]),r=Jl(i),cn(r)}}),Ql=Object.freeze({fft:Kl,ifft:Jl,rfft:ql,irfft:Zl}),tu=ln({sparseToDense_:function(t,e,n,i){void 0===i&&(i=0);var r=Ke(t,"sparseIndices","sparseToDense","int32"),o=Ke(e,"sparseValues","sparseToDense"),s=Ke(i,"defaultValue","sparseToDense",o.dtype);return function(t,e,n,i){if("int32"!==t.dtype)throw new Error("tf.sparseToDense() expects the indices to be int32 type, but the dtype was "+t.dtype+".");if(t.rank>2)throw new Error("sparseIndices should be a scalar, vector, or matrix, but got shape "+t.shape+".");var r=t.rank>0?t.shape[0]:1,o=t.rank>1?t.shape[1]:1;if(n.length!==o)throw new Error("outputShape has incorrect number of elements:, "+n.length+", should be: "+o+".");var s=e.size;if(0!==e.rank&&(1!==e.rank||s!==r))throw new Error("sparseValues has incorrect shape "+e.shape+", should be [] or ["+r+"]");if(e.dtype!==i.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}(r,o,n,s),Pt.runKernelFunc(function(t){return t.sparseToDense(r,o,n,s)},{$sparseIndices:r,$sparseValues:o,$defaultValue:s})}}),eu=ln({gatherND_:function(t,e){var n=Ke(e,"indices","gatherND","int32"),i=Ke(t,"x","gatherND");return Pt.runKernelFunc(function(t){return t.gatherND(i,n)},{x:i,indices:n},null,"GatherNd")}}),nu=ln({diag_:function(t){var e=Ke(t,"x","diag").flatten(),n=t.shape.concat(t.shape);return Pt.runKernelFunc(function(t){return t.diag(e)},{$x:e}).reshape(n)}}),iu=ln({dropout_:function(t,e,n,i){var r=Ke(t,"x","dropout");if(C("float32"===r.dtype,function(){return"x has to be a floating point tensor since it's going to be scaled, but got a "+r.dtype+" tensor instead."}),C(e>=0&&e<1,function(){return"rate must be a float in the range [0, 1), but got "+e+"."}),0===e)return t instanceof bt?r.clone():r;var o=function(t,e){if(null==e)return t.shape.slice();if(I(t.shape,e))return e;if(t.shape.length===e.length){for(var n=[],i=0;i1?a.div(fn(s)):a}if(n===ou.SUM_BY_NONZERO_WEIGHTS){if(null==r)return o.sum().div(fn(i.size));var l=r.mul(yn(i.shape)).notEqual(fn(0)).sum().toFloat();return o.sum().div(l)}throw Error("Unknown reduction: "+n)}}),du=ln({cosineDistance_:function(t,e,n,i,r){void 0===r&&(r=ou.SUM_BY_NONZERO_WEIGHTS);var o=Ke(t,"labels","cosineDistance"),s=Ke(e,"predictions","cosineDistance"),a=null;null!=i&&(a=Ke(i,"weights","cosineDistance")),S(o.shape,s.shape,"Error in cosineDistance: ");var l=fn(1).sub(o.mul(s).sum(n,!0));return pu(l,a,r)}}),fu=ln({hingeLoss_:function(t,e,n,i){void 0===i&&(i=ou.SUM_BY_NONZERO_WEIGHTS);var r=Ke(t,"labels","hingeLoss"),o=Ke(e,"predictions","hingeLoss"),s=null;null!=n&&(s=Ke(n,"weights","hingeLoss")),S(r.shape,o.shape,"Error in hingeLoss: ");var a=fn(1);r=fn(2).mul(r).sub(a);var l=a.sub(r.mul(o)).relu();return pu(l,s,i)}}),gu=ln({huberLoss_:function(t,e,n,i,r){void 0===i&&(i=1),void 0===r&&(r=ou.SUM_BY_NONZERO_WEIGHTS);var o=Ke(t,"labels","huberLoss"),s=Ke(e,"predictions","huberLoss"),a=null;null!=n&&(a=Ke(n,"weights","huberLoss")),S(o.shape,s.shape,"Error in huberLoss: ");var l=fn(i),u=s.sub(o).abs(),c=ga(u,l),h=u.sub(c),p=fn(.5).mul(c.square()).add(l.mul(h));return pu(p,a,r)}}),mu=ln({logLoss_:function(t,e,n,i,r){void 0===i&&(i=1e-7),void 0===r&&(r=ou.SUM_BY_NONZERO_WEIGHTS);var o=Ke(t,"labels","logLoss"),s=Ke(e,"predictions","logLoss"),a=null;null!=n&&(a=Ke(n,"weights","logLoss")),S(o.shape,s.shape,"Error in logLoss: ");var l=fn(1),u=fn(i),c=o.mul(s.add(u).log()).neg().sub(l.sub(o).mul(l.sub(s).add(u).log()));return pu(c,a,r)}}),vu=ln({meanSquaredError_:function(t,e,n,i){void 0===i&&(i=ou.SUM_BY_NONZERO_WEIGHTS);var r=Ke(t,"labels","meanSquaredError"),o=Ke(e,"predictions","meanSquaredError"),s=null;null!=n&&(s=Ke(n,"weights","meanSquaredError")),S(r.shape,o.shape,"Error in meanSquaredError: ");var a=r.squaredDifference(o);return pu(a,s,i)}}),_u=ln({sigmoidCrossEntropy_:function(t,e,n,i,r){void 0===i&&(i=0),void 0===r&&(r=ou.SUM_BY_NONZERO_WEIGHTS);var o=Ke(t,"multiClassLabels","sigmoidCrossEntropy"),s=Ke(e,"logits","sigmoidCrossEntropy"),a=null;if(null!=n&&(a=Ke(n,"weights","sigmoidCrossEntropy")),S(o.shape,s.shape,"Error in sigmoidCrossEntropy: "),i>0){var l=fn(i),u=fn(1),c=fn(.5);o=o.mul(u.sub(l)).add(c.mul(l))}var h=function(t,e){var n=Ke(t,"labels","sigmoidCrossEntropyWithLogits"),i=Ke(e,"logits","sigmoidCrossEntropyWithLogits");S(n.shape,i.shape,"Error in sigmoidCrossEntropyWithLogits: ");var r=i.relu(),o=i.mul(n),s=i.abs().neg().exp().log1p();return r.sub(o).add(s)}(o,s);return pu(h,a,r)}}),yu=ln({softmaxCrossEntropy_:function(t,e,n,i,r){void 0===i&&(i=0),void 0===r&&(r=ou.SUM_BY_NONZERO_WEIGHTS);var o=Ke(t,"onehotLabels","softmaxCrossEntropy"),s=Ke(e,"logits","softmaxCrossEntropy"),a=null;if(null!=n&&(a=Ke(n,"weights","softmaxCrossEntropy")),S(o.shape,s.shape,"Error in softmaxCrossEntropy: "),i>0){var l=fn(i),u=fn(1),c=fn(o.shape[1]);o=o.mul(u.sub(l)).add(l.div(c))}var h=function(t,e,n){if(void 0===n&&(n=-1),-1===n&&(n=e.rank-1),n!==e.rank-1)throw Error("Softmax cross entropy along a non-last dimension is not yet supported. Labels / logits was rank "+e.rank+" and dim was "+n);return Ni(function(t,e,i){var r=e.logSumExp([n],!0),o=e.toFloat().sub(r);return i([t,o]),{value:o.mul(t).neg().sum([n]),gradFunc:function(t,e){var i=e[0],r=e[1],o=tn(t.shape,[n]);return[t.reshape(o).mul(i.toFloat().sub(r.exp())),t.reshape(o).mul(r.exp().sub(i.toFloat()))]}}})(t,e)}(o,s);return pu(h,a,r)}}),bu=Object.freeze({get Reduction(){return ou},absoluteDifference:hu,computeWeightedLoss:pu,cosineDistance:du,hingeLoss:fu,huberLoss:gu,logLoss:mu,meanSquaredError:vu,sigmoidCrossEntropy:_u,softmaxCrossEntropy:yu});function Tu(t,e){return void 0===e&&(e=!1),Pt.tidy(function(){if(2!==t.shape.length)throw new Error("qr2d() requires a 2D Tensor, but got a "+t.shape.length+"D Tensor.");for(var n=t.shape[0],i=t.shape[1],r=qn(n),o=t.clone(),s=mn([[1]],[1,1]),a=s.clone(),l=n>=i?i:n,u=function(t){var e,l=o,u=a,c=r;e=Pt.tidy(function(){var e=o.slice([t,t],[n-t,1]),l=e.norm(),u=o.slice([t,t],[1,1]),c=mn([[-1]]).where(u.greater(0),mn([[1]])),h=u.sub(c.mul(l)),p=e.div(h);a=1===p.shape[0]?s.clone():s.concat(p.slice([1,0],[p.shape[0]-1,p.shape[1]]),0);var d=c.matMul(h).div(l).neg(),f=o.slice([t,0],[n-t,i]),g=d.mul(a);if(0===t)o=f.sub(g.matMul(a.transpose().matMul(f)));else{var m=f.sub(g.matMul(a.transpose().matMul(f)));o=o.slice([0,0],[t,i]).concat(m,0)}var v=r.slice([0,t],[n,r.shape[1]-t]);if(0===t)r=v.sub(v.matMul(a).matMul(g.transpose()));else{var _=v.sub(v.matMul(a).matMul(g.transpose()));r=r.slice([0,0],[n,t]).concat(_,1)}return[a,o,r]}),a=e[0],o=e[1],r=e[2],ze([l,u,c])},c=0;ci&&(r=r.slice([0,0],[n,i]),o=o.slice([0,0],[i,i])),[r,o]})}var Eu=ln({bandPart_:function(t,e,n){if(e%1!=0)throw new Error("bandPart(): numLower must be an integer, got "+e+".");if(n%1!=0)throw new Error("bandPart(): numUpper must be an integer, got "+n+".");var i=Ke(t,"a","bandPart");if(i.rank<2)throw new Error("bandPart(): Rank must be at least 2, got "+i.rank+".");var r=i.shape,o=i.shape.slice(-2),s=o[0],a=o[1];if(!(e<=s))throw new Error("bandPart(): numLower ("+e+") must not be greater than the number of rows ("+s+").");if(!(n<=a))throw new Error("bandPart(): numUpper ("+n+") must not be greater than the number of columns ("+a+").");e<0&&(e=s),n<0&&(n=a);var l=En(0,s,1,"int32").reshape([-1,1]),u=En(0,a,1,"int32"),c=Sa(l,u),h=Qs(c.lessEqual(fn(+e,"int32")),c.greaterEqual(fn(-n,"int32"))),p=bn([s,a],i.dtype);return pi(gi(i.reshape([-1,s,a])).map(function(t){return ia(h,t,p)})).reshape(r)}}),Cu=ln({gramSchmidt_:function(t){var e;if(Array.isArray(t)){e=!1,C(null!=t&&t.length>0,function(){return"Gram-Schmidt process: input must not be null, undefined, or empty"});for(var n=t[0].shape[0],i=function(e){C(t[e].shape[0]===n,function(){return"Gram-Schmidt: Non-unique lengths found in the input vectors: ("+t[e].shape[0]+" vs. "+n+")"})},r=1;r0)for(var n=0;n= 2, but got rank "+t.rank);if(2===t.rank)return Tu(t,e);var n=t.shape.slice(0,t.shape.length-2).reduce(function(t,e){return t*e}),i=[],r=[];return gi(t.reshape([n,t.shape[t.shape.length-2],t.shape[t.shape.length-1]]),0).forEach(function(t){var n=Tu(t,e),o=n[0],s=n[1];i.push(o),r.push(s)}),[pi(i,0).reshape(t.shape),pi(r,0).reshape(t.shape)]}}),wu=Object.freeze({bandPart:Eu,gramSchmidt:Cu,qr:Su});function ku(t,e,n,i,r,o){null==i&&(i=.5),null==r&&(r=Number.NEGATIVE_INFINITY),null==o&&(o=0);var s=t.shape[0];return n=Math.min(n,s),C(0<=i&&i<=1,function(){return"iouThreshold must be in [0, 1], but was '"+i+"'"}),C(2===t.rank,function(){return"boxes must be a 2D tensor, but was of rank '"+t.rank+"'"}),C(4===t.shape[1],function(){return"boxes must have 4 columns, but 2nd dimension was "+t.shape[1]}),C(1===e.rank,function(){return"scores must be a 1D tensor"}),C(e.shape[0]===s,function(){return"scores has incompatible shape with boxes. Expected "+s+", but was "+e.shape[0]}),C(0<=o&&o<=1,function(){return"softNmsSigma must be in [0, 1], but was '"+o+"'"}),{maxOutputSize:n,iouThreshold:i,scoreThreshold:r,softNmsSigma:o}}var xu=ln({resizeBilinear_:function(t,e,n){void 0===n&&(n=!1);var i=Ke(t,"images","resizeBilinear");C(3===i.rank||4===i.rank,function(){return"Error in resizeBilinear: x must be rank 3 or 4, but got rank "+i.rank+"."}),C(2===e.length,function(){return"Error in resizeBilinear: new shape must 2D, but got shape "+e+"."});var r=i,o=!1;3===i.rank&&(o=!0,r=i.as4D(1,i.shape[0],i.shape[1],i.shape[2]));var s=e[0],a=e[1],l=Pt.runKernelFunc(function(t,e){return e([r]),t.resizeBilinear(r,s,a,n)},{x:r},function(t,e){return{x:function(){return Pt.runKernelFunc(function(i){return i.resizeBilinearBackprop(t,e[0],n)},{})}}},"ResizeBilinear",{alignCorners:n,newHeight:s,newWidth:a});return o?l.as3D(l.shape[1],l.shape[2],l.shape[3]):l}}),Iu=ln({resizeNearestNeighbor_:function(t,e,n){void 0===n&&(n=!1);var i=Ke(t,"images","resizeNearestNeighbor");C(3===i.rank||4===i.rank,function(){return"Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank "+i.rank+"."}),C(2===e.length,function(){return"Error in resizeNearestNeighbor: new shape must 2D, but got shape "+e+"."}),C("float32"===i.dtype||"int32"===i.dtype,function(){return"`images` must have `int32` or `float32` as dtype"});var r=i,o=!1;3===i.rank&&(o=!0,r=i.as4D(1,i.shape[0],i.shape[1],i.shape[2]));var s=e[0],a=e[1],l=Pt.runKernelFunc(function(t,e){return e([r]),t.resizeNearestNeighbor(r,s,a,n)},{batchImages:r},function(t,e){return{batchImages:function(){return Pt.runKernelFunc(function(i){return i.resizeNearestNeighborBackprop(t,e[0],n)},{})}}});return o?l.as3D(l.shape[1],l.shape[2],l.shape[3]):l}}),Ru=ln({nonMaxSuppression_:function(t,e,n,i,r){void 0===i&&(i=.5),void 0===r&&(r=Number.NEGATIVE_INFINITY);var o=Ke(t,"boxes","nonMaxSuppression"),s=Ke(e,"scores","nonMaxSuppression"),a=ku(o,s,n,i,r);n=a.maxOutputSize,i=a.iouThreshold,r=a.scoreThreshold;var l={maxOutputSize:n,iouThreshold:i,scoreThreshold:r};return Pt.runKernelFunc(function(t){return t.nonMaxSuppression(o,s,n,i,r)},{boxes:o,scores:s},null,"NonMaxSuppressionV3",l)}}),Ou=ln({nonMaxSuppressionWithScore_:function(t,e,n,i,r,o){void 0===i&&(i=.5),void 0===r&&(r=Number.NEGATIVE_INFINITY),void 0===o&&(o=0);var s=Ke(t,"boxes","nonMaxSuppression"),a=Ke(e,"scores","nonMaxSuppression"),l=ku(s,a,n,i,r,o),u={maxOutputSize:n=l.maxOutputSize,iouThreshold:i=l.iouThreshold,scoreThreshold:r=l.scoreThreshold,softNmsSigma:o=l.softNmsSigma},c=Pt.runKernel("NonMaxSuppressionV5",{boxes:s,scores:a},u);return{selectedIndices:c[0],selectedScores:c[1]}}}),Du=ln({cropAndResize_:function(t,e,n,i,r,o){var s=Ke(t,"image","cropAndResize"),a=Ke(e,"boxes","cropAndResize","float32"),l=Ke(n,"boxInd","cropAndResize","int32");r=r||"bilinear",o=o||0;var u=a.shape[0];return C(4===s.rank,function(){return"Error in cropAndResize: image must be rank 4,but got rank "+s.rank+"."}),C(2===a.rank&&4===a.shape[1],function(){return"Error in cropAndResize: boxes must be have size ["+u+",4] but had shape "+a.shape+"."}),C(1===l.rank&&l.shape[0]===u,function(){return"Error in cropAndResize: boxInd must be have size ["+u+"] but had shape "+a.shape+"."}),C(2===i.length,function(){return"Error in cropAndResize: cropSize must be of length 2, but got length "+i.length+"."}),C(i[0]>=1&&i[1]>=1,function(){return"cropSize must be atleast [1,1], but was "+i}),C("bilinear"===r||"nearest"===r,function(){return"method must be bilinear or nearest, but was "+r}),Pt.runKernelFunc(function(t,e){return t.cropAndResize(s,a,l,i,r,o)},{images:s,boxes:a,boxInd:l},null,"CropAndResize",{method:r,extrapolationValue:o,cropSize:i})}}),Au=Object.freeze({resizeBilinear:xu,resizeNearestNeighbor:Iu,nonMaxSuppression:Ru,nonMaxSuppressionAsync:function(t,e,n,i,r){return void 0===i&&(i=.5),void 0===r&&(r=Number.NEGATIVE_INFINITY),a(this,void 0,void 0,function(){var o,s,a,u,c,h,p;return l(this,function(l){switch(l.label){case 0:return o=Ke(t,"boxes","nonMaxSuppressionAsync"),s=Ke(e,"scores","nonMaxSuppressionAsync"),a=ku(o,s,n,i,r),n=a.maxOutputSize,i=a.iouThreshold,r=a.scoreThreshold,[4,Promise.all([o.data(),s.data()])];case 1:return u=l.sent(),c=u[0],h=u[1],p=cr(c,h,n,i,r),o!==t&&o.dispose(),s!==e&&s.dispose(),[2,p]}})})},nonMaxSuppressionWithScore:Ou,nonMaxSuppressionWithScoreAsync:function(t,e,n,i,r,o){return void 0===i&&(i=.5),void 0===r&&(r=Number.NEGATIVE_INFINITY),void 0===o&&(o=0),a(this,void 0,void 0,function(){var s,a,u,c,h,p,d;return l(this,function(l){switch(l.label){case 0:return s=Ke(t,"boxes","nonMaxSuppressionAsync"),a=Ke(e,"scores","nonMaxSuppressionAsync"),u=ku(s,a,n,i,r,o),n=u.maxOutputSize,i=u.iouThreshold,r=u.scoreThreshold,o=u.softNmsSigma,[4,Promise.all([s.data(),a.data()])];case 1:return c=l.sent(),h=c[0],p=c[1],d=hr(h,p,n,i,r,o),s!==t&&s.dispose(),a!==e&&a.dispose(),[2,d]}})})},cropAndResize:Du}),Mu=function(t,e){return!(t>0)||"linear"===e},Nu=function(t,e,n){if(null==n||"linear"===n)return t;if("relu"===n)return t.mul(e.step());throw new Error("Gradient for activation "+n+" has not been implemented yet.")},Lu=function(t,e){var n=e,i=Hi(t.shape,e.shape);return i.length>0&&(n=n.sum(i)),n.reshape(t.shape)},Pu=function(t,e,n){if("linear"===e)return t;if("relu"===e)return Bl(t);if("elu"===e)return Nl(t);if("relu6"===e)return Fl(t);if("prelu"===e)return Pl(t,n);throw new Error("Unknown fused activation "+e+".")},Bu=ln({fusedMatMul_:function(t){var e,n=t.a,i=t.b,r=t.transposeA,o=void 0!==r&&r,s=t.transposeB,a=void 0!==s&&s,l=t.bias,u=t.activation,c=void 0===u?"linear":u,h=t.preluActivationWeights;if(!1===Mu(Pt.state.gradientDepth,c)){var p=nl(n,i,o,a);return null!=l&&(p=oa(p,l)),Pu(p,c,h)}var d=Ke(n,"a","fused matMul"),f=Ke(i,"b","fused matMul");e=Ot(d,f),d=e[0],f=e[1];var g=o?d.shape[d.rank-2]:d.shape[d.rank-1],m=a?f.shape[f.rank-1]:f.shape[f.rank-2],v=o?d.shape[d.rank-1]:d.shape[d.rank-2],_=a?f.shape[f.rank-2]:f.shape[f.rank-1],y=d.shape.slice(0,-2),b=f.shape.slice(0,-2),T=x(y),E=x(b);C(d.rank>=2&&f.rank>=2&&d.rank===f.rank,function(){return"Error in fused matMul: inputs must have the same rank of at least 2, got ranks "+d.rank+" and "+f.rank+"."}),C(I(y,b),function(){return"Error in fused matMul: outer dimensions ("+y+") and ("+b+") of Tensors with shapes "+d.shape+" and "+f.shape+" must match."}),C(g===m,function(){return"Error in fused matMul: inner shapes ("+g+") and ("+m+") of Tensors with shapes "+d.shape+" and "+f.shape+" and transposeA="+o+" and transposeB="+a+" must match."});var S,w,k=d.shape.slice(0,-2).concat([v,_]),R=o?d.as3D(T,g,v):d.as3D(T,v,g),O=a?f.as3D(E,_,m):f.as3D(E,m,_);null!=l&&Wi(k,(S=Ot(S=Ke(l,"bias","fused matMul"),d)[0]).shape),null!=h&&(w=Ke(h,"prelu weights","fused matMul"));var D={a:R,b:O};null!=l&&(D.bias=S),null!=h&&(D.preluActivationWeights=w);var A=[R,O];return Pt.runKernelFunc(function(t,e){var n=t.fusedBatchMatMul({a:R,b:O,transposeA:o,transposeB:a,bias:S,activation:c,preluActivationWeights:w});return e([R,O,n]),n},D,function(t,e){var n=e[0],i=e[1],r=e[2],s=Nu(t,r,c),u={};return null!=l&&(u={bias:function(){return Lu(S,s)}}),o||a?!o&&a?Object.assign({a:function(){return s.matMul(i,!1,!1)},b:function(){return s.matMul(n,!0,!1)}},u):o&&!a?Object.assign({a:function(){return i.matMul(s,!1,!0)},b:function(){return n.matMul(s,!1,!1)}},u):Object.assign({a:function(){return i.matMul(s,!0,!0)},b:function(){return s.matMul(n,!0,!0)}},u):Object.assign({a:function(){return s.matMul(i,!1,!0)},b:function(){return n.matMul(s,!0,!1)}},u)},"_FusedMatMul",{transposeA:o,transposeB:a,activation:c},A,[!0]).reshape(k)}}),Fu=ln({fusedConv2d_:function(t){var e=t.x,n=t.filter,i=t.strides,r=t.pad,o=t.dataFormat,s=void 0===o?"NHWC":o,a=t.dilations,l=void 0===a?[1,1]:a,u=t.dimRoundingMode,c=t.bias,h=t.activation,p=void 0===h?"linear":h,d=t.preluActivationWeights;if(p=p||"linear",!1===Mu(Pt.state.gradientDepth,p)){var f=$a(e,n,i,r,s,l,u);return null!=c&&(f=oa(f,c)),Pu(f,p,d)}var g=Ke(e,"x","conv2d"),m=Ke(n,"filter","conv2d"),v=g,_=!1;3===g.rank&&(_=!0,v=g.as4D(1,g.shape[0],g.shape[1],g.shape[2])),C(4===v.rank,function(){return"Error in fused conv2d: input must be rank 4, but got rank "+v.rank+"."}),C(4===m.rank,function(){return"Error in fused conv2d: filter must be rank 4, but got rank "+m.rank+"."}),null!=u&&C(R(r),function(){return"Error in fused conv2d: pad must be an integer when using, dimRoundingMode "+u+" but got pad "+r+"."}),C(v.shape[3]===m.shape[2],function(){return"Error in conv2d: depth of input ("+v.shape[3]+") must match input depth for filter "+m.shape[2]+"."}),C(Qi(i,l),function(){return"Error in conv2D: Either strides or dilations must be 1. Got strides "+i+" and dilations '"+l+"'"}),C("NHWC"===s,function(){return"Error in conv2d: got dataFormat of "+s+" but only NHWC is currently supported."});var y,b,T=zi(v.shape,m.shape,i,l,r,u);null!=c&&(y=Ot(y=Ke(c,"bias","fused conv2d"),g)[0],Wi(T.outShape,y.shape)),null!=d&&(b=Ke(d,"prelu weights","fused conv2d"));var E={x:v,filter:m};null!=c&&(E.bias=y),null!=d&&(E.preluActivationWeights=b);var S=[m,v],w=Pt.runKernelFunc(function(t,e){var n=t.fusedConv2d({input:v,filter:m,convInfo:T,bias:y,activation:p,preluActivationWeights:b});return e([m,v,n]),n},E,function(t,e){var n=e,o=n[0],s=n[1],a=n[2],u=Nu(t,a,p);C(Zi(l),function(){return"Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '"+l+"'"});var h={};return null!=c&&(h={bias:function(){return Lu(y,u)}}),Object.assign({x:function(){return Ka(s.shape,u,o,i,r)},filter:function(){return Ya(s,u,o.shape,i,r)}},h)},"FusedConv2D",{convInfo:T,activation:p},S,[!0]);return _?w.as3D(w.shape[1],w.shape[2],w.shape[3]):w}}),Uu=ln({fusedDepthwiseConv2d_:function(t){var e=t.x,n=t.filter,i=t.strides,r=t.pad,o=t.dataFormat,s=void 0===o?"NHWC":o,a=t.dilations,l=void 0===a?[1,1]:a,u=t.dimRoundingMode,c=t.bias,h=t.activation,p=void 0===h?"linear":h,d=t.preluActivationWeights;if(!1===Mu(Pt.state.gradientDepth,p)){var f=Ja(e,n,i,r,s,l,u);return null!=c&&(f=oa(f,c)),Pu(f,p,d)}var g=Ke(e,"x","depthwiseConv2d"),m=Ke(n,"filter","depthwiseConv2d"),v=g,_=!1;3===g.rank&&(_=!0,v=g.as4D(1,g.shape[0],g.shape[1],g.shape[2])),C(4===v.rank,function(){return"Error in fused depthwiseConv2d: input must be rank 4, but got rank "+v.rank+"."}),C(4===m.rank,function(){return"Error in fused depthwiseConv2d: filter must be rank 4, but got rank "+m.rank+"."}),C(v.shape[3]===m.shape[2],function(){return"Error in fused depthwiseConv2d: number of input channels ("+v.shape[3]+") must match the inChannels dimension in filter "+m.shape[2]+"."}),null==l&&(l=[1,1]),C(Qi(i,l),function(){return"Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides "+i+" and dilations '"+l+"'"}),null!=u&&C(R(r),function(){return"Error in fused depthwiseConv2d: pad must be an integer when using dimRoundingMode "+u+" but got pad "+r+"."});var y,b,T=zi(v.shape,m.shape,i,l,r,u,!0);null!=c&&(y=Ot(y=Ke(c,"bias","fused conv2d"),g)[0],Wi(T.outShape,y.shape)),null!=d&&(b=Ke(d,"prelu weights","fused depthwiseConv2d"));var E={x:v,filter:m};null!=c&&(E.bias=y),null!=d&&(E.preluActivationWeights=b);var S=[m,v],w=Pt.runKernelFunc(function(t,e){var n=t.fusedDepthwiseConv2D({input:v,filter:m,convInfo:T,bias:y,activation:p,preluActivationWeights:b});return e([m,v,n]),n},E,function(t,e){C(Zi(l),function(){return"Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '"+l+"'"});var n=e[0],i=e[1],r=e[2],o=Nu(t,r,p),s={};return null!=c&&(s={bias:function(){return Lu(y,o)}}),Object.assign({x:function(){return qa(i.shape,o,n,T)},filter:function(){return Za(i,o,n.shape,T)}},s)},"FusedDepthwiseConv2D",{convInfo:T,activation:p},S,[!0]);return _?w.as3D(w.shape[1],w.shape[2],w.shape[3]):w}}),Vu=Object.freeze({matMul:Bu,conv2d:Fu,depthwiseConv2d:Uu}),Hu=Object.freeze({image:Au,linalg:wu,losses:bu,spectral:Ql,fused:Vu,signal:cu,square:ns,squaredDifference:rs,conv1d:za,conv2d:$a,conv3d:Xa,depthwiseConv2d:Ja,separableConv2d:Qa,conv2dTranspose:tl,conv3dTranspose:el,op:ln,batchNormalization2d:zs,batchNormalization3d:$s,batchNormalization4d:Xs,batchNormalization:Ys,batchNorm:Ks,batchNorm2d:Js,batchNorm3d:qs,batchNorm4d:Zs,booleanMaskAsync:function(t,e,n){return a(this,void 0,void 0,function(){var i,r,o,s,a,u,c,h,p,d,f,g,m;return l(this,function(l){switch(l.label){case 0:for(i=Ke(t,"tensor","boolMask"),r=Ke(e,"mask","boolMask","bool"),o=null==n?0:n,s=r.rank,a=i.shape,C(s>0,function(){return"mask cannot be scalar"}),S(a.slice(o,o+s),r.shape,"mask's shape must match the first K dimensions of tensor's shape,"),u=1,c=o;c1,function(){return"inTopK() expects the predictions to be of rank 2 or higher, but got "+i.rank}),C(i.rank-1===r.rank,function(){return"predictions rank should be 1 larger than targets rank, but got predictions rank "+i.rank+" and targets rank "+r.rank}),S(i.shape.slice(0,i.shape.length-1),r.shape,"predictions's shape should be align with the targets' shape, except the last dimension."),o=i.shape[i.shape.length-1],C(n>0&&n<=o,function(){return"'k' passed to inTopK() must be > 0 && <= the predictions last dimension ("+o+"), but got "+n}),[4,i.data()];case 1:return s=l.sent(),[4,r.data()];case 2:for(a=l.sent(),u=[s.length/o,o],h=u[1],p=B("bool",c=u[0]),d=0;dp&&(p=g,d=f)}l[c]=d}return s},e.prototype.cumsum=function(t,e,n,i){if(Wu(t,"cumsum"),e!==t.rank-1)throw new Error("backend.cumsum in CPU expects an inner-most axis="+(t.rank-1)+" but got axis="+e);for(var r=It(t.dtype,"int32"),o=bn(t.shape,r),s=this.readSync(o.dataId),a=this.readSync(t.dataId),l=t.shape[t.rank-1],u=i?function(t,e){return t+l-e-1}:function(t,e){return t+e},c=0;ce?1:0})},e.prototype.greaterEqual=function(t,e){return Wu([t,e],"greaterEqual"),this.broadcastedBinaryOp(t,e,"bool",function(t,e){return t>=e?1:0})},e.prototype.logicalNot=function(t){Wu(t,"logicalNot");for(var e=this.readSync(t.dataId),n=new Uint8Array(e.length),i=0;i1||1===e.rank?1:x(e.shape.slice(1)),c=0;c=0&&e>=0?n:(n+e)%e})},e.prototype.max=function(t,e){Wu(t,"max"),en("max",e,t.rank);for(var n=Qe(t.shape,e),i=n[0],r=n[1],o=bn(i,t.dtype),s=x(r),a=this.readSync(o.dataId),l=this.readSync(t.dataId),u=0;uh&&(h=d)}a[u]=h}return o},e.prototype.maximum=function(t,e){return Wu([t,e],"maximum"),this.broadcastedBinaryOp(t,e,t.dtype,function(t,e){return Math.max(t,e)})},e.prototype.all=function(t,e){Wu(t,"all"),en("all",e,t.rank);for(var n=Qe(t.shape,e),i=n[0],r=n[1],o=bn(i,t.dtype),s=x(r),a=this.readSync(o.dataId),l=this.readSync(t.dataId),u=0;u0?n[i]=1:n[i]=0;return this.makeOutput(n,t.shape,"float32")},e.prototype.isNaN=function(t){Wu(t,"x");for(var e=this.readSync(t.dataId),n=new Uint8Array(e.length),i=0;i.5?n[i]=Math.ceil(e[i]):n[i]=r%2==0?r:r+1}return this.makeOutput(n,t.shape,"float32")},e.prototype.exp=function(t){Wu(t,"exp");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),i=0;i=0?r:Math.exp(r)-1}return this.makeOutput(e,t.shape,"float32")},e.prototype.eluDer=function(t,e){Wu([t,e],"eluDer");for(var n=new Float32Array(e.size),i=this.readSync(e.dataId),r=this.readSync(t.dataId),o=0;o=1?r[o]:r[o]*(s+1)}return this.makeOutput(n,e.shape,"float32")},e.prototype.selu=function(t){Wu(t,"selu");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),i=0;i=0?1.0507009873554805*r:1.7580993408473768*(Math.exp(r)-1)}return this.makeOutput(e,t.shape,"float32")},e.prototype.clip=function(t,e,n){Wu(t,"clip");for(var i=new Float32Array(t.size),r=this.readSync(t.dataId),o=0;on?n:s-e,a=i[r]0?1:e}return this.makeOutput(n,t.shape,"float32")},e.prototype.fusedConv2d=function(t){var e=t.input,n=t.filter,i=t.convInfo,r=t.bias,o=t.activation,s=t.preluActivationWeights,a=this.conv2d(e,n,i);return r&&(a=this.add(a,r)),o&&(a=Gu(this,a,o,s)),a},e.prototype.conv2d=function(t,e,n){Wu([t,e],"conv2d");for(var i=n.filterHeight,r=n.filterWidth,o=n.dilationHeight,s=n.dilationWidth,a=n.padInfo.left,l=n.padInfo.top,u="channelsLast"===n.dataFormat,c=Gn(n.outShape,t.dtype),h=t.strides[0],p=u?t.strides[1]:t.strides[2],d=u?t.strides[2]:1,f=u?1:t.strides[1],g=c.strides[0],m=u?c.strides[1]:c.strides[2],v=u?c.strides[2]:1,_=u?1:c.strides[1],y=this.readSync(t.dataId),b=this.readSync(e.dataId),T=c.values,E=0;E=n.inHeight))for(var O=I*e.strides[0],D=C+R*p,A=0;A=n.inWidth))for(var B=D+P*d,F=O+L*e.strides[1],U=0;U=n.inDepth))for(var S=E*e.strides[0],w=v+C*t.strides[1],k=0;k=n.inHeight))for(var D=S+R*e.strides[1],A=w+O*t.strides[2],M=0;M=n.inWidth))for(var F=D+P*e.strides[2],U=A+B*n.inChannels,V=F,H=0;H=n.inHeight))for(var E=b*e.strides[0],C=g+T*t.strides[1],S=0;S=n.inWidth))for(var R=E+x*e.strides[1],O=C+I*n.inChannels,D=w,A=R,M=0;MD?D=B:"avg"===n&&(A+=B,M++)}if(isNaN(D))break}f[k+x*v+T]="avg"===n?A/M:D}return d.toTensor()},e.prototype.maxPool=function(t,e){return this.pool(t,e,"max")},e.prototype.maxPoolPositions=function(t,e){for(var n=Gn(e.outShape,"int32"),i=e.strideHeight,r=e.strideWidth,o=e.dilationHeight,s=e.dilationWidth,a=e.effectiveFilterHeight,l=e.effectiveFilterWidth,u=e.padInfo.top,c=e.padInfo.left,h=this.bufferSync(t),p=0;pE&&(E=I,C=w*l+x)}n.set(C,p,f,_,d)}}return n.toTensor()},e.prototype.maxPoolBackprop=function(t,e,n,i){Wu([e,n],"maxPoolBackprop");for(var r=this.maxPoolPositions(e,i),o=i.strideHeight,s=i.strideWidth,a=i.dilationHeight,l=i.dilationWidth,u=i.effectiveFilterHeight,c=i.effectiveFilterWidth,h=c-1-i.padInfo.left,p=u-1-i.padInfo.top,d=Gn(e.shape,"float32"),f=this.bufferSync(r),g=this.bufferSync(t),m=0;m=i.outHeight||Math.floor(S)!==S))for(var w=0;w=i.outWidth||Math.floor(k)!==k)){var x=u*c-1-f.get(m,S,k,v)===C*c+w?1:0;0!==x&&(E+=g.get(m,S,k,v)*x)}}}d.set(E,m,_,y,v)}return d.toTensor()},e.prototype.avgPoolBackprop=function(t,e,n){Wu([t,e],"avgPoolBackprop");for(var i=n.strideHeight,r=n.strideWidth,o=n.filterHeight,s=n.filterWidth,a=n.dilationHeight,l=n.dilationWidth,u=n.effectiveFilterHeight,c=n.effectiveFilterWidth,h=c-1-n.padInfo.left,p=u-1-n.padInfo.top,d=Gn(e.shape,"float32"),f=1/(o*s),g=this.bufferSync(t),m=0;m=n.outHeight||Math.floor(S)!==S))for(var w=0;w=n.outWidth||Math.floor(k)!==k||(E+=g.get(m,S,k,v))}}d.set(E*f,m,_,y,v)}return d.toTensor()},e.prototype.pool3d=function(t,e,n){Wu(t,"pool3d");for(var i=e.strideDepth,r=e.strideHeight,o=e.strideWidth,s=e.dilationDepth,a=e.dilationHeight,l=e.dilationWidth,u=e.effectiveFilterDepth,c=e.effectiveFilterHeight,h=e.effectiveFilterWidth,p=e.padInfo.front,d=e.padInfo.top,f=e.padInfo.left,g="max"===n?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,m=this.readSync(t.dataId),v=Gn(e.outShape,t.dtype),_=v.values,y=e.outShape[1]*e.outShape[2]*e.outShape[3]*e.outShape[4],b=e.outShape[2]*e.outShape[3]*e.outShape[4],T=e.outShape[3]*e.outShape[4],E=e.outShape[4],C=0;CW?W=J:"avg"===n&&(G+=J,j++),isNaN(W))break}if(isNaN(W))break}if(isNaN(W))break}_[H+k]="avg"===n?G/j:W}}}return v.toTensor()},e.prototype.avgPool3d=function(t,e){return Wu(t,"avgPool3d"),this.pool3d(t,e,"avg").toFloat()},e.prototype.avgPool3dBackprop=function(t,e,n){Wu([t,e],"avgPool3dBackprop");for(var i=n.strideDepth,r=n.strideHeight,o=n.strideWidth,s=n.filterDepth,a=n.filterHeight,l=n.filterWidth,u=n.dilationDepth,c=n.dilationHeight,h=n.dilationWidth,p=n.effectiveFilterDepth,d=n.effectiveFilterHeight,f=n.effectiveFilterWidth,g=p-1-n.padInfo.front,m=f-1-n.padInfo.left,v=d-1-n.padInfo.top,_=Gn(e.shape,"float32"),y=1/(s*a*l),b=this.bufferSync(t),T=0;T=n.outDepth||Math.floor(D)!==D))for(var A=0;A=n.outHeight||Math.floor(M)!==M))for(var N=0;N=n.outWidth||Math.floor(L)!==L||(R+=b.get(T,D,M,L,E))}}}_.set(R*y,T,C,S,w,E)}return _.toTensor()},e.prototype.maxPool3d=function(t,e){return Wu(t,"maxPool3d"),this.pool3d(t,e,"max").toFloat()},e.prototype.maxPool3dPositions=function(t,e){for(var n=Gn(e.outShape,"int32"),i=e.strideDepth,r=e.strideHeight,o=e.strideWidth,s=e.dilationDepth,a=e.dilationHeight,l=e.dilationWidth,u=e.effectiveFilterDepth,c=e.effectiveFilterHeight,h=e.effectiveFilterWidth,p=e.padInfo.front,d=e.padInfo.top,f=e.padInfo.left,g=this.bufferSync(t),m=0;m=O&&(O=F,D=M*c*h+L*c+B)}n.set(D,m,_,E,k,v)}}}return n.toTensor()},e.prototype.maxPool3dBackprop=function(t,e,n,i){Wu([e,n],"maxPool3dBackprop");for(var r=this.maxPool3dPositions(e,i),o=i.strideDepth,s=i.strideHeight,a=i.strideWidth,l=i.dilationDepth,u=i.dilationHeight,c=i.dilationWidth,h=i.effectiveFilterDepth,p=i.effectiveFilterHeight,d=i.effectiveFilterWidth,f=h-1-i.padInfo.front,g=d-1-i.padInfo.left,m=p-1-i.padInfo.top,v=Gn(e.shape,"float32"),_=this.bufferSync(r),y=this.bufferSync(t),b=0;b=i.outDepth||Math.floor(O)!==O))for(var D=0;D=i.outHeight||Math.floor(A)!==A))for(var M=0;M=i.outWidth||Math.floor(N)!==N)){var L=h*p*d-1-_.get(b,O,A,N,T)===R*p*d+D*d+M?1:0;0!==L&&(I+=y.get(b,O,A,N,T)*L)}}}}v.set(I,b,E,C,S,T)}return v.toTensor()},e.prototype.cast=function(t,e){return er(t,e,this)},e.prototype.reshape=function(t,e){return nr(t,e)},e.prototype.avgPool=function(t,e){return Wu(t,"avgPool"),this.pool(t,e,"avg").toFloat()},e.prototype.resizeBilinear=function(t,e,n,i){Wu(t,"resizeBilinear");for(var r=t.shape,o=r[0],s=r[1],a=r[2],l=r[3],u=this.readSync(t.dataId),c=new Float32Array(x([o,e,n,l])),h=[i&&e>1?s-1:s,i&&n>1?a-1:a],p=[i&&e>1?e-1:e,i&&n>1?n-1:n],d=0,f=h[0]/p[0],g=h[1]/p[1],m=0;m1?o-1:o,n&&c>1?s-1:s],d=[n&&u>1?u-1:u,n&&c>1?c-1:c],f=p[0]/d[0],g=p[1]/d[1],m=this.readSync(t.dataId),v=0,_=0;_1?s-1:s,i&&n>1?a-1:a],p=[i&&e>1?e-1:e,i&&n>1?n-1:n],d=h[0]/p[0],f=h[1]/p[1],g=0,m=0;m1?o-1:o,n&&c>1?s-1:s],f=[n&&u>1?u-1:u,n&&c>1?c-1:c],g=d[0]/f[0],m=d[1]/f[1],v=1/g,_=1/m,y=2*Math.ceil(v)+2,b=2*Math.ceil(_)+2,T=0;T=u)){var L=E+N*t.strides[1],P=N*g;if(C===Math.min(o-1,n?Math.round(P):Math.floor(P)))for(var B=0;B=c)){var U=L+F*t.strides[2],V=F*m;x===Math.min(s-1,n?Math.round(V):Math.floor(V))&&(A+=p[U+D])}}}}h[I+D]=A}return _n(h,e.shape,e.dtype)},e.prototype.batchNormalization=function(t,e,n,i,r,o){Wu([t,e,n,r,o],"batchNorm");for(var s=this.readSync(t.dataId),a=this.readSync(e.dataId),l=this.readSync(n.dataId),u=r?this.readSync(r.dataId):new Float32Array([1]),c=o?this.readSync(o.dataId):new Float32Array([0]),h=new Float32Array(s.length),p=c.length,d=u.length,f=l.length,g=a.length,m=0,v=0,_=0,y=0,b=0;b=p&&(m=0),v>=g&&(v=0),_>=d&&(_=0),y>=f&&(y=0);return _n(h,t.shape)},e.prototype.localResponseNormalization4D=function(t,e,n,i,r){Wu(t,"localResponseNormalization4D");var o=t.shape[3],s=o-1,a=this.readSync(t.dataId),l=t.size,u=new Float32Array(l);function c(t){for(var n=t%o,i=t-n+Math.max(0,n-e),r=t-n+Math.min(n+e,s),l=0;i<=r;i++){var u=a[i];l+=u*u}return l}for(var h=0;h=0&&o[s]1,function(){return"blockSize should be > 1 for depthToSpace, but was: "+e});for(var i=t.shape[0],r=t.shape[1],o=t.shape[2],s=t.shape[3],a=r*e,l=o*e,u=s/(e*e),c=this.readSync(t.dataId),h=new Float32Array(i*a*l*u),p=0,d=0;d=a))for(var x=p>1?(S-E)*(l-1)/(p-1):0,I=d>1?(w-C)*(u-1)/(d-1):0,R=0;R1?E*(l-1)+R*x:.5*(E+S)*(l-1);if(O<0||O>l-1)for(var D=0;D1?C*(u-1)+D*I:.5*(C+w)*(u-1))<0||z>u-1)for(A=0;A1?C*(u-1)+D*I:.5*(C+w)*(u-1))<0||z>u-1)for(A=0;A=t.size/a)throw new Error("Invalid indices: "+d+" does not index into "+t.shape);for(var v=0;v=i/r)throw new Error("Invalid indices: "+g+" does not index into "+n);for(var y=0;y0,function(){return"scheme must not be an empty string."});var i=t.getInstance();C(null==i.managers[e],function(){return"A model store manager is already registered for scheme '"+e+"'."}),i.managers[e]=n},t.getManager=function(t){var e=this.getInstance().managers[t];if(null==e)throw new Error("Cannot find model manager for scheme '"+t+"'");return e},t.getSchemes=function(){return Object.keys(this.getInstance().managers)},t}();function pc(t){if(-1===t.indexOf(cc))throw new Error("The url string provided does not contain a scheme. Supported schemes are: "+hc.getSchemes().join(","));return{scheme:t.split(cc)[0],path:t.split(cc)[1]}}function dc(t,e,n){return void 0===n&&(n=!1),a(this,void 0,void 0,function(){var i,r,o,s,a,u,c,h,p;return l(this,function(l){switch(l.label){case 0:return C(t!==e,function(){return"Old path and new path are the same: '"+t+"'"}),C((i=uc.getLoadHandlers(t)).length>0,function(){return"Copying failed because no load handler is found for source URL "+t+"."}),C(i.length<2,function(){return"Copying failed because more than one ("+i.length+") load handlers for source URL "+t+"."}),r=i[0],C((o=uc.getSaveHandlers(e)).length>0,function(){return"Copying failed because no save handler is found for destination URL "+e+"."}),C(o.length<2,function(){return"Copying failed because more than one ("+i.length+") save handlers for destination URL "+e+"."}),s=o[0],a=pc(t).scheme,u=pc(t).path,c=a===pc(t).scheme,[4,r.load()];case 1:return h=l.sent(),n&&c?[4,hc.getManager(a).removeModel(u)]:[3,3];case 2:l.sent(),l.label=3;case 3:return[4,s.save(h)];case 4:return p=l.sent(),!n||c?[3,6]:[4,hc.getManager(a).removeModel(u)];case 5:l.sent(),l.label=6;case 6:return[2,p.modelArtifactsInfo]}})})}var fc="models_store",gc="model_info_store";function mc(){if(!c().getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");var t=window||self,e=t.indexedDB||t.mozIndexedDB||t.webkitIndexedDB||t.msIndexedDB||t.shimIndexedDB;if(null==e)throw new Error("The current browser does not appear to support IndexedDB.");return e}function vc(t){var e=t.result;e.createObjectStore(fc,{keyPath:"modelPath"}),e.createObjectStore(gc,{keyPath:"modelPath"})}var _c=function(){function t(t){if(this.indexedDB=mc(),null==t||!t)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=t}return t.prototype.save=function(t){return a(this,void 0,void 0,function(){return l(this,function(e){if(t.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");return[2,this.databaseAction(this.modelPath,t)]})})},t.prototype.load=function(){return a(this,void 0,void 0,function(){return l(this,function(t){return[2,this.databaseAction(this.modelPath)]})})},t.prototype.databaseAction=function(t,e){var n=this;return new Promise(function(t,i){var r=n.indexedDB.open("tensorflowjs",1);r.onupgradeneeded=function(){return vc(r)},r.onsuccess=function(){var o=r.result;if(null==e){var s=o.transaction(fc,"readonly"),a=s.objectStore(fc).get(n.modelPath);a.onsuccess=function(){if(null==a.result)return o.close(),i(new Error("Cannot find model with path '"+n.modelPath+"' in IndexedDB."));t(a.result.modelArtifacts)},a.onerror=function(t){return o.close(),i(a.error)},s.oncomplete=function(){return o.close()}}else{var l,u=lc(e),c=o.transaction(gc,"readwrite"),h=c.objectStore(gc),p=h.put({modelPath:n.modelPath,modelArtifactsInfo:u});p.onsuccess=function(){var r=(l=o.transaction(fc,"readwrite")).objectStore(fc).put({modelPath:n.modelPath,modelArtifacts:e,modelArtifactsInfo:u});r.onsuccess=function(){return t({modelArtifactsInfo:u})},r.onerror=function(t){var e=(h=c.objectStore(gc)).delete(n.modelPath);e.onsuccess=function(){return o.close(),i(r.error)},e.onerror=function(t){return o.close(),i(r.error)}}},p.onerror=function(t){return o.close(),i(p.error)},c.oncomplete=function(){null==l?o.close():l.oncomplete=function(){return o.close()}}}},r.onerror=function(t){return i(r.error)}})},t.URL_SCHEME="indexeddb://",t}(),yc=function(t){return c().getBool("IS_BROWSER")&&!Array.isArray(t)&&t.startsWith(_c.URL_SCHEME)?(e=t.slice(_c.URL_SCHEME.length),new _c(e)):null;var e};uc.registerSaveRouter(yc),uc.registerLoadRouter(yc);var bc=function(){function t(){this.indexedDB=mc()}return t.prototype.listModels=function(){return a(this,void 0,void 0,function(){var t=this;return l(this,function(e){return[2,new Promise(function(e,n){var i=t.indexedDB.open("tensorflowjs",1);i.onupgradeneeded=function(){return vc(i)},i.onsuccess=function(){var t=i.result,r=t.transaction(gc,"readonly"),o=r.objectStore(gc).getAll();o.onsuccess=function(){for(var t={},n=0,i=o.result;n0,function(){return"promises must be a none empty array"})}(t),function(t,e){C(t>=0&&t<=1,function(){return"Progress fraction must be in range [0, 1], but got startFraction "+t}),C(e>=0&&e<=1,function(){return"Progress fraction must be in range [0, 1], but got endFraction "+e}),C(e>=t,function(){return"startFraction must be no more than endFraction, but got startFraction "+t+" and endFraction "+e})}(n=null==n?0:n,i=null==i?1:i);var r=0;return Promise.all(t.map(function(o){return o.then(function(o){var s=n+ ++r/t.length*(i-n);return e(s),o}),o}))}function Vc(t,e){return a(this,void 0,void 0,function(){var n,i,r,o,s,a,u,h,p;return l(this,function(l){switch(l.label){case 0:return null==e&&(e={}),n=null==e.fetchFunc?c().platform.fetch:e.fetchFunc,i=t.map(function(t){return n(t,e.requestInit,{isBinary:!0})}),r=0,o=.5,null!=e.onProgress?[3,2]:[4,Promise.all(i)];case 1:return s=l.sent(),[3,4];case 2:return[4,Uc(i,e.onProgress,r,o)];case 3:s=l.sent(),l.label=4;case 4:return a=s.map(function(t){return t.arrayBuffer()}),u=.5,h=1,null!=e.onProgress?[3,6]:[4,Promise.all(a)];case 5:return p=l.sent(),[3,8];case 6:return[4,Uc(a,e.onProgress,u,h)];case 7:p=l.sent(),l.label=8;case 8:return[2,p]}})})}function Hc(t){var e=this;return function(n,i,r){return void 0===i&&(i=""),a(e,void 0,void 0,function(){var e,o,s,a,u,c,h,p,d,f;return l(this,function(l){switch(l.label){case 0:if(e=n.map(function(){return!1}),o={},s=null!=r?r.map(function(){return!1}):[],a=[],n.forEach(function(t,n){var i=0;t.weights.forEach(function(t){var l="quantization"in t?t.quantization.dtype:t.dtype,u=ec[l]*x(t.shape),c=function(){e[n]=!0,null==o[n]&&(o[n]=[]),o[n].push({manifestEntry:t,groupOffset:i,sizeBytes:u})};null!=r?r.forEach(function(e,n){e===t.name&&(c(),s[n]=!0)}):c(),a.push(t.name),i+=u})}),!s.every(function(t){return t}))throw u=r.filter(function(t,e){return!s[e]}),new Error("Could not find weights in manifest with names: "+u.join(", ")+". \nManifest JSON has weights with names: "+a.join(", ")+".");return c=e.reduce(function(t,e,n){return e&&t.push(n),t},[]),h=[],c.forEach(function(t){n[t].paths.forEach(function(t){var e=i+(i.endsWith("/")?"":"/")+t;h.push(e)})}),[4,t(h)];case 1:return p=l.sent(),d={},f=0,c.forEach(function(t){for(var e=n[t].paths.length,i=0,r=0;r0,function(){return"URL path for http must not be null, undefined or empty."}),Array.isArray(t)&&C(2===t.length,function(){return"URL paths for http must have a length of 2, (actual length is "+t.length+")."}),this.path=t,null!=e.requestInit&&null!=e.requestInit.body)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=e.requestInit||{}}return t.prototype.save=function(t){return a(this,void 0,void 0,function(){var e,n,i,r;return l(this,function(o){switch(o.label){case 0:if(t.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");return(e=Object.assign({method:this.DEFAULT_METHOD},this.requestInit)).body=new FormData,n=[{paths:["./model.weights.bin"],weights:t.weightSpecs}],i={modelTopology:t.modelTopology,format:t.format,generatedBy:t.generatedBy,convertedBy:t.convertedBy,userDefinedMetadata:t.userDefinedMetadata,weightsManifest:n},e.body.append("model.json",new Blob([JSON.stringify(i)],{type:"application/json"}),"model.json"),null!=t.weightData&&e.body.append("model.weights.bin",new Blob([t.weightData],{type:"application/octet-stream"}),"model.weights.bin"),[4,this.fetch(this.path,e)];case 1:if((r=o.sent()).ok)return[2,{modelArtifactsInfo:lc(t),responses:[r]}];throw new Error("BrowserHTTPRequest.save() failed due to HTTP response status "+r.status+".")}})})},t.prototype.load=function(){return a(this,void 0,void 0,function(){var t,e,n,i,r,o,s,a,u,c,h,p;return l(this,function(l){switch(l.label){case 0:return[4,this.fetch(this.path,this.requestInit)];case 1:if(!(t=l.sent()).ok)throw new Error("Request to "+this.path+" failed with status code "+t.status+". Please verify this URL points to the model JSON of the model to load.");l.label=2;case 2:return l.trys.push([2,4,,5]),[4,t.json()];case 3:return e=l.sent(),[3,5];case 4:throw l.sent(),n="Failed to parse model JSON of response from "+this.path+".",this.path.endsWith(".pb")?n+=" 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.":n+=" Please make sure the server is serving valid JSON for this request.",new Error(n);case 5:if(i=e.modelTopology,r=e.weightsManifest,o=e.generatedBy,s=e.convertedBy,a=e.format,u=e.userDefinedMetadata,null==i&&null==r)throw new Error("The JSON from HTTP path "+this.path+" contains neither model topology or manifest for weights.");return null==r?[3,7]:[4,this.loadWeights(r)];case 6:p=l.sent(),c=p[0],h=p[1],l.label=7;case 7:return[2,{modelTopology:i,weightSpecs:c,weightData:h,userDefinedMetadata:u,generatedBy:o,convertedBy:s,format:a}]}})})},t.prototype.loadWeights=function(t){return a(this,void 0,void 0,function(){var e,n,i,r,o,s,a,u,c,h,p;return l(this,function(l){switch(l.label){case 0:for(e=Array.isArray(this.path)?this.path[1]:this.path,n=function(t){var e=t.lastIndexOf("/"),n=t.lastIndexOf("?");return[t.substring(0,e)+"/",n>e?t.substring(n):""]}(e),i=n[0],r=n[1],o=this.weightPathPrefix||i,s=[],a=0,u=t;a0&&Number.isInteger(n),function(){return"If provided, numClasses must be a positive integer, but got "+n}),C(1===i.rank,function(){return"Expected the rank of labels to be 1, but got "+i.rank}),C(1===r.rank,function(){return"Expected the rank of predictions to be 1, but got "+r.rank}),C(i.shape[0]===r.shape[0],function(){return"Mismatch in the number of examples: "+i.shape[0]+" vs. "+r.shape[0]+". Labels and predictions should have the same number of elements."}),C(n>0&&Number.isInteger(n),function(){return"numClasses is required to be a positive integer, but got "+n});var o=Qn(i.asType("int32"),n),s=Qn(r.asType("int32"),n);return o.transpose().matMul(s).asType("int32")}}),qc=(Object.freeze({confusionMatrix:Jc}),ln({fromPixels_:function(t,e){if(void 0===e&&(e=3),e>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");if(null==t)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");var n=!1,i=!1,r=!1,o=!1,s=!1;if(t.data instanceof Uint8Array)n=!0;else if("undefined"!=typeof ImageData&&t instanceof ImageData)i=!0;else if("undefined"!=typeof HTMLVideoElement&&t instanceof HTMLVideoElement)r=!0;else if("undefined"!=typeof HTMLImageElement&&t instanceof HTMLImageElement)o=!0;else{if(null==t.getContext)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 "+t.constructor.name);s=!0}if(r&&r&&t.readyState<2)throw new Error("The video element has not loaded data yet. Please wait for `loadeddata` event on the