!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t=t||self).faceapi=t.faceapi||{})}(this,function(t){"use strict";var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])})(t,n)};function n(t,n){function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}var r=function(){return(r=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])&&(6===i[0]||2===i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])&&(6===i[0]||2===i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0;)r=Math.random()*e|0,n=t[--e],t[e]=t[r],t[r]=n}function g(t,e,n){return Math.max(t,Math.min(e,n))}function y(t){return t%2==0?t:t+1}function x(t){for(var e=0,n=0;n=n?o():setTimeout(a,s)}};a()})}function T(t,e){for(var n=1,r=-1,o=0;o=0)n*=t[o];else if(-1===t[o]){if(-1!==r)throw Error("Shapes can only have 1 implicit size. Found -1 at dim "+r+" and dim "+o);r=o}else if(t[o]<0)throw Error("Shapes can not be < 0. Found "+t[o]+" at dim "+o);if(-1===r){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 i=t.slice();return i[r]=e/n,i}function D(t,e){var n=e.length;return b((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]),r.push(a)),o[i]<=a&&i++}1!==t[a]&&(n.push(t[a]),r.push(a))}return{newShape:n,keptDims:r}}function M(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 O(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 P(t,e,n){if("float32"===e)for(var r=0;r=0;--r)n[r]=n[r+1]*t[r+1];return n}function Y(t,e,n){if("string"===e)throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(t)&&(t=E(t)),n&&B(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 r=new Uint8Array(t.length),o=0;o=0,function(){return"Tensor must have a shape comprised of positive integers but got shape ["+t+"]."})})}function nt(t,e){return f.platform.fetch(t,e)}var rt=Object.freeze({shuffle:m,clamp:g,nearestLargerEven:y,sum:x,randUniform:function(t,e){var n=Math.random();return e*n+(1-n)*t},distSquared:function(t,e){for(var n=0,r=0;r=this.shape[n]){var a="Requested out of range element at "+t+". Buffer shape="+this.shape;throw new Error(a)}n++}for(var s=t[t.length-1],u=0;u1)for(var c=0;cat){var l=st*s,h=Array.from(e.slice(0,l)),p=Array.from(e.slice(u-st*s,u));return"complex64"===r&&(h=ht(h),p=ht(p)),["["+h.map(function(t,e){return ct(t,i[e],r)}).join(", ")+", ..., "+p.map(function(t,e){return ct(t,i[u-st+e],r)}).join(", ")+"]"]}return["["+("complex64"===r?ht(e):Array.from(e)).map(function(t,e){return ct(t,i[e],r)}).join(", ")+"]"]}var f=n.slice(1),d=o.slice(1),v=o[0]*s,m=[];if(u>at){for(var g=0;g0&&(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 c(this,void 0,void 0,function(){var e,n;return l(this,function(r){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){var r={};t.forEach(function(t,e){r[e]=t});var o={id:this.state.nextTapeNodeId++,name:this.state.activeScope.name,inputs:r,outputs:[e],gradient:function(t){var e=n(t),r={};return e.forEach(function(t,e){r[e]=function(){return t}}),r}};this.state.activeTape.push(o)},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=kt(t),r=new Set(n.map(function(t){return t.id})),o=0;o0,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 i=this.scopedRun(function(){return o.startTape()},function(){return o.endTape()},function(){return o.tidy("forward",t)});b(i instanceof mt,function(){return"The result y returned by f() must be a tensor."});var a=function(t,e,n){for(var r={},o={},i=0;i=0;i--)for(a=(d=t[i]).inputs,l=0;l0)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,r,s={};s[i.id]=null==n?(r=J(_(t=i.shape),"float32"),mt.make(t,{values:r})):n,function(t,e,n){for(var r=function(r){var o=e[r],i=[];if(o.outputs.forEach(function(e){var n=t[e.id];if(null!=n)i.push(n);else{var r=mt.make(e.shape,{values:Z(e.size,e.dtype)},e.dtype);i.push(r)}}),null==o.gradient)throw new Error("Cannot compute gradient: gradient function not found for "+o.name+".");var a=o.gradient(1===o.outputs.length?i[0]:i),s=function(e){if(!(e in a))throw new Error("Cannot backprop through input "+e+". Available gradients found: "+Object.keys(a)+".");var r=n(function(){return a[e]()});if("float32"!==r.dtype)throw new Error("Error in gradient for op "+o.name+". The gradient of input "+e+" must have 'float32' dtype, but has '"+r.dtype+"'");var i=o.inputs[e];if(!I(r.shape,i.shape))throw new Error("Error in gradient for op "+o.name+". The gradient of input '"+e+"' has shape '"+r.shape+"', which does not match the shape of the input '"+i.shape+"'");if(null==t[i.id])t[i.id]=r;else{var s=t[i.id];t[i.id]=s.add(r),s.dispose()}};for(var u in o.inputs)s(u)},o=e.length-1;o>=0;o--)r(o)}(s,a,function(t){return o.tidy(t)});var u=e.map(function(t){return s[t.id]});return 0===o.state.gradientDepth&&(o.state.activeTape.forEach(function(t){for(var e in t.saved)t.saved[e].dispose()}),o.state.activeTape=null),{value:i,grads:u}})},t.prototype.customGrad=function(t){var e=this;return b($(t),function(){return"The f passed in customGrad(f) must be a function."}),function(){for(var n,r=[],o=0;on||e>n)throw r="["+t+"x"+e+"]",new Error("Requested texture size "+r+" greater than WebGL maximum on this browser / GPU ["+n+"x"+n+"].")}function oe(t,e){return de(t,e,function(){return t.createFramebuffer()},"Unable to create WebGLFramebuffer.")}function ie(t,e,n,r,o,i,a,s){var u=t.getAttribLocation(n,r);return-1!==u&&(zt(t,e,function(){return t.bindBuffer(t.ARRAY_BUFFER,o)}),zt(t,e,function(){return t.vertexAttribPointer(u,i,t.FLOAT,!1,a,s)}),zt(t,e,function(){return t.enableVertexAttribArray(u)}),!0)}function ae(t,e,n,r){ve(t,r),zt(t,e,function(){return t.activeTexture(t.TEXTURE0+r)}),zt(t,e,function(){return t.bindTexture(t.TEXTURE_2D,n)})}function se(t,e,n,r){return de(t,e,function(){return t.getUniformLocation(n,r)},'uniform "'+r+'" not present in program.')}function ue(t,e,n){return t.getUniformLocation(e,n)}function ce(t,e,n,r,o,i){zt(t,e,function(){return ae(t,e,r,i)}),zt(t,e,function(){return t.uniform1i(o,i)})}function le(t,e,n,r){zt(t,e,function(){return t.bindFramebuffer(t.FRAMEBUFFER,r)}),zt(t,e,function(){return t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,n,0)})}function he(t,e,n){zt(t,e,function(){return t.bindFramebuffer(t.FRAMEBUFFER,n)}),zt(t,e,function(){return t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,null,0)})}function pe(t){var e=t.checkFramebufferStatus(t.FRAMEBUFFER);if(e!==t.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+fe(t,e))}function fe(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 de(t,e,n,r){var o=zt(t,e,function(){return n()});if(null==o)throw new Error(r);return o}function ve(t,e){var n=t.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,r=e+t.TEXTURE0;if(rn)throw new Error("textureUnit must be in [gl.TEXTURE0, gl.TEXTURE"+n+"].")}function me(t,e){return void 0===e&&(e=2),_(t.slice(0,t.length-e))}function ge(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 ye(t){var e=[1,1,1];return 0===t.length||1===t.length&&1===t[0]||(e=[me(t)].concat(ge(t))),e}function xe(t,e){var n;void 0===e&&(e=!1);var r=f.getNumber("WEBGL_MAX_TEXTURE_SIZE");if(e&&(r*=2,1===(t=t.map(function(e,n){return n>=t.length-2?y(t[n]):t[n]})).length&&(t=[2,t[0]])),2!==t.length){var o=F(t);t=o.newShape}var i=_(t);if(t.length<=1&&i<=r)return[1,i];if(2===t.length&&t[0]<=r&&t[1]<=r)return t;if(3===t.length&&t[0]*t[1]<=r&&t[2]<=r)return[t[0]*t[1],t[2]];if(3===t.length&&t[0]<=r&&t[1]*t[2]<=r)return[t[0],t[1]*t[2]];if(4===t.length&&t[0]*t[1]*t[2]<=r&&t[3]<=r)return[t[0]*t[1]*t[2],t[3]];if(4===t.length&&t[0]<=r&&t[1]*t[2]*t[3]<=r)return[t[0],t[1]*t[2]*t[3]];if(e){var a=me(t),s=2,u=2;return t.length&&(s=(n=ge(t))[0],u=n[1]),N(i=a*(s/2)*(u/2)).map(function(t){return 2*t})}return N(i)}function be(t){return t%2==0}function we(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],r=e.slice(-1)[0];if(n===r)return!0;if(be(n)&&be(r)&&(1===t[0]||1===e[0]))return!0}return t[1]===e[1]&&be(t[0])&&be(e[0])}function Ce(t){if(null==Kt){var e=Wt(t);Kt=e.getParameter(e.MAX_TEXTURE_SIZE)}return Kt}function Ee(t){if(null==Xt){var e=Wt(t);Xt=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,Xt)}function _e(t){if(0===t)return 0;var e=Wt(t);return Ie(e,"EXT_disjoint_timer_query_webgl2")&&2===t?2:Ie(e,"EXT_disjoint_timer_query")?1:0}function Ie(t,e){return null!=t.getExtension(e)}function Se(t){try{if(null!=Wt(t))return!0}catch(t){return!1}return!1}function Re(t){if(0===t)return!1;var e=Wt(t);if(1===t){if(!Ie(e,"OES_texture_float"))return!1}else if(!Ie(e,"EXT_color_buffer_float"))return!1;return ke(e,t)}function Ne(t){if(0===t)return!1;var e=Wt(t);if(1===t){if(!Ie(e,"OES_texture_float"))return!1;if(!Ie(e,"WEBGL_color_buffer_float"))return!1}else if(!Ie(e,"EXT_color_buffer_float"))return!1;return ke(e,t)}function ke(t,e){var n=t.createFramebuffer(),r=t.createTexture();t.bindTexture(t.TEXTURE_2D,r);var o=2===e?t.RGBA32F:t.RGBA;t.texImage2D(t.TEXTURE_2D,0,o,1,1,0,t.RGBA,t.FLOAT,null),t.bindFramebuffer(t.FRAMEBUFFER,n),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,r,0);var i=t.checkFramebufferStatus(t.FRAMEBUFFER)===t.FRAMEBUFFER_COMPLETE;return t.bindTexture(t.TEXTURE_2D,null),t.bindFramebuffer(t.FRAMEBUFFER,null),t.deleteTexture(r),t.deleteFramebuffer(n),i}function Ae(t){return 2===t&&null!=Wt(t).fenceSync}var Te=Object.freeze({callAndCheck:zt,canBeRepresented:Gt,getWebGLErrorMessage:jt,getExtensionOrThrow:Ht,createVertexShader:qt,createFragmentShader:$t,createProgram:Qt,linkProgram:Jt,validateProgram:Zt,createStaticVertexBuffer:te,createStaticIndexBuffer:ee,getNumChannels:function(){return 2===f.getNumber("WEBGL_VERSION")?1:4},createTexture:ne,validateTextureSize:re,createFramebuffer:oe,bindVertexBufferToProgramAttribute:ie,bindTextureUnit:ae,unbindTextureUnit:function(t,e,n){ve(t,n),zt(t,e,function(){return t.activeTexture(t.TEXTURE0+n)}),zt(t,e,function(){return t.bindTexture(t.TEXTURE_2D,null)})},getProgramUniformLocationOrThrow:se,getProgramUniformLocation:ue,bindTextureToProgramUniformSampler:ce,bindCanvasToFramebuffer:function(t,e){zt(t,e,function(){return t.bindFramebuffer(t.FRAMEBUFFER,null)}),zt(t,e,function(){return t.viewport(0,0,t.canvas.width,t.canvas.height)}),zt(t,e,function(){return t.scissor(0,0,t.canvas.width,t.canvas.height)})},bindColorTextureToFramebuffer:le,unbindColorTextureFromFramebuffer:he,validateFramebuffer:pe,getFramebufferErrorMessage:fe,getBatchDim:me,getRowsCols:ge,getShapeAs3D:ye,getTextureShapeFromLogicalShape:xe,isReshapeFree:we,get MAX_TEXTURE_SIZE(){return Kt},get MAX_TEXTURES_IN_SHADER(){return Xt},getWebGLMaxTextureSize:Ce,getMaxTexturesInShader:Ee,getWebGLDisjointQueryTimerVersion:_e,isWebGLVersionEnabled:Se,isRenderToFloatTextureEnabled:Re,isDownloadFloatTextureEnabled:Ne,isWebGLFenceEnabled:Ae});function De(t){f.getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(t+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}function Fe(t,e){return Mt.tidy(t,e)}function Me(t){kt(t).forEach(function(t){return t.dispose()})}function Oe(t){return Mt.keep(t)}function Pe(){for(var t=[],e=0;e0,function(){return"Element arr["+r.join("][")+"] should be a primitive, but is an array of "+e.length+" elements"}),b(e.length===n[0],function(){return"Element arr["+r.join("][")+"] should have "+n[0]+" elements, but has "+e.length+" elements"});for(var o=n.slice(1),i=0;i=0&&(o=r),Le(r,o,e,n),null==t||!z(t)&&!Array.isArray(t)&&"number"!=typeof t&&"boolean"!=typeof t&&"string"!=typeof t){var i=null==t?"null":t.constructor.name;throw new Error("Argument '"+e+"' passed to '"+n+"' must be a Tensor or TensorLike, but got '"+i+"'")}var a=Be(t);z(t)||Array.isArray(t)||(t=[t]);var s="string"!==o?Y(t,o,f.getBool("DEBUG")):E(t);return mt.make(a,{values:s},o)}function ze(t,e,n,r){if(void 0===r&&(r="numeric"),!Array.isArray(t))throw new Error("Argument "+e+" passed to "+n+" must be a `Tensor[]` or `TensorLike[]`");return t.map(function(t,r){return We(t,e+"["+r+"]",n)},r)}function Ue(t,e){for(var n=0;n=0&&e0}),f.registerFlag("WEBGL_VERSION",function(){return Se(2)?2:Se(1)?1:0}),f.registerFlag("WEBGL_BUFFER_SUPPORTED",function(){return 2===f.get("WEBGL_VERSION")}),f.registerFlag("WEBGL_CPU_FORWARD",function(){return!0}),f.registerFlag("WEBGL_PACK",function(){return f.getBool("HAS_WEBGL")}),f.registerFlag("WEBGL_PACK_NORMALIZATION",function(){return f.getBool("WEBGL_PACK")}),f.registerFlag("WEBGL_PACK_CLIP",function(){return f.getBool("WEBGL_PACK")}),f.registerFlag("WEBGL_PACK_DEPTHWISECONV",function(){return!1}),f.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",function(){return f.getBool("WEBGL_PACK")}),f.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",function(){return f.getBool("WEBGL_PACK")}),f.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",function(){return f.getBool("WEBGL_PACK")}),f.registerFlag("WEBGL_PACK_REDUCE",function(){return f.getBool("WEBGL_PACK")}),f.registerFlag("WEBGL_LAZILY_UNPACK",function(){return f.getBool("WEBGL_PACK")}),f.registerFlag("WEBGL_CONV_IM2COL",function(){return f.getBool("WEBGL_PACK")}),f.registerFlag("WEBGL_MAX_TEXTURE_SIZE",function(){return Ce(f.getNumber("WEBGL_VERSION"))}),f.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",function(){return Ee(f.getNumber("WEBGL_VERSION"))}),f.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",function(){var t=f.getNumber("WEBGL_VERSION");return 0===t?0:_e(t)}),f.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",function(){return f.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}),f.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",function(){return Re(f.getNumber("WEBGL_VERSION"))}),f.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",function(){return Ne(f.getNumber("WEBGL_VERSION"))}),f.registerFlag("WEBGL_FENCE_API_ENABLED",function(){return Ae(f.getNumber("WEBGL_VERSION"))}),f.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",function(){return f.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0}),vt=De;var Je=Qe({complex_:function(t,e){var n=We(t,"real","complex"),r=We(e,"imag","complex");return w(n.shape,r.shape,"real and imag shapes, "+n.shape+" and "+r.shape+", must match in call to tf.complex()."),Mt.runKernel(function(t){return t.complex(n,r)},{$real:n,$imag:r})}}),Ze=Qe({real_:function(t){var e=We(t,"input","real");return Mt.runKernel(function(t){return t.real(e)},{$input:e})}}),tn=Qe({imag_:function(t){var e=We(t,"input","imag");return Mt.runKernel(function(t){return t.imag(e)},{$input:e})}});function en(t,e,n){return nn(t,e,Be(t),n)}function nn(t,e,n,r){if(null==r&&(r=q(t)),"complex64"===r)throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!z(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){et(e);var o=_(e),i=_(n);b(o===i,function(){return"Based on the provided shape, ["+e+"], the tensor should have "+o+" values but has "+i});for(var a=0;a1)return pn([0],r);var o=Z(Math.abs(Math.ceil((e-t)/n)),r);e=1,function(){return"Pass at least one tensor to concat"});var n=ze(t,"tensors","concat");e=D(e,n[0].shape)[0];var r=Ye(n.map(function(t){return t.shape}),e);if(0===_(r))return en([],r);if(1===(n=n.filter(function(t){return t.size>0})).length)return n[0];var o=n.map(function(t){return t.shape});Xe(o,e);var i=n;return Mt.runKernel(function(t){return t.concat(n,e)},i,function(t){var n=o.map(function(t){return t[e]});return En(t,n,e).map(function(t){return function(){return t}})})}}),xn=Qe({concat1d_:function(t){return yn(t,0)}}),bn=Qe({concat2d_:function(t,e){return yn(t,e)}}),wn=Qe({concat3d_:function(t,e){return yn(t,e)}}),Cn=Qe({concat4d_:function(t,e){return yn(t,e)}}),En=Qe({split_:function(t,e,n){void 0===n&&(n=0);var r,o=We(t,"x","split");return n=D(n,o.shape)[0],"number"==typeof e?(b(o.shape[n]%e==0,function(){return"Number of splits must evenly divide the axis."}),r=new Array(e).fill(o.shape[n]/e)):(b(o.shape[n]===e.reduce(function(t,e){return t+e}),function(){return"The sum of sizes must match the size of the axis dimension."}),r=e),Mt.runKernel(function(t){return t.split(o,r,n)},{$x:o},function(t){return{$x:function(){return yn(t,n)}}})}});function _n(t,e){return t(e={exports:{}},e.exports),e.exports}var In=_n(function(t){!function(t,e,n){function r(t){var e,n=this,r=(e=4022871197,function(t){t=t.toString();for(var n=0;n>>0,e=(r*=e)>>>0,e+=4294967296*(r-=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=r(" "),n.s1=r(" "),n.s2=r(" "),n.s0-=r(t),n.s0<0&&(n.s0+=1),n.s1-=r(t),n.s1<0&&(n.s1+=1),n.s2-=r(t),n.s2<0&&(n.s2+=1),r=null}function o(t,e){return e.c=t.c,e.s0=t.s0,e.s1=t.s1,e.s2=t.s2,e}function i(t,e){var n=new r(t),i=e&&e.state,a=n.next;return a.int32=function(){return 4294967296*n.next()|0},a.double=function(){return a()+11102230246251565e-32*(2097152*a()|0)},a.quick=a,i&&("object"==typeof i&&o(i,n),a.state=function(){return o(n,{})}),a}e&&e.exports?e.exports=i:this.alea=i}(0,t)}),Sn=_n(function(t){!function(t,e,n){function r(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 r=0;r>>0)/4294967296};return a.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},a.int32=n.next,a.quick=a,i&&("object"==typeof i&&o(i,n),a.state=function(){return o(n,{})}),a}e&&e.exports?e.exports=i:this.xor128=i}(0,t)}),Rn=_n(function(t){!function(t,e,n){function r(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 r=0;r>>4),e.next()}function o(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 i(t,e){var n=new r(t),i=e&&e.state,a=function(){return(n.next()>>>0)/4294967296};return a.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},a.int32=n.next,a.quick=a,i&&("object"==typeof i&&o(i,n),a.state=function(){return o(n,{})}),a}e&&e.exports?e.exports=i:this.xorwow=i}(0,t)}),Nn=_n(function(t){!function(t,e,n){function r(t){var e=this;e.next=function(){var t,n,r=e.x,o=e.i;return t=r[o],n=(t^=t>>>7)^t<<24,n^=(t=r[o+1&7])^t>>>10,n^=(t=r[o+3&7])^t>>>3,n^=(t=r[o+4&7])^t<<7,t=r[o+7&7],n^=(t^=t<<13)^t<<9,r[o]=n,e.i=o+1&7,n},function(t,e){var n,r=[];if(e===(0|e))r[0]=e;else for(e=""+e,n=0;n0;--n)t.next()}(e,t)}function o(t,e){return e.x=t.x.slice(),e.i=t.i,e}function i(t,e){null==t&&(t=+new Date);var n=new r(t),i=e&&e.state,a=function(){return(n.next()>>>0)/4294967296};return a.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},a.int32=n.next,a.quick=a,i&&(i.x&&o(i,n),a.state=function(){return o(n,{})}),a}e&&e.exports?e.exports=i:this.xorshift7=i}(0,t)}),kn=_n(function(t){!function(t,e,n){function r(t){var e=this;e.next=function(){var t,n,r=e.w,o=e.X,i=e.i;return e.w=r=r+1640531527|0,n=o[i+34&127],t=o[i=i+1&127],n^=n<<13,t^=t<<17,n^=n>>>15,t^=t>>>12,n=o[i]=n^t,e.i=i,n+(r^r>>>16)|0},function(t,e){var n,r,o,i,a,s=[],u=128;for(e===(0|e)?(r=e,e=null):(e+="\0",r=0,u=Math.max(u,e.length)),o=0,i=-32;i>>15,r^=r<<4,r^=r>>>13,i>=0&&(a=a+1640531527|0,o=0==(n=s[127&i]^=r+a)?o+1:0);for(o>=128&&(s[127&(e&&e.length||0)]=-1),o=127,i=512;i>0;--i)r=s[o+34&127],n=s[o=o+1&127],r^=r<<13,n^=n<<17,r^=r>>>15,n^=n>>>12,s[o]=r^n;t.w=a,t.X=s,t.i=o}(e,t)}function o(t,e){return e.i=t.i,e.w=t.w,e.X=t.X.slice(),e}function i(t,e){null==t&&(t=+new Date);var n=new r(t),i=e&&e.state,a=function(){return(n.next()>>>0)/4294967296};return a.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},a.int32=n.next,a.quick=a,i&&(i.X&&o(i,n),a.state=function(){return o(n,{})}),a}e&&e.exports?e.exports=i:this.xor4096=i}(0,t)}),An=_n(function(t){!function(t,e,n){function r(t){var e=this,n="";e.next=function(){var t=e.b,n=e.c,r=e.d,o=e.a;return t=t<<25^t>>>7^n,n=n-r|0,r=r<<24^r>>>8^o,o=o-t|0,e.b=t=t<<20^t>>>12^n,e.c=n=n-r|0,e.d=r<<16^n>>>16^o,e.a=o-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 r=0;r>>0)/4294967296};return a.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},a.int32=n.next,a.quick=a,i&&("object"==typeof i&&o(i,n),a.state=function(){return o(n,{})}),a}e&&e.exports?e.exports=i:this.tychei=i}(0,t)}),Tn=_n(function(t){!function(e,n){var r,o=this,i=256,a=6,s="random",u=n.pow(i,a),c=n.pow(2,52),l=2*c,h=i-1;function p(t,h,p){var g=[],y=v(function t(e,n){var r,o=[],i=typeof e;if(n&&"object"==i)for(r in e)try{o.push(t(e[r],n-1))}catch(t){}return o.length?o:"string"==i?e:e+"\0"}((h=1==h?{entropy:!0}:h||{}).entropy?[t,m(e)]:null==t?function(){try{var t;return r&&(t=r.randomBytes)?t=t(i):(t=new Uint8Array(i),(o.crypto||o.msCrypto).getRandomValues(t)),m(t)}catch(t){var n=o.navigator,a=n&&n.plugins;return[+new Date,o,a,o.screen,m(e)]}}():t,3),g),x=new f(g),b=function(){for(var t=x.g(a),e=u,n=0;t=l;)t/=2,e/=2,n>>>=1;return(t+n)/e};return b.int32=function(){return 0|x.g(4)},b.quick=function(){return x.g(4)/4294967296},b.double=b,v(m(x.S),e),(h.pass||p||function(t,e,r,o){return o&&(o.S&&d(o,x),t.state=function(){return d(x,{})}),r?(n[s]=t,e):t})(b,y,"global"in h?h.global:this==n,h.state)}function f(t){var e,n=t.length,r=this,o=0,a=r.i=r.j=0,s=r.S=[];for(n||(t=[n++]);o=1||0===a);var s=Math.sqrt(-2*Math.log(a)/a);e=this.mean+this.stdDev*o*s,n=this.mean+this.stdDev*i*s,this.truncated&&!this.isValidTruncated(e)||(r=!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}(),Mn=function(){function t(t,e,n,r){void 0===t&&(t=0),void 0===e&&(e=1);var o=this;if(this.canReturnFloat=function(){return null==o.dtype||"float32"===o.dtype},this.min=t,this.range=e-t,this.dtype=n,null==r&&(r=Math.random()),"number"==typeof r&&(r=r.toString()),!this.canReturnFloat()&&this.range<=1)throw new Error("The difference between "+t+" - "+e+" <= 1 and dtype is not float");this.random=Dn(r)}return t.prototype.convertValue=function(t){return this.canReturnFloat()?t:Math.round(t)},t.prototype.nextValue=function(){return this.convertValue(this.min+this.range*this.random())},t}();function On(t,e,n){return void 0===e&&(e="float32"),e=e||"float32",et(t),new pt(t,e,n)}function Pn(t,e){void 0===e&&(e=!1),console.log(t.toString(e))}var Bn=Qe({batchToSpaceND_:function(t,e,n){var r=We(t,"x","batchToSpaceND"),o=e.reduce(function(t,e){return t*e});return b(r.rank>=1+e.length,function(){return"input rank is "+r.rank+" but should be > than blockShape.length "+e.length}),b(n.length===e.length,function(){return"crops.length is "+n.length+" but should be equal to blockShape.length "+e.length}),b(r.shape[0]%o==0,function(){return"input tensor batch is "+r.shape[0]+" but is not divisible by the product of the elements of blockShape "+e.join(" * ")+" === "+o}),Mt.runKernel(function(t){return t.batchToSpaceND(r,e,n)},{$x:r},function(t){return{$x:function(){return t.spaceToBatchND(e,n)}}})}}),Ln=Qe({cast_:function(t,e){var n=We(t,"x","cast");if(!L(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");return Mt.runKernel(function(t){return t.cast(n,e)},{$x:n},function(t){return{$x:function(){return t.clone()}}})}}),Wn=Qe({clone_:function(t){var e=We(t,"x","clone",null);return Mt.runKernel(function(t){return mt.make(e.shape,{dataId:e.dataId},e.dtype)},{$x:e},function(t){return{$x:function(){return t.toFloat()}}})}}),zn=Qe({cumsum_:function(t,e,n,r){void 0===e&&(e=0),void 0===n&&(n=!1),void 0===r&&(r=!1);var o=We(t,"x","cumsum"),i=qe([e|=0],o.rank),a=o;null!=i&&(a=o.transpose(i));var s=Ke(1,o.rank)[0],u=Mt.runKernel(function(t){return t.cumsum(a,s,n,r)},{permutedX:a},function(t){return{permutedX:function(){return t.cumsum(e,n,!r)}}});return null!=i&&(u=u.transpose(i)),u}}),Un=Qe({depthToSpace_:function(t,e,n){void 0===n&&(n="NHWC");var r=We(t,"x","depthToSpace"),o="NHWC"===n?r.shape[1]:r.shape[2],i="NHWC"===n?r.shape[2]:r.shape[3],a="NHWC"===n?r.shape[3]:r.shape[1];return b(o*e>=0,function(){return"Negative dimension size caused by overflow when multiplying\n "+o+" and "+e+" for depthToSpace with input shape\n "+r.shape}),b(i*e>=0,function(){return"Negative dimension size caused by overflow when multiplying\n "+i+" and "+e+" for depthToSpace with input shape\n "+r.shape}),b(a%(e*e)==0,function(){return"Dimension size must be evenly divisible by "+e*e+" but is "+a+" for depthToSpace with input shape "+r.shape}),Mt.runKernel(function(t){return t.depthToSpace(r,e,n)},{$x:r})}}),Vn=Qe({expandDims_:function(t,e){void 0===e&&(e=0);var n=We(t,"x","expandDims",null);b(e<=n.rank,function(){return"Axis must be <= rank of the tensor"});var r=n.shape.slice();return e<0&&(b(-(n.rank+1)<=e,function(){return"Axis must be in the interval ["+-(n.rank+1)+", "+n.rank+"]"}),e=n.rank+e+1),r.splice(e,0,1),tr(n,r)}}),Gn=Qe({eye_:function(t,e,n,r){void 0===r&&(r="float32"),null==e&&(e=t);for(var o=On([t,e],r),i=t<=e?t:e,a=0;a2)throw new Error("Rank of probabilities must be 1 or 2, but is "+a);n=n||Math.random();var s=1===a?o.as2D(1,-1):o,u=Mt.runKernel(function(t){return t.multinomial(s,r,e,n)},{logits2D:s});return 1===a?u.as1D():u}}),Hn=Qe({oneHot_:function(t,e,n,r){if(void 0===n&&(n=1),void 0===r&&(r=0),e<2)throw new Error("Error in oneHot: depth must be >=2, but it is "+e);var o=We(t,"indices","oneHot","int32"),i=o.shape.concat([e]);return o=o.flatten(),Mt.runKernel(function(t){return t.oneHot(o,e,n,r)},{$indices:o},function(t){return{$indices:function(){return pn(o.shape,"float32")}}}).reshape(i)}}),qn=Qe({pad_:function(t,e,n){void 0===n&&(n=0);var r=We(t,"x","pad");if(0===r.rank)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");var o=e.map(function(t){return t[0]});return Mt.runKernel(function(t){return t.pad(r,e,n)},{$x:r},function(t){return{$x:function(){return t.slice(o,r.shape)}}})}}),$n=Qe({pad1d_:function(t,e,n){return void 0===n&&(n=0),b(2===e.length,function(){return"Invalid number of paddings. Must be length of 2."}),qn(t,[e],n)}}),Kn=Qe({pad2d_:function(t,e,n){return void 0===n&&(n=0),b(2===e.length&&2===e[0].length&&2===e[1].length,function(){return"Invalid number of paddings. Must be length of 2 each."}),qn(t,e,n)}}),Xn=Qe({pad3d_:function(t,e,n){return void 0===n&&(n=0),b(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."}),qn(t,e,n)}}),Yn=Qe({pad4d_:function(t,e,n){return void 0===n&&(n=0),b(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."}),qn(t,e,n)}}),Qn=Qe({rand_:function(t,e,n){var r=_(t),o=null;if(null==n||"float32"===n)o=new Float32Array(r);else if("int32"===n)o=new Int32Array(r);else{if("bool"!==n)throw new Error("Unknown data type "+n);o=new Uint8Array(r)}for(var i=0;i=1+e.length,function(){return"input rank "+r.rank+" should be > than [blockShape] "+e.length}),b(n.length===e.length,function(){return"paddings.shape[0] "+n.length+" must be equal to [blockShape] "+e.length}),b(r.shape.reduce(function(t,r,o){return o>0&&o<=e.length?t&&(r+n[o-1][0]+n[o-1][1])%e[o-1]==0:t},!0),function(){return"input spatial dimensions "+r.shape.slice(1)+" with paddings "+n.toString()+" must be divisible by blockShapes "+e.toString()}),Mt.runKernel(function(t){return t.spaceToBatchND(r,e,n)},{$x:r},function(t){return{$x:function(){return t.batchToSpaceND(e,n)}}})}}),nr=Qe({squeeze_:function(t,e){var n=We(t,"x","squeeze");return tr(n,F(n.shape,e).newShape)}}),rr=Qe({stack_:function(t,e){void 0===e&&(e=0);var n=ze(t,"tensors","stack");if(b(n.length>=1,function(){return"Pass at least one tensor to tf.stack"}),1===n.length)return n[0].expandDims(e);var r=n[0].rank,o=n[0].shape,i=n[0].dtype;b(e<=r,function(){return"Axis must be <= rank of the tensor"}),n.forEach(function(t){w(o,t.shape,"All tensors passed to stack must have matching shapes")}),n.forEach(function(t){b(i===t.dtype,function(){return"All tensors passed to stack must have matching dtypes"})});var a=n.map(function(t){return t.expandDims(e)});return yn(a,e)}}),or=Qe({tile_:function(t,e){var n=We(t,"x","tile",null);return b(n.rank===e.length,function(){return"Error in transpose: rank of input "+n.rank+" must match length of reps "+e+"."}),Mt.runKernel(function(t,r){var o=t.tile(n,e);return r([n]),o},{$x:n},function(t,n){var r=n[0];return{$x:function(){var n=gn(r);if(1===r.rank)for(var o=0;o=-n.shape.length&&e=2*e+1||o%2==1?a.push(o):i.push(o);r.push.apply(r,i),r.push(0),r.push.apply(r,a)}return r}function lr(t,e,n,r){void 0===r&&(r=!0);var o=[];r?o.push(t[0]/n):o.push(t[0]*n);for(var i=1;it.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,r=n[n.length-1],o=1,i=0;i1?e.shape[e.rank-1]:1,o=n.length,i=1,a=r;a0?i>=l[e]:i<=l[e]);i+=o)n+=1;return n}),[c,f,h]}function yr(t,e,n,r,o){var i=e[o],a=n[o]||1;(t&1<0?Number.MIN_SAFE_INTEGER:Number.MAX_SAFE_INTEGER);var s=r[o];return i<0&&(i+=s),g(0,i,s-1)}function xr(t,e,n,r,o){var i=e[o],a=n[o]||1;(t&1<0?Number.MAX_SAFE_INTEGER:Number.MIN_SAFE_INTEGER);var s=r[o];return i<0&&(i+=s),a>0?g(0,i,s):g(-1,i,s-1)}function br(t,e,n){for(var r=n.length,o=0;o1){r=o;break}for(o=r+1;o0||n[o]!==t[o])return!1;return!0}function wr(t,e){for(var n=t.length>0?t[t.length-1]:1,r=0;r0,function(){return"variableGrads() expects at least one of the input variables to be trainable, but none of the "+i+" variables is trainable."});var a=Mt.gradients(t,e,null,!0),s=a.value,u=a.grads;b(u.some(function(t){return null!=t}),function(){return"Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize()."}),b(0===s.rank,function(){return"The f passed in variableGrads(f) must return a scalar, but it returned a rank-"+s.rank+" tensor"});var c={};return e.forEach(function(t,e){null!=u[e]&&(c[t.name]=u[e])}),null!=o&&o.forEach(function(t){return c[t.name]=null}),{value:s,grads:c}}function Er(t){return Mt.customGrad(t)}function _r(t){if(t.filter(function(t){return null==t}).length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that\n the f you passed encloses all operations that lead from x to y.")}var Ir=Qe({softmax_:function(t,e){void 0===e&&(e=-1);var n=We(t,"logits","softmax");if(-1===e&&(e=n.rank-1),e!==n.rank-1)throw Error("Softmax along a non-last dimension is not yet supported. Logits was rank "+n.rank+" and dim was "+e);return Er(function(t,n){var r=t.logSumExp([e],!0),o=t.toFloat().sub(r).exp();return n([o]),{value:o,gradFunc:function(t,n){var r=n[0],o=t.mul(r);return o.sub(o.sum([e],!0).mul(r))}}})(n)}}),Sr=Qe({logSoftmax_:function(t,e){void 0===e&&(e=-1);var n=We(t,"logits","logSoftmax");if(-1===e&&(e=n.rank-1),e!==n.rank-1)throw Error("Log Softmax along a non-last dimension is not yet supported. Logits was rank "+n.rank+" and axis was "+e);return Er(function(t,n){var r=t.max(e,!0),o=t.sub(r),i=o.toFloat().sub(o.exp().sum(e,!0).log());return n([i]),{value:i,gradFunc:function(t,n){var r=n[0].exp();return t.sub(t.sum(e,!0).mul(r))}}})(n)}}),Rr=function(){function t(t,e){this.backend=t,this.dataMover=e,this.data=new WeakMap}return t.prototype.get=function(t){return this.data.has(t)||this.dataMover.moveData(this.backend,t),this.data.get(t)},t.prototype.set=function(t,e){this.data.set(t,e)},t.prototype.has=function(t){return this.data.has(t)},t.prototype.delete=function(t){return this.data.delete(t)},t}(),Nr=function(){function t(){}return t.prototype.time=function(t){throw new Error("Not yet implemented.")},t.prototype.read=function(t){throw new Error("Not yet implemented.")},t.prototype.readSync=function(t){throw new Error("Not yet implemented.")},t.prototype.disposeData=function(t){throw new Error("Not yet implemented.")},t.prototype.write=function(t,e){throw new Error("Not yet implemented.")},t.prototype.fromPixels=function(t,e){throw new Error("Not yet implemented.")},t.prototype.register=function(t,e,n){throw new Error("Not yet implemented.")},t.prototype.memory=function(){throw new Error("Not yet implemented.")},t.prototype.floatPrecision=function(){throw new Error("Not yet implemented")},t.prototype.epsilon=function(){return 32===this.floatPrecision()?1e-7:1e-4},t.prototype.batchMatMul=function(t,e,n,r){throw new Error("Not yet implemented")},t.prototype.fusedBatchMatMul=function(t,e,n,r,o,i){throw new Error("Not yet implemented")},t.prototype.slice=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.stridedSlice=function(t,e,n,r,o,i,a,s,u){throw new Error("Not yet implemented")},t.prototype.unstack=function(t,e){throw new Error("Not yet implemented")},t.prototype.reverse=function(t,e){throw new Error("Not yet implemented")},t.prototype.concat=function(t,e){throw new Error("Not yet implemented")},t.prototype.neg=function(t){throw new Error("Not yet implemented")},t.prototype.add=function(t,e){throw new Error("Not yet implemented")},t.prototype.addN=function(t){throw new Error("Not yet implemented")},t.prototype.subtract=function(t,e){throw new Error("Not yet implemented")},t.prototype.multiply=function(t,e){throw new Error("Not yet implemented")},t.prototype.realDivide=function(t,e){throw new Error("Not yet implemented")},t.prototype.floorDiv=function(t,e){throw new Error("Not yet implemented")},t.prototype.sum=function(t,e){throw new Error("Not yet implemented")},t.prototype.prod=function(t,e){throw new Error("Not yet implemented")},t.prototype.unsortedSegmentSum=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.argMin=function(t,e){throw new Error("Not yet implemented")},t.prototype.argMax=function(t,e){throw new Error("Not yet implemented")},t.prototype.equal=function(t,e){throw new Error("Not yet implemented")},t.prototype.notEqual=function(t,e){throw new Error("Not yet implemented")},t.prototype.less=function(t,e){throw new Error("Not yet implemented")},t.prototype.lessEqual=function(t,e){throw new Error("Not yet implemented")},t.prototype.greater=function(t,e){throw new Error("Not yet implemented")},t.prototype.greaterEqual=function(t,e){throw new Error("Not yet implemented")},t.prototype.logicalNot=function(t){throw new Error("Not yet implemented")},t.prototype.logicalAnd=function(t,e){throw new Error("Not yet implemented")},t.prototype.logicalOr=function(t,e){throw new Error("Not yet implemented")},t.prototype.where=function(t){throw new Error("Not yet implemented")},t.prototype.select=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.topk=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.min=function(t,e){throw new Error("Not yet implemented")},t.prototype.minimum=function(t,e){throw new Error("Not yet implemented")},t.prototype.mod=function(t,e){throw new Error("Not yet implemented")},t.prototype.max=function(t,e){throw new Error("Not yet implemented")},t.prototype.maximum=function(t,e){throw new Error("Not yet implemented")},t.prototype.all=function(t,e){throw new Error("Not yet implemented")},t.prototype.any=function(t,e){throw new Error("Not yet implemented")},t.prototype.squaredDifference=function(t,e){throw new Error("Not yet implemented")},t.prototype.ceil=function(t){throw new Error("Not yet implemented")},t.prototype.floor=function(t){throw new Error("Not yet implemented")},t.prototype.round=function(t){throw new Error("Not yet implemented")},t.prototype.sign=function(t){throw new Error("Not yet implemented")},t.prototype.isNaN=function(t){throw new Error("Not yet implemented")},t.prototype.isInf=function(t){throw new Error("Not yet implemented")},t.prototype.isFinite=function(t){throw new Error("Not yet implemented")},t.prototype.pow=function(t,e){throw new Error("Not yet implemented")},t.prototype.exp=function(t){throw new Error("Not yet implemented")},t.prototype.expm1=function(t){throw new Error("Not yet implemented")},t.prototype.log=function(t){throw new Error("Not yet implemented")},t.prototype.log1p=function(t){throw new Error("Not yet implemented")},t.prototype.sqrt=function(t){throw new Error("Not yet implemented")},t.prototype.rsqrt=function(t){throw new Error("Not yet implemented")},t.prototype.square=function(t){throw new Error("Not yet implemented")},t.prototype.reciprocal=function(t){throw new Error("Not yet implemented")},t.prototype.relu=function(t){throw new Error("Not yet implemented")},t.prototype.prelu=function(t,e){throw new Error("Not yet implemented")},t.prototype.elu=function(t){throw new Error("Not yet implemented")},t.prototype.eluDer=function(t,e){throw new Error("Not yet implemented")},t.prototype.selu=function(t){throw new Error("Not yet implemented")},t.prototype.int=function(t){throw new Error("Not yet implemented")},t.prototype.clip=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.abs=function(t){throw new Error("Not yet implemented")},t.prototype.complexAbs=function(t){throw new Error("Not yet implemented")},t.prototype.sigmoid=function(t){throw new Error("Not yet implemented")},t.prototype.softplus=function(t){throw new Error("Not yet implemented")},t.prototype.sin=function(t){throw new Error("Not yet implemented")},t.prototype.cos=function(t){throw new Error("Not yet implemented")},t.prototype.tan=function(t){throw new Error("Not yet implemented")},t.prototype.asin=function(t){throw new Error("Not yet implemented")},t.prototype.acos=function(t){throw new Error("Not yet implemented")},t.prototype.atan=function(t){throw new Error("Not yet implemented")},t.prototype.atan2=function(t,e){throw new Error("Not yet implemented")},t.prototype.sinh=function(t){throw new Error("Not yet implemented")},t.prototype.cosh=function(t){throw new Error("Not yet implemented")},t.prototype.tanh=function(t){throw new Error("Not yet implemented")},t.prototype.asinh=function(t){throw new Error("Not yet implemented")},t.prototype.acosh=function(t){throw new Error("Not yet implemented")},t.prototype.atanh=function(t){throw new Error("Not yet implemented")},t.prototype.erf=function(t){throw new Error("Not yet implemented")},t.prototype.step=function(t,e){throw new Error("Not yet implemented")},t.prototype.conv2d=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.conv2dDerInput=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.conv2dDerFilter=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.depthwiseConv2D=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.depthwiseConv2DDerInput=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.depthwiseConv2DDerFilter=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.conv3d=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.conv3dDerInput=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.conv3dDerFilter=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.maxPool=function(t,e){throw new Error("Not yet implemented")},t.prototype.maxPoolBackprop=function(t,e,n,r){throw new Error("Not yet implemented")},t.prototype.avgPool=function(t,e){throw new Error("Not yet implemented")},t.prototype.avgPoolBackprop=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.reshape=function(t,e){throw new Error("Not yet implemented")},t.prototype.cast=function(t,e){throw new Error("Not yet implemented")},t.prototype.tile=function(t,e){throw new Error("Not yet implemented")},t.prototype.pad=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.transpose=function(t,e){throw new Error("Not yet implemented")},t.prototype.gather=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.gatherND=function(t,e){throw new Error("Not yet implemented")},t.prototype.scatterND=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.batchToSpaceND=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.spaceToBatchND=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.resizeBilinear=function(t,e,n,r){throw new Error("Not yet implemented")},t.prototype.resizeBilinearBackprop=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.resizeNearestNeighbor=function(t,e,n,r){throw new Error("Not yet implemented")},t.prototype.resizeNearestNeighborBackprop=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.batchNormalization=function(t,e,n,r,o,i){throw new Error("Not yet implemented")},t.prototype.localResponseNormalization4D=function(t,e,n,r,o){throw new Error("Not yet implemented")},t.prototype.LRNGrad=function(t,e,n,r,o,i,a){throw new Error("Not yet implemented")},t.prototype.multinomial=function(t,e,n,r){throw new Error("Not yet implemented")},t.prototype.oneHot=function(t,e,n,r){throw new Error("Not yet implemented")},t.prototype.cumsum=function(t,e,n,r){throw new Error("Not yet implemented")},t.prototype.nonMaxSuppression=function(t,e,n,r,o){throw new Error("Not yet implemented")},t.prototype.fft=function(t){throw new Error("Not yet implemented")},t.prototype.ifft=function(t){throw new Error("Not yet implemented")},t.prototype.complex=function(t,e){throw new Error("Not yet implemented")},t.prototype.real=function(t){throw new Error("Not yet implemented")},t.prototype.imag=function(t){throw new Error("Not yet implemented")},t.prototype.cropAndResize=function(t,e,n,r,o,i){throw new Error("Not yet implemented")},t.prototype.depthToSpace=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.split=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.sparseToDense=function(t,e,n,r){throw new Error("Not yet implemented")},t.prototype.fill=function(t,e,n){throw new Error("Not yet implemented.")},t.prototype.onesLike=function(t){throw new Error("Not yet implemented")},t.prototype.zerosLike=function(t){throw new Error("Not yet implemented")},t.prototype.linspace=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.dispose=function(){throw new Error("Not yet implemented")},t}();function kr(t,e){for(var n=t.length,r=[],o=0;o1&&1===a&&r.unshift(i)}return r}function Ar(t,e){for(var n=[],r=0;r1)&&n.unshift(i)}return n}function Tr(t,e){for(var n=[],r=Math.max(t.length,e.length),o=0;oo}).sort(function(t,e){return e.score-t.score}),a=[],s=0;s=0;--p)if(Qr(t,l,a[p])>=r){h=!0;break}if(!h&&(a.push(l),a.length>=n))break}return on(a,"int32")}function Qr(t,e,n){var r=t.subarray(4*e,4*e+4),o=t.subarray(4*n,4*n+4),i=Math.min(r[0],r[2]),a=Math.min(r[1],r[3]),s=Math.max(r[0],r[2]),u=Math.max(r[1],r[3]),c=Math.min(o[0],o[2]),l=Math.min(o[1],o[3]),h=Math.max(o[0],o[2]),p=Math.max(o[1],o[3]),f=(s-i)*(u-a),d=(h-c)*(p-l);if(f<=0||d<=0)return 0;var v=Math.max(i,c),m=Math.max(a,l),g=Math.min(s,h),y=Math.min(u,p),x=Math.max(g-v,0)*Math.max(y-m,0);return x/(f+d-x)}function Jr(t,e,n){var r=new Array(t.rank).fill(0),o=t.shape.slice();return e.map(function(e){o[n]=e;var i=t.slice(r,o);return r[n]+=e,i})}function Zr(t,e){for(var n=new Array(t.rank),r=0;r":"<",u=n?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = outIdx * "+r+";\n\n int bestIndex = inOffset;\n float bestValue = getA(batch, bestIndex);\n\n for (int i = 0; i < "+r+"; i++) {\n int inIdx = "+u+";\n float candidate = getA(batch, inIdx);\n if (candidate "+s+" bestValue) {\n bestValue = candidate;\n bestIndex = inIdx;\n }\n }\n setOutput(float(bestIndex));\n }\n "};function io(t,e){return["x","y","z","w","u","v"].slice(0,e).map(function(e){return t+"."+e})}function ao(t,e){return 1===e?[t]:io(t,e)}function so(){var t,e,n,r,o,i,a,s,u,c;return 2===f.getNumber("WEBGL_VERSION")?(t="#version 300 es",e="in",n="out",r="in",o="texture",i="outputColor",a="out vec4 outputColor;",s="\n bool isnan_custom(float val) {\n return (val > 0. || val < 0. || val == 0.) ? false : true;\n }\n ",u="\n const float INFINITY = uintBitsToFloat(uint(0x7f800000));\n ",c="\n #define round(value) newRound(value)\n int newRound(float value) {\n return int(floor(value + 0.5));\n }\n\n ivec4 newRound(vec4 value) {\n return ivec4(floor(value + vec4(0.5)));\n }\n "):(t="",e="attribute",n="varying",r="varying",o="texture2D",i="gl_FragColor",a="",s="\n bool isnan_custom(float val) {\n return (val > 0. || val < 1. || val == 0.) ? false : true;\n }\n ",u="\n uniform float INFINITY;\n\n bool isinf(float val) {\n return abs(val) == INFINITY;\n }\n bvec4 isinf(vec4 val) {\n return equal(abs(val), vec4(INFINITY));\n }\n ",c="\n int round(float value) {\n return int(floor(value + 0.5));\n }\n\n ivec4 round(vec4 value) {\n return ivec4(floor(value + vec4(0.5)));\n }\n "),{version:t,attribute:e,varyingVs:n,varyingFs:r,texture2D:o,output:i,defineOutput:a,defineSpecialNaN:s,defineSpecialInf:u,defineRound:c}}function uo(t,e,n){void 0===n&&(n="index");var r=X(e);return r.map(function(e,o){return"int "+t[o]+" = "+n+" / "+e+"; "+(o===r.length-1?"int "+t[o+1]+" = "+n+" - "+t[o]+" * "+e:"index -= "+t[o]+" * "+e)+";"}).join("")}function co(t){var e=X(t).map(function(t){return t.toString()});return"\n int getFlatIndex(ivec3 coords) {\n return coords.x * "+e[0]+" + coords.y * "+e[1]+" + coords.z;\n }\n"}var lo="\n const float FLOAT_MAX = 1.70141184e38;\n const float FLOAT_MIN = 1.17549435e-38;\n\n lowp vec4 encode_float(highp float v) {\n if (isnan(v)) {\n return vec4(255, 255, 255, 255);\n }\n\n highp float av = abs(v);\n\n if(av < FLOAT_MIN) {\n return vec4(0.0, 0.0, 0.0, 0.0);\n } else if(v > FLOAT_MAX) {\n return vec4(0.0, 0.0, 128.0, 127.0) / 255.0;\n } else if(v < -FLOAT_MAX) {\n return vec4(0.0, 0.0, 128.0, 255.0) / 255.0;\n }\n\n highp vec4 c = vec4(0,0,0,0);\n\n highp float e = floor(log2(av));\n highp float m = exp2(fract(log2(av))) - 1.0;\n\n c[2] = floor(128.0 * m);\n m -= c[2] / 128.0;\n c[1] = floor(32768.0 * m);\n m -= c[1] / 32768.0;\n c[0] = floor(8388608.0 * m);\n\n highp float ebias = e + 127.0;\n c[3] = floor(ebias / 2.0);\n ebias -= c[3] * 2.0;\n c[2] += floor(ebias) * 128.0;\n\n c[3] += 128.0 * step(0.0, -v);\n\n return c / 255.0;\n }\n";function ho(t,e,n,r){var o=[];t.forEach(function(t){var e=_(t.shapeInfo.logicalShape);t.shapeInfo.isUniform?o.push("uniform float "+t.name+(e>1?"["+e+"]":"")+";"):(o.push("uniform sampler2D "+t.name+";"),o.push("uniform int offset"+t.name+";"))});var i,a,s=o.join("\n"),u=t.map(function(t){return function(t,e,n){void 0===n&&(n=!1);var r="";r+=n?function t(e){var n,r,o;switch(e.shapeInfo.logicalShape.length){case 0:return n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),o=so(),"\n vec4 "+r+"() {\n return "+o.texture2D+"("+n+", halfCR);\n }\n ";case 1:return function(t){var e=t.name,n="get"+e.charAt(0).toUpperCase()+e.slice(1),r=t.shapeInfo.texShape,o=[Math.ceil(r[0]/2),Math.ceil(r[1]/2)],i=so();return"\n vec4 "+n+"(int index) {\n vec2 uv = packedUVfrom1D(\n "+o[0]+", "+o[1]+", index);\n return "+i.texture2D+"("+e+", uv);\n }\n "}(e);case 2:return function(t){var e=t.shapeInfo.logicalShape,n=t.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),o=t.shapeInfo.texShape,i=o[0],a=o[1],s=so();if(null!=o&&I(e,o))return"\n vec4 "+r+"(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2("+a+".0, "+i+".0);\n\n return "+s.texture2D+"("+n+", uv);\n }\n ";var u=[Math.ceil(o[0]/2),Math.ceil(o[1]/2)],c=Math.ceil(e[1]/2);return"\n vec4 "+r+"(int row, int col) {\n vec2 uv = packedUVfrom2D("+c+", "+u[0]+", "+u[1]+", row, col);\n return "+s.texture2D+"("+n+", uv);\n }\n "}(e);case 3:return function(e){var n=e.shapeInfo.logicalShape,r=e.name,o="get"+r.charAt(0).toUpperCase()+r.slice(1),i=e.shapeInfo.texShape,a=[Math.ceil(i[0]/2),Math.ceil(i[1]/2)];if(1===n[0]){var s=n.slice(1),u=bo(e,s);return"\n "+t(u)+"\n vec4 "+o+"(int b, int row, int col) {\n return "+o+"("+wo(["b","row","col"],[1,2])+");\n }\n "}var c=a[0],l=a[1],h=Math.ceil(n[2]/2),p=h*Math.ceil(n[1]/2),f=so();return"\n vec4 "+o+"(int b, int row, int col) {\n vec2 uv = packedUVfrom3D(\n "+c+", "+l+", "+p+", "+h+", b, row, col);\n return "+f.texture2D+"("+r+", uv);\n }\n "}(e);default:return function(t){for(var e=t.shapeInfo.logicalShape,n=e.length,r=t.name,o="get"+r.charAt(0).toUpperCase()+r.slice(1),i=t.shapeInfo.texShape,a=[Math.ceil(i[0]/2),Math.ceil(i[1]/2)],s=a[0],u=a[1],c=Math.ceil(e[n-1]/2),l=c*Math.ceil(e[n-2]/2),h="int b, int row, int col",p="b * "+l+" + (row / 2) * "+c+" + (col / 2)",f=2;f=1?"coords = 0;":u.map(function(t){return"coords."+h[t+l]+" = 0;"}).join("\n");var p;p=s<2&&a>0?"coords":t.shapeInfo.logicalShape.map(function(t,e){return"coords."+h[e+l]}).join(", ");var f="return outputValue;",d=1===_(t.shapeInfo.logicalShape),v=1===_(e.logicalShape);if(1!==a||d||v){if(d&&!v)f=1===s?"\n return vec4(outputValue.x, outputValue.x, 0., 0.);\n ":"\n return vec4(outputValue.x);\n ";else if(u.length){var m=a-2,g=a-1;u.indexOf(m)>-1&&u.indexOf(g)>-1?f="return vec4(outputValue.x);":u.indexOf(m)>-1?f="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":u.indexOf(g)>-1&&(f="return vec4(outputValue.xx, outputValue.zz);")}}else f="\n return vec4(outputValue.xy, outputValue.xy);\n ";return"\n vec4 "+i+"() {\n "+c+" coords = getOutputCoords();\n "+n+"\n vec4 outputValue = get"+o+"("+p+");\n "+f+"\n }\n "}(t,e):function(t,e){var n=t.name,r=n.charAt(0).toUpperCase()+n.slice(1),o="get"+r+"AtOutCoords",i=e.texShape,a=t.shapeInfo.texShape,s=t.shapeInfo.logicalShape.length,u=e.logicalShape.length;if(!t.shapeInfo.isUniform&&s===u&&null==t.shapeInfo.flatOffset&&I(a,i))return"\n float "+o+"() {\n return sampleTexture("+n+", resultUV);\n }\n ";var c=xo(u),l=kr(t.shapeInfo.logicalShape,e.logicalShape),h=u-s,p=["x","y","z","w","u","v"];return"\n float "+o+"() {\n "+c+" coords = getOutputCoords();\n "+(0===s?"":u<2&&l.length>=1?"coords = 0;":l.map(function(t){return"coords."+p[t+h]+" = 0;"}).join("\n"))+"\n return get"+r+"("+(u<2&&s>0?"coords":t.shapeInfo.logicalShape.map(function(t,e){return"coords."+p[e+h]}).join(", "))+");\n }\n "}(t,e)),r}(t,e,r)}).join("\n"),c=e.texShape,l=so(),h="\n float sampleTexture(sampler2D textureSampler, vec2 uv) {\n return "+l.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 #define isnan(value) isnan_custom(value)\n "+t.defineSpecialNaN+"\n bvec4 isnan_custom(vec4 val) {\n return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w));\n }\n\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 "+po+"\n "+fo+"\n "+vo+"\n "}(l);return e.isPacked?(i=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 r=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 / "+r+");\n int c = imod(index, "+r+") * 2;\n\n return ivec2(r, c);\n }\n "}(t,e);case 3:return n=t,r=e,o=[Math.ceil(r[0]/2),Math.ceil(r[1]/2)],a=(i=Math.ceil(n[2]/2))*Math.ceil(n[1]/2),"\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+o[0]+", "+o[1]+"));\n int index = resTexRC.x * "+o[1]+" + resTexRC.y;\n\n int b = index / "+a+";\n index -= b * "+a+";\n\n int r = 2 * (index / "+i+");\n int c = imod(index, "+i+") * 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)],r=Math.ceil(t[t.length-1]/2),o=r*Math.ceil(t[t.length-2]/2),i=o,a="",s="b, r, c",u=2;u2,function(){return"Packed arg"+(n.charAt(0).toUpperCase()+n.slice(1))+" supports only inputs with rank above 2."});var o=t[t.length-1],i=Math.ceil(o/e);this.outputShape=t.slice(0,-1),i>1&&this.outputShape.push(i),r||this.variableNames.push("bestIndicesA");var a,s,u=this.outputShape,c=u.length,l=xo(c),h=ao("coords",c);if(1===i){var p=xo(s=c+1);a="\n "+p+" sourceLocR = "+p+"("+h.join()+", 0);\n ++"+h[c-1]+";\n "+p+" sourceLocG = "+p+"("+h.join()+", 0);\n ++"+h[c-2]+";\n "+p+" sourceLocA = "+p+"("+h.join()+", 0);\n --"+h[c-1]+";\n "+p+" sourceLocB = "+p+"("+h.join()+", 0);\n --"+h[c-2]+";"}else s=c,a="\n "+l+" sourceLocR = coords;\n ++"+h[c-1]+";\n "+l+" sourceLocG = coords;\n ++"+h[c-2]+";\n "+l+" sourceLocA = coords;\n --"+h[c-1]+";\n "+l+" sourceLocB = coords;\n --"+h[c-2]+";";var f=["x","y","z","w","u","v"].slice(0,s),d="."+f[s-1],v=f.map(function(t){return"int "+t}),m=ao("sourceLocR",s-1).concat("inIdx.r"),g=ao("sourceLocG",s-1).concat("inIdx.g"),y=ao("sourceLocB",s-1).concat("inIdx.b"),x=ao("sourceLocA",s-1).concat("inIdx.a"),w="max"===n?"greaterThan":"lessThan",C=r?"":"\n inIdx = round(vec4(getBestIndicesAChannel("+m.join()+"),\n getBestIndicesAChannel("+g.join()+"),\n getBestIndicesAChannel("+y.join()+"),\n getBestIndicesAChannel("+x.join()+")));",E="vec4(\n getAChannel("+m.join()+"),\n hasNextCol ? getAChannel("+g.join()+") : 0.,\n hasNextRow ? getAChannel("+y.join()+") : 0.,\n hasNextRow && hasNextCol ? getAChannel("+x.join()+") : 0.)",_=r?"":"\n float getBestIndicesAChannel("+v.join()+") {\n return getChannel(getBestIndicesA("+f.join()+"),\n vec2("+f.slice(-2).join()+"));\n }";this.userCode="\n float getAChannel("+v.join()+") {\n return getChannel(getA("+f.join()+"),\n vec2("+f.slice(-2).join()+"));\n }\n "+_+"\n void main() {\n "+l+" coords = getOutputCoords();\n bool hasNextCol = "+h[c-1]+" < "+(u[c-1]-1)+";\n bool hasNextRow = "+h[c-2]+" < "+(u[c-2]-1)+";\n "+a+"\n ivec4 srcIdx = ivec4(sourceLocR"+d+", sourceLocG"+d+",\n sourceLocB"+d+", sourceLocA"+d+") * "+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 "+C+"\n vec4 candidate = "+E+";\n bvec4 nan = isnan(candidate);\n bvec4 replace = bvec4(\n vec4("+w+"(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 "},Eo=function(t){this.variableNames=["dy"],this.outputShape=t.inShape;var e=t.filterHeight,n=t.filterWidth,r=t.strideHeight,o=t.strideWidth,i=t.dilationHeight,a=t.dilationWidth,s=t.effectiveFilterHeight,u=t.effectiveFilterWidth,c=s-1-t.padInfo.top,l=u-1-t.padInfo.left,h=1/(e*n);this.userCode="\n const ivec2 pads = ivec2("+c+", "+l+");\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 < "+s+";\n wR += "+i+") {\n float dyR = float(dyRCorner + wR) / "+r+".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 < "+u+";\n wC+= "+a+") {\n float dyC = float(dyCCorner + wC) / "+o+".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 "},_o=function(t,e,n,r,o,i){this.outputShape=[],this.variableNames=["x","mean","variance"],Tr(t,e),Tr(t,n);var a="0.0";null!=r&&(Tr(t,r),this.variableNames.push("offset"),a="getOffsetAtOutCoords()");var s="1.0";null!=o&&(Tr(t,o),this.variableNames.push("scale"),s="getScaleAtOutCoords()"),this.outputShape=t,this.userCode="\n void main() {\n float x = getXAtOutCoords();\n float mean = getMeanAtOutCoords();\n float variance = getVarianceAtOutCoords();\n float offset = "+a+";\n float scale = "+s+";\n float inv = scale * inversesqrt(variance + float("+i+"));\n setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));\n }\n "},Io=function(t,e,n,r,o,i){this.usesPackedTextures=!0,this.variableNames=["x","mean","variance"],Tr(t,e),Tr(t,n);var a="vec4(0.0)";null!=r&&(Tr(t,r),this.variableNames.push("offset"),a="getOffsetAtOutCoords()");var s="vec4(1.0)";null!=o&&(Tr(t,o),this.variableNames.push("scale"),s="getScaleAtOutCoords()"),this.outputShape=t,this.userCode="\n void main() {\n vec4 offset = "+a+";\n vec4 scale = "+s+";\n\n vec4 x = getXAtOutCoords();\n vec4 mean = getMeanAtOutCoords();\n vec4 variance = getVarianceAtOutCoords();\n\n vec4 inv = scale * inversesqrt(variance + vec4("+i+"));\n\n setOutput((x - mean) * inv + offset);\n }\n "},So=function(t,e,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=Tr(e,n),this.userCode="\n float binaryOpComplex(\n float areal, float aimag, float breal, float bimag) {\n "+t+"\n }\n\n void main() {\n float areal = getARealAtOutCoords();\n float aimag = getAImagAtOutCoords();\n float breal = getBRealAtOutCoords();\n float bimag = getBImagAtOutCoords();\n setOutput(binaryOpComplex(areal, aimag, breal, bimag));\n }\n "},Ro="return a + b;",No="return a - b;",ko="return a * b;",Ao=function(t,e,n){this.variableNames=["A","B"],this.outputShape=Tr(e,n),this.userCode="\n float binaryOperation(float a, float b) {\n "+t+"\n }\n\n void main() {\n float a = getAAtOutCoords();\n float b = getBAtOutCoords();\n setOutput(binaryOperation(a, b));\n }\n "},To=function(t,e,n,r){void 0===r&&(r=!1),this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.usesPackedTextures=!0,this.outputShape=Tr(e,n);var o=this.outputShape.length,i="";if(r)if(0===o||1===_(this.outputShape))i="\n result.y = 0.;\n result.z = 0.;\n result.w = 0.;\n ";else if(i="\n "+xo(o)+" coords = getOutputCoords();\n ",1===o)i+="\n result.y = (coords + 1) >= "+this.outputShape[0]+" ? 0. : result.y;\n result.z = 0.;\n result.w = 0.;\n ";else{var a=ao("coords",o);i+="\n bool nextRowOutOfBounds =\n ("+a[o-2]+" + 1) >= "+this.outputShape[o-2]+";\n bool nextColOutOfBounds =\n ("+a[o-1]+" + 1) >= "+this.outputShape[o-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 "+i+"\n\n setOutput(result);\n }\n "},Do=function(){function t(t){this.variableNames=["A"],this.outputShape=t,this.userCode="\n uniform float min;\n uniform float max;\n\n void main() {\n float value = getAAtOutCoords();\n if (isnan(value)) {\n setOutput(value);\n return;\n }\n\n setOutput(clamp(value, min, max));\n }\n "}return t.prototype.getCustomSetupFunc=function(t,e){var n=this;return function(r,o){null==n.minLoc&&(n.minLoc=r.getUniformLocationNoThrow(o,"min"),n.maxLoc=r.getUniformLocationNoThrow(o,"max")),r.gl.uniform1f(n.minLoc,t),r.gl.uniform1f(n.maxLoc,e)}},t}(),Fo=function(){function t(t){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=t,this.userCode="\n uniform float min;\n uniform float max;\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(min), vec4(max)));\n }\n "}return t.prototype.getCustomSetupFunc=function(t,e){var n=this;return function(r,o){null==n.minLoc&&(n.minLoc=r.getUniformLocationNoThrow(o,"min"),n.maxLoc=r.getUniformLocationNoThrow(o,"max")),r.gl.uniform1f(n.minLoc,t),r.gl.uniform1f(n.maxLoc,e)}},t}(),Mo=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 "},Oo=function(t){this.outputShape=[],this.outputShape=Ye(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;n= "+t.inHeight+") {\n continue;\n }\n\n for (int yC = 0; yC < "+t.outWidth+"; yC++) {\n int xC = wC + yC * "+n+" - "+o+";\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 "},Lo=function(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterHeight,n=t.filterWidth,r=t.strideHeight,o=t.strideWidth,i=e-1-t.padInfo.top,a=n-1-t.padInfo.left;this.userCode="\n const ivec2 pads = ivec2("+i+", "+a+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords[3];\n\n ivec2 dyCorner = coords.yz - 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) / "+r+".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) / "+o+".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 float xValue = getDy(batch, idyR, idyC, d2);\n float wValue = getW(wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n }\n }\n }\n setOutput(dotProd);\n }\n "},Wo=function(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;var e=t.strideDepth,n=t.strideHeight,r=t.strideWidth,o=t.padInfo.front,i=t.padInfo.top,a=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+" - "+o+";\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+" - "+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 * "+r+" - "+a+";\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 "},zo=function(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterDepth,n=t.filterHeight,r=t.filterWidth,o=t.strideDepth,i=t.strideHeight,a=t.strideWidth,s=e-1-t.padInfo.front,u=n-1-t.padInfo.top,c=r-1-t.padInfo.left;this.userCode="\n const ivec3 pads = ivec3("+s+", "+u+", "+c+");\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) / "+o+".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) / "+i+".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 < "+r+"; wC++) {\n float dyC = float(dyCCorner + wC) / "+a+".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 = "+r+" - 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 "},Uo=function(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;var e=t.strideHeight,n=t.strideWidth,r=t.padInfo.top,o=t.padInfo.left,i=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 * "+i+" + dm;\n\n float dotProd = 0.0;\n\n // TODO: 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+" - "+r+";\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+" - "+o+";\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 "},Vo=function(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterHeight,n=t.filterWidth,r=t.strideHeight,o=t.strideWidth,i=e-1-t.padInfo.top,a=n-1-t.padInfo.left,s=t.outChannels/t.inChannels;this.userCode="\n const ivec2 pads = ivec2("+i+", "+a+");\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) / "+r+".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) / "+o+".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 // TODO: Vec4 over the channelMul\n for (int dm = 0; dm < "+s+"; dm++) {\n int d2 = d1 * "+s+" + 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 "},Go=function(t){this.variableNames=["x","W"],this.outputShape=t.outShape;var e=t.padInfo.top,n=t.padInfo.left,r=t.strideHeight,o=t.strideWidth,i=t.dilationHeight,a=t.dilationWidth,s=t.filterHeight,u=t.filterWidth,c=4*Math.floor(t.inChannels/4),l=t.inChannels%4;this.userCode="\n const ivec2 strides = ivec2("+r+", "+o+");\n const ivec2 pads = ivec2("+e+", "+n+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d2 = coords[3];\n\n ivec2 xRCCorner = coords.yz * 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 < "+s+"; wR++) {\n int xR = xRCorner + wR * "+i+";\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+u+"; wC++) {\n int xC = xCCorner + wC * "+a+";\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n for (int d1 = 0; d1 < "+c+"; d1 += 4) {\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 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 dotProd += dot(xValues, wValues);\n }\n\n if ("+(1===l)+") {\n dotProd +=\n getX(batch, xR, xC, "+c+") *\n getW(wR, wC, "+c+", d2);\n } else if ("+(2===l)+") {\n vec2 xValues = vec2(\n getX(batch, xR, xC, "+c+"),\n getX(batch, xR, xC, "+c+" + 1)\n );\n vec2 wValues = vec2(\n getW(wR, wC, "+c+", d2),\n getW(wR, wC, "+c+" + 1, d2)\n );\n dotProd += dot(xValues, wValues);\n } else if ("+(3===l)+") {\n vec3 xValues = vec3(\n getX(batch, xR, xC, "+c+"),\n getX(batch, xR, xC, "+c+" + 1),\n getX(batch, xR, xC, "+c+" + 2)\n );\n vec3 wValues = vec3(\n getW(wR, wC, "+c+", d2),\n getW(wR, wC, "+c+" + 1, d2),\n getW(wR, wC, "+c+" + 2, d2)\n );\n dotProd += dot(xValues, wValues);\n }\n }\n }\n setOutput(dotProd);\n }\n "},jo=function(t){this.variableNames=["x","W"],this.outputShape=t.outShape;var e=t.padInfo.front,n=t.padInfo.top,r=t.padInfo.left,o=t.strideDepth,i=t.strideHeight,a=t.strideWidth,s=t.dilationDepth,u=t.dilationHeight,c=t.dilationWidth,l=t.filterDepth,h=t.filterHeight,p=t.filterWidth,f=4*Math.floor(t.inChannels/4),d=t.inChannels%4;this.userCode="\n const ivec3 strides = ivec3("+o+", "+i+", "+a+");\n const ivec3 pads = ivec3("+e+", "+n+", "+r+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int d2 = coords.u;\n\n ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n int xFCorner = xFRCCorner.x;\n int xRCorner = xFRCCorner.y;\n int xCCorner = xFRCCorner.z;\n\n // Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get\n // y(yF, yR, yC, d2). ? = to be determined. : = across all\n // values in that axis.\n float dotProd = 0.0;\n for (int wF = 0; wF < "+l+"; wF++) {\n int xF = xFCorner + wF * "+s+";\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 * "+u+";\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 * "+c+";\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n for (int d1 = 0; d1 < "+f+"; 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===d)+") {\n dotProd +=\n getX(batch, xF, xR, xC, "+f+") *\n getW(wF, wR, wC, "+f+", d2);\n } else if ("+(2===d)+") {\n vec2 xValues = vec2(\n getX(batch, xF, xR, xC, "+f+"),\n getX(batch, xF, xR, xC, "+f+" + 1)\n );\n vec2 wValues = vec2(\n getW(wF, wR, wC, "+f+", d2),\n getW(wF, wR, wC, "+f+" + 1, d2)\n );\n dotProd += dot(xValues, wValues);\n } else if ("+(3===d)+") {\n vec3 xValues = vec3(\n getX(batch, xF, xR, xC, "+f+"),\n getX(batch, xF, xR, xC, "+f+" + 1),\n getX(batch, xF, xR, xC, "+f+" + 2)\n );\n vec3 wValues = vec3(\n getW(wF, wR, wC, "+f+", d2),\n getW(wF, wR, wC, "+f+" + 1, d2),\n getW(wF, wR, wC, "+f+" + 2, d2)\n );\n dotProd += dot(xValues, wValues);\n }\n }\n }\n }\n setOutput(dotProd);\n }\n "},Ho=function(t){this.variableNames=["x","W"],this.outputShape=t.outShape;var e=t.inHeight,n=t.inWidth,r=t.padInfo.top,o=t.padInfo.left,i=t.strideHeight,a=t.strideWidth,s=t.dilationHeight,u=t.dilationWidth,c=t.filterHeight,l=t.filterWidth,h=t.outChannels/t.inChannels;this.userCode="\n const ivec2 strides = ivec2("+i+", "+a+");\n const ivec2 pads = ivec2("+r+", "+o+");\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 / "+h+";\n int q = d2 - d1 * "+h+";\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 // TODO(dsmilkov): Flatten the two for loops and vec4 the operations.\n for (int wR = 0; wR < "+c+"; wR++) {\n int xR = xRCorner + wR * "+s+";\n\n if (xR < 0 || xR >= "+e+") {\n continue;\n }\n\n for (int wC = 0; wC < "+l+"; wC++) {\n int xC = xCCorner + wC * "+u+";\n\n if (xC < 0 || xC >= "+n+") {\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 setOutput(dotProd);\n }\n "},qo=function(t){this.variableNames=["x","W"],this.usesPackedTextures=!0,this.outputShape=t.outShape;for(var e=t.inHeight,n=t.inWidth,r=t.padInfo.top,o=t.padInfo.left,i=t.strideHeight,a=t.strideWidth,s=t.dilationHeight,u=t.dilationWidth,c=t.filterHeight,l=t.filterWidth,h=l,p="int xR; int xC; int xCOffset;",f=0;f= 0 && xR < "+e+" && xCOffset >= 0 && xCOffset < "+n+") {\n xTexelR"+f+"C"+d+" = getX(batch, xR, xCOffset, d1);\n } else {\n xTexelR"+f+"C"+d+" = vec4(0.);\n }\n\n xCOffset = xC + 1 - 2;\n if(xR >= 0 && xR < "+e+" && xCOffset >= 0 && xCOffset < "+n+") {\n vec4 previous = getX(batch, xR, xCOffset, d1);\n xR"+f+"C"+d+" = vec4(previous.zw, xTexelR"+f+"C"+d+".xy);\n } else {\n xR"+f+"C"+d+" = vec4(0, 0, xTexelR"+f+"C"+d+".xy);\n }\n ":"\n if(xR >= 0 && xR < "+e+" && xC >= 0 && xC < "+n+") {\n xTexelR"+f+"C"+d+" = getX(batch, xR, xC, d1);\n } else {\n xTexelR"+f+"C"+d+" = vec4(0.);\n }\n\n xR"+f+"C"+d+" = xTexelR"+f+"C"+d+";\n ",d+1= 0 && xR < "+e+" &&\n xCOffset >= 0 && xCOffset < "+n+") {\n xTexelR"+f+"C"+(d+2)+" = getX(batch, xR, xCOffset, d1);\n }\n ",u>1&&(p+="\n xCOffset -= 2;\n if(xR >= 0 && xR < "+e+" &&\n xCOffset >= 0 && xCOffset < "+n+") {\n xTexelR"+f+"C"+d+" = getX(batch, xR, xCOffset, d1);\n } else {\n xTexelR"+f+"C"+d+" = vec4(0.);\n }\n "),p+="\n xR"+f+"C"+(d+1)+" = vec4(\n xTexelR"+f+"C"+d+".zw, xTexelR"+f+"C"+(d+2)+".xy);\n "):p+="\n xCOffset = xC + "+m+";\n\n if(xR >= 0 && xR < "+e+" &&\n xCOffset >= 0 && xCOffset < "+n+") {\n xTexelR"+f+"C"+(d+2)+" = getX(batch, xR, xCOffset, d1);\n }\n\n xR"+f+"C"+(d+1)+" = xTexelR"+f+"C"+(d+2)+";\n "}}else d= 0 && xR < "+e+") {\n ",o%2==1?(p+="\n xCOffset = xC + 1 - "+a+";\n if(xCOffset >= 0 && xCOffset < "+n+") {\n xTexelR"+f+"C"+d+" = getX(batch, xR, xCOffset, d1);\n } else {\n xTexelR"+f+"C"+d+" = vec4(0.);\n }\n\n if(xC + 1 >= 0 && xC + 1 < "+n+") {\n xTexelR"+f+"C"+(d+2)+" = getX(batch, xR, xC + 1, d1);\n } else {\n xTexelR"+f+"C"+(d+2)+" = vec4(0.);\n }\n\n xR"+f+"C"+d+" = vec4(\n xTexelR"+f+"C"+d+".zw, xTexelR"+f+"C"+(d+2)+".zw);\n ",d+1= 0 && xCOffset < "+n+") {\n final = getX(batch, xR, xCOffset, d1);\n }\n xR"+f+"C"+(d+1)+" = vec4(xTexelR"+f+"C"+(d+2)+".xy, final.xy);\n ")):(p+="\n if(xC >= 0 && xC < "+n+") {\n xTexelR"+f+"C"+d+" = getX(batch, xR, xC, d1);\n } else {\n xTexelR"+f+"C"+d+" = vec4(0.);\n }\n\n xCOffset = xC + "+a+";\n if(xCOffset >= 0 && xCOffset < "+n+") {\n xTexelR"+f+"C"+(d+2)+" = getX(batch, xR, xCOffset, d1);\n } else {\n xTexelR"+f+"C"+(d+2)+" = vec4(0.);\n }\n\n xR"+f+"C"+d+" = vec4(\n xTexelR"+f+"C"+d+".xy, xTexelR"+f+"C"+(d+2)+".xy);\n ",d+11?[""+(a-1)/(l-1),"(y2-y1) * height_ratio","y1*"+d+" + float(y)*(height_scale)"]:["0.0","0.0","0.5 * (y1+y2) * "+d],g=m[0],y=m[1],x=m[2],b=h>1?[""+(s-1)/(h-1),"(x2-x1) * width_ratio","x1*"+v+" + float(x)*(width_scale)"]:["0.0","0.0","0.5 * (x1+x2) * "+v],w=b[0],C=b[1],E=b[2];this.userCode="\n const float height_ratio = float("+g+");\n const float width_ratio = float("+w+");\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 >= "+i+") {\n return;\n }\n\n float height_scale = "+y+";\n float width_scale = "+C+";\n\n float in_y = "+x+";\n if( in_y < 0.0 || in_y > "+d+" ) {\n setOutput(float("+o+"));\n return;\n }\n float in_x = "+E+";\n if( in_x < 0.0 || in_x > "+v+" ) {\n setOutput(float("+o+"));\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 "},Ko=function(t,e,n){this.variableNames=["x"],this.outputShape=t;var r=t.length,o=t[t.length-1],i=n?"<":">";this.userCode="\n int getIndex(int i) {\n "+(n?"return "+o+" -i - 1;":"return i;")+"\n }\n\n void main() {\n "+xo(r)+" coords = getOutputCoords();\n int end = "+Xo(r,"coords")+";\n float val = 0.0;\n for (int i = "+o+" - 1; i >= 0; i -= 1) {\n int idx = getIndex(i);\n if (idx "+i+" end) {\n continue;\n }\n if (idx == end && "+e+") {\n continue;\n }\n "+Xo(r,"coords")+" = idx;\n val += getX("+function(t,e){if(1===r)return""+e;if(2===r)return e+".x, "+e+".y";if(3===r)return e+".x, "+e+".y, "+e+".z";if(4===r)return e+".x, "+e+".y, "+e+".z, "+e+".w";throw Error("Cumulative sum for rank "+r+" is not yet supported")}(0,"coords")+");\n }\n setOutput(val);\n }\n "};function Xo(t,e){if(1===t)return""+e;if(2===t)return e+".y";if(3===t)return e+".z";if(4===t)return e+".w";throw Error("Cumulative sum for rank "+t+" is not yet supported")}var Yo,Qo,Jo=function(t,e){this.variableNames=["A"];var n=so();this.outputShape=t,this.userCode="\n ivec3 outCoordsFromFlatIndex(int index) {\n "+uo(["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 "},Zo=function(t,e){this.variableNames=["A"],this.usesPackedTextures=!0;var n=so();this.outputShape=t,this.userCode="\n ivec3 outCoordsFromFlatIndex(int index) {\n "+uo(["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 "},ti=function(){function t(t,e,n){this.variableNames=["x"],this.outputShape=[],this.outputShape=t,this.blockSize=e,this.dataFormat=n,this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int h = "+this.getHeightCoordString()+";\n int w = "+this.getWidthCoordString()+";\n int d = "+this.getDepthCoordString()+";\n\n int in_h = h / "+e+";\n int offset_h = imod(h, "+e+");\n int in_w = w / "+e+";\n int offset_w = imod(w, "+e+");\n int offset_d = (offset_h * "+e+" + offset_w) *\n "+this.getOutputDepthSize()+";\n int in_d = d + offset_d;\n\n float result = "+this.getInputSamplingString()+";\n setOutput(result);\n }\n "}return t.prototype.getHeightCoordString=function(){return"NHWC"===this.dataFormat?"coords[1]":"coords[2]"},t.prototype.getWidthCoordString=function(){return"NHWC"===this.dataFormat?"coords[2]":"coords[3]"},t.prototype.getDepthCoordString=function(){return"NHWC"===this.dataFormat?"coords[3]":"coords[1]"},t.prototype.getOutputDepthSize=function(){return"NHWC"===this.dataFormat?this.outputShape[3]:this.outputShape[1]},t.prototype.getInputSamplingString=function(){return"NHWC"===this.dataFormat?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"},t}(),ei=function(t){this.variableNames=["A"];var e=so();this.outputShape=t,this.userCode="\n "+lo+"\n\n void main() {\n float x = getAAtOutCoords();\n "+e.output+" = encode_float(x);\n }\n "},ni=function(t){this.variableNames=["A"],this.usesPackedTextures=!0;var e=so();this.outputShape=t,this.userCode="\n "+lo+"\n\n void main() {\n ivec3 coords = getOutputCoords();\n float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));\n "+e.output+" = encode_float(x);\n }\n "},ri=function(t,e,n){void 0===n&&(n=!1),this.variableNames=["A"];var r=so(),o=e[0],i=e[1];this.outputShape=t;var a="result";n&&(a="floor(result * 255. + 0.5)"),this.userCode="\n "+co(t)+"\n\n void main() {\n ivec3 coords = getOutputCoords();\n\n int flatIndex = getFlatIndex(coords);\n int offset = imod(flatIndex, 4);\n\n flatIndex /= 4;\n int r = flatIndex / "+i+";\n int c = imod(flatIndex, "+i+");\n vec2 uv = (vec2(c, r) + halfCR) / vec2("+i+".0, "+o+".0);\n vec4 values = "+r.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 "+r.output+" = vec4("+a+", 0., 0., 0.);\n }\n "},oi=function(t,e,n){void 0===n&&(n=!1),this.variableNames=["A"];var r=so(),o=e[0],i=e[1];this.outputShape=t;var a="",s="result";n&&(s="floor(result * 255. + 0.5)");for(var u=0;u<=1;u++)for(var c=0;c<=1;c++){var l=2*u+c;a+="\n localCoords = coords;\n if(localCoords[2] + "+c+" < "+t[2]+") {\n localCoords[2] += "+c+";\n if(localCoords[1] + "+u+" < "+t[1]+") {\n localCoords[1] += "+u+";\n\n flatIndex = getFlatIndex(localCoords);\n offset = imod(flatIndex, 4);\n \n flatIndex /= 4;\n r = flatIndex / "+i+";\n c = imod(flatIndex, "+i+");\n uv = (vec2(c, r) + halfCR) / vec2("+i+".0, "+o+".0);\n values = "+r.texture2D+"(A, uv);\n\n if(offset == 0) {\n result["+l+"] = values[0];\n } else if(offset == 1) {\n result["+l+"] = values[1];\n } else if(offset == 2) {\n result["+l+"] = values[2];\n } else {\n result["+l+"] = values[3];\n }\n }\n }\n "}this.userCode="\n "+co(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 "+a+"\n\n "+r.output+" = "+s+";\n }\n "},ii=function(t,e,n){this.variableNames=["real","imag"];var r=e[1];this.outputShape=e;var o=n?"2.0 * "+Math.PI:"-2.0 * "+Math.PI,i=n?r+".0":"1.0";this.userCode="\n const float exponentMultiplier = "+o+";\n\n float unaryOpComplex(float real, float expR, float imag, float expI) {\n "+t+"\n }\n\n float mulMatDFT(int batch, int index) {\n float indexRatio = float(index) / float("+r+");\n float exponentMultiplierTimesIndexRatio =\n exponentMultiplier * indexRatio;\n\n float result = 0.0;\n\n for (int i = 0; i < "+r+"; i++) {\n // x = (-2|2 * PI / N) * index * i;\n float x = exponentMultiplierTimesIndexRatio * float(i);\n float expR = cos(x);\n float expI = sin(x);\n float real = getReal(batch, i);\n float imag = getImag(batch, i);\n\n result +=\n unaryOpComplex(real, expR, imag, expI) / "+i+";\n }\n\n return result;\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n setOutput(mulMatDFT(coords[0], coords[1]));\n }\n "},ai=function(){function t(t,e){this.outputShape=[],this.variableNames=["x"],this.outputShape=t,this.userCode="\n uniform float value;\n void main() {\n // Input can be obtained from uniform value.\n setOutput(value);\n }\n "}return t.prototype.getCustomSetupFunc=function(t){var e=this;return function(n,r){null==e.valueLoc&&(e.valueLoc=n.getUniformLocationNoThrow(r,"value")),n.gl.uniform1f(e.valueLoc,t)}},t}(),si=function(t){this.variableNames=["A"];var e=so(),n=t[0],r=t[1];this.outputShape=t,this.userCode="\n void main() {\n ivec3 coords = getOutputCoords();\n int texR = coords[0];\n int texC = coords[1];\n int depth = coords[2];\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2("+r+".0, "+n+".0);\n\n vec4 values = "+e.texture2D+"(A, uv);\n float value;\n if (depth == 0) {\n value = values.r;\n } else if (depth == 1) {\n value = values.g;\n } else if (depth == 2) {\n value = values.b;\n } else if (depth == 3) {\n value = values.a;\n }\n\n setOutput(floor(value * 255.0 + 0.5));\n }\n "},ui=function(t){this.variableNames=["A"];var e=so(),n=t[0],r=t[1];this.outputShape=t,this.userCode="\n void main() {\n ivec3 coords = getOutputCoords();\n int texR = coords[0];\n int texC = coords[1];\n int depth = coords[2];\n\n vec4 result = vec4(0.);\n\n for(int row=0; row<=1; row++) {\n for(int col=0; col<=1; col++) {\n texC = coords[1] + row;\n depth = coords[2] + col;\n\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2("+r+".0, "+n+".0);\n vec4 values = "+e.texture2D+"(A, uv);\n float value;\n if (depth == 0) {\n value = values.r;\n } else if (depth == 1) {\n value = values.g;\n } else if (depth == 2) {\n value = values.b;\n } else if (depth == 3) {\n value = values.a;\n }\n\n result[row * 2 + col] = floor(value * 255.0 + 0.5);\n }\n }\n\n "+e.output+" = result;\n }\n "},ci=function(t,e,n){this.variableNames=["A","indices"];var r=t.slice();r[n]=e,this.outputShape=r,this.rank=r.length;var o=xo(this.rank),i=function(t,e){var n=t.length;if(n>4)throw Error("Gather for rank "+n+" is not yet supported");if(1===n)return"int(getIndices(resRC))";for(var r=["resRC.x","resRC.y","resRC.z","resRC.w"],o=[],i=0;i1?"strides[j]":"strides";this.userCode="\n "+r+" strides = "+r+"("+this.strides+");\n void main() {\n "+o+" 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 * "+i+";\n }\n setOutput(getX(flattenIndex, coords[1]));\n }\n "};function hi(t,e){return[e,t]}function pi(t){var e=_(t);return N(Math.ceil(e/4))}function fi(t,e){return[Math.max(1,Math.ceil(e/2)),Math.max(1,Math.ceil(t/2))]}function di(t,e){var n=so();return qt(t,e,n.version+"\n precision highp float;\n "+n.attribute+" vec3 clipSpacePos;\n "+n.attribute+" vec2 uv;\n "+n.varyingVs+" vec2 resultUV;\n\n void main() {\n gl_Position = vec4(clipSpacePos, 1);\n resultUV = uv;\n }")}function vi(t,e){return te(t,e,new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]))}function mi(t,e){return ee(t,e,new Uint16Array([0,1,2,2,1,3]))}function gi(t,e){var n,r,o,i,a,s,u,c,l=t;return 2===f.getNumber("WEBGL_VERSION")?(n=l.R32F,r=l.R16F,o=l.RGBA16F,i=l.RGBA32F,a=l.RED,s=4,u=1,c=l.HALF_FLOAT):(n=t.RGBA,r=t.RGBA,o=t.RGBA,i=l.RGBA,a=t.RGBA,s=4,u=4,c=null!=e?e.HALF_FLOAT_OES:null),{internalFormatFloat:n,internalFormatHalfFloat:r,internalFormatPackedHalfFloat:o,internalFormatPackedFloat:i,textureFormatFloat:a,downloadTextureFormat:t.RGBA,downloadUnpackNumChannels:s,defaultNumChannels:u,textureTypeHalfFloat:c}}function yi(t,e,n,r,o,i,a){re(n,r);var s=ne(t,e),u=t.TEXTURE_2D;return zt(t,e,function(){return t.bindTexture(u,s)}),zt(t,e,function(){return t.texParameteri(u,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE)}),zt(t,e,function(){return t.texParameteri(u,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE)}),zt(t,e,function(){return t.texParameteri(u,t.TEXTURE_MIN_FILTER,t.NEAREST)}),zt(t,e,function(){return t.texParameteri(u,t.TEXTURE_MAG_FILTER,t.NEAREST)}),zt(t,e,function(){return t.texImage2D(u,0,o,n,r,0,i,a,null)}),zt(t,e,function(){return t.bindTexture(t.TEXTURE_2D,null)}),s}function xi(t,e,n,r,o){var i=hi(n,r);return yi(t,e,i[0],i[1],o.internalFormatFloat,o.textureFormatFloat,t.FLOAT)}function bi(t,e,n,r,o){var i=hi(n,r);return yi(t,e,i[0],i[1],o.internalFormatHalfFloat,o.textureFormatFloat,o.textureTypeHalfFloat)}function wi(t,e,n,r,o){var i=hi(n,r);return yi(t,e,i[0],i[1],t.RGBA,t.RGBA,t.UNSIGNED_BYTE)}function Ci(t,e,n,r,o){var i=fi(n,r);return yi(t,e,i[0],i[1],o.internalFormatPackedFloat,t.RGBA,t.FLOAT)}function Ei(t,e,n,r,o){var i=fi(n,r);return yi(t,e,i[0],i[1],o.internalFormatPackedHalfFloat,t.RGBA,o.textureTypeHalfFloat)}function _i(t,e,n,r){return zt(t,e,function(){return t.bindBuffer(t.ARRAY_BUFFER,r)}),ie(t,e,n,"clipSpacePos",r,3,20,0)&&ie(t,e,n,"uv",r,2,20,12)}function Ii(t,e,n,r,o,i,a){var s,u,c;zt(t,e,function(){return t.bindTexture(t.TEXTURE_2D,n)}),i instanceof Uint8Array?(s=new Uint8Array(r*o*4),u=t.UNSIGNED_BYTE,c=t.RGBA):(s=new Float32Array(r*o*4),u=t.FLOAT,c=a.internalFormatPackedFloat),s.set(i),zt(t,e,function(){return t.texImage2D(t.TEXTURE_2D,0,c,r,o,0,t.RGBA,u,s)}),zt(t,e,function(){return t.bindTexture(t.TEXTURE_2D,null)})}function Si(t,e,n,r){zt(t,e,function(){return t.bindTexture(t.TEXTURE_2D,n)}),r.data instanceof Uint8Array?zt(t,e,function(){return t.texImage2D(t.TEXTURE_2D,0,t.RGBA,r.width,r.height,0,t.RGBA,t.UNSIGNED_BYTE,r.data)}):zt(t,e,function(){return t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,r)}),zt(t,e,function(){return t.bindTexture(t.TEXTURE_2D,null)})}function Ri(t,e,n,r,o){var i=t.createBuffer();zt(t,e,function(){return t.bindBuffer(t.PIXEL_PACK_BUFFER,i)});var a=16*n*r;return zt(t,e,function(){return t.bufferData(t.PIXEL_PACK_BUFFER,a,t.STREAM_READ)}),zt(t,e,function(){return t.readPixels(0,0,r,n,t.RGBA,t.FLOAT,0)}),zt(t,e,function(){return t.bindBuffer(t.PIXEL_PACK_BUFFER,null)}),i}function Ni(t,e,n){var r=t,o=new Float32Array(n);return r.bindBuffer(r.PIXEL_PACK_BUFFER,e),r.getBufferSubData(r.PIXEL_PACK_BUFFER,0,o),r.bindBuffer(r.PIXEL_PACK_BUFFER,null),o}function ki(t,e,n,r,o){var i=hi(n,r),a=i[0],s=i[1],u=new Uint8Array(n*r*4);return zt(t,e,function(){return t.readPixels(0,0,a,s,o.downloadTextureFormat,t.UNSIGNED_BYTE,u)}),new Float32Array(u.buffer)}function Ai(t,e,n,r,o,i,a,s){var u=t,c=new Float32Array(function(t,e){var n=fi(i,a);return n[0]*n[1]*4}());return u.bindBuffer(u.PIXEL_PACK_BUFFER,e),u.getBufferSubData(u.PIXEL_PACK_BUFFER,0,c),u.bindBuffer(u.PIXEL_PACK_BUFFER,null),c}function Ti(t,e,n,r){var o=new Float32Array(n*r*4);return zt(t,e,function(){return t.readPixels(0,0,r,n,t.RGBA,t.FLOAT,o)}),o}!function(t){t[t.RENDER=0]="RENDER",t[t.UPLOAD=1]="UPLOAD",t[t.PIXELS=2]="PIXELS",t[t.DOWNLOAD=3]="DOWNLOAD"}(Yo||(Yo={})),function(t){t[t.UNPACKED_FLOAT16=0]="UNPACKED_FLOAT16",t[t.UNPACKED_FLOAT32=1]="UNPACKED_FLOAT32",t[t.PACKED_4X1_UNSIGNED_BYTE=2]="PACKED_4X1_UNSIGNED_BYTE",t[t.PACKED_2X2_FLOAT32=3]="PACKED_2X2_FLOAT32",t[t.PACKED_2X2_FLOAT16=4]="PACKED_2X2_FLOAT16"}(Qo||(Qo={}));var Di=Object.freeze({createVertexShader:di,createVertexBuffer:vi,createIndexBuffer:mi,getTextureConfig:gi,createFloat32MatrixTexture:xi,createFloat16MatrixTexture:bi,createUnsignedBytesMatrixTexture:wi,createPackedMatrixTexture:Ci,createFloat16PackedMatrixTexture:Ei,bindVertexProgramAttributeStreams:_i,uploadDenseMatrixToTexture:Ii,uploadPixelDataToTexture:Si,createBufferFromOutputTexture:Ri,downloadFloat32MatrixFromBuffer:Ni,downloadByteEncodedFloatMatrixFromOutputTexture:ki,downloadPackedMatrixFromBuffer:Ai,downloadMatrixFromPackedOutputTexture:Ti}),Fi=function(){function t(t){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];var e=f.getNumber("WEBGL_VERSION");null!=t?(this.gl=t,Lt(e,t)):this.gl=Wt(e),1===f.getNumber("WEBGL_VERSION")?(this.textureFloatExtension=Ht(this.gl,this.debug,"OES_texture_float"),this.colorBufferFloatExtension=this.gl.getExtension("WEBGL_color_buffer_float"),f.getBool("WEBGL_RENDER_FLOAT32_ENABLED")||(this.textureHalfFloatExtension=Ht(this.gl,this.debug,"OES_texture_half_float"),this.colorBufferHalfFloatExtension=this.gl.getExtension("EXT_color_buffer_half_float"))):this.colorBufferFloatExtension=Ht(this.gl,this.debug,"EXT_color_buffer_float"),this.vertexBuffer=vi(this.gl,this.debug),this.indexBuffer=mi(this.gl,this.debug),this.framebuffer=oe(this.gl,this.debug),this.textureConfig=gi(this.gl,this.textureHalfFloatExtension)}return Object.defineProperty(t.prototype,"debug",{get:function(){return f.getBool("DEBUG")},enumerable:!0,configurable:!0}),t.prototype.dispose=function(){var t=this;if(!this.disposed){null!=this.program&&console.warn("Disposing a GPGPUContext that still has a bound WebGLProgram. This is probably a resource leak, delete the program with GPGPUContext.deleteProgram before disposing."),null!=this.outputTexture&&console.warn("Disposing a GPGPUContext that still has a bound output matrix texture. This is probably a resource leak, delete the output matrix texture with GPGPUContext.deleteMatrixTexture before disposing.");var e=this.gl;zt(e,this.debug,function(){return e.finish()}),zt(e,this.debug,function(){return e.bindFramebuffer(e.FRAMEBUFFER,null)}),zt(e,this.debug,function(){return e.deleteFramebuffer(t.framebuffer)}),zt(e,this.debug,function(){return e.bindBuffer(e.ARRAY_BUFFER,null)}),zt(e,this.debug,function(){return e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)}),zt(e,this.debug,function(){return e.deleteBuffer(t.indexBuffer)}),this.disposed=!0}},t.prototype.createFloat32MatrixTexture=function(t,e){return this.throwIfDisposed(),xi(this.gl,this.debug,t,e,this.textureConfig)},t.prototype.createFloat16MatrixTexture=function(t,e){return this.throwIfDisposed(),bi(this.gl,this.debug,t,e,this.textureConfig)},t.prototype.createUnsignedBytesMatrixTexture=function(t,e){return this.throwIfDisposed(),wi(this.gl,this.debug,t,e,this.textureConfig)},t.prototype.uploadPixelDataToTexture=function(t,e){this.throwIfDisposed(),Si(this.gl,this.debug,t,e)},t.prototype.uploadDenseMatrixToTexture=function(t,e,n,r){this.throwIfDisposed(),Ii(this.gl,this.debug,t,e,n,r,this.textureConfig)},t.prototype.createFloat16PackedMatrixTexture=function(t,e){return this.throwIfDisposed(),Ei(this.gl,this.debug,t,e,this.textureConfig)},t.prototype.createPackedMatrixTexture=function(t,e){return this.throwIfDisposed(),Ci(this.gl,this.debug,t,e,this.textureConfig)},t.prototype.deleteMatrixTexture=function(t){var e=this;this.throwIfDisposed(),this.outputTexture===t&&(he(this.gl,this.debug,this.framebuffer),this.outputTexture=null),zt(this.gl,this.debug,function(){return e.gl.deleteTexture(t)})},t.prototype.downloadByteEncodedFloatMatrixFromOutputTexture=function(t,e,n){var r=this;return this.downloadMatrixDriver(t,function(){return ki(r.gl,r.debug,e,n,r.textureConfig)})},t.prototype.downloadPackedMatrixFromBuffer=function(t,e,n,r,o,i){return Ai(this.gl,t,0,0,0,o,i,this.textureConfig)},t.prototype.downloadFloat32MatrixFromBuffer=function(t,e){return Ni(this.gl,t,e)},t.prototype.createBufferFromTexture=function(t,e,n){this.bindTextureToFrameBuffer(t);var r=Ri(this.gl,this.debug,e,n,this.textureConfig);return this.unbindTextureToFrameBuffer(),r},t.prototype.createAndWaitForFence=function(){var t=this.createFence(this.gl);return this.pollFence(t)},t.prototype.createFence=function(t){var e,n,r=this;if(f.getBool("WEBGL_FENCE_API_ENABLED")){var o=t,i=o.fenceSync(o.SYNC_GPU_COMMANDS_COMPLETE,0);t.flush(),n=function(){var t=o.clientWaitSync(i,0,0);return t===o.ALREADY_SIGNALED||t===o.CONDITION_SATISFIED},e=i}else f.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(e=this.beginQuery(),this.endQuery(),n=function(){return r.isQueryAvailable(e,f.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}):n=function(){return!0};return{query:e,isFencePassed:n}},t.prototype.downloadMatrixFromPackedTexture=function(t,e,n){var r=this;return this.downloadMatrixDriver(t,function(){return Ti(r.gl,r.debug,e,n)})},t.prototype.createProgram=function(t){this.throwIfDisposed();var e=this.gl,n=$t(e,this.debug,t),r=di(e,this.debug),o=Qt(e,this.debug);return zt(e,this.debug,function(){return e.attachShader(o,r)}),zt(e,this.debug,function(){return e.attachShader(o,n)}),Jt(e,this.debug,o),this.debug&&Zt(e,this.debug,o),this.vertexAttrsAreBound||(this.setProgram(o),this.vertexAttrsAreBound=_i(e,this.debug,this.program,this.vertexBuffer)),o},t.prototype.deleteProgram=function(t){var e=this;this.throwIfDisposed(),t===this.program&&(this.program=null),null!=t&&zt(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&&Zt(this.gl,this.debug,this.program),zt(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?se(this.gl,this.debug,t,e):ue(this.gl,t,e)},t.prototype.getAttributeLocation=function(t,e){var n=this;return this.throwIfDisposed(),zt(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(),ce(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 r=fi(e,n),o=r[0],i=r[1];this.setOutputMatrixTextureDriver(t,o,i)},t.prototype.setOutputMatrixWriteRegion=function(t,e,n,r){this.setOutputMatrixWriteRegionDriver(n,t,r,e)},t.prototype.setOutputPackedMatrixWriteRegion=function(t,e,n,r){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")},t.prototype.debugValidate=function(){null!=this.program&&Zt(this.gl,this.debug,this.program),pe(this.gl)},t.prototype.executeProgram=function(){this.throwIfDisposed(),this.throwIfNoProgram();var t=this.gl;this.debug&&this.debugValidate(),zt(t,this.debug,function(){return t.drawElements(t.TRIANGLES,6,t.UNSIGNED_SHORT,0)})},t.prototype.blockUntilAllProgramsCompleted=function(){var t=this;this.throwIfDisposed(),zt(this.gl,this.debug,function(){return t.gl.finish()})},t.prototype.getQueryTimerExtension=function(){return null==this.disjointQueryTimerExtension&&(this.disjointQueryTimerExtension=Ht(this.gl,this.debug,2===f.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===f.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 r=this.getQueryTimerExtensionWebGL1(),o=r.createQueryEXT();return r.beginQueryEXT(r.TIME_ELAPSED_EXT,o),o},t.prototype.endQuery=function(){if(2!==f.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 c(this,void 0,void 0,function(){var e=this;return l(this,function(n){switch(n.label){case 0:return[4,A(function(){return e.disposed||e.isQueryAvailable(t,f.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))})];case 1:return n.sent(),[2,this.getQueryTime(t,f.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 r=this.getQueryTimerExtensionWebGL1();return r.getQueryObjectEXT(t,r.QUERY_RESULT_EXT)/1e6},t.prototype.isQueryAvailable=function(t,e){if(0===e)return!0;if(2===e){var n=this.gl,r=this.getQueryTimerExtensionWebGL2(),o=n.getQueryParameter(t,n.QUERY_RESULT_AVAILABLE);return null==this.disjoint&&(this.disjoint=this.gl.getParameter(r.GPU_DISJOINT_EXT)),o&&!this.disjoint}return o=(r=this.getQueryTimerExtensionWebGL1()).getQueryObjectEXT(t,r.QUERY_RESULT_AVAILABLE_EXT),null==this.disjoint&&(this.disjoint=this.gl.getParameter(r.GPU_DISJOINT_EXT)),o&&!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||A(function(){return n.pollItems(),0===n.itemsToPoll.length})},t.prototype.bindTextureToFrameBuffer=function(t){this.throwIfDisposed(),le(this.gl,this.debug,t,this.framebuffer),this.debug&&pe(this.gl)},t.prototype.unbindTextureToFrameBuffer=function(){null!=this.outputTexture?(le(this.gl,this.debug,this.outputTexture,this.framebuffer),this.debug&&pe(this.gl)):he(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 r=this.gl;le(r,this.debug,t,this.framebuffer),this.debug&&pe(r),this.outputTexture=t,zt(r,this.debug,function(){return r.viewport(0,0,e,n)}),zt(r,this.debug,function(){return r.scissor(0,0,e,n)})},t.prototype.setOutputMatrixWriteRegionDriver=function(t,e,n,r){var o=this;this.throwIfDisposed(),zt(this.gl,this.debug,function(){return o.gl.scissor(t,e,n,r)})},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 Mi(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 r=t.logicalShape,o=e[n],i=o.shape;if(!I(r,i))throw Error("Binary was compiled with different shapes than the current args. Shapes "+r+" and "+i+" must match");if(!t.isUniform||!o.isUniform){var a=t.texShape,s=o.isUniform?null:o.texData.texShape;if(!I(a,s))throw Error("Binary was compiled with different texture shapes than the current args. Shape "+a+" and "+s+" must match")}})}var Oi=function(t,e,n){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=t;var r=n.filterWidth,o=n.inChannels,i=n.strideWidth,a=n.strideHeight,s=n.padInfo,u=n.outWidth,c=n.dilationWidth,l=n.dilationHeight,h=s.left,p=s.top,f=o*r,d=so();this.userCode="\n void main() {\n ivec2 rc = getOutputCoords();\n\n vec4 result = vec4(0);\n\n for(int row=0; row<=1; row++) {\n for(int col=0; col<=1; col++) {\n int blockIndex = rc.y + col;\n int pos = rc.x + row;\n\n if(blockIndex >= "+t[1]+" || pos >= "+t[0]+") continue;\n\n int offsetY = int(blockIndex / ("+u+")) * "+a+" - "+p+";\n int d0 = offsetY + "+l+" * (pos / "+f+");\n\n if(d0 >= "+e[0]+" || d0 < 0) continue;\n\n int offsetX = int(mod(float(blockIndex), "+u+".) * "+i+". - "+h+".);\n int d1 = offsetX + "+c+" * (int(mod(float(pos), "+f+".) / "+o+".));\n\n if(d1 >= "+e[1]+" || d1 < 0) continue;\n\n vec2 innerDims = vec2(d1, int(mod(float(pos), "+o+".)));\n result[row * 2 + col] = getChannel(getA(d0, int(innerDims.x),\n int(innerDims.y)), innerDims);\n }\n }\n\n "+d.output+" = result;\n }\n "},Pi=function(t,e,n,r,o){this.variableNames=["x"],this.outputShape=[];var i,a=e,s=t[3]-1;this.outputShape=t;var u="float("+n+") + float("+r+") * sum";i=.5===o?"inversesqrt("+u+")":1===o?"1.0/("+u+")":"exp(log("+u+") * float(-"+o+"));",this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int r = coords[1];\n int c = coords[2];\n int d = coords[3];\n float x = getX(b, r, c, d);\n float sum = 0.0;\n for (int j = -"+a+"; j <= "+a+"; j++) {\n int idx = d + j;\n if (idx >= 0 && idx <= "+s+") {\n float z = getX(b, r, c, idx);\n sum += z * z;\n }\n }\n float val = x * "+i+";\n setOutput(val);\n }\n "},Bi=function(t,e,n,r,o){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=t,this.depth=t[3],this.depthRadius=e,this.bias=n,this.alpha=r,this.beta=o,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("+r+") * norm + float("+n+");\n\n for(int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k){\n if (k < depthBegin){\n continue;\n }\n else if (k >= depthBegin && k < depthEnd){\n float dyi = -2.0 * float("+r+")\n * float("+o+")\n * getInputImage(b ,r ,c, k) * getOutputImage(b, r, c, d)\n / norm;\n if (k == d) {\n dyi += pow(norm, -1.0 * "+o+");\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 "},Li=function(t,e,n,r,o){this.variableNames=["x"],this.outputShape=[],this.usesPackedTextures=!0;var i,a=e,s=t[3]-1;this.outputShape=t;var u="float("+n+") + float("+r+") * sum";i=.5===o?"inversesqrt("+u+")":1===o?"1.0/("+u+")":"exp(log("+u+") * float(-"+o+"));",this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords.x;\n int r = coords.y;\n int c = coords.z;\n int d = coords.w;\n\n bool hasNextCol = d < "+this.outputShape[3]+";\n bool hasNextRow = c < "+this.outputShape[2]+";\n\n vec4 sum = vec4(0.);\n vec4 xFragAtOutputCoords = getX(b, r, c, d);\n\n vec4 xAtOutputCoords = vec4(\n getChannel(xFragAtOutputCoords, vec2(c, d)),\n hasNextCol ?\n getChannel(xFragAtOutputCoords, vec2(c, d + 1)) : 0.0,\n hasNextRow ?\n getChannel(xFragAtOutputCoords , vec2(c + 1, d)) : 0.0,\n (hasNextRow && hasNextCol) ?\n getChannel(xFragAtOutputCoords, vec2(c + 1, d + 1)) : 0.0\n );\n\n int firstChannel = d - "+a+";\n vec2 cache = vec2(0.);\n if(firstChannel >= 0){\n vec4 firstChannelFrag = getX(b, r, c, firstChannel);\n cache.x = getChannel(firstChannelFrag, vec2(c, firstChannel));\n if(hasNextRow){\n cache.y = getChannel(firstChannelFrag, vec2(c + 1, firstChannel));\n }\n }\n\n ivec2 depth = ivec2(d, d + 1);\n for (int j = - "+a+"; j <= "+a+"; j++) {\n ivec2 idx = depth + j;\n bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));\n bvec2 belowUpperBound = lessThanEqual(idx, ivec2("+s+"));\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 * "+i+";\n setOutput(result);\n }\n "},Wi=function(t){this.variableNames=["dy","maxPos"],this.outputShape=t.inShape;var e=t.strideHeight,n=t.strideWidth,r=t.dilationHeight,o=t.effectiveFilterHeight,i=t.effectiveFilterWidth,a=o-1-t.padInfo.top,s=i-1-t.padInfo.left,u=o*i-1;this.userCode="\n const ivec2 pads = ivec2("+a+", "+s+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n\n ivec2 dyRCCorner = coords.yz - pads;\n int dyRCorner = dyRCCorner.x;\n int dyCCorner = dyRCCorner.y;\n\n // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+o+";\n wR += "+r+") {\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 < "+i+"; 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 = "+u+" - 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 * "+i+" + wC;\n float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n dotProd += dyValue * mask;\n }\n }\n setOutput(dotProd);\n }\n "},zi=function(t,e,n,r,o,i){void 0===n&&(n=!1),void 0===r&&(r=!1),void 0===o&&(o=!1),void 0===i&&(i=null),this.variableNames=["matrixA","matrixB"],this.usesPackedTextures=!0,this.outputShape=e;var a=n?t[1]:t[2],s=Math.ceil(a/2),u=n?"i * 2, rc.y":"rc.y, i * 2",c=r?"rc.z, i * 2":"i * 2, rc.z",l=n?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],h=r?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"],p="",f="";i&&(p="vec4 activation(vec4 x) {\n "+i+"\n }",f="result = activation(result);");var d=o?"result += getBiasAtOutCoords();":"";o&&this.variableNames.push("bias"),this.userCode="\n "+p+"\n\n const float sharedDimension = "+s+".0;\n\n vec4 dot2x2ARowBCol(ivec3 rc) {\n vec4 result = vec4(0);\n for (int i = 0; i < "+s+"; i++) {\n vec4 a = getMatrixA(rc.x, "+u+");\n vec4 b = getMatrixB(rc.x, "+c+");\n\n result += ("+l[0]+" * "+h[0]+") + ("+l[1]+" * "+h[1]+");\n }\n return result;\n }\n\n void main() {\n ivec3 rc = getOutputCoords();\n vec4 result = dot2x2ARowBCol(rc);\n\n "+d+"\n\n "+f+"\n\n setOutput(result);\n }\n "},Ui=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,r){null==e.seedLoc&&(e.seedLoc=n.getUniformLocation(r,"seed")),n.gl.uniform1f(e.seedLoc,t)}},t}(),Vi=function(t,e,n,r){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("+r+"), float("+n+"),\n float(index == coords.y)));\n }\n "},Gi=function(t){this.variableNames=["A"],this.outputShape=t;var e=t.length;if(0===e)this.userCode="\n void main() {\n setOutput(vec4(getA(), 0., 0., 0.));\n }\n ";else{var n=ao("rc",e),r=xo(e),o=function(t,e,n){if(1===t)return"rc > "+e[0];for(var r="",o=t-2;o= "+e[o],o= "+e+";\n bool rEdge = rp1 >= "+n+";\n "}(e,t[t.length-1],t[t.length-2],n),a=function(t,e){var n=t.length,r=function(t,e){for(var n=[],r=0;r<=1;r++)for(var o=0;o<=1;o++){for(var i=(0===r?"r":"rp1")+", "+(0===o?"c":"cp1"),a=2;a= "+t[0]+" ? 0. : getA(rc + 1),\n 0, 0":"getA("+r[0]+"),\n cEdge ? 0. : getA("+r[1]+"),\n rEdge ? 0. : getA("+r[2]+"),\n rEdge || cEdge ? 0. : getA("+r[3]+")"}(t,n);this.userCode="\n void main() {\n "+r+" rc = getOutputCoords();\n\n if("+o+") {\n setOutput(vec4(0));\n } else {\n "+i+"\n\n setOutput(vec4("+a+"));\n }\n }\n "}},ji=function(t,e,n){this.variableNames=["x"],this.outputShape=e.map(function(e,n){return e[0]+t[n]+e[1]});var r=t.length,o=xo(r),i=e.map(function(t){return t[0]}).join(","),a=e.map(function(e,n){return e[0]+t[n]}).join(","),s=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,r);this.userCode=1!==r?"\n "+o+" start = "+o+"("+i+");\n "+o+" end = "+o+"("+a+");\n\n void main() {\n "+o+" outC = getOutputCoords();\n if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {\n setOutput(float("+n+"));\n } else {\n "+o+" coords = outC - start;\n setOutput(getX("+s+"));\n }\n }\n ":"\n int start = "+i+";\n int end = "+a+";\n\n void main() {\n int outC = getOutputCoords();\n if (outC < start || outC >= end) {\n setOutput(float("+n+"));\n } else {\n setOutput(getX(outC - start));\n }\n }\n "},Hi=function(t,e,n){this.variableNames=["x"],this.usesPackedTextures=!0,this.outputShape=e.map(function(e,n){return e[0]+t[n]+e[1]});for(var r=t.length,o=xo(r),i=e.map(function(t){return t[0]}).join(","),a=e.map(function(e,n){return e[0]+t[n]}).join(","),s=ao("rc",r),u=ao("source",r),c=s[r-1]+" < "+this.outputShape[r-1],l=1===r?"source":"vec2("+u.slice(-2).join()+")",h=[o+" rc = outputLoc;",s[r-1]+" += 1;\n if("+c+") {\n ",1===r?"":"}\n rc = outputLoc;\n "+s[r-2]+" += 1;\n if("+s[r-2]+" < "+this.outputShape[r-2]+") {",1===r?"":" "+s[r-1]+" += 1;\n if("+c+") {"],p=1===r?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))",f="",d=0,v=1===r?2:4;d= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+c+";\n wC += "+s+") {\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 * "+c+" + wC;\n }\n }\n }\n setOutput(float(minMaxPosition));\n }\n ";else{var d=e+"("+e+"("+e+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"avg"===e&&(d="avgValue / count");var v=4*Math.floor(r/4),m=r%4,g="\n if ("+p+") {\n avgValue += dot(values, ones);\n } else {\n minMaxValue = max(values, minMaxValue);\n }\n ";this.userCode="\n const ivec2 strides = ivec2("+o+", "+i+");\n const ivec2 pads = ivec2("+l+", "+h+");\n const float initializationValue = "+f+";\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("+f+");\n float avgValue = 0.0;\n count = 0.0;\n\n for (int wR = 0; wR < "+u+";\n wR += "+a+") {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+v+"; wC += 4) {\n int xC = xCCorner + wC * "+s+";\n\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + "+s+", d),\n getValue(batch, xR, xC + 2 * "+s+", d),\n getValue(batch, xR, xC + 3 * "+s+", d)\n );\n\n "+g+"\n }\n\n int xC = xCCorner + "+v+";\n if ("+(1===m)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n "+g+"\n } else if ("+(2===m)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + "+s+", d),\n initializationValue,\n initializationValue\n );\n\n "+g+"\n } else if ("+(3===m)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + "+s+", d),\n getValue(batch, xR, xC + 2 * "+s+", d),\n initializationValue\n );\n\n "+g+"\n }\n }\n setOutput("+d+");\n }\n "}},$i=function(t,e){this.variableNames=["x"];var n=t.windowSize,r=t.batchSize,o=t.inSize,i=Math.ceil(o/n);this.outputShape=[r,i];var a="0.0",s="";"prod"===e?a="1.0":"min"===e?(a="1.0 / 1e-20",s="min"):"max"===e&&(a="-1.0 / 1e-20",s="max");var u=e+"("+e+"("+e+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"sum"===e?u="sumValue":"prod"===e?u="prodValue":"all"===e?u="allValue":"any"===e&&(u="anyValue");var c=4*Math.floor(n/4),l=n%4,h="\n if ("+("sum"===e)+") {\n sumValue += dot(values, ones);\n } else if ("+("prod"===e)+") {\n vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);\n prodValue *= tmp[0] * tmp[1];\n } else {\n minMaxValue = "+s+"(values, minMaxValue);\n }\n ",p="vec4";"all"===e?(a="1.0",h="\n bool reducedAllValue = all(values);\n float floatedReducedAllValue = float(reducedAllValue);\n allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);\n ",p="bvec4"):"any"===e&&(a="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 f="";o%n>0&&(f="\n if (inIdx < 0 || inIdx >= "+o+") {\n return initializationValue;\n }\n "),this.userCode="\n const float initializationValue = "+a+";\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float getValue(int batch, int inIdx) {\n "+f+"\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("+a+");\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 < "+c+"; 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 + "+c+";\n if ("+(1===l)+") {\n "+p+" values = "+p+"(\n getValue(batch, inIdx),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n "+h+"\n } else if ("+(2===l)+") {\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===l)+") {\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("+u+");\n }\n "},Ki=function(t,e){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=t;for(var n="",r=0;r<4;r++){var o="thisRC = rc;";r%2==1&&(o+="thisRC.z += 1;"),r>1&&(o+="thisRC.y += 1;"),n+="\n "+o+"\n "+(r>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["+r+"] =\n getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);\n "+(r>0?"}":"")+"\n "}this.userCode="\n \n ivec3 inputCoordsFromReshapedOutCoords(int index) {\n "+uo(["r","c","d"],e)+"\n return ivec3(r, c, d);\n }\n \n "+co(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 "},Xi=function(t,e,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=e.shape;var r=e.shape,o=r[1],i=r[2],a=t.shape,s=a[1],u=a[2],c=[n&&s>1?o-1:o,n&&u>1?i-1:i],l=[n&&s>1?s-1:s,n&&u>1?u-1:u],h=c[0]/l[0],p=c[1]/l[1],f=1/h,d=1/p,v=2*Math.ceil(f)+2,m=2*Math.ceil(d)+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("+f+");\n const float invWidthScale = float("+d+");\n\n const int winHeight = int("+v+");\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 >= "+s+") {\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 >= "+u+") {\n continue;\n }\n\n float dxR = float(dyR) * heightScale;\n int topDxRIndex = int(floor(dxR));\n int bottomDxRIndex = int(min(ceil(dxR), "+(o-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), "+(i-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 "},Yi=function(t,e,n,r){this.variableNames=["A"],this.outputShape=[];var o=t[0],i=t[1],a=t[2],s=t[3];this.outputShape=[o,e,n,s];var u=[r&&e>1?i-1:i,r&&n>1?a-1:a],c=[r&&e>1?e-1:e,r&&n>1?n-1:n];this.userCode="\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n "+u[0]/c[0]+",\n "+u[1]/c[1]+");\n const vec2 inputShapeRC = vec2("+i+".0, "+a+".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 "},Qi=function(t,e,n,r){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=[];var o=t[0],i=t[1],a=t[2],s=t[3];this.outputShape=[o,e,n,s];var u=[r&&e>1?i-1:i,r&&n>1?a-1:a],c=[r&&e>1?e-1:e,r&&n>1?n-1:n];this.userCode="\n const vec3 effectiveInputOverOutputRatioRC = vec3(\n "+u[0]/c[0]+",\n "+u[1]/c[1]+",\n "+u[1]/c[1]+");\n const vec3 inputShapeRC = vec3("+i+".0, "+a+".0,\n "+a+".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 < "+(s-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 "},Ji=function(t,e,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=e.shape;var r=e.shape,o=r[1],i=r[2],a=t.shape,s=a[1],u=a[2],c=[n&&s>1?o-1:o,n&&u>1?i-1:i],l=[n&&s>1?s-1:s,n&&u>1?u-1:u],h=c[0]/l[0],p=c[1]/l[1],f=1/h,d=1/p,v=2*Math.ceil(f)+2,m=2*Math.ceil(d)+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("+f+");\n const float invWidthScale = float("+d+");\n\n const int winHeight = int("+v+");\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 >= "+s+") {\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 >= "+u+") {\n continue;\n }\n\n float sourceFracRow =\n float("+c[0]+") *\n (float(dyR) / float("+l[0]+"));\n\n float sourceFracCol =\n float("+c[1]+") *\n (float(dyC) / float("+l[1]+"));\n\n int sourceNearestRow = int(min(\n float(int("+o+") - 1),\n "+n+" ? float(round(sourceFracRow)) :\n float(floor(sourceFracRow))));\n\n int sourceNearestCol = int(min(\n float(int("+i+") - 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 "},Zi=function(t,e,n,r){this.variableNames=["A"],this.outputShape=[];var o=t[0],i=t[1],a=t[2],s=t[3];this.outputShape=[o,e,n,s];var u=[r&&e>1?i-1:i,r&&n>1?a-1:a],c=[r&&e>1?e-1:e,r&&n>1?n-1:n],l=r?"0.5":"0.0";this.userCode="\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n "+u[0]/c[0]+",\n "+u[1]/c[1]+");\n const vec2 inputShapeRC = vec2("+i+".0, "+a+".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 + "+l+")));\n\n float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);\n\n setOutput(newValue);\n }\n "},ta=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 r=t.map(function(n,r){return function(n){return-1!==e.indexOf(n)&&1!==t[n]?t[n]+" - coords["+n+"] - 1":"coords["+n+"]"}(r)}).join(","),o=xo(n);this.userCode="\n void main() {\n "+o+" coords = getOutputCoords();\n setOutput(getX("+r+"));\n }\n "}else this.userCode="\n void main() {\n int coord = getOutputCoords();\n setOutput(getX("+t[0]+" - coord - 1));\n }\n "},ea=function(t,e){this.variableNames=["x"],this.usesPackedTextures=!0;var n=t.length;if(n>4)throw new Error("WebGL backend: Reverse of rank-"+n+" tensor is not yet supported");this.outputShape=t;var r=ao("rc",n),o=r[n-1]+" + 1 < "+this.outputShape[n-1],i=r[n-2]+" + 1 < "+this.outputShape[n-2],a=xo(n);function s(n){var r=t.map(function(r,o){return function(n,r){return-1!==e.indexOf(n)&&1!==t[n]?t[n]+" - "+r[n]+" - 1":""+r[n]}(o,n)});return"getChannel(getX("+r.join(",")+"), vec2("+r.slice(-2).join(",")+"))"}this.userCode=1===n?"\n void main(){\n int rc = getOutputCoords();\n vec4 result = vec4(0.);\n result.r = getChannel(getX("+t[0]+" - rc - 1),\n "+t[0]+" - rc - 1);\n if("+o+"){\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 "+a+" rc = getOutputCoords();\n vec4 result = vec4(0.);\n result.r = "+s(r.slice())+";\n if("+o+"){\n result.g = "+function(t){return t[n-1]="("+t[n-1]+" + 1)",s(t)}(r.slice())+";\n }\n if("+i+") {\n result.b = "+function(t){return t[n-2]="("+t[n-2]+" + 1)",s(t)}(r.slice())+";\n if("+o+") {\n result.a = "+function(t){return t[n-1]="("+t[n-1]+" + 1)",t[n-2]="("+t[n-2]+" + 1)",s(t)}(r.slice())+";\n }\n }\n setOutput(result);\n }\n "},na=function(t,e,n,r,o,i,a){this.variableNames=["updates","indices","defaultValue"],this.outputShape=i;var s=xo(o.length),u=xo(i.length),c="";1===n?c="i":2===n&&(c="i, j");var l="getIndices("+c+")",h="";1===r?h="i":2===r&&(h="i, coords[1]");var p="getUpdates("+h+")",f=e>1?"strides[j]":"strides";this.userCode="\n "+s+" strides = "+s+"("+o+");\n\n void main() {\n "+u+" 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("+l+");\n flattenedIndex += index * "+f+";\n }\n if (flattenedIndex == coords[0]) {\n sum += "+p+";\n found = true;\n }\n }\n setOutput(mix(getDefaultValue(), sum, float(found)));\n }\n "},ra=function(t,e){this.variableNames=["x","segmentIds"];var n=t.windowSize,r=t.batchSize,o=t.inSize,i=t.numSegments,a=i*Math.ceil(o/n);this.outputShape=[r,a];var s=4*Math.floor(n/4),u=n%4,c="\n sumValue += dot(values, segFilter);\n ",l="";o%n>0&&(l="\n if (inIdx < 0 || inIdx >= "+o+") {\n return initializationValue;\n }\n ");var h="";o%n>0&&(h="\n if (inIdx < 0 || inIdx >= "+o+") {\n return -1.0;\n }\n "),this.userCode="\n const float initializationValue = 0.0;\n\n float getValue(int batch, int inIdx) {\n "+l+"\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 "+i+")) * float("+n+"));\n int currentSeg = int(mod(float(outIdx), float("+i+")));\n\n float sumValue = 0.0;\n\n for (int i = 0; i < "+s+"; 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 "+c+"\n }\n\n int inIdx = inOffset + "+s+";\n if ("+(1===u)+") {\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 "+c+"\n } else if ("+(2===u)+") {\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 "+c+"\n } else if ("+(3===u)+") {\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 "+c+"\n }\n setOutput(sumValue);\n }\n "},oa=function(t,e,n){var r,o;if(this.variableNames=["c","a","b"],this.outputShape=e,n>4)throw Error("Where for rank "+n+" is not yet supported");if(1===n)o="resRC",r="resRC";else{for(var i=["resRC.x","resRC.y","resRC.z","resRC.w"],a=[],s=[],u=0;u= 1.0) {\n setOutput(getA("+o+"));\n } else {\n setOutput(getB("+o+"));\n }\n }\n "},ia=function(){function t(t){this.variableNames=["source"],this.outputShape=t,this.rank=t.length;var e,n=xo(this.rank),r="uniform int start["+this.rank+"];",o=function(t){if(1===t)return"sourceLoc";if(t<=6)return aa.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."+aa[e]+" = start["+e+"] + coords."+aa[e]+";"}).join("\n")+"\n ",this.userCode="\n "+r+"\n void main() {\n "+e+"\n setOutput(getSource("+o+"));\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,r){null==e.startLoc&&(e.startLoc=n.getUniformLocationNoThrow(r,"start"),null==e.startLoc)||n.gl.uniform1iv(e.startLoc,t)}},t}(),aa=["x","y","z","w","u","v"],sa=function(){function t(t){this.variableNames=["source"],this.usesPackedTextures=!0,this.outputShape=t,this.rank=t.length;var e=xo(this.rank),n=ao("coords",this.rank),r=ao("sourceLoc",this.rank),o=1===this.rank?"sourceLoc":"vec2("+r.slice(-2).join()+")",i="getChannel(getSource("+r.join()+"), "+o+")",a="\n result.x = "+i+";\n if (++"+n[this.rank-1]+" < "+t[this.rank-1]+") {\n ++"+r[this.rank-1]+";\n result.y = "+i+";\n --"+r[this.rank-1]+";\n }\n ",s=1===this.rank?"":"\n --"+n[this.rank-1]+";\n if (++"+n[this.rank-2]+" < "+t[this.rank-2]+") {\n ++"+r[this.rank-2]+";\n result.z = "+i+";\n if (++"+n[this.rank-1]+" < "+t[this.rank-1]+") {\n ++"+r[this.rank-1]+";\n result.w = "+i+";\n }\n }\n ",u=this.rank<=4?"sourceLoc = coords +\n "+e+"("+t.map(function(t,e){return"start["+e+"]"}).join()+");":t.map(function(t,e){return r[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 "+u+" \n vec4 result = vec4(0.);\n "+a+"\n "+s+"\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,r){null==e.startLoc&&(e.startLoc=n.getUniformLocationNoThrow(r,"start"),null==e.startLoc)||n.gl.uniform1iv(e.startLoc,t)}},t}(),ua=function(t,e,n,r){this.variableNames=["x"];var o=n.filter(function(t,e){return-1===r.indexOf(e)});this.outputShape=o;var i=n.length,a=xo(n.length),s=xo(o.length),u="";if(1===i)u="coords * strides + begin";else{var c=0;u=n.map(function(t,e){return-1===r.indexOf(e)?(c++,1===o.length?"coords * strides["+e+"] + begin["+e+"]":"coords["+(c-1)+"] * strides["+e+"] + begin["+e+"]"):"begin["+e+"]"}).join(",")}this.userCode="\n "+a+" begin = "+a+"("+t+");\n "+a+" strides = "+a+"("+e+");\n\n void main() {\n "+s+" coords = getOutputCoords();\n setOutput(getX("+u+"));\n }\n "},ca=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 r,o=la(e,n),i=ha(t,o,n);if(i in this.freeTextures||(this.freeTextures[i]=[]),i in this.usedTextures||(this.usedTextures[i]=[]),this.freeTextures[i].length>0){this.numFreeTextures--,this.numUsedTextures++,this.log();var a=this.freeTextures[i].shift();return this.usedTextures[i].push(a),a}return this.numUsedTextures++,this.log(),o===Qo.PACKED_2X2_FLOAT32?r=this.gpgpu.createPackedMatrixTexture(t[0],t[1]):o===Qo.PACKED_2X2_FLOAT16?r=this.gpgpu.createFloat16PackedMatrixTexture(t[0],t[1]):o===Qo.UNPACKED_FLOAT32?r=this.gpgpu.createFloat32MatrixTexture(t[0],t[1]):o===Qo.UNPACKED_FLOAT16?r=this.gpgpu.createFloat16MatrixTexture(t[0],t[1]):o===Qo.PACKED_4X1_UNSIGNED_BYTE&&(r=this.gpgpu.createUnsignedBytesMatrixTexture(t[0],t[1])),this.usedTextures[i].push(r),r},t.prototype.releaseTexture=function(t,e,n,r){if(null!=this.freeTextures){var o=ha(e,la(n,r),r);o in this.freeTextures||(this.freeTextures[o]=[]),this.freeTextures[o].push(t),this.numFreeTextures++,this.numUsedTextures--;var i=this.usedTextures[o],a=i.indexOf(t);if(a<0)throw new Error("Cannot release a texture that was never provided by this texture manager");i.splice(a,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 la(t,e){if(t===Yo.UPLOAD)return Qo.PACKED_2X2_FLOAT32;if(t===Yo.RENDER||null==t)return e?f.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?Qo.PACKED_2X2_FLOAT32:Qo.PACKED_2X2_FLOAT16:f.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?Qo.UNPACKED_FLOAT32:Qo.UNPACKED_FLOAT16;if(t===Yo.DOWNLOAD||t===Yo.PIXELS)return Qo.PACKED_4X1_UNSIGNED_BYTE;throw new Error("Unknown logical texture type "+t)}function ha(t,e,n){return t[0]+"_"+t[1]+"_"+e+"_"+n}var pa=function(t,e){this.variableNames=["A"];for(var n=new Array(t.length),r=0;r5)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"],r=[],o=0;o6)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"],r=new Array(e),o=0;o6)throw Error("Packed transpose for rank "+this.rank+" is not yet supported.");var o=xo(this.rank),i=io("rc",this.rank),a=new Array(this.rank);for(r=0;r0?this.gpgpu.beginQuery():{startMs:performance.now(),endMs:null}},t.prototype.endTimer=function(t){return f.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(this.gpgpu.endQuery(),t):(t.endMs=performance.now(),t)},t.prototype.getQueryTime=function(t){return c(this,void 0,void 0,function(){var e;return l(this,function(n){return f.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?[2,this.gpgpu.waitForQueryAndGetTime(t)]:[2,(e=t).endMs-e.startMs]})})},t.prototype.disposeData=function(t){if(!this.pendingDisposal.has(t))if(this.pendingRead.has(t))this.pendingDisposal.add(t);else 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)}},t.prototype.releaseGPUData=function(t){var e=this.texData.get(t),n=e.texture,r=e.dtype,o=e.texShape,i=e.usage,a=e.isPacked,s=e.slice,u=s&&s.origDataId||t,c=this.dataRefCount.get(u);c>1?this.dataRefCount.set(u,c-1):(this.dataRefCount.delete(u),null!=n&&(this.numBytesInGPU-=this.computeBytes(o,r),this.textureManager.releaseTexture(n,o,i,a)));var l=this.texData.get(t);l.texture=null,l.texShape=null,l.isPacked=!1,l.slice=null},t.prototype.getTexture=function(t){return this.uploadToGPU(t),this.texData.get(t).texture},t.prototype.getCPUBackend=function(){return f.getBool("WEBGL_CPU_FORWARD")?(null==this.cpuBackend&&(this.cpuBackend=Mt.findBackend("cpu")),this.cpuBackend):null},t.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.sizef.getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){var n=Math.floor(t.length/2),r=this.concat(t.slice(0,n),e),o=this.concat(t.slice(n),e);return this.concat([r,o],e)}if(f.getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&t[0].rank>1){var i=new Po(t.map(function(t){return t.shape}),e);return this.compileAndRun(i,t)}var a=Ye(t.map(function(t){return t.shape}),e),s=t.map(function(t){return t.as2D(-1,_(t.shape.slice(e)))}),u=new Oo(s.map(function(t){return t.shape}));return this.compileAndRun(u,s).reshape(a)},t.prototype.neg=function(t){var e=new ga(t.shape,"return -x;");return this.compileAndRun(e,[t])},t.prototype.batchMatMul=function(t,e,n,r){var o=n?t.shape[2]:t.shape[1],i=r?e.shape[1]:e.shape[2],a=n?t.shape[1]:t.shape[2],s=t.shape[0];if((1===o||1===i)&&a>1e3){n&&(t=t.transpose([0,2,1])),r&&(e=e.transpose([0,2,1]));var u=1===i?t:t.as3D(s,a,1),c=1===i?2:1,l=1===i?e.as3D(s,1,a):e;return this.multiply(u,l).sum(c,!0)}var h=It(t.dtype,e.dtype),p=new zi(t.shape,[s,o,i],n,r),f=this.makePackedTensor(p.outputShape,h);return this.compileAndRun(p,[t,e],f)},t.prototype.fusedBatchMatMul=function(t,e,n,r,o,i){var a=n?t.shape[2]:t.shape[1],s=r?e.shape[1]:e.shape[2],u=t.shape[0],c=It(t.dtype,e.dtype),l=new zi(t.shape,[u,a,s],n,r,!!o,i?function(t,e){if(void 0===e&&(e=!1),"linear"===i)return"return x;";if("relu"===i)return e?wa:xa;throw new Error("Activation "+i+" has not been implemented for the WebGL backend.")}(0,!0):null),h=this.makePackedTensor(l.outputShape,c),p=[t,e];return o&&p.push(o),this.compileAndRun(l,p,h)},t.prototype.multiply=function(t,e){if("complex64"===t.dtype){var n=this.texData.get(t.dataId),r=this.texData.get(e.dataId),o=new So("return areal * breal - aimag * bimag;",t.shape,e.shape),i=new So("return areal * bimag + aimag * breal;",t.shape,e.shape),a=[this.makeComplexComponentTensorHandle(t,n.complexTensors.real),this.makeComplexComponentTensorHandle(t,n.complexTensors.imag),this.makeComplexComponentTensorHandle(e,r.complexTensors.real),this.makeComplexComponentTensorHandle(e,r.complexTensors.imag)],s=this.compileAndRun(o,a),u=this.compileAndRun(i,a),c=this.complex(s,u);return s.dispose(),u.dispose(),c}if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.multiply(t,e);if(f.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,ko,t.dtype);var l=new Ao(ko,t.shape,e.shape),h=this.makeOutputArray(l.outputShape,t.dtype);return this.compileAndRun(l,[t,e],h)},t.prototype.batchNormalization=function(t,e,n,r,o,i){var a=[t,e,n],s=null;null!=i&&(s=i.shape,a.push(i));var u=null;if(null!=o&&(u=o.shape,a.push(o)),f.getBool("WEBGL_PACK_NORMALIZATION")){var c=new Io(t.shape,e.shape,n.shape,s,u,r);return this.compileAndRun(c,a)}var l=new _o(t.shape,e.shape,n.shape,s,u,r);return this.compileAndRun(l,a)},t.prototype.localResponseNormalization4D=function(t,e,n,r,o){var i=f.getBool("WEBGL_PACK_NORMALIZATION")?new Li(t.shape,e,n,r,o):new Pi(t.shape,e,n,r,o);return this.compileAndRun(i,[t])},t.prototype.LRNGrad=function(t,e,n,r,o,i,a){var s=new Bi(e.shape,r,o,i,a);return this.compileAndRun(s,[e,n,t])},t.prototype.tile=function(t,e){if("string"===t.dtype)return Zr(On(t.shape,t.dtype,this.readSync(t.dataId)),e);var n=new pa(t.shape,e);return this.compileAndRun(n,[t])},t.prototype.pad=function(t,e,n){var r=f.getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Hi(t.shape,e,n):new ji(t.shape,e,n);return this.compileAndRun(r,[t])},t.prototype.transpose=function(t,e){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.transpose(t,e);var n=f.getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new da(t.shape,e):new fa(t.shape,e);return this.compileAndRun(n,[t])},t.prototype.gather=function(t,e,n){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.gather(t,e,n);var r=new ci(t.shape,e.size,n);return this.compileAndRun(r,[t,e])},t.prototype.batchToSpaceND=function(t,e,n){b(t.rank<=4,function(){return"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet"});var r=e.reduce(function(t,e){return t*e}),o=ur(t.shape,e,r),i=cr(o.length,e.length),a=lr(t.shape,e,r),s=hr(n,e.length),u=pr(a,n,e.length);return t.reshape(o).transpose(i).reshape(a).slice(s,u)},t.prototype.spaceToBatchND=function(t,e,n){b(t.rank<=4,function(){return"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet"});var r=e.reduce(function(t,e){return t*e}),o=[[0,0]];o.push.apply(o,n);for(var i=1+e.length;ie||n===t?r=!0:n=K(t,n+1);return n}(a,o),u=new ra({windowSize:s,inSize:a,batchSize:i,numSegments:o},e),c=u.outputShape,l=c[0],h=c[1],p=this.makeOutputArray([l,h],r);return this.compileAndRun(u,[t,n],p),p.shape[1]===o?p:(n=vn(0,o).tile([a/s]),this.segOpCompute(p,e,n,r,o))},t.prototype.argMinMaxReduce=function(t,e,n){var r=[e];if(He("arg"+n.charAt(0).toUpperCase()+n.slice(1),r,t.rank),!f.getBool("WEBGL_PACK_REDUCE")||t.rank<=2){var o=Ge(t.shape,r),i=o[0],a=_(o[1]),s=t.as2D(-1,a);return this.argReduce(s,n).reshape(i)}return this.argReducePacked(t,n)},t.prototype.argMin=function(t,e){return this.argMinMaxReduce(t,e,"min")},t.prototype.argMax=function(t,e){return this.argMinMaxReduce(t,e,"max")},t.prototype.cumsum=function(t,e,n,r){if(e!==t.rank-1)throw new Error("WebGL cumsum shader expects an inner-most axis="+(t.rank-1)+" but got axis="+e);var o=new Ko(t.shape,n,r);return this.compileAndRun(o,[t])},t.prototype.equal=function(t,e){if(f.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(equal(a, b));\n","bool");var n=new Ao("return float(a == b);",t.shape,e.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[t,e],r)},t.prototype.notEqual=function(t,e){if(f.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(notEqual(a, b));\n","bool");var n=new Ao("return float(a != b);",t.shape,e.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[t,e],r)},t.prototype.less=function(t,e){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.less(t,e);if(f.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(lessThan(a, b));\n","bool");var n=new Ao("return float(a < b);",t.shape,e.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[t,e],r)},t.prototype.lessEqual=function(t,e){if(f.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(lessThanEqual(a, b));\n","bool");var n=new Ao("return float(a <= b);",t.shape,e.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[t,e],r)},t.prototype.greater=function(t,e){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.greater(t,e);if(f.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(greaterThan(a, b));\n","bool");var n=new Ao("return float(a > b);",t.shape,e.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[t,e],r)},t.prototype.greaterEqual=function(t,e){if(f.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(greaterThanEqual(a, b));\n","bool");var n=new Ao("return float(a >= b);",t.shape,e.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[t,e],r)},t.prototype.logicalNot=function(t){var e=new ga(t.shape,"return float(!(x >= 1.0));");return this.compileAndRun(e,[t])},t.prototype.logicalAnd=function(t,e){if(f.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 Ao("return float(a >= 1.0 && b >= 1.0);",t.shape,e.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[t,e],r)},t.prototype.logicalOr=function(t,e){if(f.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 Ao("return float(a >= 1.0 || b >= 1.0);",t.shape,e.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[t,e],r)},t.prototype.select=function(t,e,n){var r=new oa(t.rank,e.shape,e.rank),o=this.makeOutputArray(r.outputShape,It(e.dtype,n.dtype));return this.compileAndRun(r,[t,e,n],o)},t.prototype.where=function(t){Pe("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");var e=t.dataSync();return eo(t.shape,e)},t.prototype.topk=function(t,e,n){return to(t.dataSync(),t.shape,t.dtype,e)},t.prototype.min=function(t,e){He("min",e,t.rank);var n=Ge(t.shape,e),r=n[0],o=_(n[1]),i=t.as2D(-1,o);return this.reduce(i,"min",i.dtype).reshape(r)},t.prototype.minimum=function(t,e){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.minimum(t,e);var n=f.getBool("WEBGL_PACK_BINARY_OPERATIONS")?new To("\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 Ao("\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])},t.prototype.mod=function(t,e){var n=f.getBool("WEBGL_PACK_BINARY_OPERATIONS")?new To("\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 Ao("if (b == 0.0) return NAN;\n return mod(a, b);",t.shape,e.shape);return this.compileAndRun(n,[t,e])},t.prototype.max=function(t,e){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.max(t,e);He("max",e,t.rank);var n=Ge(t.shape,e),r=n[0],o=_(n[1]),i=t.as2D(-1,o);return this.reduce(i,"max",i.dtype).reshape(r)},t.prototype.maximum=function(t,e){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.maximum(t,e);var n=f.getBool("WEBGL_PACK_BINARY_OPERATIONS")?new To("\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 Ao("\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])},t.prototype.all=function(t,e){He("all",e,t.rank);var n=Ge(t.shape,e),r=n[0],o=_(n[1]),i=t.as2D(-1,o);return this.reduce(i,"all",i.dtype).reshape(r)},t.prototype.any=function(t,e){He("any",e,t.rank);var n=Ge(t.shape,e),r=n[0],o=_(n[1]),i=t.as2D(-1,o);return this.reduce(i,"any",i.dtype).reshape(r)},t.prototype.squaredDifference=function(t,e){var n=f.getBool("WEBGL_PACK_BINARY_OPERATIONS")?new To("return (a - b) * (a - b);",t.shape,e.shape):new Ao("return (a - b) * (a - b);",t.shape,e.shape);return this.compileAndRun(n,[t,e])},t.prototype.realDivide=function(t,e){if(f.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(b.x == 0.0) {\n result.x = NAN;\n } else if(a.x == b.x) {\n result.x = 1.;\n }\n if(b.y == 0.0) {\n result.y = NAN;\n } else if(a.y == b.y) {\n result.y = 1.;\n }\n if(b.z == 0.0) {\n result.z = NAN;\n } else if(a.z == b.z) {\n result.z = 1.;\n }\n if(b.w == 0.0) {\n result.w = NAN;\n } else if(a.w == b.w) {\n result.w = 1.;\n }\n \n return result;\n","float32",!0);var n=new Ao("\nif (b == 0.0) {\n return NAN;\n} \nif (a == b) {\n return 1.0;\n};\nreturn a / b;",t.shape,e.shape),r=this.makeOutputArray(n.outputShape,"float32");return this.compileAndRun(n,[t,e],r)},t.prototype.floorDiv=function(t,e){if(f.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 Ao("\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),r=this.makeOutputArray(n.outputShape,"int32");return this.compileAndRun(n,[t,e],r)},t.prototype.add=function(t,e){if("complex64"===t.dtype&&"complex64"===e.dtype)return this.complexSeparableBinaryOp(t,e,Ro);if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.add(t,e);var n=It(t.dtype,e.dtype);if(f.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,Ro,n);var r=new Ao(Ro,t.shape,e.shape),o=this.makeOutputArray(r.outputShape,n);return this.compileAndRun(r,[t,e],o)},t.prototype.packedBinaryOp=function(t,e,n,r,o){void 0===o&&(o=!1);var i=new To(n,t.shape,e.shape,o),a=this.makePackedTensor(i.outputShape,r);return this.compileAndRun(i,[t,e],a)},t.prototype.complexSeparableBinaryOp=function(t,e,n){var r=this,o=this.texData.get(t.dataId),i=this.texData.get(e.dataId),a=[[o.complexTensors.real,i.complexTensors.real],[o.complexTensors.imag,i.complexTensors.imag]].map(function(o){var i=o[0],a=o[1],s=r.makeComplexComponentTensorHandle(t,i),u=r.makeComplexComponentTensorHandle(e,a),c=new Ao(n,t.shape,e.shape),l=r.makeOutputArray(c.outputShape,It(i.dtype,a.dtype));return r.compileAndRun(c,[s,u],l)}),s=a[0],u=a[1],c=this.complex(s,u);return s.dispose(),u.dispose(),c},t.prototype.makeComplexComponentTensorHandle=function(t,e){return{dataId:e.dataId,dtype:e.dtype,shape:t.shape}},t.prototype.addN=function(t){if(1===t.length)return t[0];if(t.length>f.get("WEBGL_MAX_TEXTURES_IN_SHADER")){var e=Math.floor(t.length/2),n=this.addN(t.slice(0,e)),r=this.addN(t.slice(e));return this.addN([n,r])}var o=t.map(function(t){return t.dtype}).reduce(function(t,e){return It(t,e)}),i=t.map(function(t){return t.shape}),a=f.getBool("WEBGL_PACK"),s=a?new ro(t[0].shape,i):new no(t[0].shape,i),u=a?this.makePackedTensor(s.outputShape,o):this.makeOutputArray(s.outputShape,o);return this.compileAndRun(s,t,u)},t.prototype.subtract=function(t,e){if("complex64"===t.dtype&&"complex64"===e.dtype)return this.complexSeparableBinaryOp(t,e,No);if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.subtract(t,e);var n=It(t.dtype,e.dtype);if(f.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,No,t.dtype);var r=new Ao(No,t.shape,e.shape),o=this.makeOutputArray(r.outputShape,n);return this.compileAndRun(r,[t,e],o)},t.prototype.pow=function(t,e){var n=f.getBool("WEBGL_PACK_BINARY_OPERATIONS"),r=n?new To("\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 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 Ao("\nif(a < 0.0 && floor(b) < b){\n return NAN;\n}\nreturn (round(mod(b, 2.0)) != 1) ?\n pow(abs(a), b) : sign(a) * pow(abs(a), b);\n",t.shape,e.shape),o=It(t.dtype,e.dtype),i=n?this.makePackedTensor(r.outputShape,o):this.makeOutputArray(r.outputShape,o);return this.compileAndRun(r,[t,e],i)},t.prototype.ceil=function(t){var e=new ga(t.shape,"return ceil(x);");return this.compileAndRun(e,[t])},t.prototype.floor=function(t){var e=new ga(t.shape,"return floor(x);");return this.compileAndRun(e,[t])},t.prototype.sign=function(t){var e=new ga(t.shape,"\n if (isnan(x)) { return 0.0; }\n return sign(x);\n");return this.compileAndRun(e,[t])},t.prototype.isNaN=function(t){var e=new ga(t.shape,"return float(isnan(x));"),n=this.makeOutputArray(e.outputShape,"bool");return this.compileAndRun(e,[t],n)},t.prototype.isInf=function(t){var e=new ga(t.shape,"return float(isinf(x));"),n=this.makeOutputArray(e.outputShape,"bool");return this.compileAndRun(e,[t],n)},t.prototype.isFinite=function(t){var e=new ga(t.shape,"return float(!isnan(x) && !isinf(x));"),n=this.makeOutputArray(e.outputShape,"bool");return this.compileAndRun(e,[t],n)},t.prototype.round=function(t){var e=new ga(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])},t.prototype.exp=function(t){var e;return e=f.getBool("WEBGL_PACK")?new Ca(t.shape,ba):new ga(t.shape,ba),this.compileAndRun(e,[t])},t.prototype.expm1=function(t){var e=new ga(t.shape,"return exp(x) - 1.0;");return this.compileAndRun(e,[t])},t.prototype.log=function(t){var e;return e=f.getBool("WEBGL_PACK")?new Ca(t.shape,"\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"):new ga(t.shape,"if (x < 0.0) return NAN;\n return log(x);"),this.compileAndRun(e,[t])},t.prototype.log1p=function(t){var e=new ga(t.shape,"return log(1.0 + x);");return this.compileAndRun(e,[t])},t.prototype.sqrt=function(t){var e=new ga(t.shape,"return sqrt(x);");return this.compileAndRun(e,[t])},t.prototype.rsqrt=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.rsqrt(t);var e=new ga(t.shape,"return inversesqrt(x);");return this.compileAndRun(e,[t])},t.prototype.square=function(t){var e=new ga(t.shape,"return x * x;");return this.compileAndRun(e,[t])},t.prototype.reciprocal=function(t){var e=new ga(t.shape,"return 1.0 / x;");return this.compileAndRun(e,[t])},t.prototype.relu=function(t){var e;return e=f.getBool("WEBGL_PACK")?new Ca(t.shape,wa):new ga(t.shape,xa),this.compileAndRun(e,[t])},t.prototype.prelu=function(t,e){var n=f.getBool("WEBGL_PACK_BINARY_OPERATIONS")?new To("\n vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));\n return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\n",t.shape,e.shape):new Ao("return (a < 0.) ? b * a : a;",t.shape,e.shape);return this.compileAndRun(n,[t,e])},t.prototype.elu=function(t){var e=new ga(t.shape,"return (x >= 0.0) ? x : (exp(x) - 1.0);");return this.compileAndRun(e,[t])},t.prototype.eluDer=function(t,e){var n=f.getBool("WEBGL_PACK_BINARY_OPERATIONS")?new To("\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 Ao("return (b >= 1.0) ? a : a * (b + 1.0);",t.shape,e.shape);return this.compileAndRun(n,[t,e])},t.prototype.selu=function(t){var e=new ga(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])},t.prototype.int=function(t){var e=new ga(t.shape,"return float(int(x));"),n=this.makeOutputArray(e.outputShape,"int32");return this.compileAndRun(e,[t],n)},t.prototype.clip=function(t,e,n){var r,o=(r=f.getBool("WEBGL_PACK_CLIP")?new Fo(t.shape):new Do(t.shape)).getCustomSetupFunc(e,n);return this.compileAndRun(r,[t],null,o)},t.prototype.abs=function(t){var e=new ga(t.shape,"return abs(x);");return this.compileAndRun(e,[t])},t.prototype.complexAbs=function(t){var e=this.texData.get(t.dataId),n=new Mo(t.shape),r=[this.makeComplexComponentTensorHandle(t,e.complexTensors.real),this.makeComplexComponentTensorHandle(t,e.complexTensors.imag)];return this.compileAndRun(n,r)},t.prototype.sigmoid=function(t){var e=new ga(t.shape,"return 1.0 / (1.0 + exp(-1.0 * x));");return this.compileAndRun(e,[t])},t.prototype.softplus=function(t){var e=new ga(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])},t.prototype.sin=function(t){var e=new ga(t.shape,"if (isnan(x)) return x;\n return sin(x);\n");return this.compileAndRun(e,[t])},t.prototype.cos=function(t){var e=new ga(t.shape,"if (isnan(x)) return x;\n return cos(x);\n");return this.compileAndRun(e,[t])},t.prototype.tan=function(t){var e=new ga(t.shape,"return tan(x);");return this.compileAndRun(e,[t])},t.prototype.asin=function(t){var e=new ga(t.shape,"return asin(x);");return this.compileAndRun(e,[t])},t.prototype.acos=function(t){var e=new ga(t.shape,"return acos(x);");return this.compileAndRun(e,[t])},t.prototype.atan=function(t){var e=new ga(t.shape,"if (isnan(x)) return x;\n return atan(x);\n");return this.compileAndRun(e,[t])},t.prototype.atan2=function(t,e){var n=f.getBool("WEBGL_PACK_BINARY_OPERATIONS")?new To("\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 Ao("\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])},t.prototype.sinh=function(t){var e=new ga(t.shape,"\n float e2x = exp(x);\n return (e2x - 1.0 / e2x) / 2.0;\n");return this.compileAndRun(e,[t])},t.prototype.cosh=function(t){var e=new ga(t.shape,"\n float e2x = exp(-x);\n return (e2x + 1.0 / e2x) / 2.0;\n");return this.compileAndRun(e,[t])},t.prototype.tanh=function(t){var e=new ga(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])},t.prototype.asinh=function(t){var e=new ga(t.shape,"return log(x + sqrt(x * x + 1.0));");return this.compileAndRun(e,[t])},t.prototype.acosh=function(t){var e=new ga(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])},t.prototype.atanh=function(t){var e=new ga(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])},t.prototype.erf=function(t){var e=new ga(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 t = 1.0 / (1.0 + p * x);\n return 1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x);\n');return this.compileAndRun(e,[t])},t.prototype.step=function(t,e){var n=new ga(t.shape,function(t){return void 0===t&&(t=0),ya+"\n return x > 0.0 ? 1.0 : float("+t+");\n "}(e));return this.compileAndRun(n,[t])},t.prototype.conv2dByMatMul=function(t,e,n){var r=t.shape,o=this.texData.get(t.dataId),i=n.inChannels,a=r[0]*r[1]*r[2],s=n.outChannels,u=(1===a||1===s)&&i>1e3,c=r[2]%2!=0&&!!o.isPacked;if(u||!f.getBool("WEBGL_LAZILY_UNPACK")||!f.getBool("WEBGL_PACK_BINARY_OPERATIONS")||!c){var l=this.reshape(t,[1,r[0]*r[1]*r[2],n.inChannels]),h=this.reshape(e,[1,n.inChannels,n.outChannels]);return this.reshape(this.batchMatMul(l,h,!1,!1),n.outShape)}var p=mt.make([1,r[0]*r[1]*(r[2]+1),n.inChannels],{dataId:t.dataId},t.dtype,this),d=o.shape;o.shape=o.shape.slice(),o.shape[o.shape.length-2]++,b(we(o.shape,p.shape),function(){return"packed reshape "+o.shape+" to "+p.shape+" isn't free"});var v=this.reshape(e,[1,n.inChannels,n.outChannels]),m=this.batchMatMul(p,v,!1,!1),g=this.texData.get(m.dataId);return b(g.isPacked,function(){return"batchMatMul result is expected to be packed"}),o.shape=d,g.shape=n.outShape,mt.make(n.outShape,{dataId:m.dataId},m.dtype,this)},t.prototype.conv2dWithIm2Row=function(t,e,n){var r=n.filterWidth,o=n.filterHeight,i=n.inChannels,a=n.outWidth,s=n.outHeight,u=r*o*i,c=s*a,l=[u,c],h=t.squeeze([0]),p=e.reshape([1,u,-1]),f=new Oi(l,h.shape,n),d=this.compileAndRun(f,[h]).reshape([1,l[0],l[1]]),v=new zi(d.shape,[1,c,n.outChannels],!0,!1);return this.compileAndRun(v,[d,p]).reshape([1,s,a,n.outChannels])},t.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(f.getBool("WEBGL_CONV_IM2COL")&&1===t.shape[0])return this.conv2dWithIm2Row(t,e,n);var r=new Go(n);return this.compileAndRun(r,[t,e])},t.prototype.conv2dDerInput=function(t,e,n){var r=new Lo(n);return this.compileAndRun(r,[t,e])},t.prototype.conv2dDerFilter=function(t,e,n){var r=new Bo(n);return this.compileAndRun(r,[t,e])},t.prototype.depthwiseConv2D=function(t,e,n){var r;return f.getBool("WEBGL_PACK_DEPTHWISECONV")&&n.strideWidth<=2&&n.outChannels/n.inChannels==1?(r=new qo(n),this.compileAndRun(r,[t,e],this.makePackedTensor(n.outShape,t.dtype))):(r=new Ho(n),this.compileAndRun(r,[t,e]))},t.prototype.depthwiseConv2DDerInput=function(t,e,n){var r=new Vo(n);return this.compileAndRun(r,[t,e])},t.prototype.depthwiseConv2DDerFilter=function(t,e,n){var r=new Uo(n);return this.compileAndRun(r,[t,e])},t.prototype.conv3d=function(t,e,n){var r=new jo(n);return this.compileAndRun(r,[t,e])},t.prototype.conv3dDerInput=function(t,e,n){var r=new zo(n);return this.compileAndRun(r,[t,e])},t.prototype.conv3dDerFilter=function(t,e,n){var r=new Wo(n);return this.compileAndRun(r,[t,e])},t.prototype.maxPool=function(t,e){var n=new qi(e,"max",!1),r=this.makeOutputArray(n.outputShape,t.dtype);return this.compileAndRun(n,[t],r)},t.prototype.avgPool=function(t,e){var n=new qi(e,"avg",!1),r=this.makeOutputArray(n.outputShape,"float32");return this.compileAndRun(n,[t],r)},t.prototype.maxPoolBackprop=function(t,e,n,r){var o=new qi(r,"max",!0),i=this.compileAndRun(o,[e]),a=new Wi(r),s=this.makeOutputArray(a.outputShape,e.dtype),u=this.compileAndRun(a,[t,i],s);return i.dispose(),u},t.prototype.avgPoolBackprop=function(t,e,n){var r=new Eo(n),o=this.makeOutputArray(r.outputShape,e.dtype);return this.compileAndRun(r,[t],o)},t.prototype.cast=function(t,e){return Vr(t,e,this)},t.prototype.unstack=function(t,e){for(var n=t.shape[e],r=new Array(t.rank-1),o=0,i=0;i1,function(){return"blockSize should be > 1 for depthToSpace, but was: "+e});var r=t.shape[0],o="NHWC"===n?t.shape[1]:t.shape[2],i="NHWC"===n?t.shape[2]:t.shape[3],a="NHWC"===n?t.shape[3]:t.shape[1],s=o*e,u=i*e,c=a/(e*e),l=new ti("NHWC"===n?[r,s,u,c]:[r,c,s,u],e,n);return this.compileAndRun(l,[t])},t.prototype.split=function(t,e,n){return Jr(t,e,n)},t.prototype.scatterND=function(t,e,n){var r=mr(0,t,n),o=r.sliceRank,i=r.numUpdates,a=r.sliceSize,s=r.strides,u=r.outputSize,c=[u/a,a],l=t.reshape([i,o]),h=e.reshape([i,a]);if(0===u)return Gr(en([]),n);var p=rn(0),f=new na(i,o,l.rank,h.rank,s,c);return this.compileAndRun(f,[h,l,p]).reshape(n)},t.prototype.sparseToDense=function(t,e,n,r){var o=mr(0,t,n),i=o.sliceRank,a=o.numUpdates,s=o.strides,u=o.outputSize,c=new na(a,i,t.rank,e.rank,s,[u,1],!1);return this.compileAndRun(c,[e,t,r]).reshape(n)},t.prototype.fft=function(t){return this.fftImpl(t,!1)},t.prototype.ifft=function(t){return this.fftImpl(t,!0)},t.prototype.fftImpl=function(t,e){var n=this.texData.get(t.dataId),r=new ii("return real * expR - imag * expI;",t.shape,e),o=new ii("return real * expI + imag * expR;",t.shape,e),i=[this.makeComplexComponentTensorHandle(t,n.complexTensors.real),this.makeComplexComponentTensorHandle(t,n.complexTensors.imag)],a=this.compileAndRun(r,i),s=this.compileAndRun(o,i),u=this.complex(a,s).as2D(t.shape[0],t.shape[1]);return a.dispose(),s.dispose(),u},t.prototype.gatherND=function(t,e){var n=e.shape,r=n[n.length-1],o=fr(t,e),i=o[0],a=o[1],s=o[2],u=o[3],c=e.reshape([a,r]),l=t.reshape([t.size/s,s]),h=new li(r,u,[a,s]);return this.compileAndRun(h,[l,c]).reshape(i)},t.prototype.fill=function(t,e,n){if("string"===(n=n||q(e))){var r=O(n,_(t));return r.fill(e),mt.make(t,{values:r},n)}var o=new ai(t,e),i=o.getCustomSetupFunc(e),a=this.makeOutputArray(t,n);return this.compileAndRun(o,[],a,i)},t.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)},t.prototype.zerosLike=function(t){return this.fill(t.shape,"string"===t.dtype?"":0,t.dtype)},t.prototype.linspace=function(t,e,n){return jr(t,e,n)},t.prototype.makeOutputArray=function(t,e){return mt.make(t,{},e,this)},t.prototype.makePackedTensor=function(t,e){var n=mt.make(t,{},e,this);return this.texData.get(n.dataId).isPacked=!0,n},t.prototype.unpackTensor=function(t){var e=new Ea(t.shape);return this.compileAndRun(e,[t],mt.make(e.outputShape,{},t.dtype,this))},t.prototype.packTensor=function(t){var e=new Gi(t.shape);return this.compileAndRun(e,[t],this.makePackedTensor(t.shape,t.dtype),null,!0)},t.prototype.packedReshape=function(t,e){var n=t.reshape([me(t.shape)].concat(ge(t.shape))),r=[me(e)].concat(ge(e)),o=new Ki(r,n.shape);return this.compileAndRun(o,[n]).reshape(e)},t.prototype.decode=function(t){var e,n=this.texData.get(t),r=n.isPacked,o=n.shape,i=n.dtype,a=ye(o),s=pi(o),u=this.makeTensorHandle(o,"float32");return this.texData.get(u.dataId).isPacked=!0,this.texData.get(u.dataId).dtype=i,this.texData.get(u.dataId).texShape=s.map(function(t){return 2*t}),e=r?new Zo(a,s):new Jo(a,s),this.compileAndRun(e,[{shape:a,dtype:i,dataId:t}],u,null,!0),u},t.prototype.compileAndRun=function(t,e,n,r,o){var i=this;if(void 0===o&&(o=!1),null==n&&(n=t.usesPackedTextures?this.makePackedTensor(t.outputShape,e[0].dtype):this.makeOutputArray(t.outputShape,e[0].dtype)),0===n.size)return this.texData.get(n.dataId).values=M(n.dtype,0),n;var a=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=i.texData.get(e.dataId);if(null==n.texture){if(!t.usesPackedTextures&&_(e.shape)<=f.getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:e.shape,texData:null,isUniform:!0,uniformValues:n.values};t.usesPackedTextures&&(n.isPacked=!0,n.shape=e.shape)}else if(!!n.isPacked!=!!t.usesPackedTextures)e=n.isPacked?i.unpackTensor(e):i.packTensor(e),n=i.texData.get(e.dataId);else if(n.isPacked&&!we(n.shape,e.shape)){var r=e,o=e.shape;e.shape=n.shape,e=i.packedReshape(e,o),n=i.texData.get(e.dataId),r.shape=o}return i.uploadToGPU(e.dataId),{shape:e.shape,texData:n,isUniform:!1}});this.uploadToGPU(n.dataId);var s,u={shape:n.shape,texData:this.texData.get(n.dataId),isUniform:!1},c=function(t,e,n){var r="";a.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;r+=t.shape+"_"+n+"_"+e});var o=t.userCode;return t.constructor.name+"_"+r+"_"+o}(t,0,u),l=this.getAndSaveBinary(c,function(){return function(t,e,n,r){var o=e.userCode,i=n.map(function(t,n){var r={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&&(r.flatOffset=t.texData.slice.flatOffset),{name:e.variableNames[n],shapeInfo:r}}),a=i.map(function(t){return t.shapeInfo}),s={logicalShape:r.shape,texShape:r.texData.texShape,isUniform:!1,isPacked:r.texData.isPacked,flatOffset:null},u=ho(i,s,o,e.usesPackedTextures),c=t.createProgram(u),l=null,h=t.getUniformLocation(c,"NAN",!1);1===f.getNumber("WEBGL_VERSION")&&(l=t.getUniformLocation(c,"INFINITY",!1));for(var p={},d=0;d0?32:16})),this.floatPrecisionValue},t.prototype.epsilon=function(){return 32===this.floatPrecision()?1e-7:1e-4},t.prototype.uploadToGPU=function(t){var e,n=this.texData.get(t),r=n.shape,o=n.dtype,i=n.values,a=n.texture,s=n.usage,u=n.isPacked;if(null==a){var c,l=null!=this.activeTimers;l&&(c=performance.now());var h=n.texShape;if(null==h&&(h=xe(r,u),n.texShape=h),null!=i){var p=ye(r),f=void 0,d=h[1],v=h[0],m=i instanceof Uint8Array;u?(d=(e=fi(h[0],h[1]))[0],v=e[1],f=new oi(p,[v,d],m)):f=new ri(p,[v,d],m);var g=this.makeTensorHandle([v,d],o);this.texData.get(g.dataId).usage=m?Yo.PIXELS:Yo.UPLOAD,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(g.dataId),d,v,i);var y=this.makeTensorHandle(f.outputShape,g.dtype);y.size=_(f.outputShape),this.texData.get(y.dataId).isPacked=u,this.compileAndRun(f,[g],y);var x=this.texData.get(y.dataId);n.texture=x.texture,n.texShape=x.texShape,n.isPacked=x.isPacked,n.usage=x.usage,this.disposeData(g.dataId),this.texData.delete(y.dataId),n.values=null,l&&(this.uploadWaitMs+=performance.now()-c)}else{var b=this.acquireTexture(h,s,o,u);n.texture=b}}},t.prototype.convertAndCacheOnCPU=function(t,e){var n=this.texData.get(t),r=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),r=0;r1024*this.numMBBeforeWarning*1024){var o=(this.numBytesInGPU/1024/1024).toFixed(2);this.warnedAboutMemory=!0,console.warn("High memory usage in GPU: "+o+" MB, most likely due to a memory leak")}return this.textureManager.acquireTexture(t,e,r)},t.prototype.computeBytes=function(t,e){return t[0]*t[1]*U(e)},t}();Ot()&&Mt.registerBackend("webgl",function(){return new Sa},2);var Ra=Qe({abs_:function(t){var e=We(t,"x","abs");return"complex64"===e.dtype?Mt.runKernel(function(t){return t.complexAbs(e)},{$x:e}):Mt.runKernel(function(t,n){var r=t.abs(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.mul(n.toFloat().step(-1))}}})}}),Na=Qe({acos_:function(t){var e=We(t,"x","acos");return Mt.runKernel(function(t,n){var r=t.acos(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.divStrict(rn(1).sub(n.toFloat().square()).sqrt()).neg()}}})}}),ka=Qe({acosh_:function(t){var e=We(t,"x","acosh");return Mt.runKernel(function(t,n){var r=t.acosh(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.divStrict(n.toFloat().square().sub(1).sqrt())}}})}}),Aa=Qe({asin_:function(t){var e=We(t,"x","asin");return Mt.runKernel(function(t,n){var r=t.asin(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.divStrict(rn(1).sub(n.toFloat().square()).sqrt())}}})}}),Ta=Qe({asinh_:function(t){var e=We(t,"x","asinh");return Mt.runKernel(function(t,n){var r=t.asinh(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.divStrict(rn(1).add(n.toFloat().square()).sqrt())}}})}}),Da=Qe({atan_:function(t){var e=We(t,"x","atan");return Mt.runKernel(function(t,n){var r=t.atan(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.div(n.toFloat().square().add(1))}}})}}),Fa=Qe({atanh_:function(t){var e=We(t,"x","atanh");return Mt.runKernel(function(t,n){var r=t.atanh(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.div(rn(1).sub(n.toFloat().square()))}}})}}),Ma=Qe({ceil_:function(t){var e=We(t,"x","ceil");return Mt.runKernel(function(t){return t.ceil(e)},{$x:e},function(t){return{$x:function(){return gn(t)}}})}}),Oa=Qe({clipByValue_:function(t,e,n){var r=We(t,"x","clipByValue");return b(e<=n,function(){return"Error in clip: min ("+e+") must be less than or equal to max ("+n+")."}),Mt.runKernel(function(t,o){var i=t.clip(r,e,n);return o([r]),i},{$x:r},function(t,r){var o=r[0];return{$x:function(){return t.where(o.greaterEqual(e).logicalAnd(o.lessEqual(n)),gn(t))}}})}}),Pa=Qe({cos_:function(t){var e=We(t,"x","cos");return Mt.runKernel(function(t,n){var r=t.cos(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return n.toFloat().sin().neg().mul(t)}}})}}),Ba=Qe({cosh_:function(t){var e=We(t,"x","cosh");return Mt.runKernel(function(t,n){var r=t.cosh(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return n.toFloat().sinh().mulStrict(t)}}})}}),La=Qe({erf_:function(t){var e=We(t,"x","erf");return b("int32"===e.dtype||"float32"===e.dtype,function(){return"Input dtype must be `int32` or `float32`."}),"int32"===e.dtype&&(e=e.toFloat()),Mt.runKernel(function(t,n){var r=t.erf(e);return n([e]),r},{$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)))}}})}}),Wa=Qe({exp_:function(t){var e=We(t,"x","exp");return Mt.runKernel(function(t,n){var r=t.exp(e);return n([r]),r},{$x:e},function(t,e){return{$x:function(){return t.mulStrict(e[0])}}})}}),za=Qe({expm1_:function(t){var e=We(t,"x","expm1");return Mt.runKernel(function(t,n){var r=t.expm1(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.mul(n.exp())}}})}}),Ua=Qe({floor_:function(t){var e=We(t,"x","floor");return Mt.runKernel(function(t){return t.floor(e)},{$x:e},function(t){return{$x:function(){return gn(t)}}})}}),Va=Qe({log_:function(t){var e=We(t,"x","log");return Mt.runKernel(function(t,n){var r=t.log(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.div(n.toFloat())}}})}}),Ga=Qe({log1p_:function(t){var e=We(t,"x","log1p");return Mt.runKernel(function(t,n){var r=t.log1p(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.div(n.add(1))}}})}}),ja=Qe({logSigmoid_:function(t){var e=We(t,"x","logSigmoid");return Mt.runKernel(function(t,n){var r=t.softplus(e.neg()).neg();return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.mul(n.neg().sigmoid())}}})}}),Ha=Qe({neg_:function(t){var e=We(t,"x","neg");return Mt.runKernel(function(t){return t.neg(e)},{$x:e},function(t){return{$x:function(){return t.neg()}}})}}),qa=Qe({reciprocal_:function(t){var e=We(t,"x","reciprocal");return Mt.runKernel(function(t,n){var r=t.reciprocal(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.div(n.square().neg())}}})}}),$a=Qe({round_:function(t){var e=We(t,"x","round");return Mt.runKernel(function(t){return t.round(e)},{$x:e},function(t){return{$x:function(){return gn(t)}}})}}),Ka=Qe({rsqrt_:function(t){var e=We(t,"x","rsqrt");return Mt.runKernel(function(t,n){var r=t.rsqrt(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.div(n.pow(1.5).mul(2)).neg()}}})}}),Xa=Qe({sigmoid_:function(t){var e=We(t,"x","sigmoid");return Mt.runKernel(function(t,n){var r=t.sigmoid(e);return n([r]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.mul(n.mul(rn(1).sub(n)))}}})}}),Ya=Qe({sign_:function(t){var e=We(t,"x","sign");return Mt.runKernel(function(t){return t.sign(e)},{$x:e},function(t){return{$x:function(){return gn(t)}}})}}),Qa=Qe({isNaN_:function(t){var e=We(t,"x","isNaN");return Mt.runKernel(function(t){return t.isNaN(e)},{$x:e},function(t){return{$x:function(){return gn(t)}}})}}),Ja=Qe({isInf_:function(t){var e=We(t,"x","isInf");return Mt.runKernel(function(t){return t.isInf(e)},{$x:e},function(t){return{$x:function(){return gn(t)}}})}}),Za=Qe({isFinite_:function(t){var e=We(t,"x","isFinite");return Mt.runKernel(function(t){return t.isFinite(e)},{$x:e},function(t){return{$x:function(){return gn(t)}}})}}),ts=Qe({sin_:function(t){var e=We(t,"x","sin");return Mt.runKernel(function(t,n){var r=t.sin(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return n.toFloat().cos().mul(t)}}})}}),es=Qe({sinh_:function(t){var e=We(t,"x","sinh");return Mt.runKernel(function(t,n){var r=t.sinh(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return n.toFloat().cosh().mulStrict(t)}}})}}),ns=Qe({softplus_:function(t){var e=We(t,"x","softplus");return Mt.runKernel(function(t,n){var r=t.softplus(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.mul(n.sigmoid())}}})}}),rs=Qe({sqrt_:function(t){var e=We(t,"x","sqrt");return Mt.runKernel(function(t,n){var r=t.sqrt(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.div(n.toFloat().sqrt().mul(2))}}})}}),os=Qe({square_:function(t){var e=We(t,"x","square");return Mt.runKernel(function(t,n){return n([e]),t.square(e)},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.mul(n.toFloat().mul(2))}}})}}),is=Qe({step_:function(t,e){void 0===e&&(e=0);var n=We(t,"x","step");return Mt.runKernel(function(t){return t.step(n,e)},{$x:n},function(t){return{$x:function(){return gn(t)}}})}}),as=Qe({tan_:function(t){var e=We(t,"x","tan");return Mt.runKernel(function(t,n){var r=t.tan(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.div(n.cos().square())}}})}}),ss=Qe({tanh_:function(t){var e=We(t,"x","tanh");return Mt.runKernel(function(t,n){var r=t.tanh(e);return n([r]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return rn(1).sub(n.square()).mulStrict(t)}}})}});function us(t,e,n,r,o,i){var a,s,u=We(t,"x","batchNorm"),c=We(e,"mean","batchNorm"),l=We(n,"variance","batchNorm");return null!=o&&(a=We(o,"scale","batchNorm")),null!=r&&(s=We(r,"offset","batchNorm")),b(2===u.rank,function(){return"Error in batchNorm3D: x must be rank 3 but got rank "+u.rank+"."}),b(2===c.rank||1===c.rank,function(){return"Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank "+c.rank+"."}),b(2===l.rank||1===l.rank,function(){return"Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank "+l.rank+"."}),null!=a&&b(2===a.rank||1===a.rank,function(){return"Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank "+a.rank+"."}),null!=s&&b(2===s.rank||1===s.rank,function(){return"Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank "+s.rank+"."}),hs(u,c,l,s,a,i)}function cs(t,e,n,r,o,i){var a,s,u=We(t,"x","batchNorm"),c=We(e,"mean","batchNorm"),l=We(n,"variance","batchNorm");return null!=o&&(a=We(o,"scale","batchNorm")),null!=r&&(s=We(r,"offset","batchNorm")),b(3===u.rank,function(){return"Error in batchNorm3D: x must be rank 3 but got rank "+u.rank+"."}),b(3===c.rank||1===c.rank,function(){return"Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank "+c.rank+"."}),b(3===l.rank||1===l.rank,function(){return"Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank "+l.rank+"."}),null!=a&&b(3===a.rank||1===a.rank,function(){return"Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank "+a.rank+"."}),null!=s&&b(3===s.rank||1===s.rank,function(){return"Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank "+s.rank+"."}),hs(u,c,l,s,a,i)}function ls(t,e,n,r,o,i){var a,s,u=We(t,"x","batchNorm"),c=We(e,"mean","batchNorm"),l=We(n,"variance","batchNorm");return null!=o&&(a=We(o,"scale","batchNorm")),null!=r&&(s=We(r,"offset","batchNorm")),b(4===u.rank,function(){return"Error in batchNorm4D: x must be rank 4 but got rank "+u.rank+"."}),b(4===c.rank||1===c.rank,function(){return"Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank "+c.rank+"."}),b(4===l.rank||1===l.rank,function(){return"Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank "+l.rank+"."}),null!=a&&b(4===a.rank||1===a.rank,function(){return"Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank "+a.rank+"."}),null!=s&&b(4===s.rank||1===s.rank,function(){return"Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank "+s.rank+"."}),hs(u,c,l,s,a,i)}function hs(t,e,n,r,o,i){null==i&&(i=.001);var a,s,u,c=We(t,"x","batchNorm"),l=We(e,"mean","batchNorm"),h=We(n,"variance","batchNorm");return null!=o&&(a=We(o,"scale","batchNorm")),null!=r&&(s=We(r,"offset","batchNorm")),b(l.rank===h.rank,function(){return"Batch normalization gradient requires mean and variance to have equal ranks."}),b(null==s||l.rank===s.rank,function(){return"Batch normalization gradient requires mean and offset to have equal ranks."}),b(null==a||l.rank===a.rank,function(){return"Batch normalization gradient requires mean and scale to have equal ranks."}),u=0===c.rank||1===c.rank?c.as4D(1,1,1,c.size):2===c.rank?c.as4D(1,1,c.shape[0],c.shape[1]):3===c.rank?c.as4D(1,c.shape[0],c.shape[1],c.shape[2]):c,Mt.runKernel(function(t,e){var n=t.batchNormalization(u,ps(l),ps(h),i,ps(a),ps(s));return e([c,l,h,a]),n},{$x:c,$mean:l,$variance:h,$scale:a,$offset:s},function(t,e){var n=e,r=n[0],o=n[1],a=n[2],s=n[3],c=null==s?rn(1):s,l=Ar(o.shape,u.shape),h=[];if(1===o.rank){for(var p=0;p=2&&a.rank>=2&&i.rank===a.rank,function(){return"Error in matMul: inputs must have the same rank of at least 2, got ranks "+i.rank+" and "+a.rank+"."}),b(I(h,p),function(){return"Error in matMul: outer dimensions ("+h+") and ("+p+") of Tensors with shapes "+i.shape+" and "+a.shape+" must match."}),b(s===u,function(){return"Error in matMul: inner shapes ("+s+") and ("+u+") of Tensors with shapes "+i.shape+" and "+a.shape+" and transposeA="+n+" and transposeB="+r+" must match."});var v=i.shape.slice(0,-2).concat([c,l]),m=n?i.as3D(f,s,c):i.as3D(f,c,s),g=r?a.as3D(d,l,u):a.as3D(d,u,l);return Mt.runKernel(function(t,e){var o=t.batchMatMul(m,g,n,r);return e([m,g]),o},{$a:m,$b:g},function(t,e){var o=e,i=o[0],a=o[1];return n||r?!n&&r?{$a:function(){return t.matMul(a,!1,!1)},$b:function(){return t.matMul(i,!0,!1)}}:n&&!r?{$a:function(){return a.matMul(t,!1,!0)},$b:function(){return i.matMul(t,!1,!1)}}:{$a:function(){return a.matMul(t,!0,!0)},$b:function(){return t.matMul(i,!0,!0)}}:{$a:function(){return t.matMul(a,!1,!0)},$b:function(){return i.matMul(t,!0,!1)}}}).reshape(v)}}),Fs=Qe({dot_:function(t,e){var n=We(t,"t1","dot"),r=We(e,"t2","dot");b(!(1!==n.rank&&2!==n.rank||1!==r.rank&&2!==r.rank),function(){return"Error in dot: inputs must all be rank 1 or 2, but got ranks "+n.rank+" and "+r.rank+"."});var o=1===n.rank?n.size:n.shape[1],i=1===r.rank?r.size:r.shape[0];return b(o===i,function(){return"Error in dot: inner dimensions of inputs must match, but got "+o+" and "+i+"."}),1===n.rank&&1===r.rank?n.as2D(1,-1).matMul(r.as2D(-1,1)).asScalar():1===n.rank&&2===r.rank?n.as2D(1,-1).matMul(r.as2D(r.shape[0],r.shape[1])).as1D():2===n.rank&&1===r.rank?n.matMul(r.as2D(-1,1)).as1D():n.matMul(r.as2D(r.shape[0],r.shape[1]))}}),Ms=Qe({outerProduct_:function(t,e){var n=We(t,"v1","outerProduct"),r=We(e,"v2","outerProduct");return b(1===n.rank&&1===r.rank,function(){return"Error in outerProduct: inputs must be rank 1, but got ranks "+n.rank+" and "+r.rank+"."}),n.as2D(-1,1).matMul(r.as2D(1,-1))}}),Os=Qe({reverse_:function(t,e){var n=We(t,"x","reverse");if(0===n.rank)return n.clone();var r=D(e,n.shape);return Mt.runKernel(function(t){return t.reverse(n,r)},{$x:n},function(t){return{$x:function(){return t.reverse(r)}}}).reshapeAs(n)}}),Ps=Qe({reverse1d_:function(t){var e=We(t,"x","reverse");return b(1===e.rank,function(){return"Error in reverse1D: x must be rank 1 but got rank "+e.rank+"."}),Os(e,0)}}),Bs=Qe({reverse2d_:function(t,e){var n=We(t,"x","reverse");return b(2===n.rank,function(){return"Error in reverse2D: x must be rank 2 but got rank "+n.rank+"."}),Os(n,e)}}),Ls=Qe({reverse3d_:function(t,e){var n=We(t,"x","reverse");return b(3===n.rank,function(){return"Error in reverse3D: x must be rank 3 but got rank "+n.rank+"."}),Os(n,e)}}),Ws=Qe({reverse4d_:function(t,e){var n=We(t,"x","reverse");return b(4===n.rank,function(){return"Error in reverse4D: x must be rank 4 but got rank "+n.rank+"."}),Os(n,e)}});function zs(t,e,n,r,o,i){var a=We(t,"x","maxPool"),s=a,u=!1;3===a.rank&&(u=!0,s=a.as4D(1,a.shape[0],a.shape[1],a.shape[2])),null==r&&(r=[1,1]),b(4===s.rank,function(){return"Error in maxPool: input must be rank 4 but got rank "+s.rank+"."}),b(Ur(n,r),function(){return"Error in maxPool: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+r+"'"}),null!=i&&b(S(o),function(){return"Error in maxPool: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+o+"."});var c=Dr(s.shape,e,n,r,o,i),l=Mt.runKernel(function(t,e){var n=t.maxPool(s,c);return e([s,n]),n},{x:s},function(t,i){var a=i[0],s=i[1];return{x:function(){return function(t,e,n,r,o,i,a,s){var u=We(t,"dy","maxPoolBackprop"),c=We(e,"input","maxPoolBackprop"),l=We(n,"output","maxPoolBackprop");b(c.rank===u.rank,function(){return"Rank of input ("+c.rank+") does not match rank of dy ("+u.rank+")"}),null==i&&(i=[1,1]),b(Ur(o,i),function(){return"Error in maxPoolBackProp: Either strides or dilations must be 1. Got strides "+o+" and dilations '"+i+"'"}),b(4===u.rank,function(){return"Error in maxPoolBackprop: dy must be rank 4 but got rank "+u.rank+"."}),b(4===c.rank,function(){return"Error in maxPoolBackprop: input must be rank 4 but got rank "+c.rank+"."});var h=Dr(c.shape,r,o,i,a,s);return Mt.runKernel(function(t){return t.maxPoolBackprop(u,c,l,h)},{$dy:u,$input:c})}(t,a,s,e,n,r,o)}}});return u?l.as3D(l.shape[1],l.shape[2],l.shape[3]):l}function Us(t,e,n,r,o,i){var a=We(t,"x","avgPool","float32");null==r&&(r=[1,1]),b(Ur(n,r),function(){return"Error in avgPool: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+r+"'"});var s=a,u=!1;3===a.rank&&(u=!0,s=a.as4D(1,a.shape[0],a.shape[1],a.shape[2])),b(4===s.rank,function(){return"Error in avgPool: x must be rank 4 but got rank "+s.rank+"."}),null!=i&&b(S(o),function(){return"Error in avgPool: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+o+"."});var c=Dr(s.shape,e,n,r,o,i),l=Mt.runKernel(function(t){return t.avgPool(s,c)},{x:s},function(t){return{x:function(){return function(t,e,n,r,o,i){var a=We(t,"dy","avgPoolBackprop"),s=We(e,"input","avgPoolBackprop");b(s.rank===a.rank,function(){return"Rank of input ("+s.rank+") does not match rank of dy ("+a.rank+")"}),null==o&&(o=[1,1]),b(Ur(r,o),function(){return"Error in avgPoolBackprop: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+o+"'"});var u=s,c=a,l=!1;3===s.rank&&(l=!0,u=s.as4D(1,s.shape[0],s.shape[1],s.shape[2]),c=a.as4D(1,a.shape[0],a.shape[1],a.shape[2])),b(4===c.rank,function(){return"Error in avgPoolBackprop: dy must be rank 4 but got rank "+c.rank+"."}),b(4===u.rank,function(){return"Error in avgPoolBackprop: input must be rank 4 but got rank "+u.rank+"."});var h=Dr(u.shape,n,r,o,i),p=Mt.runKernel(function(t){return t.avgPoolBackprop(c,u,h)},{dy4D:c,input4D:u});return l?p.as3D(p.shape[1],p.shape[2],p.shape[3]):p}(t,s,e,n,r,o)}}});return l=l.cast(a.dtype),u?l.as3D(l.shape[1],l.shape[2],l.shape[3]):l}var Vs=Qe({maxPool_:function(t,e,n,r,o){return zs(t,e,n,1,r,o)}}),Gs=Qe({avgPool_:function(t,e,n,r,o){return Us(t,e,n,1,r,o)}}),js=Qe({pool_:function(t,e,n,r,o,i){null==o&&(o=[1,1]),null==i&&(i=1),0===r&&(r="valid");var a=We(t,"x","maxPool"),s=a,u=!1;3===a.rank&&(u=!0,s=a.as4D(1,a.shape[0],a.shape[1],a.shape[2])),b(Ur(i,o),function(){return"Error in pool: Either strides or dilations must be 1. Got strides "+i+" and dilations '"+o+"'"});var c,l=Dr(s.shape,e,i,o,r),h=[l.dilationHeight,l.dilationWidth];c="same"===r?function(t,e){var n=t.map(function(t,n){return t+(t-1)*(e[n]-1)}).map(function(t){return t-1}),r=n.map(function(t){return Math.floor(t/2)}),o=n.map(function(t,e){return t-r[e]});return n.map(function(t,e){return[r[e],o[e]]})}([l.filterHeight,l.filterWidth],h):[[0,0],[0,0]];var p=1===h[0]&&1===h[1],f=function(t,e,n){var r=n.map(function(t){return t[0]}),o=n.map(function(t){return t[1]}),i=t.concat(r,o),a=e.map(function(t,e){return(t-i[e]%t)%t}),s=o.map(function(t,e){return t+a[e]});return[e.map(function(t,e){return[r[e],s[e]]}),e.map(function(t,e){return[0,a[e]]})]}([l.inHeight,l.inWidth],h,c),d=f[0],v=f[1],m=p?r:"valid",g=p?s:er(s,h,d),y=("avg"===n?function(){return Us(g,e,i,1,m)}:function(){return zs(g,e,i,1,m)})(),x=p?y:Bn(y,h,v);return u?x.as3D(x.shape[1],x.shape[2],x.shape[3]):x}}),Hs=Qe({slice_:function(t,e,n){var r,o,i=We(t,"x","slice");if(0===i.rank)throw new Error("Slicing scalar is not possible");r="number"==typeof e?[e].concat(new Array(i.rank-1).fill(0)):e.length=0?t:(b(-1===t,function(){return"Bad value in size"}),i.shape[e]-r[e])}),function(t,e,n){b(t.rank===e.length,function(){return"Error in slice"+t.rank+"D: Length of begin "+e+" must match the rank of the array ("+t.rank+")."}),b(t.rank===n.length,function(){return"Error in slice"+t.rank+"D: Length of size "+n+" must match the rank of the array ("+t.rank+")."});for(var r=function(r){b(e[r]+n[r]<=t.shape[r],function(){return"Error in slice"+t.rank+"D: begin["+r+"] + size["+r+"] ("+(e[r]+n[r])+") would overflow input.shape["+r+"] ("+t.shape[r]+")"})},o=0;o0&&(e=e.sum(n)),e.reshape(r.shape)},$b:function(){var e=t,n=Ar(o.shape,i);return n.length>0&&(e=e.sum(n)),e.reshape(o.shape)}}})}}),wu=Qe({addN_:function(t){b(Array.isArray(t),function(){return"The argument passed to tf.addN() must be a list of tensors"}),b(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 We(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 r=e;return Mt.runKernel(function(t){return t.addN(e)},r,function(t){var n={};return e.forEach(function(e,r){n[r]=function(){return t.clone()}}),n})}}),Cu=Qe({addStrict_:function(t,e){var n=We(t,"a","addStrict"),r=We(e,"b","addStrict");return w(n.shape,r.shape,"Error in addStrict: "),n.add(r)}}),Eu=Qe({atan2_:function(t,e){var n,r=We(t,"a","atan2"),o=We(e,"b","atan2");n=Rt(r,o),r=n[0],o=n[1];var i=Tr(r.shape,o.shape);return Mt.runKernel(function(t,e){var n=t.atan2(r,o);return e([r,o]),n},{$a:r,$b:o},function(t,e){var n=e[0],r=e[1];return{$a:function(){var e=bu(n.square(),r.square()),o=t.mul(r.div(e)),a=Ar(n.shape,i);return a.length>0&&(o=o.sum(a)),o.reshape(n.shape)},$b:function(){var e=bu(n.square(),r.square()),o=Ha(t.mul(n.div(e))),a=Ar(r.shape,i);return a.length>0&&(o=o.sum(a)),o.reshape(r.shape)}}})}}),_u=Qe({div_:function(t,e){var n,r=We(t,"a","div"),o=We(e,"b","div");if(n=Rt(r,o),r=n[0],o=n[1],"int32"===r.dtype&&"int32"===o.dtype)return Su(r,o);var i=Tr(r.shape,o.shape);return Mt.runKernel(function(t,e){var n=t.realDivide(r,o);return e([r,o]),n},{$a:r,$b:o},function(t,e){var n=e[0],r=e[1];return{$a:function(){var e=t.div(r.toFloat()),o=Ar(n.shape,i);return o.length>0?e.sum(o).reshape(n.shape):e},$b:function(){var e=t.mul(n.toFloat()),o=Ar(r.shape,i);o.length>0&&(e=e.sum(o).reshape(r.shape));var a=r.square();return e.div(a.toFloat()).neg()}}})}}),Iu=Qe({divStrict_:function(t,e){var n=We(t,"a","div"),r=We(e,"b","div");return w(n.shape,r.shape,"Error in divideStrict: "),n.div(r)}}),Su=Qe({floorDiv_:function(t,e){var n,r=We(t,"a","floorDiv"),o=We(e,"b","floorDiv");n=Rt(r,o),r=n[0],o=n[1];var i=Tr(r.shape,o.shape);return Mt.runKernel(function(t,e){var n=t.floorDiv(r,o);return e([r,o]),n},{$a:r,$b:o},function(t,e){var n=e[0],r=e[1];return{$a:function(){var e=t.div(r.toFloat()),o=Ar(n.shape,i);return o.length>0?e.sum(o).reshape(n.shape):e},$b:function(){var e=t.mul(n.toFloat()),o=Ar(r.shape,i);o.length>0&&(e=e.sum(o).reshape(r.shape));var a=r.square();return e.div(a.toFloat()).neg()}}})}}),Ru=Qe({maximum_:function(t,e){var n,r=We(t,"a","maximum"),o=We(e,"b","maximum");return n=Rt(r,o),r=n[0],o=n[1],"bool"===r.dtype&&(r=r.toInt(),o=o.toInt()),Tr(r.shape,o.shape),Mt.runKernel(function(t,e){var n=t.maximum(r,o);return e([r,o]),n},{$a:r,$b:o},function(t,e){var n=e[0],r=e[1];return{$a:function(){return t.mul(n.greaterEqual(r).toFloat())},$b:function(){return t.mul(n.less(r).toFloat())}}})}}),Nu=Qe({maximumStrict_:function(t,e){var n=We(t,"a","maximumStrict"),r=We(e,"b","maximumStrict");return w(n.shape,r.shape,"Error in maximumStrict: "),n.maximum(r)}}),ku=Qe({minimum_:function(t,e){var n,r=We(t,"a","minimum"),o=We(e,"b","minimum");return n=Rt(r,o),r=n[0],o=n[1],"bool"===r.dtype&&(r=r.toInt(),o=o.toInt()),Tr(r.shape,o.shape),Mt.runKernel(function(t,e){var n=t.minimum(r,o);return e([r,o]),n},{$a:r,$b:o},function(t,e){var n=e[0],r=e[1];return{$a:function(){return t.mul(n.lessEqual(r).toFloat())},$b:function(){return t.mul(n.greater(r).toFloat())}}})}}),Au=Qe({minimumStrict_:function(t,e){var n=We(t,"a","minimumStrict"),r=We(e,"b","minimumStrict");return w(n.shape,r.shape,"Error in minimumStrict: "),n.minimum(r)}}),Tu=Qe({mod_:function(t,e){var n,r=We(t,"a","mod"),o=We(e,"b","mod");n=Rt(r,o),r=n[0],o=n[1];var i=Tr(r.shape,o.shape);return Mt.runKernel(function(t,e){var n=t.mod(r,o);return e([r,o]),n},{$a:r,$b:o},function(t,e){var n=e[0],r=e[1];return{$a:function(){var e=Ar(n.shape,i);return e.length>0?t.sum(e).reshape(n.shape):t},$b:function(){var e=t.mul(n.div(r).floor().neg()),o=Ar(r.shape,i);return o.length>0?e.sum(o).reshape(r.shape):e}}})}}),Du=Qe({modStrict_:function(t,e){var n=We(t,"a","modStrict"),r=We(e,"b","modStrict");return w(n.shape,r.shape,"Error in modStrict: "),n.mod(r)}}),Fu=Qe({mul_:function(t,e){var n,r=We(t,"a","mul"),o=We(e,"b","mul");n=Rt(r,o),r=n[0],o=n[1];var i=Tr(r.shape,o.shape);return Mt.runKernel(function(t,e){var n=t.multiply(r,o);return e([r,o]),n},{$a:r,$b:o},function(t,e){var n=e[0],r=e[1];return{$a:function(){var e=t.mul(r.toFloat()),o=Ar(n.shape,i);return o.length>0?e.sum(o).reshape(n.shape):e},$b:function(){var e=t.mul(n.toFloat()),o=Ar(r.shape,i);return o.length>0?e.sum(o).reshape(r.shape):e}}})}}),Mu=Qe({mulStrict_:function(t,e){var n=We(t,"a","mul"),r=We(e,"b","mul");return w(n.shape,r.shape,"Error in multiplyStrict: "),n.mul(r)}}),Ou=Qe({pow_:function(t,e){var n=We(t,"base","pow"),r=We(e,"exp","pow"),o=Tr(n.shape,r.shape);return t=n.cast(It(n.dtype,r.dtype)),e=r.cast(It(n.dtype,r.dtype)),Mt.runKernel(function(t,e){var o=t.pow(n,r);return e([n,r,o]),o},{$base:n,$exp:r},function(t,e){var n=e[0],r=e[1],i=e[2];return{$base:function(){var e=r.toFloat(),i=t.mul(e.mul(n.pow(e.sub(rn(1))))),a=Ar(n.shape,o);return a.length>0&&(i=i.sum(a)),i.reshape(n.shape)},$exp:function(){var e=n.greater(0),a=n.log().where(e,gn(n)),s=t.mul(i.mul(a)),u=Ar(r.shape,o);return u.length>0&&(s=s.sum(u)),s.reshape(r.shape)}}})}}),Pu=Qe({powStrict_:function(t,e){return w(t.shape,e.shape,"Error in powStrict: "),t.pow(e)}}),Bu=Qe({squaredDifference_:function(t,e){var n,r=We(t,"a","squaredDifference"),o=We(e,"b","squaredDifference");return n=Rt(r,o),r=n[0],o=n[1],Tr(r.shape,o.shape),Mt.runKernel(function(t,e){var n=t.squaredDifference(r,o);return e([r,o]),n},{$a:r,$b:o},function(t,e){var n=e[0],r=e[1],o=rn(2);return{$a:function(){return t.mul(n.sub(r).mul(o))},$b:function(){return t.mul(r.sub(n).mul(o))}}})}}),Lu=Qe({squaredDifferenceStrict_:function(t,e){var n=We(t,"a","squaredDifferenceStrict"),r=We(e,"b","squaredDifferenceStrict");return w(n.shape,r.shape,"Error in squaredDifferenceStrict: "),n.squaredDifference(r)}}),Wu=Qe({sub_:function(t,e){var n,r=We(t,"a","sub"),o=We(e,"b","sub");n=Rt(r,o),r=n[0],o=n[1];var i=Tr(r.shape,o.shape);return Mt.runKernel(function(t){return t.subtract(r,o)},{$a:r,$b:o},function(t){return{$a:function(){var e=t,n=Ar(r.shape,i);return n.length>0&&(e=e.sum(n)),e.reshape(r.shape)},$b:function(){var e=t,n=Ar(o.shape,i);return n.length>0&&(e=e.sum(n)),e.neg().reshape(o.shape)}}})}}),zu=Qe({subStrict_:function(t,e){var n=We(t,"a","subStrict"),r=We(e,"b","subStrict");return w(n.shape,r.shape,"Error in subStrict: "),n.sub(r)}}),Uu=Qe({logicalAnd_:function(t,e){var n=We(t,"a","logicalAnd","bool"),r=We(e,"b","logicalAnd","bool");return Tr(n.shape,r.shape),Mt.runKernel(function(t){return t.logicalAnd(n,r)},{$a:n,$b:r})}}),Vu=Qe({logicalNot_:function(t){var e=We(t,"x","logicalNot","bool");return Mt.runKernel(function(t){return t.logicalNot(e)},{$x:e})}}),Gu=Qe({logicalOr_:function(t,e){var n=We(t,"a","logicalOr","bool"),r=We(e,"b","logicalOr","bool");return Tr(n.shape,r.shape),Mt.runKernel(function(t){return t.logicalOr(n,r)},{$a:n,$b:r})}}),ju=Qe({logicalXor_:function(t,e){var n=We(t,"a","logicalXor","bool"),r=We(e,"b","logicalXor","bool");return Tr(n.shape,r.shape),Gu(t,e).logicalAnd(Uu(t,e).logicalNot())}}),Hu=Qe({where_:function(t,e,n){var r=We(e,"a","where"),o=We(n,"b","where"),i=We(t,"condition","where","bool");return w(r.shape,o.shape,"Error in where: "),1===i.rank?b(i.shape[0]===r.shape[0],function(){return"The first dimension of `a` must match the size of `condition`."}):w(i.shape,o.shape,"Error in where: "),Mt.runKernel(function(t,e){var n=t.select(i,r,o);return e([i]),n},{$condition:i,$a:r,$b:o},function(t,e){var n=e[0];return{$condition:function(){return gn(n).toFloat()},$a:function(){return t.mul(n.cast(t.dtype))},$b:function(){return t.mul(n.logicalNot().cast(t.dtype))}}})}}),qu=function(t){return c(this,void 0,void 0,function(){var e,n,r;return l(this,function(o){switch(o.label){case 0:return[4,(e=We(t,"condition","whereAsync","bool")).data()];case 1:return n=o.sent(),r=eo(e.shape,n),t!==e&&e.dispose(),[2,r]}})})},$u=Qe({elu_:function(t){var e=We(t,"x","elu");return Mt.runKernel(function(t,n){var r=t.elu(e);return n([r]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return Mt.runKernel(function(e){return e.eluDer(t,n)},{dy:t,y:n})}}})}}),Ku=Qe({leakyRelu_:function(t,e){void 0===e&&(e=.2);var n=We(t,"x","leakyRelu");return Ru(rn(e).mul(n),n)}}),Xu=Qe({prelu_:function(t,e){var n=We(t,"x","prelu"),r=We(e,"alpha","prelu");return Mt.runKernel(function(t,e){var o=t.prelu(n,r);return e([n,r]),o},{$x:n,$alpha:r},function(t,e){var n=e[0],r=e[1],o=n.greater(0);return{$x:function(){return Hu(o,t,t.mul(r))},$alpha:function(){var e=Hu(o,gn(t),t.mul(n)),i=Ar(r.shape,t.shape);return i.length>0&&(e=e.sum(i)),e.reshape(r.shape)}}})}}),Yu=Qe({relu_:function(t){var e=We(t,"x","relu");return"bool"===e.dtype?e.toInt():Mt.runKernel(function(t,n){var r=t.relu(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.mulStrict(n.step().toFloat())}}})}}),Qu=Qe({selu_:function(t){var e=We(t,"x","selu");return Mt.runKernel(function(t,n){var r=t.selu(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){var e=n.greater(rn(0)),r=rn(va),o=rn(ma),i=t.mul(o),a=t.mul(r).mul(n.toFloat().exp());return Hu(e,i,a)}}})}}),Ju=Qe({transpose_:function(t,e){var n=We(t,"x","transpose");return null==e&&(e=n.shape.map(function(t,e){return e}).reverse()),b(n.rank===e.length,function(){return"Error in transpose: rank of input "+n.rank+" must match length of perm "+e+"."}),e.forEach(function(t){b(t>=0&&to)throw new Error("'k' passed to topk() must be <= the last dimension ("+o+") but got "+e);var i=Mt.runKernel(function(t){return t.topk(r,e,n)},{$x:r});return{values:i[0],indices:i[1]}}}),lc=Qe({scatterND_:function(t,e,n){var r=We(t,"indices","scatterND","int32"),o=We(e,"updates","scatterND");return function(t,e,n){if(e.rank<1)throw new Error("tf.scatterND() expects the indices to be rank 1 or higher, but the rank was "+e.rank+".");if(t.rank<1)throw new Error("tf.scatterND() expects the updates to be rank 1 or higher, but the rank was "+t.rank+".");if("int32"!==e.dtype)throw new Error("The dtype of 'indices' should be int32, but got dtype: "+e.dtype);if(n.length<1)throw new Error("Output rank must be greater or equal to 1, but got shape: "+n);if(0===n.length){if(0===e.size)throw new Error("Indices specified for empty output. indices shape: "+e.shape);if(0===t.size)throw new Error("Updates specified for empty output. updates shape: "+t.shape)}!function(t,e,n){var r=e.rank>1?e.shape[e.rank-1]:1,o=e.rank>1?e.rank-1:1,i="Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: "+n.shape+", indices.shape: "+e.shape+", shape: "+t+", sliceDim: "+r+", and batchDim: "+o+".";if(n.rankr){var s=t.shape.map(function(t){return t});s[t.shape.length-1]=e-r,n=t.concat(pn(s),t.shape.length-1),r=e}else n=t;var u=n.zerosLike(),c=Je(n,u).as2D(o,r),l=hc(c),h=Math.floor(r/2)+1,p=Ze(l),f=tn(l),d=p.split([h,r-h],p.shape.length-1),v=f.split([h,r-h],f.shape.length-1),m=n.shape.slice();return m[n.shape.length-1]=h,Je(d[0],v[0]).reshape(m)}}),dc=Qe({irfft_:function(t){var e=t.shape[t.shape.length-1],n=t.size/e;if(e<=2){var r=t.as2D(n,e),o=pc(r);return Ze(o)}var i=[n,2*(e-1)],a=Ze(t).as2D(n,e),s=tn(t).as2D(n,e),u=a.slice([0,1],[n,e-2]).reverse(1),c=s.slice([0,1],[n,e-2]).reverse(1).mul(rn(-1)),l=a.concat(u,1),h=s.concat(c,1);return r=Je(l,h).as2D(i[0],i[1]),o=pc(r),Ze(o)}}),vc=Object.freeze({fft:hc,ifft:pc,rfft:fc,irfft:dc}),mc=Qe({sparseToDense_:function(t,e,n,r){void 0===r&&(r=0);var o=We(t,"sparseIndices","sparseToDense","int32"),i=We(e,"sparseValues","sparseToDense"),a=We(r,"defaultValue","sparseToDense",i.dtype);return function(t,e,n,r){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 o=t.rank>0?t.shape[0]:1,i=t.rank>1?t.shape[1]:1;if(n.length!==i)throw new Error("outputShape has incorrect number of elements:, "+n.length+", should be: "+i+".");var a=e.size;if(0!==e.rank&&(1!==e.rank||a!==o))throw new Error("sparseValues has incorrect shape "+e.shape+", should be [] or ["+o+"]");if(e.dtype!==r.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}(o,i,n,a),Mt.runKernel(function(t){return t.sparseToDense(o,i,n,a)},{$sparseIndices:o,$sparseValues:i,$defaultValue:a})}}),gc=Qe({gatherND_:function(t,e){var n=We(e,"indices","gatherND","int32"),r=We(t,"x","gatherND");return Mt.runKernel(function(t){return t.gatherND(r,n)},{$x:r,$indices:n})}}),yc=Qe({dropout_:function(t,e,n,r){if(null!=n&&!I(t.shape,n))throw new Error("Non-default noise shape is not implemented yet: "+JSON.stringify(n));var o=Zn(t.shape,0,1,"float32",r).greater(e);return o=o.div(Wu(1,e)),t.mul(o)}});function xc(t,e,n){for(var r=1-t%2,o=new Float32Array(t),i=0;i1?s.div(rn(a)):s}if(n===bc.SUM_BY_NONZERO_WEIGHTS){if(null==o)return i.sum().div(rn(r.size));var u=o.mul(hn(r.shape)).notEqual(rn(0)).sum().toFloat();return i.sum().div(u)}throw Error("Unknown reduction: "+n)}}),Rc=Qe({cosineDistance_:function(t,e,n,r,o){void 0===o&&(o=bc.SUM_BY_NONZERO_WEIGHTS);var i=We(t,"labels","cosineDistance"),a=We(e,"predictions","cosineDistance"),s=null;null!=r&&(s=We(r,"weights","cosineDistance")),w(i.shape,a.shape,"Error in cosineDistance: ");var u=rn(1).sub(i.mul(a).sum(n,!0));return Sc(u,s,o)}}),Nc=Qe({hingeLoss_:function(t,e,n,r){void 0===r&&(r=bc.SUM_BY_NONZERO_WEIGHTS);var o=We(t,"labels","hingeLoss"),i=We(e,"predictions","hingeLoss"),a=null;null!=n&&(a=We(n,"weights","hingeLoss")),w(o.shape,i.shape,"Error in hingeLoss: ");var s=rn(1);o=rn(2).mul(o).sub(s);var u=s.sub(o.mul(i)).relu();return Sc(u,a,r)}}),kc=Qe({huberLoss_:function(t,e,n,r,o){void 0===r&&(r=1),void 0===o&&(o=bc.SUM_BY_NONZERO_WEIGHTS);var i=We(t,"labels","huberLoss"),a=We(e,"predictions","huberLoss"),s=null;null!=n&&(s=We(n,"weights","huberLoss")),w(i.shape,a.shape,"Error in huberLoss: ");var u=rn(r),c=a.sub(i).abs(),l=ku(c,u),h=c.sub(l),p=rn(.5).mul(l.square()).add(u.mul(h));return Sc(p,s,o)}}),Ac=Qe({logLoss_:function(t,e,n,r,o){void 0===r&&(r=1e-7),void 0===o&&(o=bc.SUM_BY_NONZERO_WEIGHTS);var i=We(t,"labels","logLoss"),a=We(e,"predictions","logLoss"),s=null;null!=n&&(s=We(n,"weights","logLoss")),w(i.shape,a.shape,"Error in logLoss: ");var u=rn(1),c=rn(r),l=i.mul(a.add(c).log()).neg().sub(u.sub(i).mul(u.sub(a).add(c).log()));return Sc(l,s,o)}}),Tc=Qe({meanSquaredError_:function(t,e,n,r){void 0===r&&(r=bc.SUM_BY_NONZERO_WEIGHTS);var o=We(t,"labels","meanSquaredError"),i=We(e,"predictions","meanSquaredError"),a=null;null!=n&&(a=We(n,"weights","meanSquaredError")),w(o.shape,i.shape,"Error in meanSquaredError: ");var s=o.squaredDifference(i);return Sc(s,a,r)}}),Dc=Qe({sigmoidCrossEntropy_:function(t,e,n,r,o){void 0===r&&(r=0),void 0===o&&(o=bc.SUM_BY_NONZERO_WEIGHTS);var i=We(t,"multiClassLabels","sigmoidCrossEntropy"),a=We(e,"logits","sigmoidCrossEntropy"),s=null;if(null!=n&&(s=We(n,"weights","sigmoidCrossEntropy")),w(i.shape,a.shape,"Error in sigmoidCrossEntropy: "),r>0){var u=rn(r),c=rn(1),l=rn(.5);i=i.mul(c.sub(u)).add(l.mul(u))}var h=function(t,e){var n=We(t,"labels","sigmoidCrossEntropyWithLogits"),r=We(e,"logits","sigmoidCrossEntropyWithLogits");w(n.shape,r.shape,"Error in sigmoidCrossEntropyWithLogits: ");var o=r.relu(),i=r.mul(n),a=r.abs().neg().exp().log1p();return o.sub(i).add(a)}(i,a);return Sc(h,s,o)}}),Fc=Qe({softmaxCrossEntropy_:function(t,e,n,r,o){void 0===r&&(r=0),void 0===o&&(o=bc.SUM_BY_NONZERO_WEIGHTS);var i=We(t,"onehotLabels","softmaxCrossEntropy"),a=We(e,"logits","softmaxCrossEntropy"),s=null;if(null!=n&&(s=We(n,"weights","softmaxCrossEntropy")),w(i.shape,a.shape,"Error in softmaxCrossEntropy: "),r>0){var u=rn(r),c=rn(1),l=rn(i.shape[1]);i=i.mul(c.sub(u)).add(u.div(l))}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 Er(function(t,e,r){var o=e.logSumExp([n],!0),i=e.toFloat().sub(o);return r([t,i]),{value:i.mul(t).neg().sum([n]),gradFunc:function(t,e){var r=e[0],o=e[1],i=je(t.shape,[n]);return[t.reshape(i).mul(r.toFloat().sub(o.exp())),t.reshape(i).mul(o.exp().sub(r.toFloat()))]}}})(t,e)}(i,a);return Sc(h,s,o)}}),Mc=Object.freeze({get Reduction(){return bc},absoluteDifference:Ic,computeWeightedLoss:Sc,cosineDistance:Rc,hingeLoss:Nc,huberLoss:kc,logLoss:Ac,meanSquaredError:Tc,sigmoidCrossEntropy:Dc,softmaxCrossEntropy:Fc});function Oc(t,e){return void 0===e&&(e=!1),Mt.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],r=t.shape[1],o=Gn(n),i=t.clone(),a=an([[1]],[1,1]),s=a.clone(),u=n>=r?r:n,c=function(t){var e,u=i,c=s,l=o;e=Mt.tidy(function(){var e=i.slice([t,t],[n-t,1]),u=e.norm(),c=i.slice([t,t],[1,1]),l=c.sign().neg(),h=c.sub(l.mul(u)),p=e.div(h);s=1===p.shape[0]?a.clone():a.concat(p.slice([1,0],[p.shape[0]-1,p.shape[1]]),0);var f=l.matMul(h).div(u).neg(),d=i.slice([t,0],[n-t,r]),v=f.mul(s);i=0===t?d.sub(v.matMul(s.transpose().matMul(d))):i.slice([0,0],[t,r]).concat(d.sub(v.matMul(s.transpose().matMul(d))),0);var m=o.slice([0,t],[n,o.shape[1]-t]);return o=0===t?m.sub(m.matMul(s).matMul(v.transpose())):o.slice([0,0],[n,t]).concat(m.sub(m.matMul(s).matMul(v.transpose())),1),[s,i,o]}),s=e[0],i=e[1],o=e[2],Me([u,c,l])},l=0;lr&&(o=o.slice([0,0],[n,r]),i=i.slice([0,0],[r,r])),[o,i]})}var Pc=Qe({gramSchmidt_:function(t){var e;if(Array.isArray(t)){e=!1,b(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],r=function(e){b(t[e].shape[0]===n,function(){return"Gram-Schmidt: Non-unique lengths found in the input vectors: ("+t[e].shape[0]+" vs. "+n+")"})},o=1;o0)for(var n=0;n= 2, but got rank "+t.rank);if(2===t.rank)return Oc(t,e);var n=t.shape.slice(0,t.shape.length-2).reduce(function(t,e){return t*e}),r=ar(t.reshape([n,t.shape[t.shape.length-2],t.shape[t.shape.length-1]]),0),o=[],i=[];return r.forEach(function(t){var n=Oc(t,e),r=n[0],a=n[1];o.push(r),i.push(a)}),[rr(o,0).reshape(t.shape),rr(i,0).reshape(t.shape)]}}),Lc=Object.freeze({gramSchmidt:Pc,qr:Bc});function Wc(t,e,n,r,o){null==r&&(r=.5),null==o&&(o=Number.NEGATIVE_INFINITY);var i=t.shape[0];return n=Math.min(n,i),b(0<=r&&r<=1,function(){return"iouThreshold must be in [0, 1], but was '"+r+"'"}),b(2===t.rank,function(){return"boxes must be a 2D tensor, but was of rank '"+t.rank+"'"}),b(4===t.shape[1],function(){return"boxes must have 4 columns, but 2nd dimension was "+t.shape[1]}),b(1===e.rank,function(){return"scores must be a 1D tensor"}),b(e.shape[0]===i,function(){return"scores has incompatible shape with boxes. Expected "+i+", but was "+e.shape[0]}),{maxOutputSize:n,iouThreshold:r,scoreThreshold:o}}var zc=Qe({resizeBilinear_:function(t,e,n){void 0===n&&(n=!1);var r=We(t,"images","resizeBilinear");b(3===r.rank||4===r.rank,function(){return"Error in resizeBilinear: x must be rank 3 or 4, but got rank "+r.rank+"."}),b(2===e.length,function(){return"Error in resizeBilinear: new shape must 2D, but got shape "+e+"."});var o=r,i=!1;3===r.rank&&(i=!0,o=r.as4D(1,r.shape[0],r.shape[1],r.shape[2]));var a=e[0],s=e[1],u=Mt.runKernel(function(t,e){return e([o]),t.resizeBilinear(o,a,s,n)},{batchImages:o},function(t,e){return{batchImages:function(){return Mt.runKernel(function(r){return r.resizeBilinearBackprop(t,e[0],n)},{})}}});return i?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}}),Uc=Qe({resizeNearestNeighbor_:function(t,e,n){void 0===n&&(n=!1);var r=We(t,"images","resizeNearestNeighbor");b(3===r.rank||4===r.rank,function(){return"Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank "+r.rank+"."}),b(2===e.length,function(){return"Error in resizeNearestNeighbor: new shape must 2D, but got shape "+e+"."}),b("float32"===r.dtype||"int32"===r.dtype,function(){return"`images` must have `int32` or `float32` as dtype"});var o=r,i=!1;3===r.rank&&(i=!0,o=r.as4D(1,r.shape[0],r.shape[1],r.shape[2]));var a=e[0],s=e[1],u=Mt.runKernel(function(t,e){return e([o]),t.resizeNearestNeighbor(o,a,s,n)},{batchImages:o},function(t,e){return{batchImages:function(){return Mt.runKernel(function(r){return r.resizeNearestNeighborBackprop(t,e[0],n)},{})}}});return i?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}}),Vc=Qe({nonMaxSuppression_:function(t,e,n,r,o){void 0===r&&(r=.5),void 0===o&&(o=Number.NEGATIVE_INFINITY);var i=We(t,"boxes","nonMaxSuppression"),a=We(e,"scores","nonMaxSuppression"),s=Wc(i,a,n,r,o);return n=s.maxOutputSize,r=s.iouThreshold,o=s.scoreThreshold,Mt.runKernel(function(t){return t.nonMaxSuppression(i,a,n,r,o)},{$boxes:i})}}),Gc=Qe({cropAndResize_:function(t,e,n,r,o,i){var a=We(t,"image","cropAndResize","float32"),s=We(e,"boxes","cropAndResize","float32"),u=We(n,"boxInd","cropAndResize","int32");o=o||"bilinear",i=i||0;var c=s.shape[0];return b(4===a.rank,function(){return"Error in cropAndResize: image must be rank 4,but got rank "+a.rank+"."}),b(2===s.rank&&4===s.shape[1],function(){return"Error in cropAndResize: boxes must be have size ["+c+",4] but had shape "+s.shape+"."}),b(1===u.rank&&u.shape[0]===c,function(){return"Error in cropAndResize: boxInd must be have size ["+c+"] but had shape "+s.shape+"."}),b(2===r.length,function(){return"Error in cropAndResize: cropSize must be of length 2, but got length "+r.length+"."}),b(r[0]>=1&&r[1]>=1,function(){return"cropSize must be atleast [1,1], but was "+r}),b("bilinear"===o||"nearest"===o,function(){return"method must be bilinear or nearest, but was "+o}),Mt.runKernel(function(t,e){return t.cropAndResize(a,s,u,r,o,i)},{$image:a,$boxes:s})}}),jc=Object.freeze({resizeBilinear:zc,resizeNearestNeighbor:Uc,nonMaxSuppression:Vc,nonMaxSuppressionAsync:function(t,e,n,r,o){return void 0===r&&(r=.5),void 0===o&&(o=Number.NEGATIVE_INFINITY),c(this,void 0,void 0,function(){var i,a,s,u,c,h;return l(this,function(l){switch(l.label){case 0:return i=We(t,"boxes","nonMaxSuppressionAsync"),a=We(e,"scores","nonMaxSuppressionAsync"),s=Wc(i,a,n,r,o),n=s.maxOutputSize,r=s.iouThreshold,o=s.scoreThreshold,[4,i.data()];case 1:return u=l.sent(),[4,a.data()];case 2:return c=l.sent(),h=Yr(u,c,n,r,o),i!==t&&i.dispose(),a!==e&&a.dispose(),[2,h]}})})},cropAndResize:Gc}),Hc=Qe({matMul_:function(t,e,n,r,o,i){var a;void 0===n&&(n=!1),void 0===r&&(r=!1),void 0===i&&(i="linear");var s=We(t,"a","fused matMul"),u=We(e,"b","fused matMul");a=Rt(s,u),s=a[0],u=a[1];var c=n?s.shape[s.rank-2]:s.shape[s.rank-1],l=r?u.shape[u.rank-1]:u.shape[u.rank-2],h=n?s.shape[s.rank-1]:s.shape[s.rank-2],p=r?u.shape[u.rank-2]:u.shape[u.rank-1],f=s.shape.slice(0,-2),d=u.shape.slice(0,-2),v=_(f),m=_(d);b(s.rank>=2&&u.rank>=2&&s.rank===u.rank,function(){return"Error in fused matMul: inputs must have the same rank of at least 2, got ranks "+s.rank+" and "+u.rank+"."}),b(I(f,d),function(){return"Error in fused matMul: outer dimensions ("+f+") and ("+d+") of Tensors with shapes "+s.shape+" and "+u.shape+" must match."}),b(c===l,function(){return"Error in fused matMul: inner shapes ("+c+") and ("+l+") of Tensors with shapes "+s.shape+" and "+u.shape+" and transposeA="+n+" and transposeB="+r+" must match."});var g,y=s.shape.slice(0,-2).concat([h,p]),x=n?s.as3D(v,c,h):s.as3D(v,h,c),w=r?u.as3D(m,p,l):u.as3D(m,l,p);null!=o&&Tr(y,(g=Rt(g=We(o,"bias","fused matMul"),s)[0]).shape);var C={$a:x,$b:w};return null!=o&&(C.$bias=g),Mt.runKernel(function(t,e){var o=t.fusedBatchMatMul(x,w,n,r,g,i);return e([x,w,o]),o},C,function(t,e){var a,s=e[0],u=e[1],c=e[2];if(null==i||"linear"===i)a=t;else{if("relu"!==i)throw new Error("Gradient for activation "+i+" has not been implemented yet.");a=t.mul(c.step())}var l={};return null!=o&&(l={$bias:function(){var t=a,e=Ar(g.shape,a.shape);return e.length>0&&(t=t.sum(e)),t.reshape(g.shape)}}),n||r?!n&&r?Object.assign({$a:function(){return a.matMul(u,!1,!1)},$b:function(){return a.matMul(s,!0,!1)}},l):n&&!r?Object.assign({$a:function(){return u.matMul(a,!1,!0)},$b:function(){return s.matMul(a,!1,!1)}},l):Object.assign({$a:function(){return u.matMul(a,!0,!0)},$b:function(){return a.matMul(s,!0,!0)}},l):Object.assign({$a:function(){return a.matMul(u,!1,!0)},$b:function(){return s.matMul(a,!0,!1)}},l)}).reshape(y)}}),qc=Object.freeze({matMul:Hc}),$c=Object.freeze({image:jc,linalg:Lc,losses:Mc,spectral:vc,fused:qc,signal:_c,op:Qe,batchNormalization2d:ds,batchNormalization3d:vs,batchNormalization4d:ms,batchNormalization:gs,batchNorm:ys,batchNorm2d:xs,batchNorm3d:bs,batchNorm4d:ws,complex:Je,real:Ze,imag:tn,concat:yn,concat1d:xn,concat2d:bn,concat3d:wn,concat4d:Cn,split:En,conv1d:Is,conv2d:Ss,conv3d:Rs,conv2dDerFilter:Ns,depthwiseConv2d:ks,separableConv2d:As,conv2dTranspose:Ts,matMul:Ds,dot:Fs,outerProduct:Ms,reverse:Os,reverse1d:Ps,reverse2d:Bs,reverse3d:Ls,reverse4d:Ws,maxPool:Vs,avgPool:Gs,pool:js,slice:Hs,slice1d:qs,slice2d:$s,slice3d:Ks,slice4d:Xs,abs:Ra,acos:Na,acosh:ka,asin:Aa,asinh:Ta,atan:Da,atanh:Fa,ceil:Ma,clipByValue:Oa,cos:Pa,cosh:Ba,erf:La,exp:Wa,expm1:za,floor:Ua,log:Va,log1p:Ga,logSigmoid:ja,neg:Ha,reciprocal:qa,round:$a,rsqrt:Ka,sigmoid:Xa,sign:Ya,isNaN:Qa,isInf:Ja,isFinite:Za,sin:ts,sinh:es,softplus:ns,sqrt:rs,square:os,step:is,tan:as,tanh:ss,all:Qs,any:Js,argMax:Zs,argMin:tu,logSumExp:eu,max:nu,mean:ru,min:ou,moments:iu,sum:au,prod:su,equal:uu,equalStrict:cu,greater:lu,greaterEqual:hu,greaterEqualStrict:pu,greaterStrict:fu,less:du,lessEqual:vu,lessEqualStrict:mu,lessStrict:gu,notEqual:yu,notEqualStrict:xu,add:bu,addN:wu,addStrict:Cu,atan2:Eu,div:_u,divStrict:Iu,floorDiv:Su,maximum:Ru,maximumStrict:Nu,minimum:ku,minimumStrict:Au,mod:Tu,modStrict:Du,mul:Fu,mulStrict:Mu,pow:Ou,powStrict:Pu,squaredDifference:Bu,squaredDifferenceStrict:Lu,sub:Wu,subStrict:zu,elu:$u,leakyRelu:Ku,prelu:Xu,relu:Yu,selu:Qu,logicalAnd:Uu,logicalNot:Vu,logicalOr:Gu,logicalXor:ju,where:Hu,whereAsync:qu,buffer:On,print:Pn,batchToSpaceND:Bn,cast:Ln,clone:Wn,cumsum:zn,depthToSpace:Un,expandDims:Vn,eye:Gn,multinomial:jn,oneHot:Hn,pad:qn,pad1d:$n,pad2d:Kn,pad3d:Xn,pad4d:Yn,rand:Qn,randomNormal:Jn,randomUniform:Zn,reshape:tr,spaceToBatchND:er,squeeze:nr,stack:rr,tile:or,truncatedNormal:ir,unstack:ar,setdiff1dAsync:sr,fill:fn,linspace:dn,ones:hn,range:vn,scalar:rn,tensor:en,tensor1d:on,tensor2d:an,tensor3d:sn,tensor4d:un,tensor5d:cn,tensor6d:ln,zeros:pn,onesLike:mn,zerosLike:gn,transpose:Ju,softmax:Ir,logSoftmax:Sr,localResponseNormalization:Zu,norm:tc,gather:rc,unsortedSegmentSum:oc,basicLSTMCell:ic,multiRNNCell:ac,movingAverage:sc,stridedSlice:uc,topk:cc,scatterND:lc,fft:hc,ifft:pc,rfft:fc,irfft:dc,sparseToDense:mc,gatherND:gc,dropout:yc,hannWindow:wc,hammingWindow:Cc,frame:Ec}),Kc=function(){function t(){if(this.blockSize=48,this.firstUse=!0,f.get("IS_BROWSER")){var t=function(){if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(300,150);if("undefined"!=typeof document)return document.createElement("canvas");throw new Error("Cannot create a canvas in this context")}();this.fromPixels2DContext=t.getContext("2d")}this.data=new Rr(this,Mt)}return t.prototype.register=function(t,e,n){if(this.firstUse&&(this.firstUse=!1,f.get("IS_NODE")&&Pe("\n============================\nHi there 👋. Looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, which binds to TensorFlow C++, by running npm i @tensorflow/tfjs-node, or npm i @tensorflow/tfjs-node-gpu if you have CUDA. Then call require('@tensorflow/tfjs-node'); (-gpu suffix for CUDA) at the start of your program. Visit https://github.com/tensorflow/tfjs-node for more details.\n============================\n")),this.data.has(t))throw new Error("Data buffer is already registered");this.data.set(t,{dtype:n})},t.prototype.write=function(t,e){if(null==e)throw new Error("MathBackendCPU.write(): values can not be null");this.data.get(t).values=e},t.prototype.fromPixels=function(t,e){if(null==t)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");var n,r;if(f.get("IS_NODE")&&null==t.getContext)throw new Error("When running in node, pixels must be an HTMLCanvasElement like the one returned by the `canvas` npm package");if(null!=t.getContext)n=t.getContext("2d").getImageData(0,0,t.width,t.height).data;else if(t instanceof ImageData||t.data instanceof Uint8Array)n=t.data;else{if(!(t instanceof HTMLImageElement||t instanceof HTMLVideoElement))throw new Error("pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData or {data: Uint32Array, width: number, height: number}, but was "+t.constructor.name);if(null==this.fromPixels2DContext)throw new Error("Can't read pixels from HTMLImageElement outside the browser.");this.fromPixels2DContext.canvas.width=t.width,this.fromPixels2DContext.canvas.height=t.height,this.fromPixels2DContext.drawImage(t,0,0,t.width,t.height),n=this.fromPixels2DContext.getImageData(0,0,t.width,t.height).data}if(4===e)r=new Int32Array(n);else{var o=t.width*t.height;r=new Int32Array(o*e);for(var i=0;ip&&(p=v,f=d)}u[l]=f}return a},t.prototype.cumsum=function(t,e,n,r){if(this.assertNotComplex(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 o=It(t.dtype,"int32"),i=pn(t.shape,o),a=this.readSync(i.dataId),s=this.readSync(t.dataId),u=t.shape[t.rank-1],c=r?function(t,e){return t+u-e-1}:function(t,e){return t+e},l=0;le?1:0})},t.prototype.greaterEqual=function(t,e){return this.assertNotComplex([t,e],"greaterEqual"),this.broadcastedBinaryOp(t,e,"bool",function(t,e){return t>=e?1:0})},t.prototype.logicalNot=function(t){this.assertNotComplex(t,"logicalNot");for(var e=this.readSync(t.dataId),n=new Uint8Array(e.length),r=0;r1||1===e.rank?1:e.shape[1],l=0;l=0&&e>=0?n:(n+e)%e})},t.prototype.max=function(t,e){this.assertNotComplex(t,"max"),He("max",e,t.rank);for(var n=Ge(t.shape,e),r=n[0],o=n[1],i=pn(r,t.dtype),a=_(o),s=this.readSync(i.dataId),u=this.readSync(t.dataId),c=0;ch&&(h=f)}s[c]=h}return i},t.prototype.maximum=function(t,e){return this.assertNotComplex([t,e],"maximum"),this.broadcastedBinaryOp(t,e,t.dtype,function(t,e){return Math.max(t,e)})},t.prototype.all=function(t,e){this.assertNotComplex(t,"all"),He("all",e,t.rank);for(var n=Ge(t.shape,e),r=n[0],o=n[1],i=pn(r,t.dtype),a=_(o),s=this.readSync(i.dataId),u=this.readSync(t.dataId),c=0;c0?n[r]=1:n[r]=0;return mt.make(t.shape,{values:n})},t.prototype.isNaN=function(t){this.assertNotComplex(t,"x");for(var e=this.readSync(t.dataId),n=new Uint8Array(e.length),r=0;r.5?n[r]=Math.ceil(e[r]):n[r]=o%2==0?o:o+1}return mt.make(t.shape,{values:n})},t.prototype.exp=function(t){this.assertNotComplex(t,"exp");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r=0?o:Math.exp(o)-1}return mt.make(t.shape,{values:e})},t.prototype.eluDer=function(t,e){this.assertNotComplex([t,e],"eluDer");for(var n=new Float32Array(e.size),r=this.readSync(e.dataId),o=this.readSync(t.dataId),i=0;i=1?o[i]:o[i]*(a+1)}return mt.make(e.shape,{values:n})},t.prototype.selu=function(t){this.assertNotComplex(t,"selu");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r=0?1.0507009873554805*o:1.7580993408473768*(Math.exp(o)-1)}return mt.make(t.shape,{values:e})},t.prototype.clip=function(t,e,n){this.assertNotComplex(t,"clip");for(var r=new Float32Array(t.size),o=this.readSync(t.dataId),i=0;in?n:a-e,s=r[o]0?1:e}return mt.make(t.shape,{values:n})},t.prototype.conv2d=function(t,e,n){this.assertNotComplex([t,e],"conv2d");for(var r=n.filterHeight,o=n.filterWidth,i=n.dilationHeight,a=n.dilationWidth,s=n.padInfo.left,u=n.padInfo.top,c=On(n.outShape,t.dtype),l=this.readSync(t.dataId),h=this.readSync(e.dataId),p=c.values,f=0;f=n.inHeight))for(var w=x*e.strides[0],C=d+b*t.strides[1],E=0;E=n.inWidth))for(var N=w+S*e.strides[1],k=C+R*n.inChannels,A=N,T=0;T=n.inDepth))for(var _=C*e.strides[0],I=g+E*t.strides[1],S=0;S=n.inHeight))for(var T=_+k*e.strides[1],D=I+A*t.strides[2],F=0;F=n.inWidth))for(var L=T+P*e.strides[2],W=D+B*n.inChannels,z=L,U=0;U=n.inHeight))for(var C=b*e.strides[0],E=v+w*t.strides[1],_=0;_=n.inWidth))for(var k=C+R*e.strides[1],A=E+N*n.inChannels,T=I,D=k,F=0;FT?T=B:"avg"===n&&(D+=B,F++)}if(isNaN(T))break}d[S+R*g+w]="avg"===n?D/F:T}return f.toTensor()},t.prototype.maxPool=function(t,e){return this.pool(t,e,"max")},t.prototype.maxPoolPositions=function(t,e){for(var n=On(e.outShape,"int32"),r=e.strideHeight,o=e.strideWidth,i=e.dilationHeight,a=e.dilationWidth,s=e.effectiveFilterHeight,u=e.effectiveFilterWidth,c=e.padInfo.top,l=e.padInfo.left,h=this.bufferSync(t),p=0;pC&&(C=N,E=I*u+R)}n.set(E,p,d,y,f)}}return n.toTensor()},t.prototype.maxPoolBackprop=function(t,e,n,r){this.assertNotComplex([e,n],"maxPoolBackprop");for(var o=this.maxPoolPositions(e,r),i=r.strideHeight,a=r.strideWidth,s=r.dilationHeight,u=r.dilationWidth,c=r.effectiveFilterHeight,l=r.effectiveFilterWidth,h=l-1-r.padInfo.left,p=c-1-r.padInfo.top,f=On(e.shape,"float32"),d=this.bufferSync(o),v=this.bufferSync(t),m=0;m=r.outHeight||Math.floor(_)!==_))for(var I=0;I=r.outWidth||Math.floor(S)!==S)){var R=c*l-1-d.get(m,_,S,g)===E*l+I?1:0;0!==R&&(C+=v.get(m,_,S,g)*R)}}}f.set(C,m,y,x,g)}return f.toTensor()},t.prototype.avgPoolBackprop=function(t,e,n){this.assertNotComplex([t,e],"avgPoolBackprop");for(var r=n.strideHeight,o=n.strideWidth,i=n.filterHeight,a=n.filterWidth,s=n.dilationHeight,u=n.dilationWidth,c=n.effectiveFilterHeight,l=n.effectiveFilterWidth,h=l-1-n.padInfo.left,p=c-1-n.padInfo.top,f=On(e.shape,"float32"),d=1/(i*a),v=this.bufferSync(t),m=0;m=n.outHeight||Math.floor(_)!==_))for(var I=0;I=n.outWidth||Math.floor(S)!==S||(C+=v.get(m,_,S,g))}}f.set(C*d,m,y,x,g)}return f.toTensor()},t.prototype.cast=function(t,e){return Vr(t,e,this)},t.prototype.reshape=function(t,e){return Gr(t,e)},t.prototype.avgPool=function(t,e){return this.assertNotComplex(t,"avgPool"),this.pool(t,e,"avg").toFloat()},t.prototype.resizeBilinear=function(t,e,n,r){this.assertNotComplex(t,"resizeBilinear");for(var o=t.shape,i=o[0],a=o[1],s=o[2],u=o[3],c=this.readSync(t.dataId),l=new Float32Array(_([i,e,n,u])),h=[r&&e>1?a-1:a,r&&n>1?s-1:s],p=[r&&e>1?e-1:e,r&&n>1?n-1:n],f=0,d=h[0]/p[0],v=h[1]/p[1],m=0;m1?i-1:i,n&&l>1?a-1:a],f=[n&&c>1?c-1:c,n&&l>1?l-1:l],d=p[0]/f[0],v=p[1]/f[1],m=this.readSync(t.dataId),g=0,y=0;y1?a-1:a,r&&n>1?s-1:s],p=[r&&e>1?e-1:e,r&&n>1?n-1:n],f=h[0]/p[0],d=h[1]/p[1],v=0,m=0;m1?i-1:i,n&&l>1?a-1:a],d=[n&&c>1?c-1:c,n&&l>1?l-1:l],v=f[0]/d[0],m=f[1]/d[1],g=1/v,y=1/m,x=2*Math.ceil(g)+2,b=2*Math.ceil(y)+2,w=0;w=c)){var O=C+M*t.strides[1],P=M*v;if(E===Math.min(i-1,n?Math.round(P):Math.floor(P)))for(var B=0;B=l)){var W=O+L*t.strides[2],z=L*m;R===Math.min(a-1,n?Math.round(z):Math.floor(z))&&(D+=p[W+T])}}}}h[N+T]=D}return un(h,e.shape,e.dtype)},t.prototype.batchNormalization=function(t,e,n,r,o,i){this.assertNotComplex([t,e,n,o,i],"batchNorm");for(var a=this.readSync(t.dataId),s=this.readSync(e.dataId),u=this.readSync(n.dataId),c=o?this.readSync(o.dataId):new Float32Array([1]),l=i?this.readSync(i.dataId):new Float32Array([0]),h=new Float32Array(a.length),p=l.length,f=c.length,d=u.length,v=s.length,m=0,g=0,y=0,x=0,b=0;b=p&&(m=0),g>=v&&(g=0),y>=f&&(y=0),x>=d&&(x=0);return un(h,t.shape)},t.prototype.localResponseNormalization4D=function(t,e,n,r,o){this.assertNotComplex(t,"localResponseNormalization4D");var i=t.shape[3],a=i-1,s=this.readSync(t.dataId),u=t.size,c=new Float32Array(u);function l(t){for(var n=t%i,r=t-n+Math.max(0,n-e),o=t-n+Math.min(n+e,a),u=0;r<=o;r++){var c=s[r];u+=c*c}return u}for(var h=0;h=0&&i[a]1,function(){return"blockSize should be > 1 for depthToSpace, but was: "+e});for(var r=t.shape[0],o=t.shape[1],i=t.shape[2],a=t.shape[3],s=o*e,u=i*e,c=a/(e*e),l=this.readSync(t.dataId),h=new Float32Array(r*s*u*c),p=0,f=0;f=s))for(var R=p>1?(_-C)*(u-1)/(p-1):0,N=f>1?(I-E)*(c-1)/(f-1):0,k=0;k1?C*(u-1)+k*R:.5*(C+_)*(u-1);if(A<0||A>u-1)for(var T=0;T1?E*(c-1)+T*N:.5*(E+I)*(c-1))<0||H>c-1)for(D=0;D1?E*(c-1)+T*N:.5*(E+I)*(c-1))<0||H>c-1)for(D=0;D=t.size/s)throw new Error("Invalid indices: "+f+" does not index into "+t.shape);for(var g=0;g=r/o)throw new Error("Invalid indices: "+v+" does not index into "+n);for(var x=0;x0,function(){return"scheme must not be an empty string."});var r=t.getInstance();b(null==r.managers[e],function(){return"A model store manager is already registered for scheme '"+e+"'."}),r.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 cl(t){if(-1===t.indexOf(sl))throw new Error("The url string provided does not contain a scheme. Supported schemes are: "+ul.getSchemes().join(","));return{scheme:t.split(sl)[0],path:t.split(sl)[1]}}function ll(t,e,n){return void 0===n&&(n=!1),c(this,void 0,void 0,function(){var r,o,i,a,s,u,c,h,p;return l(this,function(l){switch(l.label){case 0:return b(t!==e,function(){return"Old path and new path are the same: '"+t+"'"}),b((r=al.getLoadHandlers(t)).length>0,function(){return"Copying failed because no load handler is found for source URL "+t+"."}),b(r.length<2,function(){return"Copying failed because more than one ("+r.length+") load handlers for source URL "+t+"."}),o=r[0],b((i=al.getSaveHandlers(e)).length>0,function(){return"Copying failed because no save handler is found for destination URL "+e+"."}),b(i.length<2,function(){return"Copying failed because more than one ("+r.length+") save handlers for destination URL "+e+"."}),a=i[0],s=cl(t).scheme,u=cl(t).path,c=s===cl(t).scheme,[4,o.load()];case 1:return h=l.sent(),n&&c?[4,ul.getManager(s).removeModel(u)]:[3,3];case 2:l.sent(),l.label=3;case 3:return[4,a.save(h)];case 4:return p=l.sent(),!n||c?[3,6]:[4,ul.getManager(s).removeModel(u)];case 5:l.sent(),l.label=6;case 6:return[2,p.modelArtifactsInfo]}})})}var hl="models_store",pl="model_info_store";function fl(){if(!f.getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");var t=window,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 dl(t){var e=t.result;e.createObjectStore(hl,{keyPath:"modelPath"}),e.createObjectStore(pl,{keyPath:"modelPath"})}var vl=function(){function t(t){if(this.indexedDB=fl(),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 c(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 c(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,r){var o=n.indexedDB.open("tensorflowjs",1);o.onupgradeneeded=function(){return dl(o)},o.onsuccess=function(){var i=o.result;if(null==e){var a=i.transaction(hl,"readonly"),s=a.objectStore(hl).get(n.modelPath);s.onsuccess=function(){if(null==s.result)return i.close(),r(new Error("Cannot find model with path '"+n.modelPath+"' in IndexedDB."));t(s.result.modelArtifacts)},s.onerror=function(t){return i.close(),r(s.error)},a.oncomplete=function(){return i.close()}}else{var u,c=il(e),l=i.transaction(pl,"readwrite"),h=l.objectStore(pl),p=h.put({modelPath:n.modelPath,modelArtifactsInfo:c});p.onsuccess=function(){var o=(u=i.transaction(hl,"readwrite")).objectStore(hl).put({modelPath:n.modelPath,modelArtifacts:e,modelArtifactsInfo:c});o.onsuccess=function(){return t({modelArtifactsInfo:c})},o.onerror=function(t){var e=(h=l.objectStore(pl)).delete(n.modelPath);e.onsuccess=function(){return i.close(),r(o.error)},e.onerror=function(t){return i.close(),r(o.error)}}},p.onerror=function(t){return i.close(),r(p.error)},l.oncomplete=function(){null==u?i.close():u.oncomplete=function(){return i.close()}}}},o.onerror=function(t){return r(o.error)}})},t.URL_SCHEME="indexeddb://",t}(),ml=function(t){return f.getBool("IS_BROWSER")&&!Array.isArray(t)&&t.startsWith(vl.URL_SCHEME)?(e=t.slice(vl.URL_SCHEME.length),new vl(e)):null;var e};al.registerSaveRouter(ml),al.registerLoadRouter(ml);var gl=function(){function t(){this.indexedDB=fl()}return t.prototype.listModels=function(){return c(this,void 0,void 0,function(){var t=this;return l(this,function(e){return[2,new Promise(function(e,n){var r=t.indexedDB.open("tensorflowjs",1);r.onupgradeneeded=function(){return dl(r)},r.onsuccess=function(){var t=r.result,o=t.transaction(pl,"readonly"),i=o.objectStore(pl).getAll();i.onsuccess=function(){for(var t={},n=0,r=i.result;n0,function(){return"promises must be a none empty array"})}(t),function(t,e){b(t>=0&&t<=1,function(){return"Progress fraction must be in range [0, 1], but got startFraction "+t}),b(e>=0&&e<=1,function(){return"Progress fraction must be in range [0, 1], but got endFraction "+e}),b(e>=t,function(){return"startFraction must be no more than endFraction, but got startFraction "+t+" and endFraction "+e})}(n=null==n?0:n,r=null==r?1:r);var o=0;return Promise.all(t.map(function(i){return i.then(function(i){var a=n+ ++o/t.length*(r-n);return e(a),i}),i}))}function Bl(t,e){return c(this,void 0,void 0,function(){var n,r,o,i,a,s,u,c,h;return l(this,function(l){switch(l.label){case 0:return null==e&&(e={}),n=null==e.fetchFunc?nt:e.fetchFunc,r=t.map(function(t){return n(t,e.requestInit)}),o=0,i=.5,null!=e.onProgress?[3,2]:[4,Promise.all(r)];case 1:return a=l.sent(),[3,4];case 2:return[4,Pl(r,e.onProgress,o,i)];case 3:a=l.sent(),l.label=4;case 4:return s=a.map(function(t){return t.arrayBuffer()}),u=.5,c=1,null!=e.onProgress?[3,6]:[4,Promise.all(s)];case 5:return h=l.sent(),[3,8];case 6:return[4,Pl(s,e.onProgress,u,c)];case 7:h=l.sent(),l.label=8;case 8:return[2,h]}})})}function Ll(t){var e=this;return function(n,r,o){return void 0===r&&(r=""),c(e,void 0,void 0,function(){var e,i,a,s,u,c,h,p,f,d;return l(this,function(l){switch(l.label){case 0:if(e=n.map(function(){return!1}),i={},a=null!=o?o.map(function(){return!1}):[],s=[],n.forEach(function(t,n){var r=0;t.weights.forEach(function(t){var u="quantization"in t?t.quantization.dtype:t.dtype,c=Jc[u]*_(t.shape),l=function(){e[n]=!0,null==i[n]&&(i[n]=[]),i[n].push({manifestEntry:t,groupOffset:r,sizeBytes:c})};null!=o?o.forEach(function(e,n){e===t.name&&(l(),a[n]=!0)}):l(),s.push(t.name),r+=c})}),!a.every(function(t){return t}))throw u=o.filter(function(t,e){return!a[e]}),new Error("Could not find weights in manifest with names: "+u.join(", ")+". \nManifest JSON has weights with names: "+s.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=r+(r.endsWith("/")?"":"/")+t;h.push(e)})}),[4,t(h)];case 1:return p=l.sent(),f={},d=0,c.forEach(function(t){for(var e=n[t].paths.length,r=0,o=0;o0,function(){return"URL path for http must not be null, undefined or empty."}),Array.isArray(t)&&b(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 c(this,void 0,void 0,function(){var e,n,r,o;return l(this,function(i){switch(i.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}],r={modelTopology:t.modelTopology,format:t.format,generatedBy:t.generatedBy,convertedBy:t.convertedBy,weightsManifest:n},e.body.append("model.json",new Blob([JSON.stringify(r)],{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((o=i.sent()).ok)return[2,{modelArtifactsInfo:il(t),responses:[o]}];throw new Error("BrowserHTTPRequest.save() failed due to HTTP response status "+o.status+".")}})})},t.prototype.load=function(){return c(this,void 0,void 0,function(){var t,e,n,r,o,i,a,s;return l(this,function(u){switch(u.label){case 0:return[4,this.fetch(this.path,this.requestInit)];case 1:if(!(t=u.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.");u.label=2;case 2:return u.trys.push([2,4,,5]),[4,t.json()];case 3:return e=u.sent(),[3,5];case 4:throw u.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(r=e.modelTopology,o=e.weightsManifest,null==r&&null==o)throw new Error("The JSON from HTTP path "+this.path+" contains neither model topology or manifest for weights.");return null==o?[3,7]:[4,this.loadWeights(o)];case 6:s=u.sent(),i=s[0],a=s[1],u.label=7;case 7:return[2,{modelTopology:r,weightSpecs:i,weightData:a}]}})})},t.prototype.loadWeights=function(t){return c(this,void 0,void 0,function(){var e,n,r,o,i,a,s,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),r=n[0],o=n[1],i=this.weightPathPrefix||r,a=[],s=0,u=t;s0&&(t=u({weightSpecs:this.weightSpecs},t)),null!=this.weightData&&this.weightData.byteLength>0&&(t=u({weightData:this.weightData},t)),null!=this.trainingConfig&&(t=u({trainingConfig:this.trainingConfig},t)),[2,t]})})},t}(),jl=function(){function t(t){this.saveHandler=t}return t.prototype.save=function(t){return c(this,void 0,void 0,function(){return l(this,function(e){return[2,this.saveHandler(t)]})})},t}(),Hl=Object.freeze({browserFiles:function(t){return new Ol(t)},browserHTTPRequest:function(t,e){return Vl(t,e)},concatenateArrayBuffers:rl,decodeWeights:Zc,encodeWeights:function(t,e){return c(this,void 0,void 0,function(){var n,r,o,i,a,s=this;return l(this,function(u){switch(u.label){case 0:for(n=[],r=[],o=Array.isArray(t)?t.map(function(t){return t.name}):Object.keys(t),i=function(i){var a=o[i],u=Array.isArray(t)?t[i].tensor:t[a];if("float32"!==u.dtype&&"int32"!==u.dtype&&"bool"!==u.dtype&&"string"!==u.dtype)throw new Error("Unsupported dtype in weight '"+a+"': "+u.dtype);var h={name:a,shape:u.shape,dtype:u.dtype};if("string"===u.dtype){var p=new Promise(function(t){return c(s,void 0,void 0,function(){var e,n,r;return l(this,function(o){switch(o.label){case 0:return e=h,[4,u.data()];case 1:return n=o.sent(),r=f.platform.encodeUTF8(n.join("\0")),e.byteLength=r.length,e.delimiter="\0",t(r),[2]}})})});r.push(p)}else r.push(u.data());null!=e&&(h.group=e),n.push(h)},a=0;a0&&Number.isInteger(n),function(){return"If provided, numClasses must be a positive integer, but got "+n}),b(1===r.rank,function(){return"Expected the rank of labels to be 1, but got "+r.rank}),b(1===o.rank,function(){return"Expected the rank of predictions to be 1, but got "+o.rank}),b(r.shape[0]===o.shape[0],function(){return"Mismatch in the number of examples: "+r.shape[0]+" vs. "+o.shape[0]+". Labels and predictions should have the same number of elements."}),b(n>0&&Number.isInteger(n),function(){return"numClasses is required to be a positive integer, but got "+n});var i=Hn(r.asType("int32"),n),a=Hn(o.asType("int32"),n);return i.transpose().matMul(a).asType("int32")}}),$l=Object.freeze({confusionMatrix:ql}),Kl=Qe({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.");return Mt.fromPixels(t,e)}}),Xl=Object.freeze({toPixels:function(t,e){return c(this,void 0,void 0,function(){var n,r,o,i,a,s,u,c,h,p,f,d,v,m,g,y,x,b,w,C,E,_,I;return l(this,function(l){switch(l.label){case 0:if(n=We(t,"img","toPixels"),t instanceof mt||(n=n.toInt()),2!==n.rank&&3!==n.rank)throw new Error("toPixels only supports rank 2 or 3 tensors, got rank "+n.rank+".");if(r=n.shape.slice(0,2),o=r[0],i=r[1],(a=2===n.rank?1:n.shape[2])>4||2===a)throw new Error("toPixels only supports depth of size 1, 3 or 4 but got "+a);return[4,n.data()];case 1:return s=l.sent(),u=n.min(),c=n.max(),[4,Promise.all([u.data(),c.data()])];case 2:if(h=l.sent(),p=h[0],f=h[1],d=p[0],v=f[0],u.dispose(),c.dispose(),"float32"===n.dtype){if(d<0||v>1)throw new Error("Tensor values for a float32 Tensor must be in the range [0 - 1] but got range ["+d+" - "+v+"].")}else{if("int32"!==n.dtype)throw new Error("Unsupported type for toPixels: "+n.dtype+". Please use float32 or int32 tensors.");if(d<0||v>255)throw new Error("Tensor values for a int32 Tensor must be in the range [0 - 255] but got range ["+d+" - "+v+"].")}for(m="float32"===n.dtype?255:1,g=new Uint8ClampedArray(i*o*4),y=0;y0,function(){return"Class being registered has an empty-string as its className, which is disallowed."}),Ql.register(t)}var Zl=Object.freeze({Serializable:Yl,SerializationMap:Ql,registerClass:Jl}),th=.001,eh=.1;function nh(){return 32===Mt.backend.floatPrecision()?th:eh}function rh(t,e,n){var r=!0;if((z(t)||z(e))&&(r=!1),z(t)&&z(e)&&(r=!0),r){var o=t.constructor.name,i=e.constructor.name;if(o!==i)throw new Error("Arrays are of different type. Actual: "+o+". Expected: "+i)}if(Array.isArray(t)&&Array.isArray(e)){var a=Be(t),s=Be(e);if(!I(a,s))throw new Error("Arrays have different shapes. Actual: ["+a+"]. Expected: ["+s+"]")}var u=z(t)?t:E(t),c=z(e)?e:E(e);if(u.length!==c.length)throw new Error("Arrays have different lengths actual: "+u.length+" vs expected: "+c.length+".\nActual: "+u+".\nExpected: "+c+".");for(var l=0;ln)}var ih=Object.freeze({TEST_EPSILON_FLOAT16:eh,expectArraysClose:function(t,e,n){return null==n&&(n=nh()),rh(t,e,function(t,e){return oh(t,e,n)})},testEpsilon:nh,expectPromiseToFail:function(t,e){t().then(function(){return e.fail()},function(){return e()})},expectArraysEqual:function(t,e){var n="string"==typeof e||"number"==typeof e||"boolean"==typeof e?[e]:e;return G(t)||G(t[0])||G(e)||G(e[0])?rh(t,n,function(t,e){return t==e}):rh(t,e,function(t,e){return oh(t,e,0)})},expectNumbersClose:function(t,e,n){if(null==n&&(n=nh()),!oh(t,e,n))throw new Error("Numbers differ: actual === "+t+", expected === "+e)},expectValuesInRange:function(t,e,n){for(var r=0;rn)throw new Error("Value out of range:"+t[r]+" low: "+e+", high: "+n)},expectArrayBuffersEqual:function(t,e){expect(new Float32Array(t)).toEqual(new Float32Array(e))}}),ah=Object.freeze({gpgpu_util:Di,webgl_util:Te,MathBackendWebGL:Sa,setWebGLContext:Lt,GPGPUContext:Fi}),sh=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return s(e,t),e.prototype.minimize=function(t,e,n){void 0===e&&(e=!1);var r=this.computeGradients(t,n),o=r.value,i=r.grads;if(null!=n){var a=n.map(function(t){return{name:t.name,tensor:i[t.name]}});this.applyGradients(a)}else this.applyGradients(i);return Me(i),e?o:(o.dispose(),null)},Object.defineProperty(e.prototype,"iterations",{get:function(){return null==this.iterations_&&(this.iterations_=0),this.iterations_},enumerable:!0,configurable:!0}),e.prototype.incrementIterations=function(){this.iterations_=this.iterations+1},e.prototype.computeGradients=function(t,e){return Cr(t,e)},e.prototype.dispose=function(){null!=this.iterations_&&Me(this.iterations_)},e.prototype.saveIterations=function(){return c(this,void 0,void 0,function(){return l(this,function(t){return null==this.iterations_&&(this.iterations_=0),[2,{name:"iter",tensor:rn(this.iterations_,"int32")}]})})},e.prototype.getWeights=function(){return c(this,void 0,void 0,function(){return l(this,function(t){throw new Error("getWeights() is not implemented for this optimizer yet.")})})},e.prototype.setWeights=function(t){return c(this,void 0,void 0,function(){return l(this,function(t){throw new Error("setWeights() is not implemented for this optimizer class "+this.getClassName())})})},e.prototype.extractIterations=function(t){return c(this,void 0,void 0,function(){var e;return l(this,function(n){switch(n.label){case 0:return e=this,[4,t[0].tensor.data()];case 1:return e.iterations_=n.sent()[0],[2,t.slice(1)]}})})},e}(Yl);Object.defineProperty(sh,Symbol.hasInstance,{value:function(t){return null!=t.minimize&&null!=t.computeGradients&&null!=t.applyGradients}});var uh=function(t){function e(e,n,r){void 0===r&&(r=null);var o=t.call(this)||this;return o.learningRate=e,o.rho=n,o.epsilon=r,o.accumulatedGrads=[],o.accumulatedUpdates=[],null==r&&(o.epsilon=Mt.backend.epsilon()),o}return s(e,t),e.prototype.applyGradients=function(t){var e=this;(Array.isArray(t)?t.map(function(t){return t.name}):Object.keys(t)).forEach(function(n,r){var o=Mt.registeredVariables[n];null==e.accumulatedGrads[r]&&(e.accumulatedGrads[r]={originalName:n+"/accum_grad",variable:Fe(function(){return gn(o).variable(!1)})}),null==e.accumulatedUpdates[r]&&(e.accumulatedUpdates[r]={originalName:n+"/accum_var",variable:Fe(function(){return gn(o).variable(!1)})});var i=Array.isArray(t)?t[r].tensor:t[n];if(null!=i){var a=e.accumulatedGrads[r].variable,s=e.accumulatedUpdates[r].variable;Fe(function(){var t=a.mul(e.rho).add(i.square().mul(1-e.rho)),n=s.add(e.epsilon).sqrt().div(a.add(e.epsilon).sqrt()).mul(i),r=s.mul(e.rho).add(n.square().mul(1-e.rho));a.assign(t),s.assign(r);var u=n.mul(-e.learningRate).add(o);o.assign(u)})}}),this.incrementIterations()},e.prototype.dispose=function(){null!=this.accumulatedUpdates&&(Me(this.accumulatedGrads.map(function(t){return t.variable})),Me(this.accumulatedUpdates.map(function(t){return t.variable})))},e.prototype.getWeights=function(){return c(this,void 0,void 0,function(){var t;return l(this,function(e){switch(e.label){case 0:return t=this.accumulatedGrads.concat(this.accumulatedUpdates),[4,this.saveIterations()];case 1:return[2,[e.sent()].concat(t.map(function(t){return{name:t.originalName,tensor:t.variable}}))]}})})},e.prototype.setWeights=function(t){return c(this,void 0,void 0,function(){var e;return l(this,function(n){switch(n.label){case 0:return[4,this.extractIterations(t)];case 1:return t=n.sent(),e=t.length/2,this.accumulatedGrads=t.slice(0,e).map(function(t){return{originalName:t.name,variable:t.tensor.variable(!1)}}),this.accumulatedUpdates=t.slice(e,2*e).map(function(t){return{originalName:t.name,variable:t.tensor.variable(!1)}}),[2]}})})},e.prototype.getConfig=function(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}},e.fromConfig=function(t,e){return new t(e.learningRate,e.rho,e.epsilon)},e.className="AdadeltaOptimizer",e}(sh);Jl(uh);var ch=function(t){function e(e,n){void 0===n&&(n=.1);var r=t.call(this)||this;return r.learningRate=e,r.initialAccumulatorValue=n,r.accumulatedGrads=[],r}return s(e,t),e.prototype.applyGradients=function(t){var e=this;(Array.isArray(t)?t.map(function(t){return t.name}):Object.keys(t)).forEach(function(n,r){var o=Mt.registeredVariables[n];null==e.accumulatedGrads[r]&&(e.accumulatedGrads[r]={originalName:n+"/accumulator",variable:Fe(function(){return fn(o.shape,e.initialAccumulatorValue).variable(!1)})});var i=Array.isArray(t)?t[r].tensor:t[n];if(null!=i){var a=e.accumulatedGrads[r].variable;Fe(function(){var t=a.add(i.square());a.assign(t);var n=i.div(t.add(Mt.backend.epsilon()).sqrt()).mul(-e.learningRate).add(o);o.assign(n)})}}),this.incrementIterations()},e.prototype.dispose=function(){null!=this.accumulatedGrads&&Me(this.accumulatedGrads.map(function(t){return t.variable}))},e.prototype.getWeights=function(){return c(this,void 0,void 0,function(){return l(this,function(t){switch(t.label){case 0:return[4,this.saveIterations()];case 1:return[2,[t.sent()].concat(this.accumulatedGrads.map(function(t){return{name:t.originalName,tensor:t.variable}}))]}})})},e.prototype.setWeights=function(t){return c(this,void 0,void 0,function(){return l(this,function(e){switch(e.label){case 0:return[4,this.extractIterations(t)];case 1:return t=e.sent(),this.accumulatedGrads=t.map(function(t){return{originalName:t.name,variable:t.tensor.variable(!1)}}),[2]}})})},e.prototype.getConfig=function(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}},e.fromConfig=function(t,e){return new t(e.learningRate,e.initialAccumulatorValue)},e.className="Adagrad",e}(sh);Jl(ch);var lh=function(t){function e(e,n,r,o){void 0===o&&(o=null);var i=t.call(this)||this;return i.learningRate=e,i.beta1=n,i.beta2=r,i.epsilon=o,i.accumulatedFirstMoment=[],i.accumulatedSecondMoment=[],Fe(function(){i.accBeta1=rn(n).variable(),i.accBeta2=rn(r).variable()}),null==o&&(i.epsilon=Mt.backend.epsilon()),i}return s(e,t),e.prototype.applyGradients=function(t){var e=this,n=Array.isArray(t)?t.map(function(t){return t.name}):Object.keys(t);Fe(function(){var r=Wu(1,e.accBeta1),o=Wu(1,e.accBeta2);n.forEach(function(n,i){var a=Mt.registeredVariables[n];null==e.accumulatedFirstMoment[i]&&(e.accumulatedFirstMoment[i]={originalName:n+"/m",variable:Fe(function(){return gn(a).variable(!1)})}),null==e.accumulatedSecondMoment[i]&&(e.accumulatedSecondMoment[i]={originalName:n+"/v",variable:Fe(function(){return gn(a).variable(!1)})});var s=Array.isArray(t)?t[i].tensor:t[n];if(null!=s){var u=e.accumulatedFirstMoment[i].variable,c=e.accumulatedSecondMoment[i].variable,l=u.mul(e.beta1).add(s.mul(1-e.beta1)),h=c.mul(e.beta2).add(s.square().mul(1-e.beta2)),p=l.div(r),f=h.div(o);u.assign(l),c.assign(h);var d=p.div(f.sqrt().add(e.epsilon)).mul(-e.learningRate).add(a);a.assign(d)}}),e.accBeta1.assign(e.accBeta1.mul(e.beta1)),e.accBeta2.assign(e.accBeta2.mul(e.beta2))}),this.incrementIterations()},e.prototype.dispose=function(){this.accBeta1.dispose(),this.accBeta2.dispose(),null!=this.accumulatedFirstMoment&&Me(this.accumulatedFirstMoment.map(function(t){return t.variable})),null!=this.accumulatedSecondMoment&&Me(this.accumulatedSecondMoment.map(function(t){return t.variable}))},e.prototype.getWeights=function(){return c(this,void 0,void 0,function(){var t;return l(this,function(e){switch(e.label){case 0:return t=this.accumulatedFirstMoment.concat(this.accumulatedSecondMoment),[4,this.saveIterations()];case 1:return[2,[e.sent()].concat(t.map(function(t){return{name:t.originalName,tensor:t.variable}}))]}})})},e.prototype.setWeights=function(t){return c(this,void 0,void 0,function(){var e,n=this;return l(this,function(r){switch(r.label){case 0:return[4,this.extractIterations(t)];case 1:return t=r.sent(),Fe(function(){n.accBeta1.assign(Ou(n.beta1,n.iterations_+1)),n.accBeta2.assign(Ou(n.beta2,n.iterations_+1))}),e=t.length/2,this.accumulatedFirstMoment=t.slice(0,e).map(function(t){return{originalName:t.name,variable:t.tensor.variable(!1)}}),this.accumulatedSecondMoment=t.slice(e,2*e).map(function(t){return{originalName:t.name,variable:t.tensor.variable(!1)}}),[2]}})})},e.prototype.getConfig=function(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}},e.fromConfig=function(t,e){return new t(e.learningRate,e.beta1,e.beta2,e.epsilon)},e.className="Adam",e}(sh);Jl(lh);var hh=function(t){function e(e,n,r,o,i){void 0===o&&(o=null),void 0===i&&(i=0);var a=t.call(this)||this;return a.learningRate=e,a.beta1=n,a.beta2=r,a.epsilon=o,a.decay=i,a.accumulatedFirstMoment=[],a.accumulatedWeightedInfNorm=[],Fe(function(){a.iteration=rn(0).variable(),a.accBeta1=rn(n).variable()}),null==o&&(a.epsilon=Mt.backend.epsilon()),a}return s(e,t),e.prototype.applyGradients=function(t){var e=this,n=Array.isArray(t)?t.map(function(t){return t.name}):Object.keys(t);Fe(function(){var r=Wu(1,e.accBeta1),o=_u(-e.learningRate,e.iteration.mul(e.decay).add(1));n.forEach(function(n,i){var a=Mt.registeredVariables[n];null==e.accumulatedFirstMoment[i]&&(e.accumulatedFirstMoment[i]={originalName:n+"/m",variable:gn(a).variable(!1)}),null==e.accumulatedWeightedInfNorm[i]&&(e.accumulatedWeightedInfNorm[i]={originalName:n+"/v",variable:gn(a).variable(!1)});var s=Array.isArray(t)?t[i].tensor:t[n];if(null!=s){var u=e.accumulatedFirstMoment[i].variable,c=e.accumulatedWeightedInfNorm[i].variable,l=u.mul(e.beta1).add(s.mul(1-e.beta1)),h=c.mul(e.beta2),p=s.abs(),f=h.maximum(p);u.assign(l),c.assign(f);var d=o.div(r).mul(l.div(f.add(e.epsilon))).add(a);a.assign(d)}}),e.iteration.assign(e.iteration.add(1)),e.accBeta1.assign(e.accBeta1.mul(e.beta1))}),this.incrementIterations()},e.prototype.dispose=function(){this.accBeta1.dispose(),this.iteration.dispose(),null!=this.accumulatedFirstMoment&&Me(this.accumulatedFirstMoment.map(function(t){return t.variable})),null!=this.accumulatedWeightedInfNorm&&Me(this.accumulatedWeightedInfNorm.map(function(t){return t.variable}))},e.prototype.getWeights=function(){return c(this,void 0,void 0,function(){return l(this,function(t){throw new Error("getWeights() is not implemented for Adamax yet.")})})},e.prototype.setWeights=function(t){return c(this,void 0,void 0,function(){return l(this,function(t){throw new Error("setWeights() is not implemented for Adamax yet.")})})},e.prototype.getConfig=function(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon,decay:this.decay}},e.fromConfig=function(t,e){return new t(e.learningRate,e.beta1,e.beta2,e.epsilon,e.decay)},e.className="Adamax",e}(sh);Jl(hh);var ph=function(t){function e(e){var n=t.call(this)||this;return n.learningRate=e,n.setLearningRate(e),n}return s(e,t),e.prototype.applyGradients=function(t){var e=this;(Array.isArray(t)?t.map(function(t){return t.name}):Object.keys(t)).forEach(function(n,r){var o=Array.isArray(t)?t[r].tensor:t[n];if(null!=o){var i=Mt.registeredVariables[n];Fe(function(){var t=e.c.mul(o).add(i);i.assign(t)})}}),this.incrementIterations()},e.prototype.setLearningRate=function(t){this.learningRate=t,null!=this.c&&this.c.dispose(),this.c=Oe(rn(-t))},e.prototype.dispose=function(){this.c.dispose()},e.prototype.getWeights=function(){return c(this,void 0,void 0,function(){return l(this,function(t){switch(t.label){case 0:return[4,this.saveIterations()];case 1:return[2,[t.sent()]]}})})},e.prototype.setWeights=function(t){return c(this,void 0,void 0,function(){return l(this,function(e){switch(e.label){case 0:return[4,this.extractIterations(t)];case 1:if(0!==(t=e.sent()).length)throw new Error("SGD optimizer does not have settable weights.");return[2]}})})},e.prototype.getConfig=function(){return{learningRate:this.learningRate}},e.fromConfig=function(t,e){return new t(e.learningRate)},e.className="SGD",e}(sh);Jl(ph);var fh=function(t){function e(e,n,r){void 0===r&&(r=!1);var o=t.call(this,e)||this;return o.learningRate=e,o.momentum=n,o.useNesterov=r,o.accumulations=[],o.m=rn(o.momentum),o}return s(e,t),e.prototype.applyGradients=function(t){var e=this;(Array.isArray(t)?t.map(function(t){return t.name}):Object.keys(t)).forEach(function(n,r){var o=Mt.registeredVariables[n];null==e.accumulations[r]&&(e.accumulations[r]={originalName:n+"/momentum",variable:Fe(function(){return gn(o).variable(!1)})});var i=e.accumulations[r].variable,a=Array.isArray(t)?t[r].tensor:t[n];null!=a&&Fe(function(){var t,n=e.m.mul(i).add(a);t=e.useNesterov?e.c.mul(a.add(n.mul(e.m))).add(o):e.c.mul(n).add(o),i.assign(n),o.assign(t)})}),this.incrementIterations()},e.prototype.dispose=function(){this.m.dispose(),null!=this.accumulations&&Me(this.accumulations.map(function(t){return t.variable}))},e.prototype.setMomentum=function(t){this.momentum=t},e.prototype.getWeights=function(){return c(this,void 0,void 0,function(){return l(this,function(t){switch(t.label){case 0:return[4,this.saveIterations()];case 1:return[2,[t.sent()].concat(this.accumulations.map(function(t){return{name:t.originalName,tensor:t.variable}}))]}})})},e.prototype.setWeights=function(t){return c(this,void 0,void 0,function(){return l(this,function(e){switch(e.label){case 0:return[4,this.extractIterations(t)];case 1:return t=e.sent(),this.accumulations=t.map(function(t){return{originalName:t.name,variable:t.tensor.variable(!1)}}),[2]}})})},e.prototype.getConfig=function(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}},e.fromConfig=function(t,e){return new t(e.learningRate,e.momentum,e.useNesterov)},e.className="MomentumOptimizer",e}(ph);Jl(fh);var dh=function(t){function e(e,n,r,o,i){void 0===n&&(n=.9),void 0===r&&(r=0),void 0===o&&(o=null),void 0===i&&(i=!1);var a=t.call(this)||this;return a.learningRate=e,a.decay=n,a.momentum=r,a.epsilon=o,a.accumulatedMeanSquares=[],a.accumulatedMoments=[],a.accumulatedMeanGrads=[],a.centered=i,null==o&&(a.epsilon=Mt.backend.epsilon()),a}return s(e,t),e.prototype.applyGradients=function(t){var e=this;(Array.isArray(t)?t.map(function(t){return t.name}):Object.keys(t)).forEach(function(n,r){var o=Mt.registeredVariables[n];null==e.accumulatedMeanSquares[r]&&(e.accumulatedMeanSquares[r]={originalName:n+"/rms",variable:Fe(function(){return gn(o).variable(!1)})}),null==e.accumulatedMoments[r]&&(e.accumulatedMoments[r]={originalName:n+"/momentum",variable:Fe(function(){return gn(o).variable(!1)})}),null==e.accumulatedMeanGrads[r]&&e.centered&&(e.accumulatedMeanGrads[r]={originalName:n+"/mg",variable:Fe(function(){return gn(o).variable(!1)})});var i=Array.isArray(t)?t[r].tensor:t[n];if(null!=i){var a=e.accumulatedMeanSquares[r].variable,s=e.accumulatedMoments[r].variable;Fe(function(){var t=a.mul(e.decay).add(i.square().mul(1-e.decay));if(e.centered){var n=e.accumulatedMeanGrads[r].variable,u=n.mul(e.decay).add(i.mul(1-e.decay)),c=s.mul(e.momentum).add(i.mul(e.learningRate).div(t.sub(u.square().add(e.epsilon)).sqrt()));a.assign(t),n.assign(u),s.assign(c);var l=o.sub(c);o.assign(l)}else{var h=a.mul(e.decay).add(i.square().mul(1-e.decay));c=s.mul(e.momentum).add(i.mul(e.learningRate).div(h.add(e.epsilon).sqrt())),a.assign(h),s.assign(c),l=o.sub(c),o.assign(l)}})}}),this.incrementIterations()},e.prototype.dispose=function(){null!=this.accumulatedMeanSquares&&Me(this.accumulatedMeanSquares.map(function(t){return t.variable})),null!=this.accumulatedMeanGrads&&this.centered&&Me(this.accumulatedMeanGrads.map(function(t){return t.variable})),null!=this.accumulatedMoments&&Me(this.accumulatedMoments.map(function(t){return t.variable}))},e.prototype.getWeights=function(){return c(this,void 0,void 0,function(){var t;return l(this,function(e){switch(e.label){case 0:return t=this.accumulatedMeanSquares.concat(this.accumulatedMoments),this.centered&&t.push.apply(t,this.accumulatedMeanGrads),[4,this.saveIterations()];case 1:return[2,[e.sent()].concat(t.map(function(t){return{name:t.originalName,tensor:t.variable}}))]}})})},e.prototype.setWeights=function(t){return c(this,void 0,void 0,function(){var e;return l(this,function(n){switch(n.label){case 0:return[4,this.extractIterations(t)];case 1:return t=n.sent(),e=this.centered?t.length/3:t.length/2,this.accumulatedMeanSquares=t.slice(0,e).map(function(t){return{originalName:t.name,variable:t.tensor.variable(!1)}}),this.accumulatedMoments=t.slice(e,2*e).map(function(t){return{originalName:t.name,variable:t.tensor.variable(!1)}}),this.centered&&(this.accumulatedMeanGrads=t.slice(2*e,3*e).map(function(t){return{originalName:t.name,variable:t.tensor.variable(!1)}})),[2]}})})},e.prototype.getConfig=function(){return{learningRate:this.learningRate,decay:this.decay,momentum:this.momentum,epsilon:this.epsilon,centered:this.centered}},e.fromConfig=function(t,e){return new t(e.learningRate,e.decay,e.momentum,e.epsilon,e.centered)},e.className="RMSProp",e}(sh);Jl(dh);var vh=function(){function t(){}return t.sgd=function(t){return new ph(t)},t.momentum=function(t,e,n){return void 0===n&&(n=!1),new fh(t,e,n)},t.rmsprop=function(t,e,n,r,o){return void 0===e&&(e=.9),void 0===n&&(n=0),void 0===r&&(r=null),void 0===o&&(o=!1),new dh(t,e,n,r,o)},t.adam=function(t,e,n,r){return void 0===t&&(t=.001),void 0===e&&(e=.9),void 0===n&&(n=.999),void 0===r&&(r=null),new lh(t,e,n,r)},t.adadelta=function(t,e,n){return void 0===t&&(t=.001),void 0===e&&(e=.95),void 0===n&&(n=null),new uh(t,e,n)},t.adamax=function(t,e,n,r,o){return void 0===t&&(t=.002),void 0===e&&(e=.9),void 0===n&&(n=.999),void 0===r&&(r=null),void 0===o&&(o=0),new hh(t,e,n,r,o)},t.adagrad=function(t,e){return void 0===e&&(e=.1),new ch(t,e)},t}(),mh={sgd:vh.sgd,momentum:vh.momentum,adadelta:vh.adadelta,adagrad:vh.adagrad,rmsprop:vh.rmsprop,adamax:vh.adamax,adam:vh.adam},gh="undefined"!=typeof requestAnimationFrame?requestAnimationFrame:"undefined"!=typeof setImmediate?setImmediate:function(t){return t()};dt=$c;var yh=Object.freeze({AdadeltaOptimizer:uh,AdagradOptimizer:ch,AdamOptimizer:lh,AdamaxOptimizer:hh,DataStorage:Rr,get ENV(){return f},Environment:h,KernelBackend:Nr,MomentumOptimizer:fh,Optimizer:sh,RMSPropOptimizer:dh,get Rank(){return yt},get Reduction(){return bc},SGDOptimizer:ph,Tensor:mt,TensorBuffer:pt,Variable:gt,abs:Ra,acos:Na,acosh:ka,add:bu,addN:wu,addStrict:Cu,all:Qs,any:Js,argMax:Zs,argMin:tu,asin:Aa,asinh:Ta,atan:Da,atan2:Eu,atanh:Fa,avgPool:Gs,backend:function(){return Mt.backend},backend_util:Hr,basicLSTMCell:ic,batchNorm:ys,batchNorm2d:xs,batchNorm3d:bs,batchNorm4d:ws,batchNormalization:gs,batchNormalization2d:ds,batchNormalization3d:vs,batchNormalization4d:ms,batchToSpaceND:Bn,browser:Xl,buffer:On,cast:Ln,ceil:Ma,clipByValue:Oa,clone:Wn,complex:Je,concat:yn,concat1d:xn,concat2d:bn,concat3d:wn,concat4d:Cn,conv1d:Is,conv2d:Ss,conv2dDerFilter:Ns,conv2dTranspose:Ts,conv3d:Rs,cos:Pa,cosh:Ba,cumsum:zn,customGrad:Er,deprecationWarn:De,depthToSpace:Un,depthwiseConv2d:ks,disableDeprecationWarnings:function(){f.set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")},dispose:Me,disposeVariables:function(){Mt.disposeVariables()},div:_u,divStrict:Iu,dot:Fs,dropout:yc,elu:$u,enableDebugMode:function(){f.set("DEBUG",!0)},enableProdMode:function(){f.set("PROD",!0)},environment:v,equal:uu,equalStrict:cu,erf:La,exp:Wa,expandDims:Vn,expm1:za,eye:Gn,fft:hc,fill:fn,findBackend:function(t){return Mt.findBackend(t)},findBackendFactory:function(t){return Mt.findBackendFactory(t)},floor:Ua,floorDiv:Su,frame:Ec,fused:qc,gather:rc,gatherND:gc,getBackend:function(){return Mt.backendName},grad:function(t){return b($(t),function(){return"The f passed in grad(f) must be a function"}),function(e,n){var r=We(e,"x","tf.grad",null),o=null!=n?We(n,"dy","tf.grad"):null;return Mt.tidy(function(){var e=Mt.gradients(function(){return t(r)},[r],o),n=e.value,i=e.grads;return null!=o&&w(n.shape,o.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),_r(i),i[0]})}},grads:function(t){return b($(t),function(){return"The f passed in grads(f) must be a function"}),function(e,n){b(Array.isArray(e),function(){return"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s"});var r=ze(e,"args","tf.grads",null),o=null!=n?We(n,"dy","tf.grads"):null;return Mt.tidy(function(){var e=Mt.gradients(function(){return t.apply(void 0,r)},r,o),n=e.value,i=e.grads;return null!=o&&w(n.shape,o.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),_r(i),i})}},greater:lu,greaterEqual:hu,greaterEqualStrict:pu,greaterStrict:fu,hammingWindow:Cc,hannWindow:wc,ifft:pc,imag:tn,image:jc,io:Hl,irfft:dc,isFinite:Za,isInf:Ja,isNaN:Qa,keep:Oe,leakyRelu:Ku,less:du,lessEqual:vu,lessEqualStrict:mu,lessStrict:gu,linalg:Lc,linspace:dn,localResponseNormalization:Zu,log:Va,log1p:Ga,logSigmoid:ja,logSoftmax:Sr,logSumExp:eu,logicalAnd:Uu,logicalNot:Vu,logicalOr:Gu,logicalXor:ju,losses:Mc,matMul:Ds,math:$l,max:nu,maxPool:Vs,maximum:Ru,maximumStrict:Nu,mean:ru,memory:function(){return Mt.memory()},min:ou,minimum:ku,minimumStrict:Au,mod:Tu,modStrict:Du,moments:iu,movingAverage:sc,mul:Fu,mulStrict:Mu,multiRNNCell:ac,multinomial:jn,neg:Ha,nextFrame:function(){return new Promise(function(t){return gh(function(){return t()})})},norm:tc,notEqual:yu,notEqualStrict:xu,oneHot:Hn,ones:hn,onesLike:mn,op:Qe,outerProduct:Ms,pad:qn,pad1d:$n,pad2d:Kn,pad3d:Xn,pad4d:Yn,pool:js,pow:Ou,powStrict:Pu,prelu:Xu,print:Pn,prod:su,profile:function(t){return Mt.profile(t)},rand:Qn,randomNormal:Jn,randomUniform:Zn,range:vn,ready:function(){return Mt.ready()},real:Ze,reciprocal:qa,registerBackend:function(t,e,n){return void 0===n&&(n=1),Mt.registerBackend(t,e,n)},relu:Yu,removeBackend:function(t){Mt.removeBackend(t)},reshape:tr,reverse:Os,reverse1d:Ps,reverse2d:Bs,reverse3d:Ls,reverse4d:Ws,rfft:fc,round:$a,rsqrt:Ka,scalar:rn,scatterND:lc,selu:Qu,separableConv2d:As,serialization:Zl,setBackend:function(t){return Mt.setBackend(t)},setPlatform:function(t,e){f.setPlatform(t,e)},setdiff1dAsync:sr,sigmoid:Xa,sign:Ya,signal:_c,sin:ts,sinh:es,slice:Hs,slice1d:qs,slice2d:$s,slice3d:Ks,slice4d:Xs,softmax:Ir,softplus:ns,spaceToBatchND:er,sparseToDense:mc,spectral:vc,split:En,sqrt:rs,square:os,squaredDifference:Bu,squaredDifferenceStrict:Lu,squeeze:nr,stack:rr,step:is,stridedSlice:uc,sub:Wu,subStrict:zu,sum:au,tan:as,tanh:ss,tensor:en,tensor1d:on,tensor2d:an,tensor3d:sn,tensor4d:un,tensor5d:cn,tensor6d:ln,tensor_util:Tt,test_util:ih,tidy:Fe,tile:or,time:function(t){return Mt.time(t)},topk:cc,train:mh,transpose:Ju,truncatedNormal:ir,unsortedSegmentSum:oc,unstack:ar,util:rt,valueAndGrad:function(t){return b($(t),function(){return"The f passed in valueAndGrad(f) must be a function"}),function(e,n){b(e instanceof mt,function(){return"The x passed in valueAndGrad(f)(x) must be a tensor"}),b(null==n||n instanceof mt,function(){return"The dy passed in valueAndGrad(f)(x, dy) must be a tensor"});var r=Mt.gradients(function(){return t(e)},[e],n),o=r.grads,i=r.value;return _r(o),{grad:o[0],value:i}}},valueAndGrads:function(t){return b($(t),function(){return"The f passed in valueAndGrads(f) must be a function"}),function(e,n){b(Array.isArray(e)&&e.every(function(t){return t instanceof mt}),function(){return"The args passed in valueAndGrads(f)(args) must be array of tensors"}),b(null==n||n instanceof mt,function(){return"The dy passed in valueAndGrads(f)(args, dy) must be a tensor"});var r=Mt.gradients(function(){return t.apply(void 0,e)},e,n);return null!=n&&w(r.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),_r(r.grads),r}},variable:Et,variableGrads:Cr,version_core:"1.2.2",webgl:ah,where:Hu,whereAsync:qu,zeros:pn,zerosLike:gn}),xh=function(){function t(t,e){if(!Dh(t)||!Dh(e))throw new Error("Dimensions.constructor - expected width and height to be valid numbers, instead have "+JSON.stringify({width:t,height:e}));this._width=t,this._height=e}return Object.defineProperty(t.prototype,"width",{get:function(){return this._width},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"height",{get:function(){return this._height},enumerable:!0,configurable:!0}),t.prototype.reverse=function(){return new t(1/this.width,1/this.height)},t}(),bh=function(){function t(t,e){this._x=t,this._y=e}return Object.defineProperty(t.prototype,"x",{get:function(){return this._x},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"y",{get:function(){return this._y},enumerable:!0,configurable:!0}),t.prototype.add=function(e){return new t(this.x+e.x,this.y+e.y)},t.prototype.sub=function(e){return new t(this.x-e.x,this.y-e.y)},t.prototype.mul=function(e){return new t(this.x*e.x,this.y*e.y)},t.prototype.div=function(e){return new t(this.x/e.x,this.y/e.y)},t.prototype.abs=function(){return new t(Math.abs(this.x),Math.abs(this.y))},t.prototype.magnitude=function(){return Math.sqrt(Math.pow(this.x,2)+Math.pow(this.y,2))},t.prototype.floor=function(){return new t(Math.floor(this.x),Math.floor(this.y))},t}();function wh(t,e){return t instanceof mt&&t.shape.length===e}function Ch(t){return wh(t,2)}function Eh(t){return wh(t,3)}function _h(t){return wh(t,4)}function Ih(t){return t%1!=0}function Sh(t){return t%2==0}function Rh(t,e){void 0===e&&(e=2);var n=Math.pow(10,e);return Math.floor(t*n)/n}function Nh(t){return t&&t.width&&t.height}function kh(t,e){var n=t.width,r=t.height,o=e/Math.max(r,n);return new xh(Math.round(n*o),Math.round(r*o))}function Ah(t){return t.reduce(function(t,e){return t.add(e)},new bh(0,0)).div(new bh(t.length,t.length))}function Th(t,e,n){return Array(t).fill(0).map(function(t,r){return e+r*n})}function Dh(t){return!!t&&t!==1/0&&t!==-1/0&&!isNaN(t)||0===t}function Fh(t){return Dh(t)&&0<=t&&t<=1}var Mh,Oh=function(){function t(e,n){void 0===n&&(n=!0);var r=e||{},o=[r.left,r.top,r.right,r.bottom].every(Dh),i=[r.x,r.y,r.width,r.height].every(Dh);if(!i&&!o)throw new Error("Box.constructor - expected box to be IBoundingBox | IRect, instead have "+JSON.stringify(r));var a=i?[r.x,r.y,r.width,r.height]:[r.left,r.top,r.right-r.left,r.bottom-r.top],s=a[0],u=a[1],c=a[2],l=a[3];t.assertIsValidBox({x:s,y:u,width:c,height:l},"Box.constructor",n),this._x=s,this._y=u,this._width=c,this._height=l}return t.isRect=function(t){return!!t&&[t.x,t.y,t.width,t.height].every(Dh)},t.assertIsValidBox=function(e,n,r){if(void 0===r&&(r=!1),!t.isRect(e))throw new Error(n+" - invalid box: "+JSON.stringify(e)+", expected object with properties x, y, width, height");if(!r&&(e.width<0||e.height<0))throw new Error(n+" - width ("+e.width+") and height ("+e.height+") must be positive numbers")},Object.defineProperty(t.prototype,"x",{get:function(){return this._x},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"y",{get:function(){return this._y},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"width",{get:function(){return this._width},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"height",{get:function(){return this._height},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"left",{get:function(){return this.x},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"top",{get:function(){return this.y},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"right",{get:function(){return this.x+this.width},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"bottom",{get:function(){return this.y+this.height},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"area",{get:function(){return this.width*this.height},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"topLeft",{get:function(){return new bh(this.left,this.top)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"topRight",{get:function(){return new bh(this.right,this.top)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"bottomLeft",{get:function(){return new bh(this.left,this.bottom)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"bottomRight",{get:function(){return new bh(this.right,this.bottom)},enumerable:!0,configurable:!0}),t.prototype.round=function(){var e=[this.x,this.y,this.width,this.height].map(function(t){return Math.round(t)});return new t({x:e[0],y:e[1],width:e[2],height:e[3]})},t.prototype.floor=function(){var e=[this.x,this.y,this.width,this.height].map(function(t){return Math.floor(t)});return new t({x:e[0],y:e[1],width:e[2],height:e[3]})},t.prototype.toSquare=function(){var e=this.x,n=this.y,r=this.width,o=this.height,i=Math.abs(r-o);return re&&(o=-u+e+n,u=e),c>t&&(i=-c+t+r,c=t),a<1&&(i=2-a,a=1),s<1&&(i=2-s,s=1),{dy:1,edy:i,dx:1,edx:o,y:s,ey:c,x:a,ex:u,w:n,h:r}},t.prototype.calibrate=function(e){return new t({left:this.left+e.left*this.width,top:this.top+e.top*this.height,right:this.right+e.right*this.width,bottom:this.bottom+e.bottom*this.height}).toSquare().round()},t}(),Ph=function(t){function e(e,n,r,o,i){return void 0===i&&(i=!1),t.call(this,{left:e,top:n,right:r,bottom:o},i)||this}return n(e,t),e}(Oh),Bh=function(t){function e(e,n){var r=t.call(this,e)||this;return r._label=n,r}return n(e,t),e.assertIsValidLabeledBox=function(t,e){if(Oh.assertIsValidBox(t,e),!Dh(t.label))throw new Error(e+" - expected property label ("+t.label+") to be a number")},Object.defineProperty(e.prototype,"label",{get:function(){return this._label},enumerable:!0,configurable:!0}),e}(Oh),Lh=function(){function t(t,e,n,r,o){this._imageDims=new xh(o.width,o.height),this._score=t,this._classScore=e,this._className=n,this._box=new Oh(r).rescale(this._imageDims)}return Object.defineProperty(t.prototype,"score",{get:function(){return this._score},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"classScore",{get:function(){return this._classScore},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"className",{get:function(){return this._className},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"box",{get:function(){return this._box},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"imageDims",{get:function(){return this._imageDims},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"imageWidth",{get:function(){return this.imageDims.width},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"imageHeight",{get:function(){return this.imageDims.height},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"relativeBox",{get:function(){return new Oh(this._box).rescale(this.imageDims.reverse())},enumerable:!0,configurable:!0}),t.prototype.forSize=function(e,n){return new t(this.score,this.classScore,this.className,this.relativeBox,{width:e,height:n})},t}(),Wh=function(t){function e(e,n,r,o){var i=t.call(this,e,n)||this;return i._score=r,i._classScore=o,i}return n(e,t),e.assertIsValidPredictedBox=function(t,e){if(Bh.assertIsValidLabeledBox(t,e),!Fh(t.score)||!Fh(t.classScore))throw new Error(e+" - expected properties score ("+t.score+") and ("+t.classScore+") to be a number between [0, 1]")},Object.defineProperty(e.prototype,"score",{get:function(){return this._score},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"classScore",{get:function(){return this._classScore},enumerable:!0,configurable:!0}),e}(Bh),zh=function(t){function e(e,n,r,o,i){return void 0===i&&(i=!1),t.call(this,{x:e,y:n,width:r,height:o},i)||this}return n(e,t),e}(Oh);function Uh(){var t=window.fetch||function(){throw new Error("fetch - missing fetch implementation for browser environment")};return{Canvas:HTMLCanvasElement,CanvasRenderingContext2D:CanvasRenderingContext2D,Image:HTMLImageElement,ImageData:ImageData,Video:HTMLVideoElement,createCanvasElement:function(){return document.createElement("canvas")},createImageElement:function(){return document.createElement("img")},fetch:t,readFile:function(){throw new Error("readFile - filesystem not available for browser environment")}}}function Vh(t){var e="";if(!t)try{t=require("fs")}catch(t){e=t.toString()}return{readFile:t?function(e){return new Promise(function(n,r){t.readFile(e,function(t,e){return t?r(t):n(e)})})}:function(){throw new Error("readFile - failed to require fs in nodejs environment with error: "+e)}}}function Gh(){var t=global.Canvas||global.HTMLCanvasElement,e=global.Image||global.HTMLImageElement,n=global.fetch||function(){throw new Error("fetch - missing fetch implementation for nodejs environment")},o=Vh();return r({Canvas:t||function(){},CanvasRenderingContext2D:global.CanvasRenderingContext2D||function(){},Image:e||function(){},ImageData:global.ImageData||function(){},Video:global.HTMLVideoElement||function(){},createCanvasElement:function(){if(t)return new t;throw new Error("createCanvasElement - missing Canvas implementation for nodejs environment")},createImageElement:function(){if(e)return new e;throw new Error("createImageElement - missing Image implementation for nodejs environment")},fetch:n},o)}function jh(){return"object"==typeof window&&"undefined"!=typeof document&&"undefined"!=typeof HTMLImageElement&&"undefined"!=typeof HTMLCanvasElement&&"undefined"!=typeof HTMLVideoElement&&"undefined"!=typeof ImageData&&"undefined"!=typeof CanvasRenderingContext2D}function Hh(){return"object"==typeof global&&"function"==typeof require&&"undefined"!=typeof module&&"undefined"!=typeof process&&!!process.version}function qh(t){Mh=t}function $h(){jh()&&qh(Uh()),Hh()&&qh(Gh())}var Kh,Xh={getEnv:function(){if(!Mh)throw new Error("getEnv - environment is not defined, check isNodejs() and isBrowser()");return Mh},setEnv:qh,initialize:$h,createBrowserEnv:Uh,createFileSystem:Vh,createNodejsEnv:Gh,monkeyPatch:function(t){if(Mh||$h(),!Mh)throw new Error("monkeyPatch - environment is not defined, check isNodejs() and isBrowser()");var e=t.Canvas,n=void 0===e?Mh.Canvas:e,r=t.Image,o=void 0===r?Mh.Image:r;Mh.Canvas=n,Mh.Image=o,Mh.createCanvasElement=t.createCanvasElement||function(){return new n},Mh.createImageElement=t.createImageElement||function(){return new o},Mh.ImageData=t.ImageData||Mh.ImageData,Mh.Video=t.Video||Mh.Video,Mh.fetch=t.fetch||Mh.fetch,Mh.readFile=t.readFile||Mh.readFile},isBrowser:jh,isNodejs:Hh};function Yh(t){return Xh.isNodejs()||"string"!=typeof t?t:document.getElementById(t)}function Qh(t){var e=Xh.getEnv(),n=e.Canvas;if(t instanceof e.CanvasRenderingContext2D)return t;var r=Yh(t);if(!(r instanceof n))throw new Error("resolveContext2d - expected canvas to be of instance of Canvas");var o=r.getContext("2d");if(!o)throw new Error("resolveContext2d - canvas 2d context is null");return o}$h(),function(t){t.TOP_LEFT="TOP_LEFT",t.TOP_RIGHT="TOP_RIGHT",t.BOTTOM_LEFT="BOTTOM_LEFT",t.BOTTOM_RIGHT="BOTTOM_RIGHT"}(Kh||(Kh={}));var Jh=function(t){void 0===t&&(t={});var e=t.anchorPosition,n=t.backgroundColor,r=t.fontColor,o=t.fontSize,i=t.fontStyle,a=t.padding;this.anchorPosition=e||Kh.TOP_LEFT,this.backgroundColor=n||"rgba(0, 0, 0, 0.5)",this.fontColor=r||"rgba(255, 255, 255, 1)",this.fontSize=o||14,this.fontStyle=i||"Georgia",this.padding=a||4},Zh=function(){function t(e,n,r){void 0===r&&(r={}),this.text="string"==typeof e?[e]:e instanceof t?e.text:e,this.anchor=n,this.options=new Jh(r)}return t.prototype.measureWidth=function(t){var e=this.options.padding;return this.text.map(function(e){return t.measureText(e).width}).reduce(function(t,e){return t=3}function dp(t){return new Promise(function(e,n){if(t instanceof Xh.getEnv().Canvas||fp(t))return e();function r(t){t.currentTarget&&(t.currentTarget.removeEventListener("load",r),t.currentTarget.removeEventListener("error",o),e(t))}function o(t){t.currentTarget&&(t.currentTarget.removeEventListener("load",r),t.currentTarget.removeEventListener("error",o),n(t))}t.addEventListener("load",r),t.addEventListener("error",o)})}function vp(t){return new Promise(function(e,n){if(!(t instanceof Blob))return n("bufferToImage - expected buf to be of type: Blob");var r=new FileReader;r.onload=function(){if("string"!=typeof r.result)return n("bufferToImage - expected reader.result to be a string, in onload");var t=Xh.getEnv().createImageElement();t.onload=function(){return e(t)},t.onerror=n,t.src=r.result},r.onerror=n,r.readAsDataURL(t)})}function mp(t){var e=Xh.getEnv(),n=e.Image,r=e.Video;return t instanceof n?new xh(t.naturalWidth,t.naturalHeight):t instanceof r?new xh(t.videoWidth,t.videoHeight):new xh(t.width,t.height)}function gp(t){var e=t.width,n=t.height,r=(0,Xh.getEnv().createCanvasElement)();return r.width=e,r.height=n,r}function yp(t,e){var n=Xh.getEnv().ImageData;if(!(t instanceof n||fp(t)))throw new Error("createCanvasFromMedia - media has not finished loading yet");var r=e||mp(t),o=r.width,i=r.height,a=gp({width:o,height:i});return t instanceof n?Qh(a).putImageData(t,0,0):Qh(a).drawImage(t,0,0,o,i),a}function xp(t,e){return o(this,void 0,void 0,function(){var n;return i(this,function(r){switch(r.label){case 0:return[4,(0,Xh.getEnv().fetch)(t,e)];case 1:if(!((n=r.sent()).status<400))throw new Error("failed to fetch: ("+n.status+") "+n.statusText+", from url: "+n.url);return[2,n]}})})}function bp(t){return o(this,void 0,void 0,function(){return i(this,function(e){switch(e.label){case 0:return[4,xp(t)];case 1:return[2,e.sent().json()]}})})}function wp(t,e){return o(this,void 0,void 0,function(){var n,r,o,a,s,u;return i(this,function(i){switch(i.label){case 0:return n=e||Xh.getEnv().createCanvasElement(),r=t.shape.slice(_h(t)?1:0),o=r[0],a=r[1],s=r[2],u=Fe(function(){return t.as3D(o,a,s).toInt()}),[4,Xl.toPixels(u,n)];case 1:return i.sent(),u.dispose(),[2,n]}})})}function Cp(t,e,n){void 0===n&&(n=!1);var r=Xh.getEnv(),o=r.Image,i=r.Canvas;if(!(t instanceof o||t instanceof i))throw new Error("imageToSquare - expected arg0 to be HTMLImageElement | HTMLCanvasElement");var a=mp(t),s=e/Math.max(a.height,a.width),u=s*a.width,c=s*a.height,l=gp({width:e,height:e}),h=t instanceof i?t:yp(t),p=Math.abs(u-c)/2,f=n&&uo?2:1,u=function(e){var n=t.shape.slice();return n[s]=e,fn(n,0)},c=u(a),l=i-c.shape[s],h=[e&&l?u(l):null,t,c].filter(function(t){return!!t}).map(function(t){return t.toFloat()});return yn(h,s)})}var Sp=function(){function t(t,e){var n=this;if(void 0===e&&(e=!1),this._imageTensors=[],this._canvases=[],this._treatAsBatchInput=!1,this._inputDimensions=[],!Array.isArray(t))throw new Error("NetInput.constructor - expected inputs to be an Array of TResolvedNetInput or to be instanceof tf.Tensor4D, instead have "+t);this._treatAsBatchInput=e,this._batchSize=t.length,t.forEach(function(t,e){if(Eh(t))return n._imageTensors[e]=t,void(n._inputDimensions[e]=t.shape);if(_h(t)){var r=t.shape[0];if(1!==r)throw new Error("NetInput - tf.Tensor4D with batchSize "+r+" passed, but not supported in input array");return n._imageTensors[e]=t,void(n._inputDimensions[e]=t.shape.slice(1))}var o=t instanceof Xh.getEnv().Canvas?t:yp(t);n._canvases[e]=o,n._inputDimensions[e]=[o.height,o.width,3]})}return Object.defineProperty(t.prototype,"imageTensors",{get:function(){return this._imageTensors},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"canvases",{get:function(){return this._canvases},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isBatchInput",{get:function(){return this.batchSize>1||this._treatAsBatchInput},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"batchSize",{get:function(){return this._batchSize},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"inputDimensions",{get:function(){return this._inputDimensions},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"inputSize",{get:function(){return this._inputSize},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"reshapedInputDimensions",{get:function(){var t=this;return Th(this.batchSize,0,1).map(function(e,n){return t.getReshapedInputDimensions(n)})},enumerable:!0,configurable:!0}),t.prototype.getInput=function(t){return this.canvases[t]||this.imageTensors[t]},t.prototype.getInputDimensions=function(t){return this._inputDimensions[t]},t.prototype.getInputHeight=function(t){return this._inputDimensions[t][0]},t.prototype.getInputWidth=function(t){return this._inputDimensions[t][1]},t.prototype.getReshapedInputDimensions=function(t){if("number"!=typeof this.inputSize)throw new Error("getReshapedInputDimensions - inputSize not set, toBatchTensor has not been called yet");return kh({width:this.getInputWidth(t),height:this.getInputHeight(t)},this.inputSize)},t.prototype.toBatchTensor=function(t,e){var n=this;return void 0===e&&(e=!0),this._inputSize=t,Fe(function(){var r=Th(n.batchSize,0,1).map(function(r){var o=n.getInput(r);if(o instanceof mt){var i=_h(o)?o:o.expandDims();return(i=Ip(i,e)).shape[1]===t&&i.shape[2]===t||(i=jc.resizeBilinear(i,[t,t])),i.as3D(t,t,3)}if(o instanceof Xh.getEnv().Canvas)return Xl.fromPixels(Cp(o,t,e));throw new Error("toBatchTensor - at batchIdx "+r+", expected input to be instanceof tf.Tensor or instanceof HTMLCanvasElement, instead have "+o)});return rr(r.map(function(t){return t.toFloat()})).as4D(n.batchSize,t,t,3)})},t}();function Rp(t){return o(this,void 0,void 0,function(){var e,n,r;return i(this,function(o){switch(o.label){case 0:if(t instanceof Sp)return[2,t];if(!(e=Array.isArray(t)?t:[t]).length)throw new Error("toNetInput - empty array passed as input");return n=function(e){return Array.isArray(t)?" at input index "+e+":":""},(r=e.map(Yh)).forEach(function(t,r){if(!Ep(t)&&!Eh(t)&&!_h(t)){if("string"==typeof e[r])throw new Error("toNetInput -"+n(r)+" string passed, but could not resolve HTMLElement for element id "+e[r]);throw new Error("toNetInput -"+n(r)+" expected media to be of type HTMLImageElement | HTMLVideoElement | HTMLCanvasElement | tf.Tensor3D, or to be an element id")}if(_h(t)){var o=t.shape[0];if(1!==o)throw new Error("toNetInput -"+n(r)+" tf.Tensor4D with batchSize "+o+" passed, but not supported in input array")}}),[4,Promise.all(r.map(function(t){return Ep(t)&&dp(t)}))];case 1:return o.sent(),[2,new Sp(r,Array.isArray(t))]}})})}var Np=function(){function t(t){this._name=t,this._params=void 0,this._paramMappings=[]}return Object.defineProperty(t.prototype,"params",{get:function(){return this._params},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"paramMappings",{get:function(){return this._paramMappings},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isLoaded",{get:function(){return!!this.params},enumerable:!0,configurable:!0}),t.prototype.getParamFromPath=function(t){var e=this.traversePropertyPath(t);return e.obj[e.objProp]},t.prototype.reassignParamFromPath=function(t,e){var n=this.traversePropertyPath(t),r=n.obj,o=n.objProp;r[o].dispose(),r[o]=e},t.prototype.getParamList=function(){var t=this;return this._paramMappings.map(function(e){var n=e.paramPath;return{path:n,tensor:t.getParamFromPath(n)}})},t.prototype.getTrainableParams=function(){return this.getParamList().filter(function(t){return t.tensor instanceof gt})},t.prototype.getFrozenParams=function(){return this.getParamList().filter(function(t){return!(t.tensor instanceof gt)})},t.prototype.variable=function(){var t=this;this.getFrozenParams().forEach(function(e){var n=e.path,r=e.tensor;t.reassignParamFromPath(n,r.variable())})},t.prototype.freeze=function(){var t=this;this.getTrainableParams().forEach(function(e){var n=e.path,r=e.tensor,o=en(r.dataSync());r.dispose(),t.reassignParamFromPath(n,o)})},t.prototype.dispose=function(t){void 0===t&&(t=!0),this.getParamList().forEach(function(e){if(t&&e.tensor.isDisposed)throw new Error("param tensor has already been disposed for path "+e.path);e.tensor.dispose()}),this._params=void 0},t.prototype.serializeParams=function(){return new Float32Array(this.getParamList().map(function(t){var e=t.tensor;return Array.from(e.dataSync())}).reduce(function(t,e){return t.concat(e)}))},t.prototype.load=function(t){return o(this,void 0,void 0,function(){return i(this,function(e){switch(e.label){case 0:return t instanceof Float32Array?(this.extractWeights(t),[2]):[4,this.loadFromUri(t)];case 1:return e.sent(),[2]}})})},t.prototype.loadFromUri=function(t){return o(this,void 0,void 0,function(){var e;return i(this,function(n){switch(n.label){case 0:if(t&&"string"!=typeof t)throw new Error(this._name+".loadFromUri - expected model uri");return[4,_p(t,this.getDefaultModelName())];case 1:return e=n.sent(),this.loadFromWeightMap(e),[2]}})})},t.prototype.loadFromDisk=function(t){return o(this,void 0,void 0,function(){var e,n,r,o,a,s,u,c,l,h;return i(this,function(i){switch(i.label){case 0:if(t&&"string"!=typeof t)throw new Error(this._name+".loadFromDisk - expected model file path");return e=Xh.getEnv().readFile,n=pp(t,this.getDefaultModelName()),r=n.manifestUri,o=n.modelBaseUri,a=function(t){return Promise.all(t.map(function(t){return e(t).then(function(t){return t.buffer})}))},s=Hl.weightsLoaderFactory(a),l=(c=JSON).parse,[4,e(r)];case 1:return u=l.apply(c,[i.sent().toString()]),[4,s(u,o)];case 2:return h=i.sent(),this.loadFromWeightMap(h),[2]}})})},t.prototype.loadFromWeightMap=function(t){var e=this.extractParamsFromWeigthMap(t),n=e.paramMappings,r=e.params;this._paramMappings=n,this._params=r},t.prototype.extractWeights=function(t){var e=this.extractParams(t),n=e.paramMappings,r=e.params;this._paramMappings=n,this._params=r},t.prototype.traversePropertyPath=function(t){if(!this.params)throw new Error("traversePropertyPath - model has no loaded params");var e=t.split("/").reduce(function(e,n){if(!e.nextObj.hasOwnProperty(n))throw new Error("traversePropertyPath - object does not have property "+n+", for path "+t);return{obj:e.nextObj,objProp:n,nextObj:e.nextObj[n]}},{nextObj:this.params}),n=e.obj,r=e.objProp;if(!(n&&r&&n[r]instanceof mt))throw new Error("traversePropertyPath - parameter is not a tensor, for path "+t);return{obj:n,objProp:r}},t}();function kp(t,e,n){void 0===n&&(n=!0);var r=Math.max(0,Math.min(t.right,e.right)-Math.max(t.left,e.left))*Math.max(0,Math.min(t.bottom,e.bottom)-Math.max(t.top,e.top));return n?r/(t.area+e.area-r):r/Math.min(t.area,e.area)}function Ap(t,e,n,r){void 0===r&&(r=!0);for(var o=e.map(function(t,e){return{score:t,boxIndex:e}}).sort(function(t,e){return t.score-e.score}).map(function(t){return t.boxIndex}),i=[],a=function(){var e=o.pop();i.push(e);for(var a=o,s=[],u=0;u0;)a();return i}function Tp(t,e){return Fe(function(){var n=e[0],r=e[1],o=e[2],i=fn(t.shape.slice(0,3).concat([1]),n),a=fn(t.shape.slice(0,3).concat([1]),r),s=fn(t.shape.slice(0,3).concat([1]),o),u=yn([i,a,s],3);return Wu(t,u)})}function Dp(t){return 1/(1+Math.exp(-t))}var Fp,Mp=function(t){return"number"==typeof t};function Op(t){if(!t)throw new Error("invalid config: "+t);if("boolean"!=typeof t.withSeparableConvs)throw new Error("config.withSeparableConvs has to be a boolean, have: "+t.withSeparableConvs);if(!Mp(t.iouThreshold)||t.iouThreshold<0||t.iouThreshold>1)throw new Error("config.iouThreshold has to be a number between [0, 1], have: "+t.iouThreshold);if(!Array.isArray(t.classes)||!t.classes.length||!t.classes.every(function(t){return"string"==typeof t}))throw new Error("config.classes has to be an array class names: string[], have: "+JSON.stringify(t.classes));if(!Array.isArray(t.anchors)||!t.anchors.length||!t.anchors.map(function(t){return t||{}}).every(function(t){return Mp(t.x)&&Mp(t.y)}))throw new Error("config.anchors has to be an array of { x: number, y: number }, have: "+JSON.stringify(t.anchors));if(t.meanRgb&&(!Array.isArray(t.meanRgb)||3!==t.meanRgb.length||!t.meanRgb.every(Mp)))throw new Error("config.meanRgb has to be an array of shape [number, number, number], have: "+JSON.stringify(t.meanRgb))}function Pp(t){return Fe(function(){var e=Fu(t,rn(.10000000149011612));return bu(Yu(Wu(t,e)),e)})}function Bp(t,e){return Fe(function(){var n=qn(t,[[0,0],[1,1],[1,1],[0,0]]);return n=Ss(n,e.conv.filters,[1,1],"valid"),n=Wu(n,e.bn.sub),n=Fu(n,e.bn.truediv),Pp(n=bu(n,e.conv.bias))})}function Lp(t,e){return Fe(function(){var n=qn(t,[[0,0],[1,1],[1,1],[0,0]]);return n=As(n,e.depthwise_filter,e.pointwise_filter,[1,1],"valid"),Pp(n=bu(n,e.bias))})}function Wp(t,e){var n=ip(t,e);var r=up(t,e);return{extractConvParams:n,extractConvWithBatchNormParams:function(r,o,i){return{conv:n(r,o,3,i+"/conv"),bn:function(n,r){var o=on(t(n)),i=on(t(n));return e.push({paramPath:r+"/sub"},{paramPath:r+"/truediv"}),{sub:o,truediv:i}}(o,i+"/bn")}},extractSeparableConvParams:r}}function zp(t,e){var n=lp(t,e);function r(t){return{filters:n(t+"/filters",4),bias:n(t+"/bias",1)}}return{extractConvParams:r,extractConvWithBatchNormParams:function(t){return{conv:r(t+"/conv"),bn:function(t){return{sub:n(t+"/sub",1),truediv:n(t+"/truediv",1)}}(t+"/bn")}},extractSeparableConvParams:cp(n)}}!function(t){t[t.XS=224]="XS",t[t.SM=320]="SM",t[t.MD=416]="MD",t[t.LG=608]="LG"}(Fp||(Fp={}));var Up=function(){function t(t){var e=void 0===t?{}:t,n=e.inputSize,r=e.scoreThreshold;if(this._name="TinyYolov2Options",this._inputSize=n||416,this._scoreThreshold=r||.5,"number"!=typeof this._inputSize||this._inputSize%32!=0)throw new Error(this._name+" - expected inputSize to be a number divisible by 32");if("number"!=typeof this._scoreThreshold||this._scoreThreshold<=0||this._scoreThreshold>=1)throw new Error(this._name+" - expected scoreThreshold to be a number between 0 and 1")}return Object.defineProperty(t.prototype,"inputSize",{get:function(){return this._inputSize},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"scoreThreshold",{get:function(){return this._scoreThreshold},enumerable:!0,configurable:!0}),t}(),Vp=function(t){function e(e){var n=t.call(this,"TinyYolov2")||this;return Op(e),n._config=e,n}return n(e,t),Object.defineProperty(e.prototype,"config",{get:function(){return this._config},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"withClassScores",{get:function(){return this.config.withClassScores||this.config.classes.length>1},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"boxEncodingSize",{get:function(){return 5+(this.withClassScores?this.config.classes.length:0)},enumerable:!0,configurable:!0}),e.prototype.runTinyYolov2=function(t,e){var n=Bp(t,e.conv0);return n=Bp(n=Vs(n,[2,2],[2,2],"same"),e.conv1),n=Bp(n=Vs(n,[2,2],[2,2],"same"),e.conv2),n=Bp(n=Vs(n,[2,2],[2,2],"same"),e.conv3),n=Bp(n=Vs(n,[2,2],[2,2],"same"),e.conv4),n=Bp(n=Vs(n,[2,2],[2,2],"same"),e.conv5),n=Bp(n=Vs(n,[2,2],[1,1],"same"),e.conv6),rp(n=Bp(n,e.conv7),e.conv8,"valid",!1)},e.prototype.runMobilenet=function(t,e){var n=this.config.isFirstLayerConv2d?Pp(rp(t,e.conv0,"valid",!1)):Lp(t,e.conv0);return n=Lp(n=Vs(n,[2,2],[2,2],"same"),e.conv1),n=Lp(n=Vs(n,[2,2],[2,2],"same"),e.conv2),n=Lp(n=Vs(n,[2,2],[2,2],"same"),e.conv3),n=Lp(n=Vs(n,[2,2],[2,2],"same"),e.conv4),n=Lp(n=Vs(n,[2,2],[2,2],"same"),e.conv5),n=Vs(n,[2,2],[1,1],"same"),n=e.conv6?Lp(n,e.conv6):n,rp(n=e.conv7?Lp(n,e.conv7):n,e.conv8,"valid",!1)},e.prototype.forwardInput=function(t,e){var n=this,r=this.params;if(!r)throw new Error("TinyYolov2 - load model before inference");return Fe(function(){var o=t.toBatchTensor(e,!1).toFloat();return o=(o=n.config.meanRgb?Tp(o,n.config.meanRgb):o).div(rn(256)),n.config.withSeparableConvs?n.runMobilenet(o,r):n.runTinyYolov2(o,r)})},e.prototype.forward=function(t,e){return o(this,void 0,void 0,function(){var n;return i(this,function(r){switch(r.label){case 0:return n=this.forwardInput,[4,Rp(t)];case 1:return[4,n.apply(this,[r.sent(),e])];case 2:return[2,r.sent()]}})})},e.prototype.detect=function(t,e){return void 0===e&&(e={}),o(this,void 0,void 0,function(){var n,r,o,a,s,u,c,l,h,p,f,d,v,m=this;return i(this,function(i){switch(i.label){case 0:return n=new Up(e),r=n.inputSize,o=n.scoreThreshold,[4,Rp(t)];case 1:return a=i.sent(),[4,this.forwardInput(a,r)];case 2:return s=i.sent(),u=Fe(function(){return ar(s)[0].expandDims()}),c={width:a.getInputWidth(0),height:a.getInputHeight(0)},[4,this.extractBoxes(u,a.getReshapedInputDimensions(0),o)];case 3:return l=i.sent(),s.dispose(),u.dispose(),h=l.map(function(t){return t.box}),p=l.map(function(t){return t.score}),f=l.map(function(t){return t.classScore}),d=l.map(function(t){return m.config.classes[t.label]}),v=Ap(h.map(function(t){return t.rescale(r)}),p,this.config.iouThreshold,!0),[2,v.map(function(t){return new Lh(p[t],f[t],d[t],h[t],c)})]}})})},e.prototype.getDefaultModelName=function(){return""},e.prototype.extractParamsFromWeigthMap=function(t){return function(t,e){var n,r=[],o=zp(t,r),i=o.extractConvParams,a=o.extractConvWithBatchNormParams,s=o.extractSeparableConvParams;if(e.withSeparableConvs){var u=e.filterSizes&&e.filterSizes.length||9;n={conv0:e.isFirstLayerConv2d?i("conv0"):s("conv0"),conv1:s("conv1"),conv2:s("conv2"),conv3:s("conv3"),conv4:s("conv4"),conv5:s("conv5"),conv6:u>7?s("conv6"):void 0,conv7:u>8?s("conv7"):void 0,conv8:i("conv8")}}else n={conv0:a("conv0"),conv1:a("conv1"),conv2:a("conv2"),conv3:a("conv3"),conv4:a("conv4"),conv5:a("conv5"),conv6:a("conv6"),conv7:a("conv7"),conv8:i("conv8")};return op(t,r),{params:n,paramMappings:r}}(t,this.config)},e.prototype.extractParams=function(t){var n=this.config.filterSizes||e.DEFAULT_FILTER_SIZES,r=n?n.length:void 0;if(7!==r&&8!==r&&9!==r)throw new Error("TinyYolov2 - expected 7 | 8 | 9 convolutional filters, but found "+r+" filterSizes in config");return function(t,e,n,r){var o,i=hp(t),a=i.extractWeights,s=i.getRemainingWeights,u=[],c=Wp(a,u),l=c.extractConvParams,h=c.extractConvWithBatchNormParams,p=c.extractSeparableConvParams;if(e.withSeparableConvs){var f=r[0],d=r[1],v=r[2],m=r[3],g=r[4],y=r[5],x=r[6],b=r[7],w=r[8];o={conv0:e.isFirstLayerConv2d?l(f,d,3,"conv0"):p(f,d,"conv0"),conv1:p(d,v,"conv1"),conv2:p(v,m,"conv2"),conv3:p(m,g,"conv3"),conv4:p(g,y,"conv4"),conv5:p(y,x,"conv5"),conv6:b?p(x,b,"conv6"):void 0,conv7:w?p(b,w,"conv7"):void 0,conv8:l(w||b||x,5*n,1,"conv8")}}else{f=r[0],d=r[1],v=r[2],m=r[3],g=r[4],y=r[5],x=r[6],b=r[7],w=r[8];o={conv0:h(f,d,"conv0"),conv1:h(d,v,"conv1"),conv2:h(v,m,"conv2"),conv3:h(m,g,"conv3"),conv4:h(g,y,"conv4"),conv5:h(y,x,"conv5"),conv6:h(x,b,"conv6"),conv7:h(b,w,"conv7"),conv8:l(w,5*n,1,"conv8")}}if(0!==s().length)throw new Error("weights remaing after extract: "+s().length);return{params:o,paramMappings:u}}(t,this.config,this.boxEncodingSize,n)},e.prototype.extractBoxes=function(t,e,n){return o(this,void 0,void 0,function(){var o,a,s,u,c,l,h,p,f,d,v,m,g,y,x,b,w,C,E,_,I,S,R,N,k,A,T,D,F,M=this;return i(this,function(i){switch(i.label){case 0:return o=e.width,a=e.height,s=Math.max(o,a),u=s/o,c=s/a,l=t.shape[1],h=this.config.anchors.length,p=Fe(function(){var e=t.reshape([l,l,h,M.boxEncodingSize]);return[e.slice([0,0,0,0],[l,l,h,4]),e.slice([0,0,0,4],[l,l,h,1]),M.withClassScores?Ir(e.slice([0,0,0,5],[l,l,h,M.config.classes.length]),3):rn(0)]}),f=p[0],d=p[1],v=p[2],m=[],[4,d.array()];case 1:return g=i.sent(),[4,f.array()];case 2:y=i.sent(),x=0,i.label=3;case 3:if(!(xn?(E=(b+Dp(y[x][b][w][0]))/l*u,_=(x+Dp(y[x][b][w][1]))/l*c,I=Math.exp(y[x][b][w][2])*this.config.anchors[w].x/l*u,S=Math.exp(y[x][b][w][3])*this.config.anchors[w].y/l*c,R=E-I/2,N=_-S/2,k={row:x,col:b,anchor:w},this.withClassScores?[4,this.extractPredictedClass(v,k)]:[3,7]):[3,9]):[3,10];case 6:return F=i.sent(),[3,8];case 7:F={classScore:1,label:0},i.label=8;case 8:T=(A=F).classScore,D=A.label,m.push(r({box:new Ph(R,N,R+I,N+S),score:C,classScore:C*T,label:D},k)),i.label=9;case 9:return w++,[3,5];case 10:return b++,[3,4];case 11:return x++,[3,3];case 12:return f.dispose(),d.dispose(),v.dispose(),[2,m]}})})},e.prototype.extractPredictedClass=function(t,e){return o(this,void 0,void 0,function(){var n,r,o,a;return i(this,function(i){switch(i.label){case 0:return n=e.row,r=e.col,o=e.anchor,[4,t.array()];case 1:return a=i.sent(),[2,Array(this.config.classes.length).fill(0).map(function(t,e){return a[n][r][o][e]}).map(function(t,e){return{classScore:t,label:e}}).reduce(function(t,e){return t.classScore>e.classScore?t:e})]}})})},e.DEFAULT_FILTER_SIZES=[3,16,32,64,128,256,512,1024,1024],e}(Np),Gp=Object.freeze({convLayer:rp,disposeUnusedWeightTensors:op,extractConvParamsFactory:ip,extractFCParamsFactory:ap,extractSeparableConvParamsFactory:up,loadSeparableConvParamsFactory:cp,extractWeightEntryFactory:lp,extractWeightsFactory:hp,getModelUris:pp,SeparableConvParams:sp,TinyYolov2:Vp,get TinyYolov2SizeType(){return Fp},TinyYolov2Options:Up,validateConfig:Op});function jp(t,e,n){if(void 0===n&&(n=!1),t.beginPath(),e.slice(1).forEach(function(n,r){var o=n.x,i=n.y,a=e[r];t.moveTo(a.x,a.y),t.lineTo(o,i)}),n){var r=e[e.length-1],o=e[0];if(!r||!o)return;t.moveTo(r.x,r.y),t.lineTo(o.x,o.y)}t.stroke()}var Hp=function(t){function e(e,n,r){return t.call(this,e,e,"",n,r)||this}return n(e,t),e.prototype.forSize=function(n,r){var o=t.prototype.forSize.call(this,n,r);return new e(o.score,o.relativeBox,o.imageDims)},e}(Lh);function qp(t){return t.detection instanceof Hp}function $p(t,e){var n={detection:e};return Object.assign({},t,n)}function Kp(t,e,n){return Fe(function(){var r=As(t,e.depthwise_filter,e.pointwise_filter,n,"same");return r=bu(r,e.bias)})}function Xp(t,e,n){return void 0===n&&(n=!1),Fe(function(){var r=Yu(n?bu(Ss(t,e.conv0.filters,[2,2],"same"),e.conv0.bias):Kp(t,e.conv0,[2,2])),o=Kp(r,e.conv1,[1,1]),i=Kp(Yu(bu(r,o)),e.conv2,[1,1]);return Yu(bu(r,bu(o,i)))})}function Yp(t,e,n,r){return void 0===n&&(n=!1),void 0===r&&(r=!0),Fe(function(){var o=Yu(n?bu(Ss(t,e.conv0.filters,r?[2,2]:[1,1],"same"),e.conv0.bias):Kp(t,e.conv0,r?[2,2]:[1,1])),i=Kp(o,e.conv1,[1,1]),a=Kp(Yu(bu(o,i)),e.conv2,[1,1]),s=Kp(Yu(bu(o,bu(i,a))),e.conv3,[1,1]);return Yu(bu(o,bu(i,bu(a,s))))})}function Qp(t,e){var n=ip(t,e),r=up(t,e);function o(t,e,o,i){return void 0===i&&(i=!1),{conv0:i?n(t,e,3,o+"/conv0"):r(t,e,o+"/conv0"),conv1:r(e,e,o+"/conv1"),conv2:r(e,e,o+"/conv2")}}return{extractDenseBlock3Params:o,extractDenseBlock4Params:function(t,e,n,i){void 0===i&&(i=!1);var a=o(t,e,n,i);return{conv0:a.conv0,conv1:a.conv1,conv2:a.conv2,conv3:r(e,e,n+"/conv3")}}}}function Jp(t){return function(e){return{filters:t(e+"/filters",4),bias:t(e+"/bias",1)}}}function Zp(t,e){var n=lp(t,e),r=Jp(n),o=cp(n);return{extractDenseBlock3Params:function(t,e){return void 0===e&&(e=!1),{conv0:e?r(t+"/conv0"):o(t+"/conv0"),conv1:o(t+"/conv1"),conv2:o(t+"/conv2")}},extractDenseBlock4Params:function(t,e){return void 0===e&&(e=!1),{conv0:e?r(t+"/conv0"):o(t+"/conv0"),conv1:o(t+"/conv1"),conv2:o(t+"/conv2"),conv3:o(t+"/conv3")}}}}var tf=function(t){function e(){return t.call(this,"FaceFeatureExtractor")||this}return n(e,t),e.prototype.forwardInput=function(t){var e=this.params;if(!e)throw new Error("FaceFeatureExtractor - load model before inference");return Fe(function(){var n=Yp(Tp(t.toBatchTensor(112,!0),[122.782,117.001,104.298]).div(rn(255)),e.dense0,!0);return n=Yp(n,e.dense1),n=Yp(n,e.dense2),n=Yp(n,e.dense3),n=Gs(n,[7,7],[2,2],"valid")})},e.prototype.forward=function(t){return o(this,void 0,void 0,function(){var e;return i(this,function(n){switch(n.label){case 0:return e=this.forwardInput,[4,Rp(t)];case 1:return[2,e.apply(this,[n.sent()])]}})})},e.prototype.getDefaultModelName=function(){return"face_feature_extractor_model"},e.prototype.extractParamsFromWeigthMap=function(t){return function(t){var e=[],n=Zp(t,e).extractDenseBlock4Params,r={dense0:n("dense0",!0),dense1:n("dense1"),dense2:n("dense2"),dense3:n("dense3")};return op(t,e),{params:r,paramMappings:e}}(t)},e.prototype.extractParams=function(t){return function(t){var e=[],n=hp(t),r=n.extractWeights,o=n.getRemainingWeights,i=Qp(r,e).extractDenseBlock4Params,a=i(3,32,"dense0",!0),s=i(32,64,"dense1"),u=i(64,128,"dense2"),c=i(128,256,"dense3");if(0!==o().length)throw new Error("weights remaing after extract: "+o().length);return{paramMappings:e,params:{dense0:a,dense1:s,dense2:u,dense3:c}}}(t)},e}(Np);function ef(t,e){return Fe(function(){return bu(Ds(t,e.weights),e.bias)})}function nf(t){var e={},n={};return Object.keys(t).forEach(function(r){(r.startsWith("fc")?n:e)[r]=t[r]}),{featureExtractorMap:e,classifierMap:n}}var rf=function(t){function e(e,n){var r=t.call(this,e)||this;return r._faceFeatureExtractor=n,r}return n(e,t),Object.defineProperty(e.prototype,"faceFeatureExtractor",{get:function(){return this._faceFeatureExtractor},enumerable:!0,configurable:!0}),e.prototype.runNet=function(t){var e=this,n=this.params;if(!n)throw new Error(this._name+" - load model before inference");return Fe(function(){var r=t instanceof Sp?e.faceFeatureExtractor.forwardInput(t):t;return ef(r.as2D(r.shape[0],-1),n.fc)})},e.prototype.dispose=function(e){void 0===e&&(e=!0),this.faceFeatureExtractor.dispose(e),t.prototype.dispose.call(this,e)},e.prototype.loadClassifierParams=function(t){var e=this.extractClassifierParams(t),n=e.params,r=e.paramMappings;this._params=n,this._paramMappings=r},e.prototype.extractClassifierParams=function(t){return function(t,e,n){var r=[],o=hp(t),i=o.extractWeights,a=o.getRemainingWeights,s=ap(i,r)(e,n,"fc");if(0!==a().length)throw new Error("weights remaing after extract: "+a().length);return{paramMappings:r,params:{fc:s}}}(t,this.getClassifierChannelsIn(),this.getClassifierChannelsOut())},e.prototype.extractParamsFromWeigthMap=function(t){var e=nf(t),n=e.featureExtractorMap,r=e.classifierMap;return this.faceFeatureExtractor.loadFromWeightMap(n),function(t){var e,n=[],r=lp(t,n),o={fc:(e="fc",{weights:r(e+"/weights",2),bias:r(e+"/bias",1)})};return op(t,n),{params:o,paramMappings:n}}(r)},e.prototype.extractParams=function(t){var e=this.getClassifierChannelsIn(),n=this.getClassifierChannelsOut(),r=n*e+n,o=t.slice(0,t.length-r),i=t.slice(t.length-r);return this.faceFeatureExtractor.extractWeights(o),this.extractClassifierParams(i)},e}(Np),of=["neutral","happy","sad","angry","fearful","disgusted","surprised"],af=function(){function t(t){var e=this;if(7!==t.length)throw new Error("FaceExpressions.constructor - expected probabilities.length to be 7, have: "+t.length);of.forEach(function(n,r){e[n]=t[r]})}return t.prototype.asSortedArray=function(){var t=this;return of.map(function(e){return{expression:e,probability:t[e]}}).sort(function(t,e){return e.probability-t.probability})},t}(),sf=function(t){function e(e){return void 0===e&&(e=new tf),t.call(this,"FaceExpressionNet",e)||this}return n(e,t),e.prototype.forwardInput=function(t){var e=this;return Fe(function(){return Ir(e.runNet(t))})},e.prototype.forward=function(t){return o(this,void 0,void 0,function(){var e;return i(this,function(n){switch(n.label){case 0:return e=this.forwardInput,[4,Rp(t)];case 1:return[2,e.apply(this,[n.sent()])]}})})},e.prototype.predictExpressions=function(t){return o(this,void 0,void 0,function(){var e,n,r,a,s=this;return i(this,function(u){switch(u.label){case 0:return[4,Rp(t)];case 1:return e=u.sent(),[4,this.forwardInput(e)];case 2:return n=u.sent(),[4,Promise.all(ar(n).map(function(t){return o(s,void 0,void 0,function(){var e;return i(this,function(n){switch(n.label){case 0:return[4,t.data()];case 1:return e=n.sent(),t.dispose(),[2,e]}})})}))];case 3:return r=u.sent(),n.dispose(),a=r.map(function(t){return new af(t)}),[2,e.isBatchInput?a:a[0]]}})})},e.prototype.getDefaultModelName=function(){return"face_expression_model"},e.prototype.getClassifierChannelsIn=function(){return 256},e.prototype.getClassifierChannelsOut=function(){return 7},e}(rf);function uf(t){return t.expressions instanceof af}function cf(t,e){var n={expressions:e};return Object.assign({},t,n)}var lf=function(){function t(t,e,n){void 0===n&&(n=new bh(0,0));var r=e.width,o=e.height;this._imgDims=new xh(r,o),this._shift=n,this._positions=t.map(function(t){return t.mul(new bh(r,o)).add(n)})}return Object.defineProperty(t.prototype,"shift",{get:function(){return new bh(this._shift.x,this._shift.y)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"imageWidth",{get:function(){return this._imgDims.width},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"imageHeight",{get:function(){return this._imgDims.height},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"positions",{get:function(){return this._positions},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"relativePositions",{get:function(){var t=this;return this._positions.map(function(e){return e.sub(t._shift).div(new bh(t.imageWidth,t.imageHeight))})},enumerable:!0,configurable:!0}),t.prototype.forSize=function(t,e){return new this.constructor(this.relativePositions,{width:t,height:e})},t.prototype.shiftBy=function(t,e){return new this.constructor(this.relativePositions,this._imgDims,new bh(t,e))},t.prototype.shiftByPoint=function(t){return this.shiftBy(t.x,t.y)},t.prototype.align=function(t,e){if(void 0===e&&(e={}),t){var n=t instanceof Hp?t.box.floor():new Oh(t);return this.shiftBy(n.x,n.y).align(null,e)}var r=Object.assign({},{useDlibAlignment:!1,minBoxPadding:.2},e),o=r.useDlibAlignment,i=r.minBoxPadding;return o?this.alignDlib():this.alignMinBbox(i)},t.prototype.alignDlib=function(){var t=this.getRefPointsForAlignment(),e=t[0],n=t[1],r=t[2],o=function(t){return r.sub(t).magnitude()},i=(o(e)+o(n))/2,a=Math.floor(i/.45),s=Ah(t),u=Math.floor(Math.max(0,s.x-.5*a)),c=Math.floor(Math.max(0,s.y-.43*a));return new zh(u,c,Math.min(a,this.imageWidth+u),Math.min(a,this.imageHeight+c))},t.prototype.alignMinBbox=function(t){var e=function(t){var e=t.map(function(t){return t.x}),n=t.map(function(t){return t.y}),r=e.reduce(function(t,e){return e or array thereof");var i=o.asSortedArray().filter(function(t){return t.probability>n}),a=qp(e)?e.detection.box.bottomLeft:r||new bh(0,0);new Zh(i.map(function(t){return t.expression+" ("+Rh(t.probability)+")"}),a).draw(t)})},DrawFaceLandmarksOptions:df,DrawFaceLandmarks:vf,drawFaceLandmarks:function(t,e){(Array.isArray(e)?e:[e]).forEach(function(e){var n=e instanceof lf?e:pf(e)?e.landmarks:void 0;if(!n)throw new Error("drawFaceLandmarks - expected faceExpressions to be FaceLandmarks | WithFaceLandmarks> or array thereof");new vf(n).draw(t)})}});function gf(t,e){var n=[],r=hp(t),o=r.extractWeights,i=r.getRemainingWeights,a=function(t,e){var n=ip(t,e),r=up(t,e);return{extractConvParams:n,extractSeparableConvParams:r,extractReductionBlockParams:function(t,e,o){return{separable_conv0:r(t,e,o+"/separable_conv0"),separable_conv1:r(e,e,o+"/separable_conv1"),expansion_conv:n(t,e,1,o+"/expansion_conv")}},extractMainBlockParams:function(t,e){return{separable_conv0:r(t,t,e+"/separable_conv0"),separable_conv1:r(t,t,e+"/separable_conv1"),separable_conv2:r(t,t,e+"/separable_conv2")}}}}(o,n),s=a.extractConvParams,u=a.extractSeparableConvParams,c=a.extractReductionBlockParams,l=a.extractMainBlockParams,h={conv_in:s(3,32,3,"entry_flow/conv_in"),reduction_block_0:c(32,64,"entry_flow/reduction_block_0"),reduction_block_1:c(64,128,"entry_flow/reduction_block_1")},p={};Th(e,0,1).forEach(function(t){p["main_block_"+t]=l(128,"middle_flow/main_block_"+t)});var f={reduction_block:c(128,256,"exit_flow/reduction_block"),separable_conv:u(256,512,"exit_flow/separable_conv")};if(0!==i().length)throw new Error("weights remaing after extract: "+i().length);return{paramMappings:n,params:{entry_flow:h,middle_flow:p,exit_flow:f}}}function yf(t,e){var n=[],r=function(t,e){var n=lp(t,e),r=Jp(n),o=cp(n);return{extractConvParams:r,extractSeparableConvParams:o,extractReductionBlockParams:function(t){return{separable_conv0:o(t+"/separable_conv0"),separable_conv1:o(t+"/separable_conv1"),expansion_conv:r(t+"/expansion_conv")}},extractMainBlockParams:function(t){return{separable_conv0:o(t+"/separable_conv0"),separable_conv1:o(t+"/separable_conv1"),separable_conv2:o(t+"/separable_conv2")}}}}(t,n),o=r.extractConvParams,i=r.extractSeparableConvParams,a=r.extractReductionBlockParams,s=r.extractMainBlockParams,u={conv_in:o("entry_flow/conv_in"),reduction_block_0:a("entry_flow/reduction_block_0"),reduction_block_1:a("entry_flow/reduction_block_1")},c={};Th(e,0,1).forEach(function(t){c["main_block_"+t]=s("middle_flow/main_block_"+t)});var l={reduction_block:a("exit_flow/reduction_block"),separable_conv:i("exit_flow/separable_conv")};return op(t,n),{params:{entry_flow:u,middle_flow:c,exit_flow:l},paramMappings:n}}function xf(t,e,n){return bu(Ss(t,e.filters,n,"same"),e.bias)}function bf(t,e,n){void 0===n&&(n=!0);var r=n?Yu(t):t;return r=Kp(r,e.separable_conv0,[1,1]),r=Kp(Yu(r),e.separable_conv1,[1,1]),r=Vs(r,[3,3],[2,2],"same"),r=bu(r,xf(t,e.expansion_conv,[2,2]))}var wf,Cf=function(t){function e(e){var n=t.call(this,"TinyXception")||this;return n._numMainBlocks=e,n}return n(e,t),e.prototype.forwardInput=function(t){var e=this,n=this.params;if(!n)throw new Error("TinyXception - load model before inference");return Fe(function(){var r=Tp(t.toBatchTensor(112,!0),[122.782,117.001,104.298]).div(rn(256)),o=Yu(xf(r,n.entry_flow.conv_in,[2,2]));return o=bf(o,n.entry_flow.reduction_block_0,!1),o=bf(o,n.entry_flow.reduction_block_1),Th(e._numMainBlocks,0,1).forEach(function(t){o=function(t,e){var n=Kp(Yu(t),e.separable_conv0,[1,1]);return n=Kp(Yu(n),e.separable_conv1,[1,1]),n=Kp(Yu(n),e.separable_conv2,[1,1]),n=bu(n,t)}(o,n.middle_flow["main_block_"+t])}),o=bf(o,n.exit_flow.reduction_block),o=Yu(Kp(o,n.exit_flow.separable_conv,[1,1]))})},e.prototype.forward=function(t){return o(this,void 0,void 0,function(){var e;return i(this,function(n){switch(n.label){case 0:return e=this.forwardInput,[4,Rp(t)];case 1:return[2,e.apply(this,[n.sent()])]}})})},e.prototype.getDefaultModelName=function(){return"tiny_xception_model"},e.prototype.extractParamsFromWeigthMap=function(t){return yf(t,this._numMainBlocks)},e.prototype.extractParams=function(t){return gf(t,this._numMainBlocks)},e}(Np);(wf=t.Gender||(t.Gender={})).FEMALE="female",wf.MALE="male";var Ef=function(e){function r(t){void 0===t&&(t=new Cf(2));var n=e.call(this,"AgeGenderNet")||this;return n._faceFeatureExtractor=t,n}return n(r,e),Object.defineProperty(r.prototype,"faceFeatureExtractor",{get:function(){return this._faceFeatureExtractor},enumerable:!0,configurable:!0}),r.prototype.runNet=function(t){var e=this,n=this.params;if(!n)throw new Error(this._name+" - load model before inference");return Fe(function(){var r=t instanceof Sp?e.faceFeatureExtractor.forwardInput(t):t,o=Gs(r,[7,7],[2,2],"valid").as2D(r.shape[0],-1);return{age:ef(o,n.fc.age).as1D(),gender:ef(o,n.fc.gender)}})},r.prototype.forwardInput=function(t){var e=this;return Fe(function(){var n=e.runNet(t),r=n.age,o=n.gender;return{age:r,gender:Ir(o)}})},r.prototype.forward=function(t){return o(this,void 0,void 0,function(){var e;return i(this,function(n){switch(n.label){case 0:return e=this.forwardInput,[4,Rp(t)];case 1:return[2,e.apply(this,[n.sent()])]}})})},r.prototype.predictAgeAndGender=function(e){return o(this,void 0,void 0,function(){var n,r,a,s,u,c,l=this;return i(this,function(h){switch(h.label){case 0:return[4,Rp(e)];case 1:return n=h.sent(),[4,this.forwardInput(n)];case 2:return r=h.sent(),a=ar(r.age),s=ar(r.gender),u=a.map(function(t,e){return{ageTensor:t,genderTensor:s[e]}}),[4,Promise.all(u.map(function(e){var n=e.ageTensor,r=e.genderTensor;return o(l,void 0,void 0,function(){var e,o,a,s,u;return i(this,function(i){switch(i.label){case 0:return[4,n.data()];case 1:return e=i.sent()[0],[4,r.data()];case 2:return o=i.sent()[0],s=(a=o>.5)?t.Gender.MALE:t.Gender.FEMALE,u=a?o:1-o,n.dispose(),r.dispose(),[2,{age:e,gender:s,genderProbability:u}]}})})}))];case 3:return c=h.sent(),r.age.dispose(),r.gender.dispose(),[2,n.isBatchInput?c:c[0]]}})})},r.prototype.getDefaultModelName=function(){return"age_gender_model"},r.prototype.dispose=function(t){void 0===t&&(t=!0),this.faceFeatureExtractor.dispose(t),e.prototype.dispose.call(this,t)},r.prototype.loadClassifierParams=function(t){var e=this.extractClassifierParams(t),n=e.params,r=e.paramMappings;this._params=n,this._paramMappings=r},r.prototype.extractClassifierParams=function(t){return function(t){var e=[],n=hp(t),r=n.extractWeights,o=n.getRemainingWeights,i=ap(r,e),a=i(512,1,"fc/age"),s=i(512,2,"fc/gender");if(0!==o().length)throw new Error("weights remaing after extract: "+o().length);return{paramMappings:e,params:{fc:{age:a,gender:s}}}}(t)},r.prototype.extractParamsFromWeigthMap=function(t){var e=nf(t),n=e.featureExtractorMap,r=e.classifierMap;return this.faceFeatureExtractor.loadFromWeightMap(n),function(t){var e=[],n=lp(t,e);function r(t){return{weights:n(t+"/weights",2),bias:n(t+"/bias",1)}}var o={fc:{age:r("fc/age"),gender:r("fc/gender")}};return op(t,e),{params:o,paramMappings:e}}(r)},r.prototype.extractParams=function(t){var e=t.slice(0,t.length-1539),n=t.slice(t.length-1539);return this.faceFeatureExtractor.extractWeights(e),this.extractClassifierParams(n)},r}(Np),_f=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return n(e,t),e.prototype.getRefPointsForAlignment=function(){var t=this.positions;return[t[0],t[1],Ah([t[3],t[4]])]},e}(lf),If=function(){function t(t,e){this._label=t,this._distance=e}return Object.defineProperty(t.prototype,"label",{get:function(){return this._label},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"distance",{get:function(){return this._distance},enumerable:!0,configurable:!0}),t.prototype.toString=function(t){return void 0===t&&(t=!0),this.label+(t?" ("+Rh(this.distance)+")":"")},t}(),Sf=function(){function t(t,e){if("string"!=typeof t)throw new Error("LabeledFaceDescriptors - constructor expected label to be a string");if(!Array.isArray(e)||e.some(function(t){return!(t instanceof Float32Array)}))throw new Error("LabeledFaceDescriptors - constructor expected descriptors to be an array of Float32Array");this._label=t,this._descriptors=e}return Object.defineProperty(t.prototype,"label",{get:function(){return this._label},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"descriptors",{get:function(){return this._descriptors},enumerable:!0,configurable:!0}),t}();function Rf(t,e){return o(this,void 0,void 0,function(){var n,r,o,a,s,u;return i(this,function(i){switch(i.label){case 0:return n=Xh.getEnv().Canvas,r=t,t instanceof n?[3,5]:[4,Rp(t)];case 1:if((o=i.sent()).batchSize>1)throw new Error("extractFaces - batchSize > 1 not supported");return(a=o.getInput(0))instanceof n?(s=a,[3,4]):[3,2];case 2:return[4,wp(a)];case 3:s=i.sent(),i.label=4;case 4:r=s,i.label=5;case 5:return u=Qh(r),[2,e.map(function(t){return t instanceof Hp?t.forSize(r.width,r.height).box.floor():t}).map(function(t){return t.clipAtImageBorders(r.width,r.height)}).map(function(t){var e=t.x,n=t.y,r=t.width,o=t.height,i=gp({width:r,height:o});return Qh(i).putImageData(u.getImageData(e,n,r,o),0,0),i})]}})})}function Nf(t,e){return o(this,void 0,void 0,function(){return i(this,function(n){if(!Eh(t)&&!_h(t))throw new Error("extractFaceTensors - expected image tensor to be 3D or 4D");if(_h(t)&&t.shape[0]>1)throw new Error("extractFaceTensors - batchSize > 1 not supported");return[2,Fe(function(){var n=t.shape.slice(_h(t)?1:0),r=n[0],o=n[1],i=n[2];return e.map(function(t){return t instanceof Hp?t.forSize(o,r).box:t}).map(function(t){return t.clipAtImageBorders(o,r)}).map(function(e){var n=e.x,a=e.y,s=e.width,u=e.height;return Ks(t.as3D(r,o,i),[a,n,0],[u,s,i])})})]})})}var kf=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return n(e,t),e.prototype.postProcess=function(t,e,n){var r=n.map(function(t){var n=t.width,r=t.height,o=e/Math.max(r,n);return{width:n*o,height:r*o}}),o=r.length;return Fe(function(){var n=function(t,e){return rr([fn([68],t),fn([68],e)],1).as2D(1,136).as1D()},i=function(t,e){var n=r[t],o=n.width,i=n.height;return e(o,i)?Math.abs(o-i)/2:0};return t.mul(fn([o,136],e)).sub(rr(Array.from(Array(o),function(t,e){return n(function(t){return i(t,function(t,e){return t 0");if("number"!=typeof this._scaleFactor||this._scaleFactor<=0||this._scaleFactor>=1)throw new Error(this._name+" - expected scaleFactor to be a number between 0 and 1");if("number"!=typeof this._maxNumScales||this._maxNumScales<0)throw new Error(this._name+" - expected maxNumScales to be a number > 0");if(!Array.isArray(this._scoreThresholds)||3!==this._scoreThresholds.length||this._scoreThresholds.some(function(t){return"number"!=typeof t}))throw new Error(this._name+" - expected scoreThresholds to be an array of numbers of length 3");if(this._scaleSteps&&(!Array.isArray(this._scaleSteps)||this._scaleSteps.some(function(t){return"number"!=typeof t})))throw new Error(this._name+" - expected scaleSteps to be an array of numbers")}return Object.defineProperty(t.prototype,"minFaceSize",{get:function(){return this._minFaceSize},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"scaleFactor",{get:function(){return this._scaleFactor},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"maxNumScales",{get:function(){return this._maxNumScales},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"scoreThresholds",{get:function(){return this._scoreThresholds},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"scaleSteps",{get:function(){return this._scaleSteps},enumerable:!0,configurable:!0}),t}();function jf(t,e){function n(n,r,o,i,a){var s=un(t(n*r*o*o),[o,o,n,r]),u=on(t(r));return e.push({paramPath:i+"/filters"},{paramPath:i+"/"+(a?"batch_norm_offset":"bias")}),{filters:s,bias:u}}function r(t,e,r,o){var i=n(t,e,r,o,!0);return{filters:i.filters,batch_norm_offset:i.bias}}function o(n,o,i){return{depthwise_conv:function(n,r){var o=un(t(9*n),[3,3,n,1]),i=on(t(n)),a=on(t(n)),s=on(t(n)),u=on(t(n));return e.push({paramPath:r+"/filters"},{paramPath:r+"/batch_norm_scale"},{paramPath:r+"/batch_norm_offset"},{paramPath:r+"/batch_norm_mean"},{paramPath:r+"/batch_norm_variance"}),{filters:o,batch_norm_scale:i,batch_norm_offset:a,batch_norm_mean:s,batch_norm_variance:u}}(n,i+"/depthwise_conv"),pointwise_conv:r(n,o,1,i+"/pointwise_conv")}}return{extractMobilenetV1Params:function(){return{conv_0:r(3,32,3,"mobilenetv1/conv_0"),conv_1:o(32,64,"mobilenetv1/conv_1"),conv_2:o(64,128,"mobilenetv1/conv_2"),conv_3:o(128,128,"mobilenetv1/conv_3"),conv_4:o(128,256,"mobilenetv1/conv_4"),conv_5:o(256,256,"mobilenetv1/conv_5"),conv_6:o(256,512,"mobilenetv1/conv_6"),conv_7:o(512,512,"mobilenetv1/conv_7"),conv_8:o(512,512,"mobilenetv1/conv_8"),conv_9:o(512,512,"mobilenetv1/conv_9"),conv_10:o(512,512,"mobilenetv1/conv_10"),conv_11:o(512,512,"mobilenetv1/conv_11"),conv_12:o(512,1024,"mobilenetv1/conv_12"),conv_13:o(1024,1024,"mobilenetv1/conv_13")}},extractPredictionLayerParams:function(){return{conv_0:r(1024,256,1,"prediction_layer/conv_0"),conv_1:r(256,512,3,"prediction_layer/conv_1"),conv_2:r(512,128,1,"prediction_layer/conv_2"),conv_3:r(128,256,3,"prediction_layer/conv_3"),conv_4:r(256,128,1,"prediction_layer/conv_4"),conv_5:r(128,256,3,"prediction_layer/conv_5"),conv_6:r(256,64,1,"prediction_layer/conv_6"),conv_7:r(64,128,3,"prediction_layer/conv_7"),box_predictor_0:{box_encoding_predictor:n(512,12,1,"prediction_layer/box_predictor_0/box_encoding_predictor"),class_predictor:n(512,9,1,"prediction_layer/box_predictor_0/class_predictor")},box_predictor_1:{box_encoding_predictor:n(1024,24,1,"prediction_layer/box_predictor_1/box_encoding_predictor"),class_predictor:n(1024,18,1,"prediction_layer/box_predictor_1/class_predictor")},box_predictor_2:{box_encoding_predictor:n(512,24,1,"prediction_layer/box_predictor_2/box_encoding_predictor"),class_predictor:n(512,18,1,"prediction_layer/box_predictor_2/class_predictor")},box_predictor_3:{box_encoding_predictor:n(256,24,1,"prediction_layer/box_predictor_3/box_encoding_predictor"),class_predictor:n(256,18,1,"prediction_layer/box_predictor_3/class_predictor")},box_predictor_4:{box_encoding_predictor:n(256,24,1,"prediction_layer/box_predictor_4/box_encoding_predictor"),class_predictor:n(256,18,1,"prediction_layer/box_predictor_4/class_predictor")},box_predictor_5:{box_encoding_predictor:n(128,24,1,"prediction_layer/box_predictor_5/box_encoding_predictor"),class_predictor:n(128,18,1,"prediction_layer/box_predictor_5/class_predictor")}}}}}function Hf(t){var e=[],n=function(t,e){var n=lp(t,e);function r(t,e,r){return{filters:n(t+"/Conv2d_"+e+"_pointwise/weights",4,r+"/filters"),batch_norm_offset:n(t+"/Conv2d_"+e+"_pointwise/convolution_bn_offset",1,r+"/batch_norm_offset")}}function o(t){var e="mobilenetv1/conv_"+t,o="MobilenetV1/Conv2d_"+t+"_depthwise",i=e+"/depthwise_conv",a=e+"/pointwise_conv";return{depthwise_conv:{filters:n(o+"/depthwise_weights",4,i+"/filters"),batch_norm_scale:n(o+"/BatchNorm/gamma",1,i+"/batch_norm_scale"),batch_norm_offset:n(o+"/BatchNorm/beta",1,i+"/batch_norm_offset"),batch_norm_mean:n(o+"/BatchNorm/moving_mean",1,i+"/batch_norm_mean"),batch_norm_variance:n(o+"/BatchNorm/moving_variance",1,i+"/batch_norm_variance")},pointwise_conv:r("MobilenetV1",t,a)}}function i(t,e){return{filters:n(t+"/weights",4,e+"/filters"),bias:n(t+"/biases",1,e+"/bias")}}function a(t){return{box_encoding_predictor:i("Prediction/BoxPredictor_"+t+"/BoxEncodingPredictor","prediction_layer/box_predictor_"+t+"/box_encoding_predictor"),class_predictor:i("Prediction/BoxPredictor_"+t+"/ClassPredictor","prediction_layer/box_predictor_"+t+"/class_predictor")}}return{extractMobilenetV1Params:function(){return{conv_0:r("MobilenetV1",0,"mobilenetv1/conv_0"),conv_1:o(1),conv_2:o(2),conv_3:o(3),conv_4:o(4),conv_5:o(5),conv_6:o(6),conv_7:o(7),conv_8:o(8),conv_9:o(9),conv_10:o(10),conv_11:o(11),conv_12:o(12),conv_13:o(13)}},extractPredictionLayerParams:function(){return{conv_0:r("Prediction",0,"prediction_layer/conv_0"),conv_1:r("Prediction",1,"prediction_layer/conv_1"),conv_2:r("Prediction",2,"prediction_layer/conv_2"),conv_3:r("Prediction",3,"prediction_layer/conv_3"),conv_4:r("Prediction",4,"prediction_layer/conv_4"),conv_5:r("Prediction",5,"prediction_layer/conv_5"),conv_6:r("Prediction",6,"prediction_layer/conv_6"),conv_7:r("Prediction",7,"prediction_layer/conv_7"),box_predictor_0:a(0),box_predictor_1:a(1),box_predictor_2:a(2),box_predictor_3:a(3),box_predictor_4:a(4),box_predictor_5:a(5)}}}}(t,e),r=n.extractMobilenetV1Params,o=n.extractPredictionLayerParams,i=t["Output/extra_dim"];if(e.push({originalPath:"Output/extra_dim",paramPath:"output_layer/extra_dim"}),!Eh(i))throw new Error("expected weightMap['Output/extra_dim'] to be a Tensor3D, instead have "+i);var a={mobilenetv1:r(),prediction_layer:o(),output_layer:{extra_dim:i}};return op(t,e),{params:a,paramMappings:e}}function qf(t,e,n){return Fe(function(){var r=Ss(t,e.filters,n,"same");return r=bu(r,e.batch_norm_offset),Oa(r,0,6)})}var $f=.0010000000474974513;function Kf(t,e){return Fe(function(){var n=null,r=qf(t,e.conv_0,[2,2]);if([e.conv_1,e.conv_2,e.conv_3,e.conv_4,e.conv_5,e.conv_6,e.conv_7,e.conv_8,e.conv_9,e.conv_10,e.conv_11,e.conv_12,e.conv_13].forEach(function(t,e){var o=e+1,i=function(t){return[2,4,6,12].some(function(e){return e===t})?[2,2]:[1,1]}(o);r=qf(r=function(t,e,n){return Fe(function(){var r=ks(t,e.filters,n,"same");return r=ys(r,e.batch_norm_mean,e.batch_norm_variance,e.batch_norm_offset,e.batch_norm_scale,$f),Oa(r,0,6)})}(r,t.depthwise_conv,i),t.pointwise_conv,[1,1]),11===o&&(n=r)}),null===n)throw new Error("mobileNetV1 - output of conv layer 11 is null");return{out:r,conv11:n}})}function Xf(t,e,n){var r=t.arraySync(),o=Math.min(r[e][0],r[e][2]),i=Math.min(r[e][1],r[e][3]),a=Math.max(r[e][0],r[e][2]),s=Math.max(r[e][1],r[e][3]),u=Math.min(r[n][0],r[n][2]),c=Math.min(r[n][1],r[n][3]),l=Math.max(r[n][0],r[n][2]),h=Math.max(r[n][1],r[n][3]),p=(a-o)*(s-i),f=(l-u)*(h-c);if(p<=0||f<=0)return 0;var d=Math.max(o,u),v=Math.max(i,c),m=Math.min(a,l),g=Math.min(s,h),y=Math.max(m-d,0)*Math.max(g-v,0);return y/(p+f-y)}function Yf(t,e){var n=function(t){var e=ar(Ju(t,[1,0])),n=[Wu(e[2],e[0]),Wu(e[3],e[1])];return{sizes:n,centers:[bu(e[0],_u(n[0],rn(2))),bu(e[1],_u(n[1],rn(2)))]}}(t),r=n.sizes,o=n.centers,i=ar(Ju(e,[1,0])),a=_u(Fu(Wa(_u(i[2],rn(5))),r[0]),rn(2)),s=bu(Fu(_u(i[0],rn(10)),r[0]),o[0]),u=_u(Fu(Wa(_u(i[3],rn(5))),r[1]),rn(2)),c=bu(Fu(_u(i[1],rn(10)),r[1]),o[1]);return Ju(rr([Wu(s,a),Wu(c,u),bu(s,a),bu(c,u)]),[1,0])}function Qf(t,e){return Fe(function(){var n=t.shape[0];return{boxPredictionEncoding:tr(rp(t,e.box_encoding_predictor),[n,-1,1,4]),classPrediction:tr(rp(t,e.class_predictor),[n,-1,3])}})}var Jf=function(){function t(t){var e=void 0===t?{}:t,n=e.minConfidence,r=e.maxResults;if(this._name="SsdMobilenetv1Options",this._minConfidence=n||.5,this._maxResults=r||100,"number"!=typeof this._minConfidence||this._minConfidence<=0||this._minConfidence>=1)throw new Error(this._name+" - expected minConfidence to be a number between 0 and 1");if("number"!=typeof this._maxResults)throw new Error(this._name+" - expected maxResults to be a number")}return Object.defineProperty(t.prototype,"minConfidence",{get:function(){return this._minConfidence},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"maxResults",{get:function(){return this._maxResults},enumerable:!0,configurable:!0}),t}(),Zf=function(t){function e(){return t.call(this,"SsdMobilenetv1")||this}return n(e,t),e.prototype.forwardInput=function(t){var e=this.params;if(!e)throw new Error("SsdMobilenetv1 - load model before inference");return Fe(function(){var n=t.toBatchTensor(512,!1).toFloat(),r=Kf(Wu(Fu(n,rn(.007843137718737125)),rn(1)),e.mobilenetv1),o=function(t,e,n){return Fe(function(){var r=qf(t,n.conv_0,[1,1]),o=qf(r,n.conv_1,[2,2]),i=qf(o,n.conv_2,[1,1]),a=qf(i,n.conv_3,[2,2]),s=qf(a,n.conv_4,[1,1]),u=qf(s,n.conv_5,[2,2]),c=qf(u,n.conv_6,[1,1]),l=qf(c,n.conv_7,[2,2]),h=Qf(e,n.box_predictor_0),p=Qf(t,n.box_predictor_1),f=Qf(o,n.box_predictor_2),d=Qf(a,n.box_predictor_3),v=Qf(u,n.box_predictor_4),m=Qf(l,n.box_predictor_5);return{boxPredictions:yn([h.boxPredictionEncoding,p.boxPredictionEncoding,f.boxPredictionEncoding,d.boxPredictionEncoding,v.boxPredictionEncoding,m.boxPredictionEncoding],1),classPredictions:yn([h.classPrediction,p.classPrediction,f.classPrediction,d.classPrediction,v.classPrediction,m.classPrediction],1)}})}(r.out,r.conv11,e.prediction_layer);return function(t,e,n){return Fe(function(){var r=t.shape[0],o=Yf(tr(or(n.extra_dim,[r,1,1]),[-1,4]),tr(t,[-1,4]));o=tr(o,[r,o.shape[0]/r,4]);var i=Xa(Hs(e,[0,0,1],[-1,-1,-1])),a=Hs(i,[0,0,0],[-1,-1,1]);return a=tr(a,[r,a.shape[1]]),{boxes:ar(o),scores:ar(a)}})}(o.boxPredictions,o.classPredictions,e.output_layer)})},e.prototype.forward=function(t){return o(this,void 0,void 0,function(){var e;return i(this,function(n){switch(n.label){case 0:return e=this.forwardInput,[4,Rp(t)];case 1:return[2,e.apply(this,[n.sent()])]}})})},e.prototype.locateFaces=function(t,e){return void 0===e&&(e={}),o(this,void 0,void 0,function(){var n,r,o,a,s,u,c,l,h,p,f,d,v,m,g,y,x,b,w,C;return i(this,function(i){switch(i.label){case 0:return n=new Jf(e),r=n.maxResults,o=n.minConfidence,[4,Rp(t)];case 1:for(a=i.sent(),s=this.forwardInput(a),u=s.boxes,c=s.scores,l=u[0],h=c[0],p=1;po}).sort(function(t,e){return e.score-t.score}),u=function(t){return t<=r?1:0},c=[];return s.forEach(function(e){if(!(c.length>=a)){for(var n=e.score,r=c.length-1;r>=0;--r){var i=Xf(t,e.boxIndex,c[r]);if(0!==i&&(e.score*=u(i),e.score<=o))break}n===e.score&&c.push(e.boxIndex)}}),c}(l,f,r,.5,o),g=a.getReshapedInputDimensions(0),y=a.inputSize,x=y/g.width,b=y/g.height,w=l.arraySync(),C=m.map(function(t){var e=[Math.max(0,w[t][0]),Math.min(1,w[t][2])].map(function(t){return t*b}),n=e[0],r=e[1],o=[Math.max(0,w[t][1]),Math.min(1,w[t][3])].map(function(t){return t*x}),i=o[0],s=o[1];return new Hp(f[t],new zh(i,n,s-i,r-n),{height:a.getInputHeight(0),width:a.getInputWidth(0)})}),l.dispose(),h.dispose(),[2,C]}})})},e.prototype.getDefaultModelName=function(){return"ssd_mobilenetv1_model"},e.prototype.extractParamsFromWeigthMap=function(t){return Hf(t)},e.prototype.extractParams=function(t){return function(t){var e=[],n=hp(t),r=n.extractWeights,o=n.getRemainingWeights,i=jf(r,e),a=i.extractMobilenetV1Params,s=i.extractPredictionLayerParams,u=a(),c=s(),l={extra_dim:sn(r(20472),[1,5118,4])};if(e.push({paramPath:"output_layer/extra_dim"}),0!==o().length)throw new Error("weights remaing after extract: "+o().length);return{params:{mobilenetv1:u,prediction_layer:c,output_layer:l},paramMappings:e}}(t)},e}(Np);function td(t){var e=new Zf;return e.extractWeights(t),e}var ed=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return n(e,t),e}(Zf),nd=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e._name="TinyFaceDetectorOptions",e}return n(e,t),e}(Up),rd=function(){function t(){}return t.prototype.then=function(t){return o(this,void 0,void 0,function(){var e;return i(this,function(n){switch(n.label){case 0:return e=t,[4,this.run()];case 1:return[2,e.apply(void 0,[n.sent()])]}})})},t.prototype.run=function(){return o(this,void 0,void 0,function(){return i(this,function(t){throw new Error("ComposableTask - run is not implemented")})})},t}();function od(t,e,n,r,a){return void 0===a&&(a=function(t){return t.alignedRect}),o(this,void 0,void 0,function(){var o,s,u,c,l;return i(this,function(i){switch(i.label){case 0:return o=t.map(function(t){return pf(t)?a(t):t.detection}),(u=r)?[3,5]:e instanceof mt?[4,Nf(e,o)]:[3,2];case 1:return c=i.sent(),[3,4];case 2:return[4,Rf(e,o)];case 3:c=i.sent(),i.label=4;case 4:u=c,i.label=5;case 5:return[4,n(s=u)];case 6:return l=i.sent(),s.forEach(function(t){return t instanceof mt&&t.dispose()}),[2,l]}})})}function id(t,e,n,r,a){return o(this,void 0,void 0,function(){var s=this;return i(this,function(u){return[2,od([t],e,function(t){return o(s,void 0,void 0,function(){return i(this,function(e){return[2,n(t[0])]})})},r,a)]})})}var ad=2,sd=12;function ud(t){var e=hp(t),n=e.extractWeights,o=e.getRemainingWeights,i=[],a=function(t,e){var n=ip(t,e),o=ap(t,e);function i(n,r){var o=on(t(n));return e.push({paramPath:r}),o}function a(t,e,r){return void 0===r&&(r=!1),{conv1:n(t[0],t[1],3,e+"/conv1"),prelu1_alpha:i(t[1],e+"/prelu1_alpha"),conv2:n(t[1],t[2],3,e+"/conv2"),prelu2_alpha:i(t[2],e+"/prelu2_alpha"),conv3:n(t[2],t[3],r?2:3,e+"/conv3"),prelu3_alpha:i(t[3],e+"/prelu3_alpha")}}return{extractPNetParams:function(){var t=a([3,10,16,32],"pnet"),e=n(32,2,1,"pnet/conv4_1"),o=n(32,4,1,"pnet/conv4_2");return r({},t,{conv4_1:e,conv4_2:o})},extractRNetParams:function(){var t=a([3,28,48,64],"rnet",!0),e=o(576,128,"rnet/fc1"),n=i(128,"rnet/prelu4_alpha"),s=o(128,2,"rnet/fc2_1"),u=o(128,4,"rnet/fc2_2");return r({},t,{fc1:e,prelu4_alpha:n,fc2_1:s,fc2_2:u})},extractONetParams:function(){var t=a([3,32,64,64],"onet"),e=n(64,128,2,"onet/conv4"),s=i(128,"onet/prelu4_alpha"),u=o(1152,256,"onet/fc1"),c=i(256,"onet/prelu5_alpha"),l=o(256,2,"onet/fc2_1"),h=o(256,4,"onet/fc2_2"),p=o(256,10,"onet/fc2_3");return r({},t,{conv4:e,prelu4_alpha:s,fc1:u,prelu5_alpha:c,fc2_1:l,fc2_2:h,fc2_3:p})}}}(n,i),s=a.extractPNetParams,u=a.extractRNetParams,c=a.extractONetParams,l=s(),h=u(),p=c();if(0!==o().length)throw new Error("weights remaing after extract: "+o().length);return{params:{pnet:l,rnet:h,onet:p},paramMappings:i}}function cd(t){var e=[],n=function(t,e){var n=lp(t,e);function o(t){return{filters:n(t+"/weights",4,t+"/filters"),bias:n(t+"/bias",1)}}function i(t){return{weights:n(t+"/weights",2),bias:n(t+"/bias",1)}}function a(t){return n(t,1)}function s(t){return{conv1:o(t+"/conv1"),prelu1_alpha:a(t+"/prelu1_alpha"),conv2:o(t+"/conv2"),prelu2_alpha:a(t+"/prelu2_alpha"),conv3:o(t+"/conv3"),prelu3_alpha:a(t+"/prelu3_alpha")}}return{extractPNetParams:function(){var t=s("pnet"),e=o("pnet/conv4_1"),n=o("pnet/conv4_2");return r({},t,{conv4_1:e,conv4_2:n})},extractRNetParams:function(){var t=s("rnet"),e=i("rnet/fc1"),n=a("rnet/prelu4_alpha"),o=i("rnet/fc2_1"),u=i("rnet/fc2_2");return r({},t,{fc1:e,prelu4_alpha:n,fc2_1:o,fc2_2:u})},extractONetParams:function(){var t=s("onet"),e=o("onet/conv4"),n=a("onet/prelu4_alpha"),u=i("onet/fc1"),c=a("onet/prelu5_alpha"),l=i("onet/fc2_1"),h=i("onet/fc2_2"),p=i("onet/fc2_3");return r({},t,{conv4:e,prelu4_alpha:n,fc1:u,prelu5_alpha:c,fc2_1:l,fc2_2:h,fc2_3:p})}}}(t,e),o=n.extractPNetParams,i=n.extractRNetParams,a=n.extractONetParams,s=o(),u=i(),c=a();return op(t,e),{params:{pnet:s,rnet:u,onet:c},paramMappings:e}}function ld(t,e){var n=e[0],r=e[1];return{height:Math.floor(n*t),width:Math.floor(r*t)}}var hd=function(t){function e(e,n,r,o){return t.call(this,{left:e,top:n,right:r,bottom:o},!0)||this}return n(e,t),e}(Oh);function pd(t){return Fe(function(){return Fu(Wu(t,rn(127.5)),rn(.0078125))})}function fd(t,e){return Fe(function(){return bu(Yu(t),Fu(e,Ha(Yu(Ha(t)))))})}function dd(t,e,n){return void 0===n&&(n=!1),Fe(function(){var r=rp(t,e.conv1,"valid");return r=fd(r,e.prelu1_alpha),r=fd(r=rp(r=Vs(r,n?[2,2]:[3,3],[2,2],"same"),e.conv2,"valid"),e.prelu2_alpha),r=fd(r=rp(r=n?r:Vs(r,[3,3],[2,2],"valid"),e.conv3,"valid"),e.prelu3_alpha)})}function vd(t,e,n,r,o){o.stage1=[];var i=e.map(function(e){return Fe(function(){var n={scale:e},o=function(t,e){return Fe(function(){var n=ld(e,t.shape.slice(1)),r=n.height,o=n.width,i=pd(jc.resizeBilinear(t,[r,o]));return Ju(i,[0,2,1,3])})}(t,e),i=Date.now(),a=function(t,e){return Fe(function(){var n=dd(t,e,!0),r=rp(n,e.conv4_1,"valid"),o=Vn(nu(r,3),3);return{prob:Ir(Wu(r,o),3),regions:rp(n,e.conv4_2,"valid")}})}(o,r),s=a.prob,u=a.regions;return n.pnet=Date.now()-i,{scoresTensor:ar(ar(s,3)[1])[0],regionsTensor:ar(u)[0],scale:e,statsForScale:n}})}).map(function(t){var e=t.scoresTensor,r=t.regionsTensor,i=t.scale,a=t.statsForScale,s=function(t,e,n,r){for(var o=[],i=t.arraySync(),a=0;a=r&&o.push(new bh(s,a));return o.map(function(t){var r=new Ph(Math.round((t.y*ad+1)/n),Math.round((t.x*ad+1)/n),Math.round((t.y*ad+sd)/n),Math.round((t.x*ad+sd)/n)),o=i[t.y][t.x],a=e.arraySync();return{cell:r,score:o,region:new hd(a[t.y][t.x][0],a[t.y][t.x][1],a[t.y][t.x][2],a[t.y][t.x][3])}})}(e,r,i,n);if(e.dispose(),r.dispose(),!s.length)return o.stage1.push(a),[];var u=Date.now(),c=Ap(s.map(function(t){return t.cell}),s.map(function(t){return t.score}),.5);return a.nms=Date.now()-u,a.numBoxes=c.length,o.stage1.push(a),c.map(function(t){return s[t]})}).reduce(function(t,e){return t.concat(e)},[]),a=[],s=[];if(i.length>0){var u=Date.now(),c=Ap(i.map(function(t){return t.cell}),i.map(function(t){return t.score}),.7);o.stage1_nms=Date.now()-u,s=c.map(function(t){return i[t].score}),a=c.map(function(t){return i[t]}).map(function(t){var e=t.cell,n=t.region;return new Ph(e.left+n.left*e.width,e.top+n.top*e.height,e.right+n.right*e.width,e.bottom+n.bottom*e.height).toSquare().round()})}return{boxes:a,scores:s}}function md(t,e,n){var r=n.width,a=n.height;return o(this,void 0,void 0,function(){var n,s,u,c=this;return i(this,function(l){switch(l.label){case 0:return n=Qh(t),[4,Promise.all(e.map(function(e){return o(c,void 0,void 0,function(){var r,o,a,s,u,c,l,h;return i(this,function(i){return r=e.padAtBorders(t.height,t.width),o=r.y,a=r.ey,s=r.x,u=r.ex,c=s-1,l=o-1,h=n.getImageData(c,l,u-c,a-l),[2,Xh.isNodejs()?yp(h):createImageBitmap(h)]})})}))];case 1:return s=l.sent(),u=[],s.forEach(function(t){var e=Qh(gp({width:r,height:a}));e.drawImage(t,0,0,r,a);for(var n=e.getImageData(0,0,r,a).data,o=[],i=0;i1?yn(u.map(function(t){return t.scores})):u[0].scores,p=(h=Array).from,[4,c.data()];case 2:return l=p.apply(h,[i.sent()]),c.dispose(),f=l.map(function(t,e){return{score:t,idx:e}}).filter(function(t){return t.score>n}).map(function(t){return t.idx}),d=f.map(function(t){return e[t]}),v=f.map(function(t){return l[t]}),m=[],g=[],d.length>0&&(o=Date.now(),y=Ap(d,v,.7),a.stage2_nms=Date.now()-o,x=y.map(function(t){var e=u[f[t]].regions.arraySync();return new hd(e[0][0],e[0][1],e[0][2],e[0][3])}),g=y.map(function(t){return v[t]}),m=y.map(function(t,e){return d[t].calibrate(x[e])})),u.forEach(function(t){t.regions.dispose(),t.scores.dispose()}),[2,{boxes:m,scores:g}]}})})}function yd(t,e,n,r,a){return o(this,void 0,void 0,function(){var o,s,u,c,l,h,p,f,d,v,m,g,y,x,b;return i(this,function(i){switch(i.label){case 0:return o=Date.now(),[4,md(t,e,{width:48,height:48})];case 1:return s=i.sent(),a.stage3_extractImagePatches=Date.now()-o,o=Date.now(),u=s.map(function(t){var e=function(t,e){return Fe(function(){var n=dd(t,e);n=fd(n=rp(n=Vs(n,[2,2],[2,2],"same"),e.conv4,"valid"),e.prelu4_alpha);var r=fd(ef(tr(n,[n.shape[0],e.fc1.weights.shape[0]]),e.fc1),e.prelu5_alpha),o=ef(r,e.fc2_1),i=Vn(nu(o,1),1),a=Ir(Wu(o,i),1),s=ef(r,e.fc2_2),u=ef(r,e.fc2_3);return{scores:ar(a,1)[1],regions:s,points:u}})}(t,r);return t.dispose(),e}),a.stage3_onet=Date.now()-o,c=u.length>1?yn(u.map(function(t){return t.scores})):u[0].scores,p=(h=Array).from,[4,c.data()];case 2:return l=p.apply(h,[i.sent()]),c.dispose(),f=l.map(function(t,e){return{score:t,idx:e}}).filter(function(t){return t.score>n}).map(function(t){return t.idx}),d=f.map(function(t){var e=u[t].regions.arraySync();return new hd(e[0][0],e[0][1],e[0][2],e[0][3])}),v=f.map(function(t,n){return e[t].calibrate(d[n])}),m=f.map(function(t){return l[t]}),g=[],y=[],x=[],v.length>0&&(o=Date.now(),b=Ap(v,m,.7,!1),a.stage3_nms=Date.now()-o,g=b.map(function(t){return v[t]}),y=b.map(function(t){return m[t]}),x=b.map(function(t,e){return Array(5).fill(0).map(function(n,r){var o=u[t].points.arraySync();return new bh(o[0][r]*(g[e].width+1)+g[e].left,o[0][r+5]*(g[e].height+1)+g[e].top)})})),u.forEach(function(t){t.regions.dispose(),t.scores.dispose(),t.points.dispose()}),[2,{boxes:g,scores:y,points:x}]}})})}var xd=function(t){function e(){return t.call(this,"Mtcnn")||this}return n(e,t),e.prototype.forwardInput=function(t,e){return void 0===e&&(e={}),o(this,void 0,void 0,function(){var n,r,o,a,s,u,c,l,h,p,f,d,v,m,g,y,x,b,w,C,E;return i(this,function(i){switch(i.label){case 0:if(!(n=this.params))throw new Error("Mtcnn - load model before inference");if(!(r=t.canvases[0]))throw new Error("Mtcnn - inputCanvas is not defined, note that passing tensors into Mtcnn.forwardInput is not supported yet.");return o={},a=Date.now(),s=Fe(function(){return t=Vn(Xl.fromPixels(r)).toFloat(),Fe(function(){return rr(ar(t,3).reverse(),3)});var t}),u=function(t){return s.dispose(),o.total=Date.now()-a,t},c=s.shape.slice(1),l=c[0],h=c[1],p=new Gf(e),f=p.minFaceSize,d=p.scaleFactor,v=p.maxNumScales,m=p.scoreThresholds,g=p.scaleSteps,y=(g||function(t,e,n){for(var r=n[0],o=n[1],i=sd/t,a=[],s=Math.min(r,o)*i,u=0;s>=12;)a.push(i*Math.pow(e,u)),s*=e,u+=1;return a}(f,d,[l,h])).filter(function(t){var e=ld(t,[l,h]);return Math.min(e.width,e.height)>sd}).slice(0,v),o.scales=y,o.pyramid=y.map(function(t){return ld(t,[l,h])}),x=Date.now(),[4,vd(s,y,m[0],n.pnet,o)];case 1:return b=i.sent(),o.total_stage1=Date.now()-x,b.boxes.length?(o.stage2_numInputBoxes=b.boxes.length,x=Date.now(),[4,gd(r,b.boxes,m[1],n.rnet,o)]):[2,u({results:[],stats:o})];case 2:return w=i.sent(),o.total_stage2=Date.now()-x,w.boxes.length?(o.stage3_numInputBoxes=w.boxes.length,x=Date.now(),[4,yd(r,w.boxes,m[2],n.onet,o)]):[2,u({results:[],stats:o})];case 3:return C=i.sent(),o.total_stage3=Date.now()-x,E=C.boxes.map(function(t,e){return ff($p({},new Hp(C.scores[e],new zh(t.left/h,t.top/l,t.width/h,t.height/l),{height:l,width:h})),new _f(C.points[e].map(function(e){return e.sub(new bh(t.left,t.top)).div(new bh(t.width,t.height))}),{width:t.width,height:t.height}))}),[2,u({results:E,stats:o})]}})})},e.prototype.forward=function(t,e){return void 0===e&&(e={}),o(this,void 0,void 0,function(){var n;return i(this,function(r){switch(r.label){case 0:return n=this.forwardInput,[4,Rp(t)];case 1:return[4,n.apply(this,[r.sent(),e])];case 2:return[2,r.sent().results]}})})},e.prototype.forwardWithStats=function(t,e){return void 0===e&&(e={}),o(this,void 0,void 0,function(){var n;return i(this,function(r){switch(r.label){case 0:return n=this.forwardInput,[4,Rp(t)];case 1:return[2,n.apply(this,[r.sent(),e])]}})})},e.prototype.getDefaultModelName=function(){return"mtcnn_model"},e.prototype.extractParamsFromWeigthMap=function(t){return cd(t)},e.prototype.extractParams=function(t){return ud(t)},e}(Np),bd=.4,wd=[new bh(1.603231,2.094468),new bh(6.041143,7.080126),new bh(2.882459,3.518061),new bh(4.266906,5.178857),new bh(9.041765,10.66308)],Cd=[117.001,114.697,97.404],Ed=function(t){function e(){var e={withSeparableConvs:!0,iouThreshold:bd,classes:["face"],anchors:wd,meanRgb:Cd,isFirstLayerConv2d:!0,filterSizes:[3,16,32,64,128,256,512]};return t.call(this,e)||this}return n(e,t),Object.defineProperty(e.prototype,"anchors",{get:function(){return this.config.anchors},enumerable:!0,configurable:!0}),e.prototype.locateFaces=function(t,e){return o(this,void 0,void 0,function(){return i(this,function(n){switch(n.label){case 0:return[4,this.detect(t,e)];case 1:return[2,n.sent().map(function(t){return new Hp(t.score,t.relativeBox,{width:t.imageWidth,height:t.imageHeight})})]}})})},e.prototype.getDefaultModelName=function(){return"tiny_face_detector_model"},e.prototype.extractParamsFromWeigthMap=function(e){return t.prototype.extractParamsFromWeigthMap.call(this,e)},e}(Vp),_d=.4,Id=[new bh(.738768,.874946),new bh(2.42204,2.65704),new bh(4.30971,7.04493),new bh(10.246,4.59428),new bh(12.6868,11.8741)],Sd=[new bh(1.603231,2.094468),new bh(6.041143,7.080126),new bh(2.882459,3.518061),new bh(4.266906,5.178857),new bh(9.041765,10.66308)],Rd=[117.001,114.697,97.404],Nd=function(t){function e(e){void 0===e&&(e=!0);var n=Object.assign({},{withSeparableConvs:e,iouThreshold:_d,classes:["face"]},e?{anchors:Sd,meanRgb:Rd}:{anchors:Id,withClassScores:!0});return t.call(this,n)||this}return n(e,t),Object.defineProperty(e.prototype,"withSeparableConvs",{get:function(){return this.config.withSeparableConvs},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"anchors",{get:function(){return this.config.anchors},enumerable:!0,configurable:!0}),e.prototype.locateFaces=function(t,e){return o(this,void 0,void 0,function(){return i(this,function(n){switch(n.label){case 0:return[4,this.detect(t,e)];case 1:return[2,n.sent().map(function(t){return new Hp(t.score,t.relativeBox,{width:t.imageWidth,height:t.imageHeight})})]}})})},e.prototype.getDefaultModelName=function(){return this.withSeparableConvs?"tiny_yolov2_separable_conv_model":"tiny_yolov2_model"},e.prototype.extractParamsFromWeigthMap=function(e){return t.prototype.extractParamsFromWeigthMap.call(this,e)},e}(Vp);var kd={ssdMobilenetv1:new Zf,tinyFaceDetector:new Ed,tinyYolov2:new Nd,mtcnn:new xd,faceLandmark68Net:new Af,faceLandmark68TinyNet:new Df,faceRecognitionNet:new Uf,faceExpressionNet:new sf,ageGenderNet:new Ef},Ad=function(t,e){return kd.ssdMobilenetv1.locateFaces(t,e)},Td=function(t){return kd.faceLandmark68Net.detectLandmarks(t)},Dd=function(t){return kd.ssdMobilenetv1.load(t)},Fd=Dd,Md=Ad,Od=Td;function Pd(t,e){var n={age:e};return Object.assign({},t,n)}function Bd(t,e,n){var r={gender:e,genderProbability:n};return Object.assign({},t,r)}var Ld=function(t){function e(e,n,r){var o=t.call(this)||this;return o.parentTask=e,o.input=n,o.extractedFaces=r,o}return n(e,t),e}(rd),Wd=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return n(e,t),e.prototype.run=function(){return o(this,void 0,void 0,function(){var t,e,n=this;return i(this,function(r){switch(r.label){case 0:return[4,this.parentTask];case 1:return[4,od(t=r.sent(),this.input,function(t){return o(n,void 0,void 0,function(){return i(this,function(e){switch(e.label){case 0:return[4,Promise.all(t.map(function(t){return kd.faceExpressionNet.predictExpressions(t)}))];case 1:return[2,e.sent()]}})})},this.extractedFaces)];case 2:return e=r.sent(),[2,t.map(function(t,n){return cf(t,e[n])})]}})})},e.prototype.withAgeAndGender=function(){return new jd(this,this.input)},e}(Ld),zd=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return n(e,t),e.prototype.run=function(){return o(this,void 0,void 0,function(){var t,e;return i(this,function(n){switch(n.label){case 0:return[4,this.parentTask];case 1:return(t=n.sent())?[4,id(t,this.input,function(t){return kd.faceExpressionNet.predictExpressions(t)},this.extractedFaces)]:[2];case 2:return e=n.sent(),[2,cf(t,e)]}})})},e.prototype.withAgeAndGender=function(){return new Hd(this,this.input)},e}(Ld),Ud=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return n(e,t),e.prototype.withAgeAndGender=function(){return new qd(this,this.input)},e.prototype.withFaceDescriptors=function(){return new Xd(this,this.input)},e}(Wd),Vd=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return n(e,t),e.prototype.withAgeAndGender=function(){return new $d(this,this.input)},e.prototype.withFaceDescriptor=function(){return new Yd(this,this.input)},e}(zd),Gd=function(t){function e(e,n,r){var o=t.call(this)||this;return o.parentTask=e,o.input=n,o.extractedFaces=r,o}return n(e,t),e}(rd),jd=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return n(e,t),e.prototype.run=function(){return o(this,void 0,void 0,function(){var t,e,n=this;return i(this,function(r){switch(r.label){case 0:return[4,this.parentTask];case 1:return[4,od(t=r.sent(),this.input,function(t){return o(n,void 0,void 0,function(){return i(this,function(e){switch(e.label){case 0:return[4,Promise.all(t.map(function(t){return kd.ageGenderNet.predictAgeAndGender(t)}))];case 1:return[2,e.sent()]}})})},this.extractedFaces)];case 2:return e=r.sent(),[2,t.map(function(t,n){var r=e[n],o=r.age;return Pd(Bd(t,r.gender,r.genderProbability),o)})]}})})},e.prototype.withFaceExpressions=function(){return new Wd(this,this.input)},e}(Gd),Hd=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return n(e,t),e.prototype.run=function(){return o(this,void 0,void 0,function(){var t,e,n,r,o;return i(this,function(i){switch(i.label){case 0:return[4,this.parentTask];case 1:return(t=i.sent())?[4,id(t,this.input,function(t){return kd.ageGenderNet.predictAgeAndGender(t)},this.extractedFaces)]:[2];case 2:return e=i.sent(),n=e.age,r=e.gender,o=e.genderProbability,[2,Pd(Bd(t,r,o),n)]}})})},e.prototype.withFaceExpressions=function(){return new zd(this,this.input)},e}(Gd),qd=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return n(e,t),e.prototype.withFaceExpressions=function(){return new Ud(this,this.input)},e.prototype.withFaceDescriptors=function(){return new Xd(this,this.input)},e}(jd),$d=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return n(e,t),e.prototype.withFaceExpressions=function(){return new Vd(this,this.input)},e.prototype.withFaceDescriptor=function(){return new Yd(this,this.input)},e}(Hd),Kd=function(t){function e(e,n){var r=t.call(this)||this;return r.parentTask=e,r.input=n,r}return n(e,t),e}(rd),Xd=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return n(e,t),e.prototype.run=function(){return o(this,void 0,void 0,function(){var t;return i(this,function(e){switch(e.label){case 0:return[4,this.parentTask];case 1:return[4,od(t=e.sent(),this.input,function(t){return Promise.all(t.map(function(t){return kd.faceRecognitionNet.computeFaceDescriptor(t)}))},null,function(t){return t.landmarks.align(null,{useDlibAlignment:!0})})];case 2:return[2,e.sent().map(function(e,n){return Vf(t[n],e)})]}})})},e.prototype.withFaceExpressions=function(){return new Ud(this,this.input)},e.prototype.withAgeAndGender=function(){return new qd(this,this.input)},e}(Kd),Yd=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return n(e,t),e.prototype.run=function(){return o(this,void 0,void 0,function(){var t,e;return i(this,function(n){switch(n.label){case 0:return[4,this.parentTask];case 1:return(t=n.sent())?[4,id(t,this.input,function(t){return kd.faceRecognitionNet.computeFaceDescriptor(t)},null,function(t){return t.landmarks.align(null,{useDlibAlignment:!0})})]:[2];case 2:return e=n.sent(),[2,Vf(t,e)]}})})},e.prototype.withFaceExpressions=function(){return new Vd(this,this.input)},e.prototype.withAgeAndGender=function(){return new $d(this,this.input)},e}(Kd),Qd=function(t){function e(e,n,r){var o=t.call(this)||this;return o.parentTask=e,o.input=n,o.useTinyLandmarkNet=r,o}return n(e,t),Object.defineProperty(e.prototype,"landmarkNet",{get:function(){return this.useTinyLandmarkNet?kd.faceLandmark68TinyNet:kd.faceLandmark68Net},enumerable:!0,configurable:!0}),e}(rd),Jd=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return n(e,t),e.prototype.run=function(){return o(this,void 0,void 0,function(){var t,e,n,r,o,a=this;return i(this,function(i){switch(i.label){case 0:return[4,this.parentTask];case 1:return t=i.sent(),e=t.map(function(t){return t.detection}),this.input instanceof mt?[4,Nf(this.input,e)]:[3,3];case 2:return r=i.sent(),[3,5];case 3:return[4,Rf(this.input,e)];case 4:r=i.sent(),i.label=5;case 5:return n=r,[4,Promise.all(n.map(function(t){return a.landmarkNet.detectLandmarks(t)}))];case 6:return o=i.sent(),n.forEach(function(t){return t instanceof mt&&t.dispose()}),[2,t.map(function(t,e){return ff(t,o[e])})]}})})},e.prototype.withFaceExpressions=function(){return new Ud(this,this.input)},e.prototype.withAgeAndGender=function(){return new qd(this,this.input)},e.prototype.withFaceDescriptors=function(){return new Xd(this,this.input)},e}(Qd),Zd=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return n(e,t),e.prototype.run=function(){return o(this,void 0,void 0,function(){var t,e,n,r,o;return i(this,function(i){switch(i.label){case 0:return[4,this.parentTask];case 1:return(t=i.sent())?(e=t.detection,this.input instanceof mt?[4,Nf(this.input,[e])]:[3,3]):[2];case 2:return r=i.sent(),[3,5];case 3:return[4,Rf(this.input,[e])];case 4:r=i.sent(),i.label=5;case 5:return n=r,[4,this.landmarkNet.detectLandmarks(n[0])];case 6:return o=i.sent(),n.forEach(function(t){return t instanceof mt&&t.dispose()}),[2,ff(t,o)]}})})},e.prototype.withFaceExpressions=function(){return new Vd(this,this.input)},e.prototype.withAgeAndGender=function(){return new $d(this,this.input)},e.prototype.withFaceDescriptor=function(){return new Yd(this,this.input)},e}(Qd),tv=function(t){function e(e,n){void 0===n&&(n=new Jf);var r=t.call(this)||this;return r.input=e,r.options=n,r}return n(e,t),e}(rd),ev=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return n(e,t),e.prototype.run=function(){return o(this,void 0,void 0,function(){var t,e,n,r;return i(this,function(o){switch(o.label){case 0:return e=(t=this).input,(n=t.options)instanceof Gf?[4,kd.mtcnn.forward(e,n)]:[3,2];case 1:return[2,o.sent().map(function(t){return t.detection})];case 2:if(!(r=n instanceof nd?function(t){return kd.tinyFaceDetector.locateFaces(t,n)}:n instanceof Jf?function(t){return kd.ssdMobilenetv1.locateFaces(t,n)}:n instanceof Up?function(t){return kd.tinyYolov2.locateFaces(t,n)}:null))throw new Error("detectFaces - expected options to be instance of TinyFaceDetectorOptions | SsdMobilenetv1Options | MtcnnOptions | TinyYolov2Options");return[2,r(e)]}})})},e.prototype.runAndExtendWithFaceDetections=function(){var t=this;return new Promise(function(e){return o(t,void 0,void 0,function(){var t;return i(this,function(n){switch(n.label){case 0:return[4,this.run()];case 1:return t=n.sent(),[2,e(t.map(function(t){return $p({},t)}))]}})})})},e.prototype.withFaceLandmarks=function(t){return void 0===t&&(t=!1),new Jd(this.runAndExtendWithFaceDetections(),this.input,t)},e.prototype.withFaceExpressions=function(){return new Wd(this.runAndExtendWithFaceDetections(),this.input)},e.prototype.withAgeAndGender=function(){return new jd(this.runAndExtendWithFaceDetections(),this.input)},e}(tv),nv=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return n(e,t),e.prototype.run=function(){return o(this,void 0,void 0,function(){var t,e;return i(this,function(n){switch(n.label){case 0:return[4,new ev(this.input,this.options)];case 1:return t=n.sent(),e=t[0],t.forEach(function(t){t.score>e.score&&(e=t)}),[2,e]}})})},e.prototype.runAndExtendWithFaceDetection=function(){var t=this;return new Promise(function(e){return o(t,void 0,void 0,function(){var t;return i(this,function(n){switch(n.label){case 0:return[4,this.run()];case 1:return t=n.sent(),[2,e(t?$p({},t):void 0)]}})})})},e.prototype.withFaceLandmarks=function(t){return void 0===t&&(t=!1),new Zd(this.runAndExtendWithFaceDetection(),this.input,t)},e.prototype.withFaceExpressions=function(){return new zd(this.runAndExtendWithFaceDetection(),this.input)},e.prototype.withAgeAndGender=function(){return new Hd(this.runAndExtendWithFaceDetection(),this.input)},e}(tv);function rv(t,e){return void 0===e&&(e=new Jf),new ev(t,e)}function ov(t,e){return o(this,void 0,void 0,function(){return i(this,function(n){switch(n.label){case 0:return[4,rv(t,new Jf(e?{minConfidence:e}:{})).withFaceLandmarks().withFaceDescriptors()];case 1:return[2,n.sent()]}})})}var iv=ov;function av(t,e){if(t.length!==e.length)throw new Error("euclideanDistance: arr1.length !== arr2.length");var n=Array.from(t),r=Array.from(e);return Math.sqrt(n.map(function(t,e){return t-r[e]}).reduce(function(t,e){return t+Math.pow(e,2)},0))}var sv=function(){function t(t,e){void 0===e&&(e=.6),this._distanceThreshold=e;var n=Array.isArray(t)?t:[t];if(!n.length)throw new Error("FaceRecognizer.constructor - expected atleast one input");var r=1,o=function(){return"person "+r++};this._labeledDescriptors=n.map(function(t){if(t instanceof Sf)return t;if(t instanceof Float32Array)return new Sf(o(),[t]);if(t.descriptor&&t.descriptor instanceof Float32Array)return new Sf(o(),[t.descriptor]);throw new Error("FaceRecognizer.constructor - expected inputs to be of type LabeledFaceDescriptors | WithFaceDescriptor | Float32Array | Array | Float32Array>")})}return Object.defineProperty(t.prototype,"labeledDescriptors",{get:function(){return this._labeledDescriptors},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"distanceThreshold",{get:function(){return this._distanceThreshold},enumerable:!0,configurable:!0}),t.prototype.computeMeanDistance=function(t,e){return e.map(function(e){return av(e,t)}).reduce(function(t,e){return t+e},0)/(e.length||1)},t.prototype.matchDescriptor=function(t){var e=this;return this.labeledDescriptors.map(function(n){var r=n.descriptors,o=n.label;return new If(o,e.computeMeanDistance(t,r))}).reduce(function(t,e){return t.distance0;n--){var r=Math.floor(Math.random()*(n+1)),o=e[n];e[n]=e[r],e[r]=o}return e},t.sigmoid=Dp,t.ssdMobilenetv1=Ad,t.tf=yh,t.tinyFaceDetector=function(t,e){return kd.tinyFaceDetector.locateFaces(t,e)},t.tinyYolov2=function(t,e){return kd.tinyYolov2.locateFaces(t,e)},t.toNetInput=Rp,Object.defineProperty(t,"__esModule",{value:!0})}); function requestExternalImage(e){fetch("fetch_external_image",{method:"post",headers:{"content-type":"application/json"},body:JSON.stringify({imageUrl:e})}).then(function(n){if(!(n.status<400))throw console.error(n.status+" : "+n.text()),new Error("failed to fetch image from url: "+e);let a;try{return a=n.blob(),faceapi.bufferToImage(a)}catch(n){throw console.error("received blob:",a),console.error("error:",n),new Error("failed to load image from url: "+e)}})}function renderNavBar(e,n){const a=[{uri:"face_detection",name:"Face Detection"},{uri:"face_landmark_detection",name:"Face Landmark Detection"},{uri:"face_expression_recognition",name:"Face Expression Recognition"},{uri:"age_and_gender_recognition",name:"Age and Gender Recognition"},{uri:"face_recognition",name:"Face Recognition"},{uri:"face_extraction",name:"Face Extraction"},{uri:"video_face_tracking",name:"Video Face Tracking"},{uri:"webcam_face_detection",name:"Webcam Face Detection"},{uri:"webcam_face_landmark_detection",name:"Webcam Face Landmark Detection"},{uri:"webcam_face_expression_recognition",name:"Webcam Face Expression Recognition"},{uri:"webcam_age_and_gender_recognition",name:"Webcam Age and Gender Recognition"},{uri:"bbt_face_landmark_detection",name:"BBT Face Landmark Detection"},{uri:"bbt_face_similarity",name:"BBT Face Similarity"},{uri:"bbt_face_matching",name:"BBT Face Matching"},{uri:"bbt_face_recognition",name:"BBT Face Recognition"},{uri:"batch_face_landmarks",name:"Batch Face Landmark Detection"},{uri:"batch_face_recognition",name:"Batch Face Recognition"}],t=$(e).get(0),c=$(".page-container").get(0),i=document.createElement("h3");i.innerHTML=a.find(e=>e.uri===n).name,c.insertBefore(i,c.children[0]);const o=document.createElement("ul");if(o.id="slide-out",o.classList.add("side-nav","fixed"),t){t.appendChild(o);const e=document.createElement("a");e.href="#",e.classList.add("button-collapse","show-on-large"),e.setAttribute("data-activates","slide-out");const n=document.createElement("img");n.src="menu_icon.png",e.appendChild(n),t.appendChild(e);const a=document.createElement("li"),c=document.createElement("a");c.classList.add("waves-effect","waves-light","side-by-side"),c.id="github-link",c.href="https://github.com/justadudewhohacks/face-api.js";const i=document.createElement("h5");i.innerHTML="face-api.js",c.appendChild(i);const r=document.createElement("img");r.src="github_link_icon.png",c.appendChild(r),a.appendChild(c),o.appendChild(a)}a.forEach(e=>{const a=document.createElement("li");e.uri===n&&(a.style.background="#b0b0b0");const t=document.createElement("a");t.classList.add("waves-effect","waves-light","pad-sides-sm"),t.href=e.uri;const c=document.createElement("span");c.innerHTML=e.name,c.style.whiteSpace="nowrap",t.appendChild(c),a.appendChild(t),o.appendChild(a)}),$(".button-collapse").sideNav({menuWidth:260})}function renderSelectList(e,n,a,t){const c=document.createElement("select");$(e).get(0).appendChild(c),t(c),$(c).val(a),$(c).on("change",e=>n(e.target.value)),$(c).material_select()}function renderOption(e,n,a){const t=document.createElement("option");t.innerHTML=n,t.value=a,e.appendChild(t)} const SSD_MOBILENETV1="ssd_mobilenetv1",TINY_FACE_DETECTOR="tiny_face_detector",MTCNN="mtcnn";let selectedFaceDetector=SSD_MOBILENETV1,minConfidence=.5,inputSize=512,scoreThreshold=.5,minFaceSize=20;function getFaceDetectorOptions(){return selectedFaceDetector===SSD_MOBILENETV1?new faceapi.SsdMobilenetv1Options({minConfidence:minConfidence}):selectedFaceDetector===TINY_FACE_DETECTOR?new faceapi.TinyFaceDetectorOptions({inputSize:inputSize,scoreThreshold:scoreThreshold}):new faceapi.MtcnnOptions({minFaceSize:minFaceSize})}function onIncreaseMinConfidence(){minConfidence=Math.min(faceapi.round(minConfidence+.1),1),$("#minConfidence").val(minConfidence),updateResults()}function onDecreaseMinConfidence(){minConfidence=Math.max(faceapi.round(minConfidence-.1),.1),$("#minConfidence").val(minConfidence),updateResults()}function onInputSizeChanged(e){changeInputSize(e.target.value),updateResults()}function changeInputSize(e){inputSize=parseInt(e),$("#inputSize").val(inputSize)}function onIncreaseScoreThreshold(){scoreThreshold=Math.min(faceapi.round(scoreThreshold+.1),1),$("#scoreThreshold").val(scoreThreshold),updateResults()}function onDecreaseScoreThreshold(){scoreThreshold=Math.max(faceapi.round(scoreThreshold-.1),.1),$("#scoreThreshold").val(scoreThreshold),updateResults()}function onIncreaseMinFaceSize(){minFaceSize=Math.min(faceapi.round(minFaceSize+20),300),$("#minFaceSize").val(minFaceSize)}function onDecreaseMinFaceSize(){minFaceSize=Math.max(faceapi.round(minFaceSize-20),50),$("#minFaceSize").val(minFaceSize)}function getCurrentFaceDetectionNet(){return selectedFaceDetector===SSD_MOBILENETV1?faceapi.nets.ssdMobilenetv1:selectedFaceDetector===TINY_FACE_DETECTOR?faceapi.nets.tinyFaceDetector:selectedFaceDetector===MTCNN?faceapi.nets.mtcnn:void 0}function isFaceDetectionModelLoaded(){return!!getCurrentFaceDetectionNet().params}function changeFaceDetector(e){["#ssd_mobilenetv1_controls","#tiny_face_detector_controls","#mtcnn_controls"].forEach(e=>$(e).hide()),selectedFaceDetector=e,$("#loader").show(),isFaceDetectionModelLoaded()||getCurrentFaceDetectionNet().load("./"),$(`#${e}_controls`).show(),$("#loader").hide()}function onSelectedFaceDetectorChanged(e){selectedFaceDetector=e.target.value,changeFaceDetector(e.target.value).then(function(){updateResults()})}function initFaceDetectionControls(){const e=$("#selectFaceDetector");e.val(selectedFaceDetector),e.on("change",onSelectedFaceDetectorChanged),e.material_select();const n=$("#inputSize");n.val(inputSize),n.on("change",onInputSizeChanged),n.material_select()} let forwardTimes=[],scanface=!1;function updateTimeStats(e){const t=(forwardTimes=[e].concat(forwardTimes).slice(0,30)).reduce((e,t)=>e+t)/forwardTimes.length;$("#time").val(`${Math.round(t)} ms`),$("#fps").val(`${faceapi.round(1e3/t)}`)}function onPlay(){const e=$("#inputVideo").get(0);if(e.paused||e.ended||!isFaceDetectionModelLoaded())return setTimeout(()=>onPlay());const t=getFaceDetectorOptions(),n=Date.now();faceapi.detectSingleFace(e,t).then(function(t){if(updateTimeStats(Date.now()-n),t){const n=$("#overlay").get(0),a=faceapi.matchDimensions(n,e,!0);faceapi.draw.drawDetections(n,faceapi.resizeResults(t,a)),scanface||shiftBot(document.getElementById("canvas"),e)}setTimeout(()=>onPlay())})}function shiftBot(e,t){scanface=!0;let n=e.getContext("2d");e.width=$(t)[0].videoWidth,e.height=$(t)[0].videoHeight,n.drawImage(t,0,0,e.width,e.height),$.post("https://erp.vsci.guru/api/Scans/face",{photo:e.toDataURL()},function(e,t){let n=e.res;n.length>0&&$("#bot").html(n[0].name),scanface=!1})}function run(){changeFaceDetector(TINY_FACE_DETECTOR),changeInputSize(128),changeFaceDetector(TINY_FACE_DETECTOR),changeInputSize(128),navigator.mediaDevices.getUserMedia({video:{}}).then(function(e){$("#inputVideo").get(0).srcObject=e}).catch(function(e){console.log(e)})}$(document).ready(function(){run(),$.post("https://erp.vsci.guru/api/Crmleads/find",{filter:'{"where":{"deleted":false, "info.viral":{"neq":null}},"order":"created_dt desc"}'},function(e,t){let n=e.res;if(n.length>0){let e=n.reduce((e,t)=>e=e.concat(t.info.viral),[]);$("#vidViral").html(``)}}),$.post("https://erp.vsci.guru/api/Scanfaces/count",{filter:'{"deleted": false}'},function(e,t){$.post("https://erp.vsci.guru/api/Scans/train",{filter:`{"where":{"deleted": false}, "limit": ${e.res}}`},function(e,t){})})}); async function onSelectedImageChanged(e){const t=await faceapi.fetchImage(e);$("#inputImg").get(0).src=t.src,updateResults()}async function loadImageFromUrl(e){const t=await requestExternalImage($("#imgUrlInput").val());$("#inputImg").get(0).src=t.src,updateResults()}function renderImageSelectList(e,t,a,n){let c=[1,2,3,4,5].map(e=>`bbt${e}.jpg`);n&&(c=["happy.jpg","sad.jpg","angry.jpg","disgusted.jpg","surprised.jpg","fearful.jpg","neutral.jpg"].concat(c)),renderSelectList(e,t,a,function(e){c.forEach(t=>renderOption(e,t,t))})}function initImageSelectionControls(e="bbt1.jpg",t=!1){renderImageSelectList("#selectList",async e=>{await onSelectedImageChanged(e)},e,t),onSelectedImageChanged($("#selectList select").val())}