(window["webpackJsonp"] = window["webpackJsonp"] || []).push([["vendor"],{ /***/ "./node_modules/@tensorflow/tfjs-converter/dist/tf-converter.esm.js": /*!**************************************************************************!*\ !*** ./node_modules/@tensorflow/tfjs-converter/dist/tf-converter.esm.js ***! \**************************************************************************/ /*! exports provided: GraphModel, loadGraphModel, deregisterOp, registerOp, version_converter */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* WEBPACK VAR INJECTION */(function(Buffer) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GraphModel", function() { return GraphModel; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadGraphModel", function() { return loadGraphModel; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "deregisterOp", function() { return deregisterOp; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "registerOp", function() { return registerOp; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "version_converter", function() { return version; }); /* harmony import */ var _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @tensorflow/tfjs-core */ "./node_modules/@tensorflow/tfjs-core/dist/tf-core.esm.js"); /** * @license * Copyright 2019 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ var DataType,SaverDef,__assign=function(){return(__assign=Object.assign||function(e){for(var t,a=1,r=arguments.length;a0&&n[n.length-1])&&(6===s[0]||2===s[0])){o=0;continue}if(3===s[0]&&(!n||s[1]>n[0]&&s[1]=this.tensors.length)throw new Error("Tried to read from index "+e+", but array size is: "+this.tensors.length);var t=this.tensors[e];if(t.cleared)throw new Error("TensorArray "+this.name+": Could not read index "+e+" twice because it was cleared after a previous read (perhaps try setting clear_after_read = false?).");return this.clearAfterRead&&(t.cleared=!0),t.read=!0,t.tensor},e.prototype.readMany=function(e){var t=this;return e.map(function(e){return t.read(e)})},e.prototype.write=function(e,t){if(this.closed_)throw new Error("TensorArray "+this.name+" has already been closed.");if(e<0||!this.dynamicSize&&e>=this.maxSize)throw new Error("Tried to write to index "+e+", but array is not resizeable and size is: "+this.maxSize);var a=this.tensors[e]||{};if(t.dtype!==this.dtype)throw new Error("TensorArray "+this.name+": Could not write to TensorArray index "+e+",\n because the value dtype is "+t.dtype+", but TensorArray dtype is "+this.dtype+".");if(0!==this.size()||null!=this.elementShape&&0!==this.elementShape.length||(this.elementShape=t.shape),this.assertShapesMatchAllowUndefinedSize(this.elementShape,t.shape,"TensorArray "+this.name+": Could not write to TensorArray index "+e+"."),a&&a.read)throw new Error("TensorArray "+this.name+": Could not write to TensorArray index "+e+", because it has already been read.");if(a&&a.written)throw new Error("TensorArray "+this.name+": Could not write to TensorArray index "+e+", because it has already been written.");a.tensor=t,a.written=!0,this.tensors[e]=a},e.prototype.writeMany=function(e,t){var a=this;if(e.length!==t.length)throw new Error("TensorArray "+this.name+": could not write multiple tensors,because the index size: "+e.length+" is not the same as tensors size: "+t.length+".");e.forEach(function(e,r){return a.write(e,t[r])})},e.prototype.gather=function(e,t){if(t&&t!==this.dtype)throw new Error("TensorArray dtype is "+this.dtype+" but gather requested dtype "+t);if(!e){e=[];for(var a=0;a=this.maxSize)throw new Error("Max index must be < array size ("+a+" vs. "+this.maxSize+")");this.writeMany(e,Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["unstack"])(t,0))},e.prototype.split=function(e,t){var a=this;if(t.dtype!==this.dtype)throw new Error("TensorArray dtype is "+this.dtype+" but tensor has dtype "+t.dtype);var r=0,n=e.map(function(e){return r+=e});if(r!==t.shape[0])throw new Error("Expected sum of lengths to be equal to\n tensor.shape[0], but sum of lengths is\n "+r+", and tensor's shape is: "+t.shape);if(!this.dynamicSize&&e.length!==this.maxSize)throw new Error("TensorArray's size is not equal to the size of lengths ("+this.maxSize+" vs. "+e.length+"), and the TensorArray is not marked as dynamically resizeable");var s=0===r?0:t.size/r,o=[];Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(function(){t=t.reshape([1,r,s]);for(var p=0;p1)for(var h=1;h1))throw new Error("Cannot exit frame, the context is empty");this.contexts=this.contexts.slice(),this.contexts.splice(-1),this.currentContextIds.shift()},e.prototype.nextIteration=function(){if(!(this.contexts&&this.contexts.length>0))throw new Error("Cannot increase frame iteration, the context is empty");this.contexts=this.contexts.slice(),this.lastId++;var e=Object.assign({},this.contexts[this.contexts.length-1]);e.iterationId+=1,e.id=this.lastId,this.contexts.splice(-1,1,e),this._currentContextIds.splice(0,1,this.contextIdforContexts(this.contexts))},e.prototype.getWeight=function(e){return this.weightMap[e]},e.prototype.addTensorArray=function(e){this.tensorArrayMap[e.id]=e},e.prototype.getTensorArray=function(e){return this.tensorArrayMap[e]},e}();function getExecutionSubgraph(e,t,a){for(var r=new Set,n=[],s=null,o=null,p=new Set,u=t.slice();u.length>0;){var i=u.pop();(isControlFlow(i)||isDynamicShape(i))&&null==s&&(o=(s=i).children.map(function(e){return e.name}).filter(function(e){return r.has(e)})),r.add(i.name),null==a[i.name]&&(null==e[i.name]&&(0!==i.inputs.length?i.inputs.forEach(function(e){p.has(e.name)||(p.add(e.name),u.push(e))}):n.push(i.name)))}return{inputs:e,outputs:t,usedNodes:r,missingInputs:n,dynamicNode:s,syncInputs:o}}function getNodesInTopologicalOrder(e,t,a){var r=a.usedNodes,n=a.inputs,s=[];Object.keys(n).map(function(t){return e.nodes[t]}).forEach(function(e){r.has(e.name)&&s.push(e)}),e.weights.forEach(function(e){r.has(e.name)&&s.push(e)});for(var o=new Set,p=[];s.length>0;){var u=s.pop();o.add(u.name),t[u.name]||p.push(u),u.children.forEach(function(e){!o.has(e.name)&&r.has(e.name)&&e.inputs.every(function(e){return o.has(e.name)})&&s.push(e)})}return p}var CONTROL_FLOW_OPS=["Switch","Merge","Enter","Exit","NextIteration"],DYNAMIC_SHAPE_OPS=["NonMaxSuppressionV2","NonMaxSuppressionV3","Where"];function isControlFlow(e){return CONTROL_FLOW_OPS.indexOf(e.op)>=0}function isDynamicShape(e){return DYNAMIC_SHAPE_OPS.indexOf(e.op)>=0}var GraphExecutor=function(){function e(e){this.graph=e,this.compiledMap=new Map,this._weightMap={},this.SEPERATOR=",",this.placeholders=e.placeholders,this._outputs=e.outputs}return Object.defineProperty(e.prototype,"weightMap",{get:function(){return this._weightMap},set:function(e){var t=Object.keys(e).map(function(t){return e[t].map(function(e){return e.id})});this.weightIds=[].concat.apply([],t),this._weightMap=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"inputs",{get:function(){return this.placeholders.map(function(e){return{name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0}})},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"outputs",{get:function(){return this._outputs.map(function(e){return{name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0}})},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"inputNodes",{get:function(){return this.placeholders.map(function(e){return e.name})},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"outputNodes",{get:function(){return this.outputs.map(function(e){return e.name})},enumerable:!0,configurable:!0}),e.prototype.getCompilationKey=function(e,t){var a=e.map(function(e){return e.name}).sort(),r=t.map(function(e){return e.name}).sort();return a.join(this.SEPERATOR)+"--"+r.join(this.SEPERATOR)},e.prototype.compile=function(e,t){var a=getExecutionSubgraph(e,t,this.weightMap),r=a.missingInputs,n=a.dynamicNode,s=a.syncInputs;if(null!=n)throw new Error("This execution contains the node '"+n.name+"', which has the dynamic op '"+n.op+"'. Please use model.executeAsync() instead. Alternatively, to avoid the dynamic ops, specify the inputs ["+s+"]");if(r.length>0){var o=t.map(function(e){return e.name}),p=Object.keys(e);throw new Error("Cannot compute the outputs ["+o+"] from the provided inputs ["+p+"]. Missing the following inputs: ["+r+"]")}return getNodesInTopologicalOrder(this.graph,this.weightMap,a)},e.prototype.execute=function(e,t){var a=this,r=Object.keys(e).sort();this.checkInputs(e),this.checkInputShapeAndType(e),this.checkOutputs(t);var n=r.map(function(e){return a.graph.nodes[e]}),s=t.map(function(e){return a.graph.nodes[parseNodeName(e)[0]]}),o=this.getCompilationKey(n,s),p=this.compiledMap.get(o);null==p&&(p=this.compile(e,s),this.compiledMap.set(o,p));var u={};return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(function(){var r=new ExecutionContext(a._weightMap,u),n=__assign({},a.weightMap);Object.keys(e).forEach(function(t){n[t]=[e[t]]});for(var s=a.getFrozenTensorIds(n),o={},i=0;i0?(g=this.processStack(n,l,t,c,f,y,a,d,p),[4,Promise.all(g)]):[3,3];case 2:return V.sent(),[3,1];case 3:if(null==i&&console.warn("This model execution did not contain any nodes with control flow or dynamic output shapes. You can use model.execute() instead."),(h=s.filter(function(e){return!isControlFlow(e)&&!getTensor(e.name,c,t)}).map(function(e){return e.name})).length>0)throw N="",null!=i&&(N="Alternatively, to avoid the dynamic ops, use model.execute() and specify the inputs ["+m+"]"),new Error("Cannot compute the outputs ["+h+"] from the provided inputs ["+r+"]. Consider providing the following inputs: ["+u+"]. "+N);return[2,c]}})})},e.prototype.processStack=function(e,t,a,r,n,s,o,p,u){for(var i=this,m=[],l=function(){var l=t.pop();a.currentContext=l.contexts;var d="";if("Enter"===l.node.op&&getParamValue("isConstant",l.node,r,a)&&(d=getNodeNameAndIndex(l.node.name,a)[0]),-1===e.indexOf(l.node)){var y=executeOp$16(l.node,r,a);d||(d=getNodeNameAndIndex(l.node.name,a)[0]);var f=a.currentContext;y instanceof Promise?m.push(y.then(function(e){return r[d]=e,a.currentContext=f,i.checkTensorForDisposal(d,l.node,r,a,s,o,p),i.processChildNodes(l.node,t,a,r,n,u),e})):(r[d]=y,c.checkTensorForDisposal(d,l.node,r,a,s,o,p),c.processChildNodes(l.node,t,a,r,n,u))}else c.processChildNodes(l.node,t,a,r,n,u)},c=this;t.length>0;)l();return m},e.prototype.processChildNodes=function(e,t,a,r,n,s){e.children.forEach(function(e){var o=getNodeNameAndIndex(e.name,a)[0];!n[o]&&s.has(e.name)&&("Merge"===e.op?e.inputNames.some(function(e){return!!getTensor(e,r,a)})&&(n[o]=!0,t.push({contexts:a.currentContext,node:e})):e.inputNames.every(function(e){return!!getTensor(e,r,a)})&&(n[o]=!0,t.push({contexts:a.currentContext,node:e})))})},e.prototype.dispose=function(){var e=this;Object.keys(this.weightMap).forEach(function(t){return e.weightMap[t].forEach(function(e){return e.dispose()})})},e.prototype.checkInputShapeAndType=function(e){var t=this;Object.keys(e).forEach(function(a){var r=e[a],n=t.graph.nodes[a];if(n.attrParams.shape&&n.attrParams.shape.value){var s=n.attrParams.shape.value,o=s.length===r.shape.length&&r.shape.every(function(e,t){return-1===s[t]||s[t]===e});_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].assert(o,function(){return"The shape of dict['"+n.name+"'] provided in model.execute(dict) must be ["+s+"], but was ["+r.shape+"]"})}n.attrParams.dtype&&n.attrParams.dtype.value&&_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].assert(r.dtype===n.attrParams.dtype.value,function(){return"The dtype of dict['"+n.name+"'] provided in model.execute(dict) must be "+n.attrParams.dtype.value+", but was "+r.dtype})})},e.prototype.checkInputs=function(e){var t=this,a=Object.keys(e).filter(function(e){return!t.graph.nodes[e]});if(a.length>0)throw new Error("The dict provided in model.execute(dict) has keys: ["+a+"] that are not part of graph")},e.prototype.checkOutputs=function(e){var t=this;e.forEach(function(e){var a=parseNodeName(e)[0];if(!t.graph.nodes[a])throw new Error("The output '"+e+"' is not found in the graph")})},e}(),TFHUB_SEARCH_PARAM="?tfjs-format=file",DEFAULT_MODEL_NAME="model.json",GraphModel=function(){function e(e,t){void 0===t&&(t={}),this.modelUrl=e,this.loadOptions=t,this.version="n/a",null==t&&(this.loadOptions={})}return Object.defineProperty(e.prototype,"modelVersion",{get:function(){return this.version},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"inputNodes",{get:function(){return this.executor.inputNodes},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"outputNodes",{get:function(){return this.executor.outputNodes},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"inputs",{get:function(){return this.executor.inputs},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"outputs",{get:function(){return this.executor.outputs},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"weights",{get:function(){return this.executor.weightMap},enumerable:!0,configurable:!0}),e.prototype.findIOHandler=function(){var e=this.modelUrl;if(null!=e.load)this.handler=e;else if(null!=this.loadOptions.requestInit)this.handler=_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["io"].browserHTTPRequest(e,this.loadOptions);else{var t=_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["io"].getLoadHandlers(e,this.loadOptions.onProgress);if(0===t.length)t.push(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["io"].browserHTTPRequest(e,this.loadOptions));else if(t.length>1)throw new Error("Found more than one ("+t.length+") load handlers for URL '"+[e]+"'");this.handler=t[0]}},e.prototype.load=function(){return __awaiter(this,void 0,void 0,function(){var e,t,a;return __generator(this,function(r){switch(r.label){case 0:if(this.findIOHandler(),null==this.handler.load)throw new Error("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");return[4,this.handler.load()];case 1:return e=r.sent(),t=e.modelTopology,this.version=t.versions.producer+"."+t.versions.minConsumer,a=_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["io"].decodeWeights(e.weightData,e.weightSpecs),this.executor=new GraphExecutor(OperationMapper.Instance.transformGraph(t)),this.executor.weightMap=this.convertTensorMapToTensorsMap(a),[2,!0]}})})},e.prototype.predict=function(e,t){return this.execute(e,this.outputNodes)},e.prototype.normalizeInputs=function(e){if(!(e instanceof _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["Tensor"]||Array.isArray(e)))return e;if((e=Array.isArray(e)?e:[e]).length!==this.inputNodes.length)throw new Error("Input tensor count mismatch,the graph model has "+this.inputNodes.length+" placeholders, while there are "+e.length+" input tensors.");return this.inputNodes.reduce(function(t,a,r){return t[a]=e[r],t},{})},e.prototype.normalizeOutputs=function(e){return e=e||this.outputNodes,Array.isArray(e)?e:[e]},e.prototype.execute=function(e,t){e=this.normalizeInputs(e),t=this.normalizeOutputs(t);var a=this.executor.execute(e,t);return a.length>1?a:a[0]},e.prototype.executeAsync=function(e,t){return __awaiter(this,void 0,void 0,function(){var a;return __generator(this,function(r){switch(r.label){case 0:return e=this.normalizeInputs(e),t=this.normalizeOutputs(t),[4,this.executor.executeAsync(e,t)];case 1:return[2,(a=r.sent()).length>1?a:a[0]]}})})},e.prototype.convertTensorMapToTensorsMap=function(e){return Object.keys(e).reduce(function(t,a){return t[a]=[e[a]],t},{})},e.prototype.dispose=function(){this.executor.dispose()},e}();function loadGraphModel(e,t){return void 0===t&&(t={}),__awaiter(this,void 0,void 0,function(){var a;return __generator(this,function(r){switch(r.label){case 0:if(null==e)throw new Error("modelUrl in loadGraphModel() cannot be null. Please provide a url or an IOHandler that loads the model");return null==t&&(t={}),t.fromTFHub&&null==e.load&&(e.endsWith("/")||(e+="/"),e=""+e+DEFAULT_MODEL_NAME+TFHUB_SEARCH_PARAM),[4,(a=new GraphModel(e,t)).load()];case 1:return r.sent(),[2,a]}})})}var version="1.2.11"; //# sourceMappingURL=tf-converter.esm.js.map /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../buffer/index.js */ "./node_modules/buffer/index.js").Buffer)) /***/ }), /***/ "./node_modules/@tensorflow/tfjs-core/dist/tf-core.esm.js": /*!****************************************************************!*\ !*** ./node_modules/@tensorflow/tfjs-core/dist/tf-core.esm.js ***! \****************************************************************/ /*! exports provided: AdadeltaOptimizer, AdagradOptimizer, AdamOptimizer, AdamaxOptimizer, DataStorage, ENV, Environment, KernelBackend, MomentumOptimizer, Optimizer, RMSPropOptimizer, Rank, Reduction, SGDOptimizer, Tensor, TensorBuffer, Variable, abs, acos, acosh, add, addN, addStrict, all, any, argMax, argMin, asin, asinh, atan, atan2, atanh, avgPool, avgPool3d, backend, backend_util, basicLSTMCell, batchNorm, batchNorm2d, batchNorm3d, batchNorm4d, batchNormalization, batchNormalization2d, batchNormalization3d, batchNormalization4d, batchToSpaceND, booleanMaskAsync, browser, buffer, cast, ceil, clipByValue, clone, complex, concat, concat1d, concat2d, concat3d, concat4d, conv1d, conv2d, conv2dTranspose, conv3d, conv3dTranspose, cos, cosh, cumsum, customGrad, deprecationWarn, depthToSpace, depthwiseConv2d, diag, disableDeprecationWarnings, dispose, disposeVariables, div, divStrict, dot, dropout, elu, enableDebugMode, enableProdMode, engine, env, equal, equalStrict, erf, exp, expandDims, expm1, eye, fft, fill, findBackend, findBackendFactory, floor, floorDiv, frame, fused, gather, gatherND, getBackend, grad, grads, greater, greaterEqual, greaterEqualStrict, greaterStrict, hammingWindow, hannWindow, ifft, imag, image, inTopKAsync, io, irfft, isFinite, isInf, isNaN, keep, leakyRelu, less, lessEqual, lessEqualStrict, lessStrict, linalg, linspace, localResponseNormalization, log, log1p, logSigmoid, logSoftmax, logSumExp, logicalAnd, logicalNot, logicalOr, logicalXor, losses, matMul, math, max, maxPool, maxPool3d, maximum, maximumStrict, mean, memory, min, minimum, minimumStrict, mod, modStrict, moments, movingAverage, mul, mulStrict, multiRNNCell, multinomial, neg, nextFrame, norm, notEqual, notEqualStrict, oneHot, ones, onesLike, op, outerProduct, pad, pad1d, pad2d, pad3d, pad4d, pool, pow, powStrict, prelu, print, prod, profile, rand, randomGamma, randomNormal, randomUniform, range, ready, real, reciprocal, registerBackend, relu, relu6, removeBackend, reshape, reverse, reverse1d, reverse2d, reverse3d, reverse4d, rfft, round, rsqrt, scalar, scatterND, selu, separableConv2d, serialization, setBackend, setPlatform, setdiff1dAsync, sigmoid, sign, signal, sin, sinh, slice, slice1d, slice2d, slice3d, slice4d, softmax, softplus, spaceToBatchND, sparseToDense, spectral, split, sqrt, square, squaredDifference, squaredDifferenceStrict, squeeze, stack, step, stft, stridedSlice, sub, subStrict, sum, tan, tanh, tensor, tensor1d, tensor2d, tensor3d, tensor4d, tensor5d, tensor6d, tensor_util, test_util, tidy, tile, time, topk, train, transpose, truncatedNormal, unsortedSegmentSum, unstack, util, valueAndGrad, valueAndGrads, variable, variableGrads, version_core, webgl, where, whereAsync, zeros, zerosLike */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* WEBPACK VAR INJECTION */(function(global, process, Buffer, setImmediate) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AdadeltaOptimizer", function() { return Ap; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AdagradOptimizer", function() { return Tp; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AdamOptimizer", function() { return Dp; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AdamaxOptimizer", function() { return _p; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DataStorage", function() { return Zr; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ENV", function() { return i; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Environment", function() { return o; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "KernelBackend", function() { return to; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MomentumOptimizer", function() { return Fp; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Optimizer", function() { return Sp; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RMSPropOptimizer", function() { return Mp; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Rank", function() { return ct; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Reduction", function() { return Pc; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SGDOptimizer", function() { return Op; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Tensor", function() { return ut; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TensorBuffer", function() { return ot; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Variable", function() { return lt; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "abs", function() { return Ts; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "acos", function() { return Ds; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "acosh", function() { return _s; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "add", function() { return Du; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addN", function() { return _u; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addStrict", function() { return Ou; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "all", function() { return Yl; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "any", function() { return Ql; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "argMax", function() { return Jl; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "argMin", function() { return Zl; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "asin", function() { return Os; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "asinh", function() { return Fs; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "atan", function() { return Ms; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "atan2", function() { return Fu; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "atanh", function() { return Bs; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "avgPool", function() { return Ul; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "avgPool3d", function() { return Gl; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "backend", function() { return Je; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "backend_util", function() { return bo; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "basicLSTMCell", function() { return mc; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "batchNorm", function() { return wu; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "batchNorm2d", function() { return Cu; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "batchNorm3d", function() { return Eu; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "batchNorm4d", function() { return Ru; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "batchNormalization", function() { return bu; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "batchNormalization2d", function() { return gu; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "batchNormalization3d", function() { return yu; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "batchNormalization4d", function() { return xu; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "batchToSpaceND", function() { return nr; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "booleanMaskAsync", function() { return dl; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "browser", function() { return vp; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "buffer", function() { return tr; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "cast", function() { return rr; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ceil", function() { return Ps; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "clipByValue", function() { return Ls; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "clone", function() { return or; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "complex", function() { return gn; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "concat", function() { return Bn; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "concat1d", function() { return Pn; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "concat2d", function() { return Ln; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "concat3d", function() { return Wn; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "concat4d", function() { return Un; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "conv1d", function() { return yl; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "conv2d", function() { return xl; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "conv2dTranspose", function() { return Nl; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "conv3d", function() { return bl; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "conv3dTranspose", function() { return Sl; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "cos", function() { return Ws; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "cosh", function() { return Us; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "cumsum", function() { return ar; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "customGrad", function() { return Xr; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "deprecationWarn", function() { return Be; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "depthToSpace", function() { return ir; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "depthwiseConv2d", function() { return El; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "diag", function() { return Ac; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "disableDeprecationWarnings", function() { return Me; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dispose", function() { return ze; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "disposeVariables", function() { return Pe; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "div", function() { return Mu; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "divStrict", function() { return Bu; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dot", function() { return Tl; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dropout", function() { return Tc; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "elu", function() { return sc; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "enableDebugMode", function() { return Fe; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "enableProdMode", function() { return Oe; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "engine", function() { return Le; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "env", function() { return a; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "equal", function() { return Ju; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "equalStrict", function() { return Zu; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "erf", function() { return Vs; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "exp", function() { return zs; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "expandDims", function() { return sr; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "expm1", function() { return Gs; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "eye", function() { return ur; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fft", function() { return Cc; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fill", function() { return Dn; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findBackend", function() { return Xe; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findBackendFactory", function() { return Ye; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "floor", function() { return Hs; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "floorDiv", function() { return Pu; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "frame", function() { return Fc; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fused", function() { return lh; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "gather", function() { return pl; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "gatherND", function() { return Sc; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getBackend", function() { return Ke; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "grad", function() { return Hr; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "grads", function() { return qr; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "greater", function() { return tl; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "greaterEqual", function() { return el; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "greaterEqualStrict", function() { return nl; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "greaterStrict", function() { return rl; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hammingWindow", function() { return Oc; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hannWindow", function() { return _c; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ifft", function() { return Ec; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "imag", function() { return xn; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "image", function() { return ah; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "inTopKAsync", function() { return Lc; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "io", function() { return hp; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "irfft", function() { return Ic; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isFinite", function() { return nu; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isInf", function() { return eu; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isNaN", function() { return tu; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "keep", function() { return Ge; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "leakyRelu", function() { return uc; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "less", function() { return ol; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "lessEqual", function() { return al; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "lessEqualStrict", function() { return il; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "lessStrict", function() { return sl; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "linalg", function() { return Jc; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "linspace", function() { return _n; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "localResponseNormalization", function() { return dc; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "log", function() { return qs; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "log1p", function() { return $s; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "logSigmoid", function() { return Ks; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "logSoftmax", function() { return Jr; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "logSumExp", function() { return tc; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "logicalAnd", function() { return Iu; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "logicalNot", function() { return ku; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "logicalOr", function() { return Nu; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "logicalXor", function() { return Su; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "losses", function() { return jc; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "matMul", function() { return Al; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "math", function() { return fp; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "max", function() { return ec; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "maxPool", function() { return Wl; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "maxPool3d", function() { return zl; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "maximum", function() { return Lu; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "maximumStrict", function() { return Wu; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mean", function() { return nc; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "memory", function() { return We; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "min", function() { return rc; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "minimum", function() { return Uu; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "minimumStrict", function() { return Vu; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mod", function() { return zu; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "modStrict", function() { return Gu; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "moments", function() { return oc; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "movingAverage", function() { return yc; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mul", function() { return Hu; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mulStrict", function() { return qu; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "multiRNNCell", function() { return gc; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "multinomial", function() { return lr; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "neg", function() { return js; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "nextFrame", function() { return Wp; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "norm", function() { return vc; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "notEqual", function() { return ul; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "notEqualStrict", function() { return ll; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "oneHot", function() { return cr; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ones", function() { return An; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "onesLike", function() { return Fn; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "op", function() { return mn; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "outerProduct", function() { return Dl; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "pad", function() { return hr; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "pad1d", function() { return pr; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "pad2d", function() { return fr; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "pad3d", function() { return dr; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "pad4d", function() { return vr; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "pool", function() { return Vl; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "pow", function() { return $u; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "powStrict", function() { return Ku; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "prelu", function() { return lc; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "print", function() { return er; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "prod", function() { return ic; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "profile", function() { return Ue; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "rand", function() { return mr; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "randomGamma", function() { return yr; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "randomNormal", function() { return gr; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "randomUniform", function() { return xr; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "range", function() { return On; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ready", function() { return $e; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "real", function() { return yn; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "reciprocal", function() { return Xs; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "registerBackend", function() { return Qe; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "relu", function() { return cc; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "relu6", function() { return hc; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "removeBackend", function() { return je; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "reshape", function() { return br; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "reverse", function() { return _l; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "reverse1d", function() { return Ol; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "reverse2d", function() { return Fl; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "reverse3d", function() { return Ml; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "reverse4d", function() { return Bl; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "rfft", function() { return Rc; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "round", function() { return Ys; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "rsqrt", function() { return Qs; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "scalar", function() { return Cn; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "scatterND", function() { return wc; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "selu", function() { return pc; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "separableConv2d", function() { return kl; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "serialization", function() { return xp; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setBackend", function() { return qe; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setPlatform", function() { return Ze; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setdiff1dAsync", function() { return Nr; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sigmoid", function() { return Js; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sign", function() { return Zs; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "signal", function() { return Bc; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sin", function() { return ru; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sinh", function() { return ou; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "slice", function() { return Hl; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "slice1d", function() { return ql; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "slice2d", function() { return $l; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "slice3d", function() { return Kl; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "slice4d", function() { return jl; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "softmax", function() { return Qr; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "softplus", function() { return au; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "spaceToBatchND", function() { return wr; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sparseToDense", function() { return Nc; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "spectral", function() { return kc; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "split", function() { return Vn; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sqrt", function() { return iu; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "square", function() { return su; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "squaredDifference", function() { return ju; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "squaredDifferenceStrict", function() { return Xu; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "squeeze", function() { return Cr; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stack", function() { return Er; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "step", function() { return uu; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stft", function() { return Mc; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stridedSlice", function() { return xc; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sub", function() { return Yu; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "subStrict", function() { return Qu; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sum", function() { return ac; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "tan", function() { return lu; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "tanh", function() { return cu; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "tensor", function() { return bn; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "tensor1d", function() { return En; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "tensor2d", function() { return Rn; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "tensor3d", function() { return In; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "tensor4d", function() { return kn; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "tensor5d", function() { return Nn; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "tensor6d", function() { return Sn; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "tensor_util", function() { return Et; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "test_util", function() { return Ip; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "tidy", function() { return Ve; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "tile", function() { return Rr; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "time", function() { return He; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "topk", function() { return bc; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "train", function() { return Pp; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "transpose", function() { return fc; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "truncatedNormal", function() { return Ir; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "unsortedSegmentSum", function() { return fl; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "unstack", function() { return kr; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "util", function() { return j; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "valueAndGrad", function() { return $r; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "valueAndGrads", function() { return Kr; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "variable", function() { return vt; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "variableGrads", function() { return jr; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "version_core", function() { return kp; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "webgl", function() { return Np; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "where", function() { return Au; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "whereAsync", function() { return Tu; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "zeros", function() { return Tn; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "zerosLike", function() { return Mn; }); /** * @license * Copyright 2019 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ var t=function(e,n){return(t=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])})(e,n)};function e(e,n){function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}function n(t,e,n,r){return new(n||(n=Promise))(function(o,a){function i(t){try{u(r.next(t))}catch(t){a(t)}}function s(t){try{u(r.throw(t))}catch(t){a(t)}}function u(t){t.done?o(t.value):new n(function(e){e(t.value)}).then(i,s)}u((r=r.apply(t,e||[])).next())})}function r(t,e){var n,r,o,a,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return a={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function s(a){return function(s){return function(a){if(n)throw new TypeError("Generator is already executing.");for(;i;)try{if(n=1,r&&(o=2&a[0]?r.return:a[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,a[1])).done)return o;switch(r=0,o&&(a=[2&a[0],o.value]),a[0]){case 0:case 1:o=a;break;case 4:return i.label++,{value:a[1],done:!1};case 5:i.label++,r=a[1],a=[0];continue;case 7:a=i.ops.pop(),i.trys.pop();continue;default:if(!(o=(o=i.trys).length>0&&o[o.length-1])&&(6===a[0]||2===a[0])){i=0;continue}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]0;)r=Math.random()*e|0,n=t[--e],t[e]=t[r],t[r]=n}function u(t,e,n){return Math.max(t,Math.min(e,n))}function l(t){return t%2==0?t:t+1}function c(t){for(var e=0,n=0;n=n?o():setTimeout(i,s)}};i()})}function C(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 a=t.slice();return a[r]=e/n,a}function E(t,e){var n=e.length;return h((t=null==t?e.map(function(t,e){return e}):[].concat(t)).every(function(t){return t>=-n&&ts)&&1===t[s]&&(n.push(t[s]),r.push(s)),a[i]<=s&&i++}1!==t[s]&&(n.push(t[s]),r.push(s))}return{newShape:n,keptDims:r}}function I(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 k(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 N(t,e){for(var n=0;n=0;--r)n[r]=n[r+1]*t[r+1];return n}function U(t,e,n){if("string"===e)throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(t)&&(t=d(t)),n&&N(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 $(t,e){return void 0===e&&(e="utf-8"),e=e||"utf-8",a().platform.encode(t,e)}function K(t,e){return void 0===e&&(e="utf-8"),e=e||"utf-8",a().platform.decode(t,e)}var j=Object.freeze({shuffle:s,clamp:u,nearestLargerEven:l,sum:c,randUniform:function(t,e){var n=Math.random();return e*n+(1-n)*t},distSquared:function(t,e){for(var n=0,r=0;r0?f:"")+" "}console.log("%c"+s+"\t%c"+i+"\t%c"+u+"D "+c+"\t%c"+l+"\t%c"+h+"\t%c"+a,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")},t}(),Q=20,J=3,Z=7;function tt(t,e,n,r){var o=W(e),a=function(t,e,n,r){var o=v(e),a=r[r.length-1],i=new Array(a).fill(0),s=e.length,u="complex64"===n?rt(t):t;if(s>1)for(var l=0;lQ){var h=J*s,p=Array.from(e.slice(0,h)),f=Array.from(e.slice(u-J*s,u));return"complex64"===r&&(p=rt(p),f=rt(f)),["["+p.map(function(t,e){return et(t,a[e],r)}).join(", ")+", ..., "+f.map(function(t,e){return et(t,a[u-J+e],r)}).join(", ")+"]"]}var d="complex64"===r?rt(e):Array.from(e);return["["+d.map(function(t,e){return et(t,a[e],r)}).join(", ")+"]"]}var v=n.slice(1);var m=o.slice(1);var g=o[0]*s;var y=[];if(u>Q){for(var x=0;x=this.shape[n]){var i="Requested out of range element at "+t+". Buffer shape="+this.shape;throw new Error(i)}n++}for(var s=t[t.length-1],u=0;u0&&(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 n(this,void 0,void 0,function(){var e,n;return r(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=wt(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 a=this.scopedRun(function(){return o.startTape()},function(){return o.endTape()},function(){return o.tidy("forward",t)});h(a instanceof ut,function(){return"The result y returned by f() must be a tensor."});var i=function(t,e,n){for(var r={},o={},a=0;a=0;a--)for(i=(d=t[a]).inputs,c=0;c0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y.");return this.tidy("backward",function(){var t,r,s={};s[a.id]=null==n?(t=a.shape,r=z(v(t),"float32"),ut.make(t,{values:r})):n,function(t,e,n){for(var r=function(r){var o=e[r],a=[];if(o.outputs.forEach(function(e){var n=t[e.id];if(null!=n)a.push(n);else{var r=ut.make(e.shape,{values:G(e.size,e.dtype)},e.dtype);a.push(r)}}),null==o.gradient)throw new Error("Cannot compute gradient: gradient function not found for "+o.name+".");var i=o.gradient(1===o.outputs.length?a[0]:a),s=function(e){if(!(e in i))throw new Error("Cannot backprop through input "+e+". Available gradients found: "+Object.keys(i)+".");var r=n(function(){return i[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 a=o.inputs[e];if(!m(r.shape,a.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 '"+a.shape+"'");if(null==t[a.id])t[a.id]=r;else{var s=t[a.id];t[a.id]=s.add(r),s.dispose()}};for(var u in o.inputs)s(u)},o=e.length-1;o>=0;o--)r(o)}(s,i,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:a,grads:u}})},t.prototype.customGrad=function(t){var e=this;return h(P(t),function(){return"The f passed in customGrad(f) must be a function."}),function(){for(var n,r=[],o=0;on||e>n){r="["+t+"x"+e+"]";throw 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 ae(t,e,n,r,o,a,i,s){var u=t.getAttribLocation(n,r);return-1!==u&&(Ut(t,e,function(){return t.bindBuffer(t.ARRAY_BUFFER,o)}),Ut(t,e,function(){return t.vertexAttribPointer(u,a,t.FLOAT,!1,i,s)}),Ut(t,e,function(){return t.enableVertexAttribArray(u)}),!0)}function ie(t,e,n,r){ve(t,r),Ut(t,e,function(){return t.activeTexture(t.TEXTURE0+r)}),Ut(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 le(t,e,n,r,o,a){Ut(t,e,function(){return ie(t,e,r,a)}),Ut(t,e,function(){return t.uniform1i(o,a)})}function ce(t,e,n,r){Ut(t,e,function(){return t.bindFramebuffer(t.FRAMEBUFFER,r)}),Ut(t,e,function(){return t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,n,0)})}function he(t,e,n){Ut(t,e,function(){return t.bindFramebuffer(t.FRAMEBUFFER,n)}),Ut(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=Ut(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),v(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=a().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(e&&(r*=2,1===(t=t.map(function(e,n){return n>=t.length-2?l(t[n]):t[n]})).length&&(t=[2,t[0]])),2!==t.length){var o=R(t);t=o.newShape}var i=v(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 s=me(t),u=2,c=2;return t.length&&(u=(n=ge(t))[0],c=n[1]),x(i=s*(u/2)*(c/2)).map(function(t){return 2*t})}return x(i)}function be(t){return t%2==0}function we(t,e){if(m(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==jt){var e=Ft(t);jt=e.getParameter(e.MAX_TEXTURE_SIZE)}return jt}function Ee(t){if(null==Xt){var e=Ft(t);Xt=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,Xt)}function Re(t){if(0===t)return 0;var e=Ft(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 ke(t){try{if(null!=Ft(t))return!0}catch(t){return!1}return!1}function Ne(t){if(0===t)return!1;var e=Ft(t);if(1===t){if(!Ie(e,"OES_texture_float"))return!1}else if(!Ie(e,"EXT_color_buffer_float"))return!1;return Ae(e)}function Se(t){if(0===t)return!1;var e=Ft(t);if(1!==t){if(Ie(e,"EXT_color_buffer_float"))return Ae(e);if(Ie(e,"EXT_color_buffer_half_float")){var n=e.getExtension("EXT_color_buffer_half_float");return function(t,e){var n=Wt(t,e),r=t.createTexture();t.bindTexture(t.TEXTURE_2D,r);t.texImage2D(t.TEXTURE_2D,0,n.internalFormatHalfFloat,1,1,0,n.textureFormatFloat,n.textureTypeHalfFloat,null);var o=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,o),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,r,0);var a=t.checkFramebufferStatus(t.FRAMEBUFFER)===t.FRAMEBUFFER_COMPLETE;return t.bindTexture(t.TEXTURE_2D,null),t.bindFramebuffer(t.FRAMEBUFFER,null),t.deleteTexture(r),t.deleteFramebuffer(o),a}(e,n)}return!1}return!!Ie(e,"OES_texture_float")&&(!!Ie(e,"WEBGL_color_buffer_float")&&Ae(e))}function Ae(t){var e=Wt(t),n=t.createTexture();t.bindTexture(t.TEXTURE_2D,n);t.texImage2D(t.TEXTURE_2D,0,e.internalFormatFloat,1,1,0,e.textureFormatFloat,e.textureTypeFloat,null);var r=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,r),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,n,0);var o=t.checkFramebufferStatus(t.FRAMEBUFFER)===t.FRAMEBUFFER_COMPLETE;return t.bindTexture(t.TEXTURE_2D,null),t.bindFramebuffer(t.FRAMEBUFFER,null),t.deleteTexture(n),t.deleteFramebuffer(r),o}function Te(t){return 2===t&&null!=Ft(t).fenceSync}var De=Object.freeze({callAndCheck:Ut,canBeRepresented:Gt,getWebGLErrorMessage:Ht,getExtensionOrThrow:qt,createVertexShader:$t,createFragmentShader:Kt,createProgram:Qt,linkProgram:Jt,validateProgram:Zt,createStaticVertexBuffer:te,createStaticIndexBuffer:ee,getNumChannels:function(){return 2===a().getNumber("WEBGL_VERSION")?1:4},createTexture:ne,validateTextureSize:re,createFramebuffer:oe,bindVertexBufferToProgramAttribute:ae,bindTextureUnit:ie,unbindTextureUnit:function(t,e,n){ve(t,n),Ut(t,e,function(){return t.activeTexture(t.TEXTURE0+n)}),Ut(t,e,function(){return t.bindTexture(t.TEXTURE_2D,null)})},getProgramUniformLocationOrThrow:se,getProgramUniformLocation:ue,bindTextureToProgramUniformSampler:le,bindCanvasToFramebuffer:function(t,e){Ut(t,e,function(){return t.bindFramebuffer(t.FRAMEBUFFER,null)}),Ut(t,e,function(){return t.viewport(0,0,t.canvas.width,t.canvas.height)}),Ut(t,e,function(){return t.scissor(0,0,t.canvas.width,t.canvas.height)})},bindColorTextureToFramebuffer:ce,unbindColorTextureFromFramebuffer:he,validateFramebuffer:pe,getFramebufferErrorMessage:fe,getBatchDim:me,getRowsCols:ge,getShapeAs3D:ye,getTextureShapeFromLogicalShape:xe,isReshapeFree:we,getWebGLMaxTextureSize:Ce,resetMaxTextureSize:function(){jt=null},resetMaxTexturesInShader:function(){Xt=null},getMaxTexturesInShader:Ee,getWebGLDisjointQueryTimerVersion:Re,hasExtension:Ie,isWebGLVersionEnabled:ke,isCapableOfRenderingToFloatTexture:Ne,isDownloadFloatTextureEnabled:Se,isWebGLFenceEnabled:Te}),_e=a();function Oe(){a().set("PROD",!0)}function Fe(){a().set("DEBUG",!0)}function Me(){a().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function Be(t){a().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(t+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}function Pe(){kt.disposeVariables()}function Le(){return kt}function We(){return kt.memory()}function Ue(t){return kt.profile(t)}function Ve(t,e){return kt.tidy(t,e)}function ze(t){wt(t).forEach(function(t){return t.dispose()})}function Ge(t){return kt.keep(t)}function He(t){return kt.time(t)}function qe(t){return kt.setBackend(t)}function $e(){return kt.ready()}function Ke(){return kt.backendName}function je(t){kt.removeBackend(t)}function Xe(t){return kt.findBackend(t)}function Ye(t){return kt.findBackendFactory(t)}function Qe(t,e,n){return void 0===n&&(n=1),kt.registerBackend(t,e,n)}function Je(){return kt.backend}function Ze(t,e){a().setPlatform(t,e)}function tn(){for(var t=[],e=0;e0,function(){return"Element arr["+r.join("][")+"] should be a primitive, but is an array of "+e.length+" elements"});h(e.length===n[0],function(){return"Element arr["+r.join("][")+"] should have "+n[0]+" elements, but has "+e.length+" elements"});var o=n.slice(1);for(var a=0;a=0&&(o=r),nn(r,o,e,n),null==t||!T(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 s=en(t,o);T(t)||Array.isArray(t)||(t=[t]);var u="string"!==o?U(t,o,a().getBool("DEBUG")):d(t,[],!0);return ut.make(s,{values:u},o)}function on(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 rn(t,e+"["+r+"]",n)},r)}function an(t,e){for(var n=0;n=0&&e0}),_e.registerFlag("WEBGL_VERSION",function(){return ke(2)?2:ke(1)?1:0}),_e.registerFlag("WEBGL_BUFFER_SUPPORTED",function(){return 2===_e.get("WEBGL_VERSION")}),_e.registerFlag("WEBGL_CPU_FORWARD",function(){return!0}),_e.registerFlag("WEBGL_FORCE_F16_TEXTURES",function(){return!1}),_e.registerFlag("WEBGL_PACK",function(){return _e.getBool("HAS_WEBGL")}),_e.registerFlag("WEBGL_PACK_NORMALIZATION",function(){return _e.getBool("WEBGL_PACK")}),_e.registerFlag("WEBGL_PACK_CLIP",function(){return _e.getBool("WEBGL_PACK")}),_e.registerFlag("WEBGL_PACK_DEPTHWISECONV",function(){return!1}),_e.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",function(){return _e.getBool("WEBGL_PACK")}),_e.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",function(){return _e.getBool("WEBGL_PACK")}),_e.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",function(){return _e.getBool("WEBGL_PACK")}),_e.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",function(){return _e.getBool("WEBGL_PACK")}),_e.registerFlag("WEBGL_PACK_REDUCE",function(){return _e.getBool("WEBGL_PACK")}),_e.registerFlag("WEBGL_LAZILY_UNPACK",function(){return _e.getBool("WEBGL_PACK")}),_e.registerFlag("WEBGL_CONV_IM2COL",function(){return _e.getBool("WEBGL_PACK")}),_e.registerFlag("WEBGL_MAX_TEXTURE_SIZE",function(){return Ce(_e.getNumber("WEBGL_VERSION"))}),_e.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",function(){return Ee(_e.getNumber("WEBGL_VERSION"))}),_e.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",function(){var t=_e.getNumber("WEBGL_VERSION");return 0===t?0:Re(t)}),_e.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",function(){return _e.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}),_e.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",function(){return Ne(_e.getNumber("WEBGL_VERSION"))}),_e.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",function(){return!_e.getBool("WEBGL_FORCE_F16_TEXTURES")&&_e.getBool("WEBGL_RENDER_FLOAT32_CAPABLE")}),_e.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",function(){return Se(_e.getNumber("WEBGL_VERSION"))}),_e.registerFlag("WEBGL_FENCE_API_ENABLED",function(){return Te(_e.getNumber("WEBGL_VERSION"))}),_e.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",function(){return _e.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0}),st=Be;var gn=mn({complex_:function(t,e){var n=rn(t,"real","complex"),r=rn(e,"imag","complex");return p(n.shape,r.shape,"real and imag shapes, "+n.shape+" and "+r.shape+", must match in call to tf.complex()."),kt.runKernel(function(t){return t.complex(n,r)},{$real:n,$imag:r})}}),yn=mn({real_:function(t){var e=rn(t,"input","real");return kt.runKernel(function(t){return t.real(e)},{$input:e})}}),xn=mn({imag_:function(t){var e=rn(t,"input","imag");return kt.runKernel(function(t){return t.imag(e)},{$input:e})}});function bn(t,e,n){return wn(t,e,en(t,n),n)}function wn(t,e,n,r){if(null==r&&(r=B(t)),"complex64"===r)throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!T(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){q(e);var o=v(e),i=v(n);h(o===i,function(){return"Based on the provided shape, ["+e+"], the tensor should have "+o+" values but has "+i});for(var s=0;s1)return Tn([0],r);var o=G(Math.abs(Math.ceil((e-t)/n)),r);e=1,function(){return"Pass at least one tensor to concat"});var n=on(t,"tensors","concat");"complex64"===n[0].dtype&&n.forEach(function(t){if("complex64"!==t.dtype)throw new Error("Cannot concatenate complex64 tensors with a tensor\n with dtype "+t.dtype+". ")}),e=E(e,n[0].shape)[0];var r=vn(n.map(function(t){return t.shape}),e);if(0===v(r))return bn([],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});dn(o,e);var a=n;return kt.runKernel(function(t){return t.concat(n,e)},a,function(t){var n=o.map(function(t){return t[e]});return Vn(t,n,e).map(function(t){return function(){return t}})})}}),Pn=mn({concat1d_:function(t){return Bn(t,0)}}),Ln=mn({concat2d_:function(t,e){return Bn(t,e)}}),Wn=mn({concat3d_:function(t,e){return Bn(t,e)}}),Un=mn({concat4d_:function(t,e){return Bn(t,e)}}),Vn=mn({split_:function(t,e,n){void 0===n&&(n=0);var r,o=rn(t,"x","split");return n=E(n,o.shape)[0],"number"==typeof e?(h(o.shape[n]%e==0,function(){return"Number of splits must evenly divide the axis."}),r=new Array(e).fill(o.shape[n]/e)):(h(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),kt.runKernel(function(t){return t.split(o,r,n)},{$x:o},function(t){return{$x:function(){return Bn(t,n)}}})}});"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;function zn(t,e){return t(e={exports:{}},e.exports),e.exports}var Gn=zn(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 a(t,e){var n=new r(t),a=e&&e.state,i=n.next;return i.int32=function(){return 4294967296*n.next()|0},i.double=function(){return i()+1.1102230246251565e-16*(2097152*i()|0)},i.quick=i,a&&("object"==typeof a&&o(a,n),i.state=function(){return o(n,{})}),i}e&&e.exports?e.exports=a:n&&n.amd?n(function(){return a}):this.alea=a}(0,t,!1)}),Hn=zn(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 i.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},i.int32=n.next,i.quick=i,a&&("object"==typeof a&&o(a,n),i.state=function(){return o(n,{})}),i}e&&e.exports?e.exports=a:n&&n.amd?n(function(){return a}):this.xor128=a}(0,t,!1)}),qn=zn(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 a(t,e){var n=new r(t),a=e&&e.state,i=function(){return(n.next()>>>0)/4294967296};return i.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},i.int32=n.next,i.quick=i,a&&("object"==typeof a&&o(a,n),i.state=function(){return o(n,{})}),i}e&&e.exports?e.exports=a:n&&n.amd?n(function(){return a}):this.xorwow=a}(0,t,!1)}),$n=zn(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 a(t,e){null==t&&(t=+new Date);var n=new r(t),a=e&&e.state,i=function(){return(n.next()>>>0)/4294967296};return i.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},i.int32=n.next,i.quick=i,a&&(a.x&&o(a,n),i.state=function(){return o(n,{})}),i}e&&e.exports?e.exports=a:n&&n.amd?n(function(){return a}):this.xorshift7=a}(0,t,!1)}),Kn=zn(function(t){!function(t,e,n){function r(t){var e=this;e.next=function(){var t,n,r=e.w,o=e.X,a=e.i;return e.w=r=r+1640531527|0,n=o[a+34&127],t=o[a=a+1&127],n^=n<<13,t^=t<<17,n^=n>>>15,t^=t>>>12,n=o[a]=n^t,e.i=a,n+(r^r>>>16)|0},function(t,e){var n,r,o,a,i,s=[],u=128;for(e===(0|e)?(r=e,e=null):(e+="\0",r=0,u=Math.max(u,e.length)),o=0,a=-32;a>>15,r^=r<<4,r^=r>>>13,a>=0&&(i=i+1640531527|0,o=0==(n=s[127&a]^=r+i)?o+1:0);for(o>=128&&(s[127&(e&&e.length||0)]=-1),o=127,a=512;a>0;--a)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=i,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 a(t,e){null==t&&(t=+new Date);var n=new r(t),a=e&&e.state,i=function(){return(n.next()>>>0)/4294967296};return i.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},i.int32=n.next,i.quick=i,a&&(a.X&&o(a,n),i.state=function(){return o(n,{})}),i}e&&e.exports?e.exports=a:n&&n.amd?n(function(){return a}):this.xor4096=a}(0,t,!1)}),jn=zn(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 i.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},i.int32=n.next,i.quick=i,a&&("object"==typeof a&&o(a,n),i.state=function(){return o(n,{})}),i}e&&e.exports?e.exports=a:n&&n.amd?n(function(){return a}):this.tychei=a}(0,t,!1)}),Xn=zn(function(t){!function(e,n){var r,o=this,a=256,i=6,s="random",u=n.pow(a,i),l=n.pow(2,52),c=2*l,h=a-1;function p(t,h,p){var g=[],y=v(function t(e,n){var r,o=[],a=typeof e;if(n&&"object"==a)for(r in e)try{o.push(t(e[r],n-1))}catch(t){}return o.length?o:"string"==a?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(a):(t=new Uint8Array(a),(o.crypto||o.msCrypto).getRandomValues(t)),m(t)}catch(t){var n=o.navigator,i=n&&n.plugins;return[+new Date,o,i,o.screen,m(e)]}}():t,3),g),x=new f(g),b=function(){for(var t=x.g(i),e=u,n=0;t=c;)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,i=r.i=r.j=0,s=r.S=[];for(n||(t=[n++]);o=1||0===i);var s=Math.sqrt(-2*Math.log(i)/i);e=this.mean+this.stdDev*o*s,n=this.mean+this.stdDev*a*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}(),Jn=function(){function t(t,e,n,r){this.alpha=t,this.beta=1/e,this.dtype=n;var o=r||Math.random();this.randu=Yn(o.toString()),this.randn=new Qn(0,1,n,!1,this.randu()),this.d=t<1?t+2/3:t-1/3,this.c=1/Math.sqrt(9*this.d)}return t.prototype.nextValue=function(){for(var t,e,n,r,o,a;;){do{r=this.randn.nextValue(),a=1+this.c*r}while(a<=0);if(a*=a*a,e=1-.331*(t=r*r)*t,n=.5*t+this.d*(1-a+Math.log(a)),(o=this.randu())=1+e.length,function(){return"input rank is "+r.rank+" but should be > than blockShape.length "+e.length}),h(n.length===e.length,function(){return"crops.length is "+n.length+" but should be equal to blockShape.length "+e.length}),h(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}),kt.runKernel(function(t){return t.batchToSpaceND(r,e,n)},{$x:r},function(t){return{$x:function(){return t.spaceToBatchND(e,n)}}})}}),rr=mn({cast_:function(t,e){var n=rn(t,"x","cast");if(!S(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 kt.runKernel(function(t){return t.cast(n,e)},{$x:n},function(t){return{$x:function(){return t.clone()}}})}}),or=mn({clone_:function(t){var e=rn(t,"x","clone",null);return kt.runKernel(function(t){return ut.make(e.shape,{dataId:e.dataId},e.dtype)},{$x:e},function(t){return{$x:function(){return t.toFloat()}}})}}),ar=mn({cumsum_:function(t,e,n,r){void 0===e&&(e=0),void 0===n&&(n=!1),void 0===r&&(r=!1);var o=rn(t,"x","cumsum"),a=hn([e|=0],o.rank),i=o;null!=a&&(i=o.transpose(a));var s=fn(1,o.rank)[0],u=kt.runKernel(function(t){return t.cumsum(i,s,n,r)},{permutedX:i},function(t){return{permutedX:function(){return t.cumsum(e,n,!r)}}});return null!=a&&(u=u.transpose(a)),u}}),ir=mn({depthToSpace_:function(t,e,n){void 0===n&&(n="NHWC");var r=rn(t,"x","depthToSpace"),o="NHWC"===n?r.shape[1]:r.shape[2],a="NHWC"===n?r.shape[2]:r.shape[3],i="NHWC"===n?r.shape[3]:r.shape[1];return h(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}),h(a*e>=0,function(){return"Negative dimension size caused by overflow when multiplying\n "+a+" and "+e+" for depthToSpace with input shape\n "+r.shape}),h(i%(e*e)==0,function(){return"Dimension size must be evenly divisible by "+e*e+" but is "+i+" for depthToSpace with input shape "+r.shape}),kt.runKernel(function(t){return t.depthToSpace(r,e,n)},{$x:r})}}),sr=mn({expandDims_:function(t,e){void 0===e&&(e=0);var n=rn(t,"x","expandDims",null);h(e<=n.rank,function(){return"Axis must be <= rank of the tensor"});var r=n.shape.slice();return e<0&&(h(-(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),br(n,r)}}),ur=mn({eye_:function(t,e,n,r){void 0===r&&(r="float32"),null==e&&(e=t);for(var o=tr([t,e],r),a=t<=e?t:e,i=0;i2)throw new Error("Rank of probabilities must be 1 or 2, but is "+i);n=n||Math.random();var s=1===i?o.as2D(1,-1):o,u=kt.runKernel(function(t){return t.multinomial(s,r,e,n)},{logits2D:s});return 1===i?u.as1D():u}}),cr=mn({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=rn(t,"indices","oneHot","int32"),a=o.shape.concat([e]);return o=o.flatten(),kt.runKernel(function(t){return t.oneHot(o,e,n,r)},{$indices:o},function(t){return{$indices:function(){return Tn(o.shape,"float32")}}}).reshape(a)}}),hr=mn({pad_:function(t,e,n){void 0===n&&(n=0);var r=rn(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 kt.runKernel(function(t){return t.pad(r,e,n)},{$x:r},function(t){return{$x:function(){return t.slice(o,r.shape)}}})}}),pr=mn({pad1d_:function(t,e,n){return void 0===n&&(n=0),h(2===e.length,function(){return"Invalid number of paddings. Must be length of 2."}),hr(t,[e],n)}}),fr=mn({pad2d_:function(t,e,n){return void 0===n&&(n=0),h(2===e.length&&2===e[0].length&&2===e[1].length,function(){return"Invalid number of paddings. Must be length of 2 each."}),hr(t,e,n)}}),dr=mn({pad3d_:function(t,e,n){return void 0===n&&(n=0),h(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."}),hr(t,e,n)}}),vr=mn({pad4d_:function(t,e,n){return void 0===n&&(n=0),h(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."}),hr(t,e,n)}}),mr=mn({rand_:function(t,e,n){var r=v(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 a=0;a=1+e.length,function(){return"input rank "+r.rank+" should be > than [blockShape] "+e.length}),h(n.length===e.length,function(){return"paddings.shape[0] "+n.length+" must be equal to [blockShape] "+e.length}),h(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()}),kt.runKernel(function(t){return t.spaceToBatchND(r,e,n)},{$x:r},function(t){return{$x:function(){return t.batchToSpaceND(e,n)}}})}}),Cr=mn({squeeze_:function(t,e){var n=rn(t,"x","squeeze");return br(n,R(n.shape,e).newShape)}}),Er=mn({stack_:function(t,e){void 0===e&&(e=0);var n=on(t,"tensors","stack");if(h(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,a=n[0].dtype;h(e<=r,function(){return"Axis must be <= rank of the tensor"}),n.forEach(function(t){p(o,t.shape,"All tensors passed to stack must have matching shapes")}),n.forEach(function(t){h(a===t.dtype,function(){return"All tensors passed to stack must have matching dtypes"})});var i=n.map(function(t){return t.expandDims(e)});return Bn(i,e)}}),Rr=mn({tile_:function(t,e){var n=rn(t,"x","tile",null);return h(n.rank===e.length,function(){return"Error in transpose: rank of input "+n.rank+" must match length of reps "+e+"."}),kt.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=Mn(r);if(1===r.rank)for(var o=0;o=-n.shape.length&&e=2*e+1||o%2==1?i.push(o):a.push(o);r.push.apply(r,a),r.push(0),r.push.apply(r,i)}return r}function Tr(t,e,n,r){void 0===r&&(r=!0);var o=[];r?o.push(t[0]/n):o.push(t[0]*n);for(var a=1;at.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,a=0;a1?e.shape[e.rank-1]:1,o=e.rank>1?e.rank-1:1,a="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.rank1?e.shape[e.rank-1]:1,o=n.length,a=1,i=r;i0;)1&t&&e.push(n),t/=2,n++;return e}function Wr(t,e,n){for(var r=[],o=0;o0?Number.MIN_SAFE_INTEGER:Number.MAX_SAFE_INTEGER);var s=r[o];return a<0&&(a+=s),a=u(0,a,s-1)}function Vr(t,e,n,r,o){var a=e[o],i=n[o]||1;(t&1<0?Number.MAX_SAFE_INTEGER:Number.MIN_SAFE_INTEGER);var s=r[o];return a<0&&(a+=s),a=i>0?u(0,a,s):u(-1,a,s-1)}function zr(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 Gr(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 "+a+" variables is trainable."});var i=kt.gradients(t,e,null,!0),s=i.value,u=i.grads;h(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()."}),h(0===s.rank,function(){return"The f passed in variableGrads(f) must return a scalar, but it returned a rank-"+s.rank+" tensor"});var l={};return e.forEach(function(t,e){null!=u[e]&&(l[t.name]=u[e])}),null!=o&&o.forEach(function(t){return l[t.name]=null}),{value:s,grads:l}}function Xr(t){return kt.customGrad(t)}function Yr(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 Qr=mn({softmax_:function(t,e){void 0===e&&(e=-1);var n=rn(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 Xr(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)}}),Jr=mn({logSoftmax_:function(t,e){void 0===e&&(e=-1);var n=rn(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 Xr(function(t,n){var r=t.max(e,!0),o=t.sub(r),a=o.toFloat().sub(o.exp().sum(e,!0).log());return n([a]),{value:a,gradFunc:function(t,n){var r=n[0].exp();return t.sub(t.sum(e,!0).mul(r))}}})(n)}}),Zr=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}(),to=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){t.a,t.b,t.transposeA,t.transposeB,t.bias,t.activation,t.preluActivationWeights;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){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.relu6=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.fusedConv2d=function(t){t.input,t.filter,t.convInfo,t.bias,t.activation,t.preluActivationWeights;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.fusedDepthwiseConv2D=function(t){t.input,t.filter,t.convInfo,t.bias,t.activation,t.preluActivationWeights;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.avgPool3d=function(t,e){throw new Error("Not yet implemented")},t.prototype.avgPool3dBackprop=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.maxPool3d=function(t,e){throw new Error("Not yet implemented")},t.prototype.maxPool3dBackprop=function(t,e,n,r){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,a){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,a,i){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,a){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.diag=function(t){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 eo(t,e){for(var n=t.length,r=[],o=0;o1&&1===i&&r.unshift(a)}return r}function no(t,e){for(var n=[],r=0;r1)&&n.unshift(a)}return n}function ro(t,e){for(var n=[],r=Math.max(t.length,e.length),o=0;oo}).sort(function(t,e){return e.score-t.score}),i=[],s=0;s=0;--p){if(ko(t,c,i[p])>=r){h=!0;break}}if(!h&&(i.push(c),i.length>=n))break}return En(i,"int32")}function ko(t,e,n){var r=t.subarray(4*e,4*e+4),o=t.subarray(4*n,4*n+4),a=Math.min(r[0],r[2]),i=Math.min(r[1],r[3]),s=Math.max(r[0],r[2]),u=Math.max(r[1],r[3]),l=Math.min(o[0],o[2]),c=Math.min(o[1],o[3]),h=Math.max(o[0],o[2]),p=Math.max(o[1],o[3]),f=(s-a)*(u-i),d=(h-l)*(p-c);if(f<=0||d<=0)return 0;var v=Math.max(a,l),m=Math.max(i,c),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 No(t,e,n){var r=new Array(t.rank).fill(0),o=t.shape.slice();return e.map(function(e){o[n]=e;var a=t.slice(r,o);return r[n]+=e,a})}function So(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 Fo(t,e){return["x","y","z","w","u","v"].slice(0,e).map(function(e){return t+"."+e})}function Mo(t,e){return 1===e?[t]:Fo(t,e)}function Bo(){var t,e,n,r,o,i,s,u,l,c;return 2===a().getNumber("WEBGL_VERSION")?(t="#version 300 es",e="in",n="out",r="in",o="texture",i="outputColor",s="out vec4 outputColor;",u="\n bool isnan_custom(float val) {\n return (val > 0.0 || val < 0.0) ? false : val != 0.0;\n }\n\n bvec4 isnan_custom(vec4 val) {\n return bvec4(isnan_custom(val.x),\n isnan_custom(val.y), isnan_custom(val.z), isnan_custom(val.w));\n }\n\n #define isnan(value) isnan_custom(value)\n ",l="",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",s="",u="\n #define isnan(value) isnan_custom(value)\n bool isnan_custom(float val) {\n return (val > 0. || val < 1. || val == 0.) ? false : true;\n }\n bvec4 isnan_custom(vec4 val) {\n return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w));\n }\n ",l="\n uniform float INFINITY;\n\n bool isinf(float val) {\n return abs(val) == INFINITY;\n }\n bvec4 isinf(vec4 val) {\n return equal(abs(val), vec4(INFINITY));\n }\n ",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:s,defineSpecialNaN:u,defineSpecialInf:l,defineRound:c}}function Po(t,e,n){void 0===n&&(n="index");var r=W(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 Lo(t){var e=W(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 Wo="\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 Uo(t,e,n,r){var o=[];t.forEach(function(t){var e=v(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 a,i,s=o.join("\n"),u=t.map(function(t){return function(t,e,n){void 0===n&&(n=!1);var r="";r+=n?zo(t):Vo(t);var o=t.shapeInfo.logicalShape,a=e.logicalShape;o.length<=a.length&&(r+=n?function(t,e){var n,r=t.name,o=r.charAt(0).toUpperCase()+r.slice(1),a="get"+o+"AtOutCoords",i=t.shapeInfo.logicalShape.length,s=e.logicalShape.length,u=eo(t.shapeInfo.logicalShape,e.logicalShape),l=Xo(s),c=s-i,h=["x","y","z","w","u","v"];n=0===i?"":s<2&&u.length>=1?"coords = 0;":u.map(function(t){return"coords."+h[t+c]+" = 0;"}).join("\n");var p="";p=s<2&&i>0?"coords":t.shapeInfo.logicalShape.map(function(t,e){return"coords."+h[e+c]}).join(", ");var f="return outputValue;",d=1===v(t.shapeInfo.logicalShape),m=1===v(e.logicalShape);if(1!==i||d||m){if(d&&!m)f=1===s?"\n return vec4(outputValue.x, outputValue.x, 0., 0.);\n ":"\n return vec4(outputValue.x);\n ";else if(u.length){var g=i-2,y=i-1;u.indexOf(g)>-1&&u.indexOf(y)>-1?f="return vec4(outputValue.x);":u.indexOf(g)>-1?f="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":u.indexOf(y)>-1&&(f="return vec4(outputValue.xx, outputValue.zz);")}}else f="\n return vec4(outputValue.xy, outputValue.xy);\n ";return"\n vec4 "+a+"() {\n "+l+" 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",a=e.texShape,i=t.shapeInfo.texShape,s=t.shapeInfo.logicalShape.length,u=e.logicalShape.length;if(!t.shapeInfo.isUniform&&s===u&&null==t.shapeInfo.flatOffset&&m(i,a))return"\n float "+o+"() {\n return sampleTexture("+n+", resultUV);\n }\n ";var l,c=Xo(u),h=eo(t.shapeInfo.logicalShape,e.logicalShape),p=u-s,f=["x","y","z","w","u","v"];l=0===s?"":u<2&&h.length>=1?"coords = 0;":h.map(function(t){return"coords."+f[t+p]+" = 0;"}).join("\n");var d="";d=u<2&&s>0?"coords":t.shapeInfo.logicalShape.map(function(t,e){return"coords."+f[e+p]}).join(", ");return"\n float "+o+"() {\n "+c+" coords = getOutputCoords();\n "+l+"\n return get"+r+"("+d+");\n }\n "}(t,e));return r}(t,e,r)}).join("\n"),l=e.texShape,c=Bo(),h=function(t){return"\n float sampleTexture(sampler2D textureSampler, vec2 uv) {\n return "+t.texture2D+"(textureSampler, uv).r;\n }\n "}(c),p=function(t){return t.version+"\n precision highp float;\n precision highp int;\n precision highp sampler2D;\n "+t.varyingFs+" vec2 resultUV;\n "+t.defineOutput+"\n const vec2 halfCR = vec2(0.5, 0.5);\n\n struct ivec5\n {\n int x;\n int y;\n int z;\n int w;\n int u;\n };\n\n struct ivec6\n {\n int x;\n int y;\n int z;\n int w;\n int u;\n int v;\n };\n\n uniform float NAN;\n "+t.defineSpecialNaN+"\n "+t.defineSpecialInf+"\n "+t.defineRound+"\n\n int imod(int x, int y) {\n return x - y * (x / y);\n }\n\n int idiv(int a, int b, float sign) {\n int res = a / b;\n int mod = imod(a, b);\n if (sign < 0. && mod != 0) {\n res -= 1;\n }\n return res;\n }\n\n //Based on the work of Dave Hoskins\n //https://www.shadertoy.com/view/4djSRW\n #define HASHSCALE1 443.8975\n float random(float seed){\n vec2 p = resultUV * seed;\n vec3 p3 = fract(vec3(p.xyx) * HASHSCALE1);\n p3 += dot(p3, p3.yzx + 19.19);\n return fract((p3.x + p3.y) * p3.z);\n }\n\n "+Go+"\n "+Ho+"\n "+qo+"\n "}(c);return e.isPacked?(a=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)];if(1===n[0])return"\n int getOutputCoords() {\n return 2 * int(resultUV.x * "+n[1]+".0);\n }\n ";if(1===n[1])return"\n int getOutputCoords() {\n return 2 * int(resultUV.y * "+n[0]+".0);\n }\n ";return"\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(m(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=Math.ceil(n[2]/2),i=a*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 / "+i+";\n index -= b * "+i+";\n\n int r = 2 * (index / "+a+");\n int c = imod(index, "+a+") * 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),a=o,i="",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],a=Math.ceil(o/e);this.outputShape=t.slice(0,-1),a>1&&this.outputShape.push(a),r||this.variableNames.push("bestIndicesA");var i,s,u=this.outputShape,l=u.length,c=Xo(l),p=Mo("coords",l);if(1===a){var f=Xo(s=l+1);i="\n "+f+" sourceLocR = "+f+"("+p.join()+", 0);\n ++"+p[l-1]+";\n "+f+" sourceLocG = "+f+"("+p.join()+", 0);\n ++"+p[l-2]+";\n "+f+" sourceLocA = "+f+"("+p.join()+", 0);\n --"+p[l-1]+";\n "+f+" sourceLocB = "+f+"("+p.join()+", 0);\n --"+p[l-2]+";"}else s=l,i="\n "+c+" sourceLocR = coords;\n ++"+p[l-1]+";\n "+c+" sourceLocG = coords;\n ++"+p[l-2]+";\n "+c+" sourceLocA = coords;\n --"+p[l-1]+";\n "+c+" sourceLocB = coords;\n --"+p[l-2]+";";var d=["x","y","z","w","u","v"].slice(0,s),v="."+d[s-1],m=d.map(function(t){return"int "+t}),g=Mo("sourceLocR",s-1).concat("inIdx.r"),y=Mo("sourceLocG",s-1).concat("inIdx.g"),x=Mo("sourceLocB",s-1).concat("inIdx.b"),b=Mo("sourceLocA",s-1).concat("inIdx.a"),w="max"===n?"greaterThan":"lessThan",C=r?"":"\n inIdx = round(vec4(getBestIndicesAChannel("+g.join()+"),\n getBestIndicesAChannel("+y.join()+"),\n getBestIndicesAChannel("+x.join()+"),\n getBestIndicesAChannel("+b.join()+")));",E="vec4(\n getAChannel("+g.join()+"),\n hasNextCol ? getAChannel("+y.join()+") : 0.,\n hasNextRow ? getAChannel("+x.join()+") : 0.,\n hasNextRow && hasNextCol ? getAChannel("+b.join()+") : 0.)",R=r?"":"\n float getBestIndicesAChannel("+m.join()+") {\n return getChannel(getBestIndicesA("+d.join()+"),\n vec2("+d.slice(-2).join()+"));\n }";this.userCode="\n float getAChannel("+m.join()+") {\n return getChannel(getA("+d.join()+"),\n vec2("+d.slice(-2).join()+"));\n }\n "+R+"\n void main() {\n "+c+" coords = getOutputCoords();\n bool hasNextCol = "+p[l-1]+" < "+(u[l-1]-1)+";\n bool hasNextRow = "+p[l-2]+" < "+(u[l-2]-1)+";\n "+i+"\n ivec4 srcIdx = ivec4(sourceLocR"+v+", sourceLocG"+v+",\n sourceLocB"+v+", sourceLocA"+v+") * "+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 "}}(),Zo=function(){return function(t){this.variableNames=["dy"],this.outputShape=t.inShape;var e=t.filterHeight,n=t.filterWidth,r=t.strideHeight,o=t.strideWidth,a=t.dilationHeight,i=t.dilationWidth,s=t.effectiveFilterHeight,u=t.effectiveFilterWidth,l=s-1-t.padInfo.top,c=u-1-t.padInfo.left,h=1/(e*n);this.userCode="\n const ivec2 pads = ivec2("+l+", "+c+");\n const float avgMultiplier = float("+h+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n\n ivec2 dyRCCorner = coords.yz - pads;\n int dyRCorner = dyRCCorner.x;\n int dyCCorner = dyRCCorner.y;\n\n // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+s+";\n wR += "+a+") {\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+= "+i+") {\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 "}}(),ta=function(){return function(t){this.variableNames=["dy"],this.outputShape=t.inShape;var e=t.filterDepth,n=t.filterHeight,r=t.filterWidth,o=t.strideDepth,a=t.strideHeight,i=t.strideWidth,s=t.dilationDepth,u=t.dilationHeight,l=t.dilationWidth,c=t.effectiveFilterDepth,h=t.effectiveFilterHeight,p=t.effectiveFilterWidth,f=c-1-t.padInfo.front,d=h-1-t.padInfo.top,v=p-1-t.padInfo.left,m=1/(e*n*r);this.userCode="\n const ivec3 pads = ivec3("+f+", "+d+", "+v+");\n const float avgMultiplier = float("+m+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n int dyDCorner = dyCorner.x;\n int dyRCorner = dyCorner.y;\n int dyCCorner = dyCorner.z;\n\n // Convolve dy(?, ?, ?, d) with pos mask(:, :, :, ch) to get\n // dx(xD, xR, xC, ch).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n\n for (int wD = 0; wD < "+c+";\n wD += "+s+") {\n float dyD = float(dyDCorner + wD) / "+o+".0;\n\n if (dyD < 0.0 || dyD >= "+t.outDepth+".0 || fract(dyD) > 0.0) {\n continue;\n }\n int idyD = int(dyD);\n\n for (int wR = 0; wR < "+h+";\n wR += "+u+") {\n float dyR = float(dyRCorner + wR) / "+a+".0;\n\n if (dyR < 0.0 || dyR >= "+t.outHeight+".0 ||\n fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < "+p+";\n wC += "+l+") {\n float dyC = float(dyCCorner + wC) / "+i+".0;\n\n if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(batch, idyD, idyR, idyC, ch);\n\n dotProd += dyValue * avgMultiplier;\n }\n }\n }\n setOutput(dotProd);\n }\n "}}(),ea=function(){return function(t,e,n,r,o,a){this.outputShape=[],this.variableNames=["x","mean","variance"],ro(t,e),ro(t,n);var i="0.0";null!=r&&(ro(t,r),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");var s="1.0";null!=o&&(ro(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 = "+i+";\n float scale = "+s+";\n float inv = scale * inversesqrt(variance + float("+a+"));\n setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));\n }\n "}}(),na=function(){return function(t,e,n,r,o,a){this.usesPackedTextures=!0,this.variableNames=["x","mean","variance"],ro(t,e),ro(t,n);var i="vec4(0.0)";null!=r&&(ro(t,r),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");var s="vec4(1.0)";null!=o&&(ro(t,o),this.variableNames.push("scale"),s="getScaleAtOutCoords()"),this.outputShape=t,this.userCode="\n void main() {\n vec4 offset = "+i+";\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("+a+"));\n\n setOutput((x - mean) * inv + offset);\n }\n "}}(),ra="return areal * breal - aimag * bimag;",oa="return areal * bimag + aimag * breal;",aa=function(){return function(t,e,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=ro(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 "}}(),ia="return a + b;",sa="return a - b;",ua="return a * b;",la="return (a < 0.) ? b * a : a;",ca=function(){return function(t,e,n){this.variableNames=["A","B"],this.outputShape=ro(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 "}}(),ha="\n vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));\n return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\n",pa=function(){return function(t,e,n,r){void 0===r&&(r=!1),this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.usesPackedTextures=!0,this.outputShape=ro(e,n);var o=this.outputShape.length,a="";if(r)if(0===o||1===v(this.outputShape))a="\n result.y = 0.;\n result.z = 0.;\n result.w = 0.;\n ";else if(a="\n "+Xo(o)+" coords = getOutputCoords();\n ",1===o)a+="\n result.y = (coords + 1) >= "+this.outputShape[0]+" ? 0. : result.y;\n result.z = 0.;\n result.w = 0.;\n ";else{var i=Mo("coords",o);a+="\n bool nextRowOutOfBounds =\n ("+i[o-2]+" + 1) >= "+this.outputShape[o-2]+";\n bool nextColOutOfBounds =\n ("+i[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 "+a+"\n\n setOutput(result);\n }\n "}}(),fa=function(){function t(t){this.variableNames=["A"],this.outputShape=t,this.userCode="\n uniform float minVal;\n uniform float maxVal;\n\n void main() {\n float value = getAAtOutCoords();\n if (isnan(value)) {\n setOutput(value);\n return;\n }\n\n setOutput(clamp(value, minVal, maxVal));\n }\n "}return t.prototype.getCustomSetupFunc=function(t,e){var n=this;return function(r,o){null==n.minLoc&&(n.minLoc=r.getUniformLocationNoThrow(o,"minVal"),n.maxLoc=r.getUniformLocationNoThrow(o,"maxVal")),r.gl.uniform1f(n.minLoc,t),r.gl.uniform1f(n.maxLoc,e)}},t}(),da=function(){function t(t){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=t,this.userCode="\n uniform float minVal;\n uniform float maxVal;\n\n void main() {\n vec4 value = getAAtOutCoords();\n\n if (any(isnan(value))) {\n setOutput(value);\n return;\n }\n\n setOutput(clamp(value, vec4(minVal), vec4(maxVal)));\n }\n "}return t.prototype.getCustomSetupFunc=function(t,e){var n=this;return function(r,o){null==n.minLoc&&(n.minLoc=r.getUniformLocationNoThrow(o,"minVal"),n.maxLoc=r.getUniformLocationNoThrow(o,"maxVal")),r.gl.uniform1f(n.minLoc,t),r.gl.uniform1f(n.maxLoc,e)}},t}(),va=function(){return 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 "}}(),ma=function(){return function(t){this.outputShape=[],this.outputShape=vn(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= "+s[u-1]+") {\n return getChannel(\n getT"+u+"("+ya(i,l,f)+"),\n vec2("+ya(c,l,f)+"));\n }"}var d=s.length,v=s[s.length-1];p+="\n return getChannel(\n getT"+d+"("+ya(i,l,v)+"),\n vec2("+ya(c,l,v)+"));",this.userCode="\n float getValue("+i.map(function(t){return"int "+t})+") {\n "+p+"\n }\n\n void main() {\n "+o+" coords = getOutputCoords();\n vec4 result = vec4(getValue("+a+"), 0., 0., 0.);\n\n "+a[r-1]+" = "+a[r-1]+" + 1;\n if ("+a[r-1]+" < "+n[r-1]+") {\n result.g = getValue("+a+");\n }\n\n "+a[r-2]+" = "+a[r-2]+" + 1;\n if ("+a[r-2]+" < "+n[r-2]+") {\n result.a = getValue("+a+");\n }\n\n "+a[r-1]+" = "+a[r-1]+" - 1;\n if ("+a[r-2]+" < "+n[r-2]+" &&\n "+a[r-1]+" < "+n[r-1]+") {\n result.b = getValue("+a+");\n }\n setOutput(result);\n }\n "}}();function ya(t,e,n){var r=t.indexOf(e);return t.map(function(t,e){return e===r?t+" - "+n:t}).join()}var xa=function(){return 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,a="channelsLast"===t.dataFormat;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int wR = coords.x;\n int wC = coords.y;\n int d1 = coords.z;\n int d2 = coords.w;\n\n // Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n\n for (int b = 0; b < "+t.batchSize+"; b++) {\n for (int yR = 0; yR < "+t.outHeight+"; yR++) {\n int xR = wR + yR * "+e+" - "+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 if ("+a+") {\n float dyValue = getDy(b, yR, yC, d2);\n float xValue = getX(b, xR, xC, d1);\n dotProd += (xValue * dyValue);\n } else {\n float dyValue = getDy(b, d2, yR, yC);\n float xValue = getX(b, d1, xR, xC);\n dotProd += (xValue * dyValue);\n }\n\n }\n }\n }\n setOutput(dotProd);\n }\n "}}(),ba=function(){return function(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterHeight,n=t.filterWidth,r=t.strideHeight,o=t.strideWidth,a="channelsLast"===t.dataFormat,i=e-1-t.padInfo.top,s=n-1-t.padInfo.left,u=a?1:2,l=a?2:3,c=a?3:1;this.userCode="\n const ivec2 pads = ivec2("+i+", "+s+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords["+c+"];\n\n ivec2 dyCorner = ivec2(coords["+u+"], coords["+l+"]) - 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\n if ("+a+") {\n float xValue = getDy(batch, idyR, idyC, d2);\n float wValue = getW(wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n } else {\n float xValue = getDy(batch, d2, idyR, idyC);\n float wValue = getW(wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n }\n\n }\n }\n }\n setOutput(dotProd);\n }\n "}}(),wa=function(){return function(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;var e=t.strideDepth,n=t.strideHeight,r=t.strideWidth,o=t.padInfo.front,a=t.padInfo.top,i=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+" - "+a+";\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+" - "+i+";\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 "}}(),Ca=function(){return function(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterDepth,n=t.filterHeight,r=t.filterWidth,o=t.strideDepth,a=t.strideHeight,i=t.strideWidth,s=e-1-t.padInfo.front,u=n-1-t.padInfo.top,l=r-1-t.padInfo.left;this.userCode="\n const ivec3 pads = ivec3("+s+", "+u+", "+l+");\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) / "+a+".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) / "+i+".0;\n\n if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n 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 "}}(),Ea=function(){return 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,a=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 * "+a+" + dm;\n\n float dotProd = 0.0;\n\n // TO DO: Vec4 over the batch size\n for (int b = 0; b < "+t.batchSize+"; b++) {\n for (int yR = 0; yR < "+t.outHeight+"; yR++) {\n int xR = wR + yR * "+e+" - "+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 "}}(),Ra=function(){return function(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterHeight,n=t.filterWidth,r=t.strideHeight,o=t.strideWidth,a=e-1-t.padInfo.top,i=n-1-t.padInfo.left,s=t.outChannels/t.inChannels;this.userCode="\n const ivec2 pads = ivec2("+a+", "+i+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords[3];\n ivec2 dyCorner = coords.yz - pads;\n int dyRCorner = dyCorner.x;\n int dyCCorner = dyCorner.y;\n\n float dotProd = 0.0;\n\n for (int wR = 0; wR < "+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 // TO DO: 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 "}}(),Ia=function(){return function(t,e,n,r){void 0===e&&(e=!1),void 0===n&&(n=null),void 0===r&&(r=!1),this.variableNames=["x","W"],this.outputShape=t.outShape;var o=t.padInfo.top,a=t.padInfo.left,i=t.strideHeight,s=t.strideWidth,u=t.dilationHeight,l=t.dilationWidth,c=t.filterHeight,h=t.filterWidth,p=4*Math.floor(t.inChannels/4),f=t.inChannels%4,d="channelsLast"===t.dataFormat,v=d?1:2,m=d?2:3,g=d?3:1,y="",x="";n&&(y=r?"float activation(float a) {\n float b = getPreluActivationWeightsAtOutCoords();\n "+n+"\n }":"\n float activation(float x) {\n "+n+"\n }\n ",x="result = activation(result);");var b=e?"result += getBiasAtOutCoords();":"";e&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),this.userCode="\n "+y+"\n\n const ivec2 strides = ivec2("+i+", "+s+");\n const ivec2 pads = ivec2("+o+", "+a+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d2 = coords["+g+"];\n\n ivec2 xRCCorner =\n ivec2(coords["+v+"], coords["+m+"]) * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+c+"; wR++) {\n int xR = xRCorner + wR * "+u+";\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+h+"; wC++) {\n int xC = xCCorner + wC * "+l+";\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n for (int d1 = 0; d1 < "+p+"; d1 += 4) {\n vec4 wValues = vec4(\n getW(wR, wC, d1, d2),\n getW(wR, wC, d1 + 1, d2),\n getW(wR, wC, d1 + 2, d2),\n getW(wR, wC, d1 + 3, d2)\n );\n\n if ("+d+") {\n vec4 xValues = vec4(\n getX(batch, xR, xC, d1),\n getX(batch, xR, xC, d1 + 1),\n getX(batch, xR, xC, d1 + 2),\n getX(batch, xR, xC, d1 + 3)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec4 xValues = vec4(\n getX(batch, d1, xR, xC),\n getX(batch, d1 + 1, xR, xC),\n getX(batch, d1 + 2, xR, xC),\n getX(batch, d1 + 3, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n }\n\n if ("+(1===f)+") {\n\n if ("+d+") {\n dotProd +=\n getX(batch, xR, xC, "+p+") *\n getW(wR, wC, "+p+", d2);\n } else {\n dotProd +=\n getX(batch, "+p+", xR, xC) *\n getW(wR, wC, "+p+", d2);\n }\n\n } else if ("+(2===f)+") {\n vec2 wValues = vec2(\n getW(wR, wC, "+p+", d2),\n getW(wR, wC, "+p+" + 1, d2)\n );\n\n if ("+d+") {\n vec2 xValues = vec2(\n getX(batch, xR, xC, "+p+"),\n getX(batch, xR, xC, "+p+" + 1)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec2 xValues = vec2(\n getX(batch, "+p+", xR, xC),\n getX(batch, "+p+" + 1, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n\n } else if ("+(3===f)+") {\n vec3 wValues = vec3(\n getW(wR, wC, "+p+", d2),\n getW(wR, wC, "+p+" + 1, d2),\n getW(wR, wC, "+p+" + 2, d2)\n );\n\n if ("+d+") {\n vec3 xValues = vec3(\n getX(batch, xR, xC, "+p+"),\n getX(batch, xR, xC, "+p+" + 1),\n getX(batch, xR, xC, "+p+" + 2)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec3 xValues = vec3(\n getX(batch, "+p+", xR, xC),\n getX(batch, "+p+" + 1, xR, xC),\n getX(batch, "+p+" + 2, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n\n }\n }\n }\n\n float result = dotProd;\n "+b+"\n "+x+"\n setOutput(result);\n }\n "}}(),ka=function(){return 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,a=t.strideHeight,i=t.strideWidth,s=t.dilationDepth,u=t.dilationHeight,l=t.dilationWidth,c=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+", "+a+", "+i+");\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 < "+c+"; 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 * "+l+";\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 "}}(),Na=function(){return function(t,e,n,r){void 0===e&&(e=!1),void 0===n&&(n=null),void 0===r&&(r=!1),this.variableNames=["x","W"],this.outputShape=t.outShape;var o=t.inHeight,a=t.inWidth,i=t.padInfo.top,s=t.padInfo.left,u=t.strideHeight,l=t.strideWidth,c=t.dilationHeight,h=t.dilationWidth,p=t.filterHeight,f=t.filterWidth,d=t.outChannels/t.inChannels,v="",m="";n&&(v=r?"float activation(float a) {\n float b = getPreluActivationWeightsAtOutCoords();\n "+n+"\n }":"\n float activation(float x) {\n "+n+"\n }\n ",m="result = activation(result);");var g=e?"result += getBiasAtOutCoords();":"";e&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),this.userCode="\n "+v+"\n\n const ivec2 strides = ivec2("+u+", "+l+");\n const ivec2 pads = ivec2("+i+", "+s+");\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 / "+d+";\n int q = d2 - d1 * "+d+";\n\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n // TO DO(dsmilkov): Flatten the two for loops and vec4 the operations.\n for (int wR = 0; wR < "+p+"; wR++) {\n int xR = xRCorner + wR * "+c+";\n\n if (xR < 0 || xR >= "+o+") {\n continue;\n }\n\n for (int wC = 0; wC < "+f+"; wC++) {\n int xC = xCCorner + wC * "+h+";\n\n if (xC < 0 || xC >= "+a+") {\n continue;\n }\n\n float xVal = getX(batch, xR, xC, d1);\n float wVal = getW(wR, wC, d1, q);\n dotProd += xVal * wVal;\n }\n }\n\n float result = dotProd;\n "+g+"\n "+m+"\n setOutput(result);\n }\n "}}(),Sa=function(){return function(t,e,n,r){void 0===e&&(e=!1),void 0===n&&(n=null),void 0===r&&(r=!1),this.variableNames=["x","W"],this.usesPackedTextures=!0,this.outputShape=t.outShape;for(var o=t.inHeight,a=t.inWidth,i=t.padInfo.top,s=t.padInfo.left,u=t.strideHeight,c=t.strideWidth,h=t.dilationHeight,p=t.dilationWidth,f=t.filterHeight,d=t.filterWidth,v=d,m="int xR; int xC; int xCOffset;",g=0;g= 0 && xR < "+o+" && xCOffset >= 0 && xCOffset < "+a+") {\n xTexelR"+g+"C"+y+" = getX(batch, xR, xCOffset, d1);\n } else {\n xTexelR"+g+"C"+y+" = vec4(0.);\n }\n\n xCOffset = xC + 1 - 2;\n if(xR >= 0 && xR < "+o+" && xCOffset >= 0 && xCOffset < "+a+") {\n vec4 previous = getX(batch, xR, xCOffset, d1);\n xR"+g+"C"+y+" = vec4(previous.zw, xTexelR"+g+"C"+y+".xy);\n } else {\n xR"+g+"C"+y+" = vec4(0, 0, xTexelR"+g+"C"+y+".xy);\n }\n ":"\n if(xR >= 0 && xR < "+o+" && xC >= 0 && xC < "+a+") {\n xTexelR"+g+"C"+y+" = getX(batch, xR, xC, d1);\n } else {\n xTexelR"+g+"C"+y+" = vec4(0.);\n }\n\n xR"+g+"C"+y+" = xTexelR"+g+"C"+y+";\n ",y+1= 0 && xR < "+o+" &&\n xCOffset >= 0 && xCOffset < "+a+") {\n xTexelR"+g+"C"+(y+2)+" = getX(batch, xR, xCOffset, d1);\n }\n ",p>1&&(m+="\n xCOffset -= 2;\n if(xR >= 0 && xR < "+o+" &&\n xCOffset >= 0 && xCOffset < "+a+") {\n xTexelR"+g+"C"+y+" = getX(batch, xR, xCOffset, d1);\n } else {\n xTexelR"+g+"C"+y+" = vec4(0.);\n }\n "),m+="\n xR"+g+"C"+(y+1)+" = vec4(\n xTexelR"+g+"C"+y+".zw, xTexelR"+g+"C"+(y+2)+".xy);\n "):m+="\n xCOffset = xC + "+b+";\n\n if(xR >= 0 && xR < "+o+" &&\n xCOffset >= 0 && xCOffset < "+a+") {\n xTexelR"+g+"C"+(y+2)+" = getX(batch, xR, xCOffset, d1);\n }\n\n xR"+g+"C"+(y+1)+" = xTexelR"+g+"C"+(y+2)+";\n "}}else y= 0 && xR < "+o+") {\n ",s%2==1?(m+="\n xCOffset = xC + 1 - "+c+";\n if(xCOffset >= 0 && xCOffset < "+a+") {\n xTexelR"+g+"C"+y+" = getX(batch, xR, xCOffset, d1);\n } else {\n xTexelR"+g+"C"+y+" = vec4(0.);\n }\n\n if(xC + 1 >= 0 && xC + 1 < "+a+") {\n xTexelR"+g+"C"+(y+2)+" = getX(batch, xR, xC + 1, d1);\n } else {\n xTexelR"+g+"C"+(y+2)+" = vec4(0.);\n }\n\n xR"+g+"C"+y+" = vec4(\n xTexelR"+g+"C"+y+".zw, xTexelR"+g+"C"+(y+2)+".zw);\n ",y+1= 0 && xCOffset < "+a+") {\n final = getX(batch, xR, xCOffset, d1);\n }\n xR"+g+"C"+(y+1)+" = vec4(xTexelR"+g+"C"+(y+2)+".xy, final.xy);\n ")):(m+="\n if(xC >= 0 && xC < "+a+") {\n xTexelR"+g+"C"+y+" = getX(batch, xR, xC, d1);\n } else {\n xTexelR"+g+"C"+y+" = vec4(0.);\n }\n\n xCOffset = xC + "+c+";\n if(xCOffset >= 0 && xCOffset < "+a+") {\n xTexelR"+g+"C"+(y+2)+" = getX(batch, xR, xCOffset, d1);\n } else {\n xTexelR"+g+"C"+(y+2)+" = vec4(0.);\n }\n\n xR"+g+"C"+y+" = vec4(\n xTexelR"+g+"C"+y+".xy, xTexelR"+g+"C"+(y+2)+".xy);\n ",y+11?[""+(i-1)/(c-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 >= "+a+") {\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 "}}(),Ta=function(){return function(t,e,n){this.variableNames=["x"],this.outputShape=t;var r=t.length,o=t[t.length-1],a=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 = "+Da(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 "+a+" end) {\n continue;\n }\n if (idx == end && "+e+") {\n continue;\n }\n "+Da(r,"coords")+" = idx;\n val += getX("+function(t,e){if(1===t)return""+e;if(2===t)return e+".x, "+e+".y";if(3===t)return e+".x, "+e+".y, "+e+".z";if(4===t)return e+".x, "+e+".y, "+e+".z, "+e+".w";throw Error("Cumulative sum for rank "+t+" is not yet supported")}(r,"coords")+");\n }\n setOutput(val);\n }\n "}}();function Da(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 _a=function(){return function(t,e){this.variableNames=["A"];var n=Bo();this.outputShape=t,this.userCode="\n ivec3 outCoordsFromFlatIndex(int index) {\n "+Po(["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 "}}(),Oa=function(){return function(t,e){this.variableNames=["A"],this.usesPackedTextures=!0;var n=Bo();this.outputShape=t,this.userCode="\n ivec3 outCoordsFromFlatIndex(int index) {\n "+Po(["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 "}}(),Fa=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}(),Ma=function(){return function(t){this.variableNames=["X"],this.outputShape=[t,t],this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n float val = coords[0] == coords[1] ? getX(coords[0]) : 0.0;\n setOutput(val);\n }\n "}}(),Ba=function(){return function(t){this.variableNames=["A"];var e=Bo();this.outputShape=t,this.userCode="\n "+Wo+"\n\n void main() {\n float x = getAAtOutCoords();\n "+e.output+" = encode_float(x);\n }\n "}}(),Pa=function(){return function(t){this.variableNames=["A"],this.usesPackedTextures=!0;var e=Bo();this.outputShape=t,this.userCode="\n "+Wo+"\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 "}}(),La=function(){return function(t,e,n){void 0===n&&(n=!1),this.variableNames=["A"];var r=Bo(),o=e[0],a=e[1];this.outputShape=t;var i="result";n&&(i="floor(result * 255. + 0.5)"),this.userCode="\n "+Lo(t)+"\n\n void main() {\n ivec3 coords = getOutputCoords();\n\n int flatIndex = getFlatIndex(coords);\n int offset = imod(flatIndex, 4);\n\n flatIndex = idiv(flatIndex, 4, 1.);\n \n int r = flatIndex / "+a+";\n int c = imod(flatIndex, "+a+");\n vec2 uv = (vec2(c, r) + halfCR) / vec2("+a+".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("+i+", 0., 0., 0.);\n }\n "}}(),Wa=function(){return function(t,e,n){void 0===n&&(n=!1),this.variableNames=["A"];var r=Bo(),o=e[0],a=e[1];this.outputShape=t;var i="",s="result";n&&(s="floor(result * 255. + 0.5)");for(var u=0;u<=1;u++)for(var l=0;l<=1;l++){var c=2*u+l;i+="\n localCoords = coords;\n if(localCoords[2] + "+l+" < "+t[2]+") {\n localCoords[2] += "+l+";\n if(localCoords[1] + "+u+" < "+t[1]+") {\n localCoords[1] += "+u+";\n\n flatIndex = getFlatIndex(localCoords);\n offset = imod(flatIndex, 4);\n \n flatIndex = idiv(flatIndex, 4, 1.);\n\n r = flatIndex / "+a+";\n c = imod(flatIndex, "+a+");\n uv = (vec2(c, r) + halfCR) / vec2("+a+".0, "+o+".0);\n values = "+r.texture2D+"(A, uv);\n\n if(offset == 0) {\n result["+c+"] = values[0];\n } else if(offset == 1) {\n result["+c+"] = values[1];\n } else if(offset == 2) {\n result["+c+"] = values[2];\n } else {\n result["+c+"] = values[3];\n }\n }\n }\n "}this.userCode="\n "+Lo(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 "+i+"\n\n "+r.output+" = "+s+";\n }\n "}}(),Ua="return real * expR - imag * expI;",Va="return real * expI + imag * expR;",za=function(){return 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,a=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) / "+a+";\n }\n\n return result;\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n setOutput(mulMatDFT(coords[0], coords[1]));\n }\n "}}(),Ga=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}(),Ha=function(){return function(t){this.variableNames=["A"];var e=Bo(),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 "}}(),qa=function(){return function(t){this.variableNames=["A"];var e=Bo(),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 "}}(),$a=function(){return 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),a=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=[],a=0;a1?"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 * "+a+";\n }\n setOutput(getX(flattenIndex, coords[1]));\n }\n "}}();function ja(t,e){var n=Bo();return $t(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 Xa(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 Ya(t,e){return ee(t,e,new Uint16Array([0,1,2,2,1,3]))}function Qa(t,e,n,r,o,a,i){re(n,r);var s=ne(t,e),u=t.TEXTURE_2D;return Ut(t,e,function(){return t.bindTexture(u,s)}),Ut(t,e,function(){return t.texParameteri(u,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE)}),Ut(t,e,function(){return t.texParameteri(u,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE)}),Ut(t,e,function(){return t.texParameteri(u,t.TEXTURE_MIN_FILTER,t.NEAREST)}),Ut(t,e,function(){return t.texParameteri(u,t.TEXTURE_MAG_FILTER,t.NEAREST)}),Ut(t,e,function(){return t.texImage2D(u,0,o,n,r,0,a,i,null)}),Ut(t,e,function(){return t.bindTexture(t.TEXTURE_2D,null)}),s}function Ja(t,e,n,r,o){var a=Bt(n,r);return Qa(t,e,a[0],a[1],o.internalFormatFloat,o.textureFormatFloat,t.FLOAT)}function Za(t,e,n,r,o){var a=Bt(n,r);return Qa(t,e,a[0],a[1],o.internalFormatHalfFloat,o.textureFormatFloat,o.textureTypeHalfFloat)}function ti(t,e,n,r,o){var a=Bt(n,r);return Qa(t,e,a[0],a[1],t.RGBA,t.RGBA,t.UNSIGNED_BYTE)}function ei(t,e,n,r,o){var a=Lt(n,r);return Qa(t,e,a[0],a[1],o.internalFormatPackedFloat,t.RGBA,t.FLOAT)}function ni(t,e,n,r,o){var a=Lt(n,r);return Qa(t,e,a[0],a[1],o.internalFormatPackedHalfFloat,t.RGBA,o.textureTypeHalfFloat)}function ri(t,e,n,r){return Ut(t,e,function(){return t.bindBuffer(t.ARRAY_BUFFER,r)}),ae(t,e,n,"clipSpacePos",r,3,20,0)&&ae(t,e,n,"uv",r,2,20,12)}function oi(t,e,n,r,o,a,i){var s,u,l;Ut(t,e,function(){return t.bindTexture(t.TEXTURE_2D,n)}),a instanceof Uint8Array?(s=new Uint8Array(r*o*4),u=t.UNSIGNED_BYTE,l=t.RGBA):(s=new Float32Array(r*o*4),u=t.FLOAT,l=i.internalFormatPackedFloat),s.set(a),Ut(t,e,function(){return t.texImage2D(t.TEXTURE_2D,0,l,r,o,0,t.RGBA,u,s)}),Ut(t,e,function(){return t.bindTexture(t.TEXTURE_2D,null)})}function ai(t,e,n,r){Ut(t,e,function(){return t.bindTexture(t.TEXTURE_2D,n)}),r.data instanceof Uint8Array?Ut(t,e,function(){return t.texImage2D(t.TEXTURE_2D,0,t.RGBA,r.width,r.height,0,t.RGBA,t.UNSIGNED_BYTE,r.data)}):Ut(t,e,function(){return t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,r)}),Ut(t,e,function(){return t.bindTexture(t.TEXTURE_2D,null)})}function ii(t,e,n,r,o){var a=t.createBuffer();Ut(t,e,function(){return t.bindBuffer(t.PIXEL_PACK_BUFFER,a)});var i=16*n*r;return Ut(t,e,function(){return t.bufferData(t.PIXEL_PACK_BUFFER,i,t.STREAM_READ)}),Ut(t,e,function(){return t.readPixels(0,0,r,n,t.RGBA,t.FLOAT,0)}),Ut(t,e,function(){return t.bindBuffer(t.PIXEL_PACK_BUFFER,null)}),a}function si(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 ui(t,e,n,r,o){var a=Bt(n,r),i=a[0],s=a[1],u=new Uint8Array(n*r*4);return Ut(t,e,function(){return t.readPixels(0,0,i,s,o.downloadTextureFormat,t.UNSIGNED_BYTE,u)}),new Float32Array(u.buffer)}function li(t,e,n,r,o,a,i,s){var u=t,l=new Float32Array(function(t,e){var n=Lt(t,e);return n[0]*n[1]*4}(a,i));return u.bindBuffer(u.PIXEL_PACK_BUFFER,e),u.getBufferSubData(u.PIXEL_PACK_BUFFER,0,l),u.bindBuffer(u.PIXEL_PACK_BUFFER,null),l}function ci(t,e,n,r){var o=new Float32Array(n*r*4);return Ut(t,e,function(){return t.readPixels(0,0,r,n,t.RGBA,t.FLOAT,o)}),o}var hi=Object.freeze({createVertexShader:ja,createVertexBuffer:Xa,createIndexBuffer:Ya,createFloat32MatrixTexture:Ja,createFloat16MatrixTexture:Za,createUnsignedBytesMatrixTexture:ti,createPackedMatrixTexture:ei,createFloat16PackedMatrixTexture:ni,bindVertexProgramAttributeStreams:ri,uploadDenseMatrixToTexture:oi,uploadPixelDataToTexture:ai,createBufferFromOutputTexture:ii,downloadFloat32MatrixFromBuffer:si,downloadByteEncodedFloatMatrixFromOutputTexture:ui,downloadPackedMatrixFromBuffer:li,downloadMatrixFromPackedOutputTexture:ci}),pi=function(){function t(t){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];var e=a().getNumber("WEBGL_VERSION");if(null!=t?(this.gl=t,Ot(e,t)):this.gl=Ft(e),1===a().getNumber("WEBGL_VERSION"))this.textureFloatExtension=qt(this.gl,this.debug,"OES_texture_float"),this.colorBufferFloatExtension=this.gl.getExtension("WEBGL_color_buffer_float"),this.textureHalfFloatExtension=qt(this.gl,this.debug,"OES_texture_half_float"),this.colorBufferHalfFloatExtension=this.gl.getExtension("EXT_color_buffer_half_float");else{if(Ie(this.gl,"EXT_color_buffer_float"))this.colorBufferFloatExtension=this.gl.getExtension("EXT_color_buffer_float");else{if(!Ie(this.gl,"EXT_color_buffer_half_float"))throw new Error("GL context does not support color renderable floats");this.colorBufferHalfFloatExtension=this.gl.getExtension("EXT_color_buffer_half_float")}}this.vertexBuffer=Xa(this.gl,this.debug),this.indexBuffer=Ya(this.gl,this.debug),this.framebuffer=oe(this.gl,this.debug),this.textureConfig=Wt(this.gl,this.textureHalfFloatExtension)}return Object.defineProperty(t.prototype,"debug",{get:function(){return a().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;Ut(e,this.debug,function(){return e.finish()}),Ut(e,this.debug,function(){return e.bindFramebuffer(e.FRAMEBUFFER,null)}),Ut(e,this.debug,function(){return e.deleteFramebuffer(t.framebuffer)}),Ut(e,this.debug,function(){return e.bindBuffer(e.ARRAY_BUFFER,null)}),Ut(e,this.debug,function(){return e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)}),Ut(e,this.debug,function(){return e.deleteBuffer(t.indexBuffer)}),this.disposed=!0}},t.prototype.createFloat32MatrixTexture=function(t,e){return this.throwIfDisposed(),Ja(this.gl,this.debug,t,e,this.textureConfig)},t.prototype.createFloat16MatrixTexture=function(t,e){return this.throwIfDisposed(),Za(this.gl,this.debug,t,e,this.textureConfig)},t.prototype.createUnsignedBytesMatrixTexture=function(t,e){return this.throwIfDisposed(),ti(this.gl,this.debug,t,e,this.textureConfig)},t.prototype.uploadPixelDataToTexture=function(t,e){this.throwIfDisposed(),ai(this.gl,this.debug,t,e)},t.prototype.uploadDenseMatrixToTexture=function(t,e,n,r){this.throwIfDisposed(),oi(this.gl,this.debug,t,e,n,r,this.textureConfig)},t.prototype.createFloat16PackedMatrixTexture=function(t,e){return this.throwIfDisposed(),ni(this.gl,this.debug,t,e,this.textureConfig)},t.prototype.createPackedMatrixTexture=function(t,e){return this.throwIfDisposed(),ei(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),Ut(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 ui(r.gl,r.debug,e,n,r.textureConfig)})},t.prototype.downloadPackedMatrixFromBuffer=function(t,e,n,r,o,a){return li(this.gl,t,0,0,0,o,a,this.textureConfig)},t.prototype.downloadFloat32MatrixFromBuffer=function(t,e){return si(this.gl,t,e)},t.prototype.createBufferFromTexture=function(t,e,n){this.bindTextureToFrameBuffer(t);var r=ii(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(a().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 a().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(e=this.beginQuery(),this.endQuery(),n=function(){return r.isQueryAvailable(e,a().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 ci(r.gl,r.debug,e,n)})},t.prototype.createProgram=function(t){this.throwIfDisposed();var e=this.gl,n=Kt(e,this.debug,t),r=ja(e,this.debug),o=Qt(e,this.debug);return Ut(e,this.debug,function(){return e.attachShader(o,r)}),Ut(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=ri(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&&Ut(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),Ut(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(),Ut(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(),le(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=Lt(e,n),o=r[0],a=r[1];this.setOutputMatrixTextureDriver(t,o,a)},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(),Ut(t,this.debug,function(){return t.drawElements(t.TRIANGLES,6,t.UNSIGNED_SHORT,0)})},t.prototype.blockUntilAllProgramsCompleted=function(){var t=this;this.throwIfDisposed(),Ut(this.gl,this.debug,function(){return t.gl.finish()})},t.prototype.getQueryTimerExtension=function(){return null==this.disjointQueryTimerExtension&&(this.disjointQueryTimerExtension=qt(this.gl,this.debug,2===a().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===a().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!==a().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 n(this,void 0,void 0,function(){var e=this;return r(this,function(n){switch(n.label){case 0:return[4,w(function(){return e.disposed||e.isQueryAvailable(t,a().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))})];case 1:return n.sent(),[2,this.getQueryTime(t,a().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}o=(r=this.getQueryTimerExtensionWebGL1()).getQueryObjectEXT(t,r.QUERY_RESULT_AVAILABLE_EXT);return 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||w(function(){return n.pollItems(),0===n.itemsToPoll.length})},t.prototype.bindTextureToFrameBuffer=function(t){this.throwIfDisposed(),ce(this.gl,this.debug,t,this.framebuffer),this.debug&&pe(this.gl)},t.prototype.unbindTextureToFrameBuffer=function(){null!=this.outputTexture?(ce(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;ce(r,this.debug,t,this.framebuffer),this.debug&&pe(r),this.outputTexture=t,Ut(r,this.debug,function(){return r.viewport(0,0,e,n)}),Ut(r,this.debug,function(){return r.scissor(0,0,e,n)})},t.prototype.setOutputMatrixWriteRegionDriver=function(t,e,n,r){var o=this;this.throwIfDisposed(),Ut(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 fi(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],a=o.shape;if(!m(r,a))throw Error("Binary was compiled with different shapes than the current args. Shapes "+r+" and "+a+" must match");if(!t.isUniform||!o.isUniform){var i=t.texShape,s=o.isUniform?null:o.texData.texShape;if(!m(i,s))throw Error("Binary was compiled with different texture shapes than the current args. Shape "+i+" and "+s+" must match")}})}var di=function(){return function(t,e,n){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=t;for(var r=n.filterWidth,o=n.inChannels,a=n.strideWidth,i=n.strideHeight,s=n.padInfo,u=n.outWidth,l=n.dilationWidth,c=n.dilationHeight,h=n.dataFormat,p=s.left,f=s.top,d=o*r,v=Bo(),m="channelsLast"===h,g=m?0:1,y=m?1:2,x="",b=0;b<=1;b++)for(var w=0;w<=1;w++)x+="\n blockIndex = rc.y + "+w+";\n pos = rc.x + "+b+";\n\n if(blockIndex < "+t[1]+" && pos < "+t[0]+") {\n offsetY = int(blockIndex / ("+u+")) * "+i+" - "+f+";\n d0 = offsetY + "+c+" * (pos / "+d+");\n\n if(d0 < "+e[g]+" && d0 >= 0) {\n\n offsetX = int(mod(float(blockIndex), "+u+".) * "+a+". - "+p+".);\n d1 = offsetX + "+l+" * (int(mod(float(pos), "+d+".) / "+o+".));\n\n if(d1 < "+e[y]+" && d1 >= 0) {\n\n ch = int(mod(float(pos), "+o+".));\n\n if ("+m+") {\n innerDims = vec2(d1, ch);\n result["+(2*b+w)+"] = getChannel(\n getA(d0, int(innerDims.x),\n int(innerDims.y)), innerDims);\n } else {\n innerDims = vec2(d0, d1);\n result["+(2*b+w)+"] = getChannel(\n getA(ch, int(innerDims.x),\n int(innerDims.y)), innerDims);\n }\n }\n }\n }\n ";this.userCode="\n void main() {\n ivec2 rc = getOutputCoords();\n\n vec4 result = vec4(0);\n\n int blockIndex, pos, offsetY, d0, offsetX, d1, ch;\n vec2 innerDims;\n\n "+x+"\n\n "+v.output+" = result;\n }\n "}}(),vi=function(){return function(t,e,n,r,o){this.variableNames=["x"],this.outputShape=[];var a,i=e,s=t[3]-1;this.outputShape=t;var u="float("+n+") + float("+r+") * sum";a=.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 = -"+i+"; j <= "+i+"; 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 * "+a+";\n setOutput(val);\n }\n "}}(),mi=function(){return 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 "}}(),gi=function(){return function(t,e,n,r,o){this.variableNames=["x"],this.outputShape=[],this.usesPackedTextures=!0;var a,i=e,s=t[3]-1;this.outputShape=t;var u="float("+n+") + float("+r+") * sum";a=.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 - "+i+";\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 = - "+i+"; j <= "+i+"; 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 * "+a+";\n setOutput(result);\n }\n "}}(),yi=function(){return function(t){this.variableNames=["dy","maxPos"],this.outputShape=t.inShape;var e=t.strideHeight,n=t.strideWidth,r=t.dilationHeight,o=t.effectiveFilterHeight,a=t.effectiveFilterWidth,i=o-1-t.padInfo.top,s=a-1-t.padInfo.left,u=o*a-1;this.userCode="\n const ivec2 pads = ivec2("+i+", "+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 < "+a+"; 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 * "+a+" + wC;\n float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n dotProd += dyValue * mask;\n }\n }\n setOutput(dotProd);\n }\n "}}(),xi=function(){return function(t){this.variableNames=["dy","maxPos"],this.outputShape=t.inShape;var e=t.strideDepth,n=t.strideHeight,r=t.strideWidth,o=t.dilationDepth,a=t.dilationHeight,i=t.dilationWidth,s=t.effectiveFilterDepth,u=t.effectiveFilterHeight,l=t.effectiveFilterWidth,c=s-1-t.padInfo.front,h=u-1-t.padInfo.top,p=l-1-t.padInfo.left,f=s*u*l-1;this.userCode="\n const ivec3 pads = ivec3("+c+", "+h+", "+p+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n int dyDCorner = dyCorner.x;\n int dyRCorner = dyCorner.y;\n int dyCCorner = dyCorner.z;\n\n // Convolve dy(?, ?, ?, ch) with pos mask(:, :, :, d) to get\n // dx(xD, xR, xC, ch).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n\n for (int wD = 0; wD < "+s+";\n wD += "+o+") {\n float dyD = float(dyDCorner + wD) / "+e+".0;\n\n if (dyD < 0.0 || dyD >= "+t.outDepth+".0 || fract(dyD) > 0.0) {\n continue;\n }\n int idyD = int(dyD);\n\n for (int wR = 0; wR < "+u+";\n wR += "+a+") {\n float dyR = float(dyRCorner + wR) / "+n+".0;\n\n if (dyR < 0.0 || dyR >= "+t.outHeight+".0 ||\n fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < "+l+";\n wC += "+i+") {\n float dyC = float(dyCCorner + wC) / "+r+".0;\n\n if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(batch, idyD, idyR, idyC, ch);\n int maxPosValue = "+f+" -\n int(getMaxPos(batch, idyD, idyR, idyC, ch));\n\n // Get the current value, check it against the value from the\n // position matrix.\n int curPosValue =\n wD * "+u+" * "+l+" +\n wR * "+l+" + wC;\n float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n dotProd += dyValue * mask;\n }\n }\n }\n setOutput(dotProd);\n }\n "}}(),bi=function(){return function(t,e,n,r,o,a,i){void 0===n&&(n=!1),void 0===r&&(r=!1),void 0===o&&(o=!1),void 0===a&&(a=null),void 0===i&&(i=!1),this.variableNames=["matrixA","matrixB"],this.usesPackedTextures=!0,this.outputShape=e;var s=n?t[1]:t[2],u=Math.ceil(s/2),l=n?"i * 2, rc.y":"rc.y, i * 2",c=r?"rc.z, i * 2":"i * 2, rc.z",h=n?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],p=r?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"],f="",d="";a&&(f=i?"vec4 activation(vec4 a) {\n vec4 b = getPreluActivationWeightsAtOutCoords();\n "+a+"\n }":"vec4 activation(vec4 x) {\n "+a+"\n }",d="result = activation(result);");var v=o?"result += getBiasAtOutCoords();":"";o&&this.variableNames.push("bias"),i&&this.variableNames.push("preluActivationWeights"),this.userCode="\n "+f+"\n\n const float sharedDimension = "+u+".0;\n\n vec4 dot2x2ARowBCol(ivec3 rc) {\n vec4 result = vec4(0);\n for (int i = 0; i < "+u+"; i++) {\n vec4 a = getMatrixA(rc.x, "+l+");\n vec4 b = getMatrixB(rc.x, "+c+");\n\n // These swizzled products need to be separately added.\n // See: https://github.com/tensorflow/tfjs/issues/1735\n result += ("+h[0]+" * "+p[0]+");\n result += ("+h[1]+" * "+p[1]+");\n }\n return result;\n }\n\n void main() {\n ivec3 rc = getOutputCoords();\n vec4 result = dot2x2ARowBCol(rc);\n\n "+v+"\n\n "+d+"\n\n setOutput(result);\n }\n "}}(),wi=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}(),Ci=function(){return 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 "}}(),Ei=function(){return 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=Mo("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),i=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 a=(0===r?"r":"rp1")+", "+(0===o?"c":"cp1"),i=2;i= "+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 "+a+"\n\n setOutput(vec4("+i+"));\n }\n }\n "}}}();var Ri=function(){return 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),a=e.map(function(t){return t[0]}).join(","),i=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+"("+a+");\n "+o+" end = "+o+"("+i+");\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 = "+a+";\n int end = "+i+";\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 "}}(),Ii=function(){return 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),a=e.map(function(t){return t[0]}).join(","),i=e.map(function(e,n){return e[0]+t[n]}).join(","),s=Mo("rc",r),u=Mo("source",r),l=s[r-1]+" < "+this.outputShape[r-1],c=1===r?"source":"vec2("+u.slice(-2).join()+")",h=[o+" rc = outputLoc;",s[r-1]+" += 1;\n if("+l+") {\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("+l+") {"],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 < "+l+";\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 * "+l+" + 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+", "+a+");\n const ivec2 pads = ivec2("+c+", "+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 += "+i+") {\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 "}}}(),Ni=function(){return function(t,e,n){if(this.variableNames=["x"],"avg"===e&&n)throw new Error("Cannot compute positions for average pool.");var r=t.filterWidth,o=t.strideDepth,a=t.strideHeight,i=t.strideWidth,s=t.dilationDepth,u=t.dilationHeight,l=t.dilationWidth,c=t.effectiveFilterDepth,h=t.effectiveFilterHeight,p=t.effectiveFilterWidth,f=t.padInfo.front,d=t.padInfo.top,v=t.padInfo.left;this.outputShape=t.outShape;var m="avg"===e,g="0.0";if(m||(g="-1.0 / 1e-20"),n)this.userCode="\n const ivec3 strides =\n ivec3("+o+", "+a+", "+i+");\n const ivec3 pads = ivec3("+f+", "+d+", "+v+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n int xDCorner = xCorner.x;\n int xRCorner = xCorner.y;\n int xCCorner = xCorner.z;\n\n // max/min x(?, ?, ?, ch) to get y(yD, yR, yC, ch).\n // ? = to be determined\n float minMaxValue = 0.0;\n float minMaxValueFound = 0.0;\n int minMaxPosition = 0;\n\n for (int wD = 0; wD < "+c+";\n wD += "+s+") {\n int xD = xDCorner + wD;\n\n if (xD < 0 || xD >= "+t.inDepth+") {\n continue;\n }\n\n for (int wR = 0; wR < "+h+";\n wR += "+u+") {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+p+";\n wC += "+l+") {\n int xC = xCCorner + wC;\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n float value = getX(batch, xD, xR, xC, ch);\n\n // If a min / max value has already been found, use it. If not,\n // use the current value.\n float currMinMaxValue = mix(\n value, minMaxValue, minMaxValueFound);\n if (value >= currMinMaxValue) {\n minMaxValue = value;\n minMaxValueFound = 1.0;\n minMaxPosition =\n wD * "+h+" * "+p+" +\n wR * "+p+" + wC;;\n }\n }\n }\n }\n setOutput(float(minMaxPosition));\n }\n ";else{var y=e+"("+e+"("+e+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"avg"===e&&(y="avgValue / count");var x=4*Math.floor(r/4),b=r%4,w="\n if ("+m+") {\n avgValue += dot(values, ones);\n } else {\n minMaxValue = max(values, minMaxValue);\n }\n ";this.userCode="\n const ivec3 strides =\n ivec3("+o+", "+a+", "+i+");\n const ivec3 pads = ivec3("+f+", "+d+", "+v+");\n const float initializationValue = "+g+";\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float count = 0.0;\n\n float getValue(int batch, int xD, int xR, int xC, int ch) {\n if (xC < 0 || xC >= "+t.inWidth+") {\n return initializationValue;\n }\n count += 1.0;\n return getX(batch, xD, xR, xC, ch);\n }\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n int xDCorner = xCorner.x;\n int xRCorner = xCorner.y;\n int xCCorner = xCorner.z;\n\n // max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch).\n // ? = to be determined\n vec4 minMaxValue = vec4("+g+");\n float avgValue = 0.0;\n count = 0.0;\n\n for (int wD = 0; wD < "+c+";\n wD += "+s+") {\n int xD = xDCorner + wD;\n\n if (xD < 0 || xD >= "+t.inDepth+") {\n continue;\n }\n\n for (int wR = 0; wR < "+h+";\n wR += "+u+") {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+x+"; wC += 4) {\n int xC = xCCorner + wC * "+l+";\n\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + "+l+", ch),\n getValue(batch, xD, xR, xC + 2 * "+l+", ch),\n getValue(batch, xD, xR, xC + 3 * "+l+", ch)\n );\n\n "+w+"\n }\n\n int xC = xCCorner + "+x+";\n if ("+(1===b)+") {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n "+w+"\n } else if ("+(2===b)+") {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + "+l+", ch),\n initializationValue,\n initializationValue\n );\n\n "+w+"\n } else if ("+(3===b)+") {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + "+l+", ch),\n getValue(batch, xD, xR, xC + 2 * "+l+", ch),\n initializationValue\n );\n\n "+w+"\n }\n }\n setOutput("+y+");\n }\n }\n "}}}(),Si=function(){return function(t,e){this.variableNames=["x"];var n=t.windowSize,r=t.batchSize,o=t.inSize,a=Math.ceil(o/n);this.outputShape=[r,a];var i="0.0",s="";"prod"===e?i="1.0":"min"===e?(i="1.0 / 1e-20",s="min"):"max"===e&&(i="-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 l=4*Math.floor(n/4),c=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?(i="1.0",h="\n bool reducedAllValue = all(values);\n float floatedReducedAllValue = float(reducedAllValue);\n allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);\n ",p="bvec4"):"any"===e&&(i="0.0",h="\n bool reducedAnyValue = any(values);\n float floatedReducedAnyValue = float(reducedAnyValue);\n anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);\n ",p="bvec4");var f="";o%n>0&&(f="\n if (inIdx < 0 || inIdx >= "+o+") {\n return initializationValue;\n }\n "),this.userCode="\n const float initializationValue = "+i+";\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float getValue(int batch, int inIdx) {\n "+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("+i+");\n float prodValue = 1.0;\n float sumValue = 0.0;\n float allValue = 1.0;\n float anyValue = 0.0;\n\n for (int i = 0; i < "+l+"; 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 + "+l+";\n if ("+(1===c)+") {\n "+p+" values = "+p+"(\n getValue(batch, inIdx),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n "+h+"\n } else if ("+(2===c)+") {\n "+p+" values = "+p+"(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n initializationValue,\n initializationValue\n );\n\n "+h+"\n } else if ("+(3===c)+") {\n "+p+" values = "+p+"(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n initializationValue\n );\n\n "+h+"\n }\n setOutput("+u+");\n }\n "}}(),Ai=function(){return 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 "+Po(["r","c","d"],e)+"\n return ivec3(r, c, d);\n }\n \n "+Lo(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 "}}();var Ti=function(){return function(t,e,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=e.shape;var r=e.shape,o=r[1],a=r[2],i=t.shape,s=i[1],u=i[2],l=[n&&s>1?o-1:o,n&&u>1?a-1:a],c=[n&&s>1?s-1:s,n&&u>1?u-1:u],h=l[0]/c[0],p=l[1]/c[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), "+(a-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 "}}(),Di=function(){return function(t,e,n,r){this.variableNames=["A"],this.outputShape=[];var o=t[0],a=t[1],i=t[2],s=t[3];this.outputShape=[o,e,n,s];var u=[r&&e>1?a-1:a,r&&n>1?i-1:i],l=[r&&e>1?e-1:e,r&&n>1?n-1:n];this.userCode="\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n "+u[0]/l[0]+",\n "+u[1]/l[1]+");\n const vec2 inputShapeRC = vec2("+a+".0, "+i+".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 "}}(),_i=function(){return function(t,e,n,r){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=[];var o=t[0],a=t[1],i=t[2],s=t[3];this.outputShape=[o,e,n,s];var u=[r&&e>1?a-1:a,r&&n>1?i-1:i],l=[r&&e>1?e-1:e,r&&n>1?n-1:n];this.userCode="\n const vec3 effectiveInputOverOutputRatioRC = vec3(\n "+u[0]/l[0]+",\n "+u[1]/l[1]+",\n "+u[1]/l[1]+");\n const vec3 inputShapeRC = vec3("+a+".0, "+i+".0,\n "+i+".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 "}}(),Oi=function(){return function(t,e,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=e.shape;var r=e.shape,o=r[1],a=r[2],i=t.shape,s=i[1],u=i[2],l=[n&&s>1?o-1:o,n&&u>1?a-1:a],c=[n&&s>1?s-1:s,n&&u>1?u-1:u],h=l[0]/c[0],p=l[1]/c[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("+l[0]+") *\n (float(dyR) / float("+c[0]+"));\n\n float sourceFracCol =\n float("+l[1]+") *\n (float(dyC) / float("+c[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("+a+") - 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 "}}(),Fi=function(){return function(t,e,n,r){this.variableNames=["A"],this.outputShape=[];var o=t[0],a=t[1],i=t[2],s=t[3];this.outputShape=[o,e,n,s];var u=[r&&e>1?a-1:a,r&&n>1?i-1:i],l=[r&&e>1?e-1:e,r&&n>1?n-1:n],c=r?"0.5":"0.0";this.userCode="\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n "+u[0]/l[0]+",\n "+u[1]/l[1]+");\n const vec2 inputShapeRC = vec2("+a+".0, "+i+".0);\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n ivec2 yRC = coords.yz;\n\n // Fractional source index.\n vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;\n\n // Compute the coordinators of nearest neighbor point.\n ivec2 sourceNearestRC = ivec2(\n min(inputShapeRC - 1.0, floor(sourceFracIndexRC + "+c+")));\n\n float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);\n\n setOutput(newValue);\n }\n "}}(),Mi=function(){return 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 "}}(),Bi=function(){return 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=Mo("rc",n),o=r[n-1]+" + 1 < "+this.outputShape[n-1],a=r[n-2]+" + 1 < "+this.outputShape[n-2],i=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 "+i+" rc = getOutputCoords();\n vec4 result = vec4(0.);\n result.r = "+function(t){return s(t)}(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("+a+") {\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 "}}(),Pi=function(){return function(t,e,n,r,o,a,i){void 0===i&&(i=!0),this.variableNames=["updates","indices","defaultValue"],this.outputShape=a;var s=Xo(o.length),u=Xo(a.length),l="";1===n?l="i":2===n&&(l="i, j");var c="getIndices("+l+")",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("+c+");\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 "}}(),Li=function(){return function(t,e){this.variableNames=["x","segmentIds"];var n=t.windowSize,r=t.batchSize,o=t.inSize,a=t.numSegments,i=a*Math.ceil(o/n);this.outputShape=[r,i];var s=4*Math.floor(n/4),u=n%4,l="\n sumValue += dot(values, segFilter);\n ",c="";o%n>0&&(c="\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 "+c+"\n return getX(batch, inIdx);\n }\n\n float getSegmentIdAtIndex(int inIdx) {\n "+h+"\n return getSegmentIds(inIdx);\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = int(floor(float(outIdx) / float(\n "+a+")) * float("+n+"));\n int currentSeg = int(mod(float(outIdx), float("+a+")));\n\n float sumValue = 0.0;\n\n for (int i = 0; i < "+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 "+l+"\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 "+l+"\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 "+l+"\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 "+l+"\n }\n setOutput(sumValue);\n }\n "}}(),Wi=function(){return 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 a=["resRC.x","resRC.y","resRC.z","resRC.w"],i=[],s=[],u=0;u= 1.0) {\n setOutput(getA("+o+"));\n } else {\n setOutput(getB("+o+"));\n }\n }\n "}}(),Ui=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 Vi.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."+Vi[e]+" = start["+e+"] + coords."+Vi[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}(),Vi=["x","y","z","w","u","v"];var zi=function(){function t(t){this.variableNames=["source"],this.usesPackedTextures=!0,this.outputShape=t,this.rank=t.length;var e=Xo(this.rank),n=Mo("coords",this.rank),r=Mo("sourceLoc",this.rank),o=1===this.rank?"sourceLoc":"vec2("+r.slice(-2).join()+")",a="getChannel(getSource("+r.join()+"), "+o+")",i="\n result.x = "+a+";\n if (++"+n[this.rank-1]+" < "+t[this.rank-1]+") {\n ++"+r[this.rank-1]+";\n result.y = "+a+";\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 = "+a+";\n if (++"+n[this.rank-1]+" < "+t[this.rank-1]+") {\n ++"+r[this.rank-1]+";\n result.w = "+a+";\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 "+i+"\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}(),Gi=function(){return function(t,e,n){this.variableNames=["x"],this.outputShape=n;var r=n.length,o=Xo(n.length),a=Xo(n.length),i="";if(1===r)i="coords * strides + begin";else{var s=0;i=n.map(function(t,e){return s++,1===n.length?"coords * strides["+e+"] + begin["+e+"]":"coords["+(s-1)+"] * strides["+e+"] + begin["+e+"]"}).join(",")}this.userCode="\n "+o+" begin = "+o+"("+t+");\n "+o+" strides = "+o+"("+e+");\n\n void main() {\n "+a+" coords = getOutputCoords();\n setOutput(getX("+i+"));\n }\n "}}(),Hi=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=qi(e,n),a=$i(t,o,n);if(a in this.freeTextures||(this.freeTextures[a]=[]),a in this.usedTextures||(this.usedTextures[a]=[]),this.freeTextures[a].length>0){this.numFreeTextures--,this.numUsedTextures++,this.log();var i=this.freeTextures[a].shift();return this.usedTextures[a].push(i),i}return this.numUsedTextures++,this.log(),o===Tt.PACKED_2X2_FLOAT32?r=this.gpgpu.createPackedMatrixTexture(t[0],t[1]):o===Tt.PACKED_2X2_FLOAT16?r=this.gpgpu.createFloat16PackedMatrixTexture(t[0],t[1]):o===Tt.UNPACKED_FLOAT32?r=this.gpgpu.createFloat32MatrixTexture(t[0],t[1]):o===Tt.UNPACKED_FLOAT16?r=this.gpgpu.createFloat16MatrixTexture(t[0],t[1]):o===Tt.PACKED_4X1_UNSIGNED_BYTE&&(r=this.gpgpu.createUnsignedBytesMatrixTexture(t[0],t[1])),this.usedTextures[a].push(r),r},t.prototype.releaseTexture=function(t,e,n,r){if(null!=this.freeTextures){var o=$i(e,qi(n,r),r);o in this.freeTextures||(this.freeTextures[o]=[]),this.freeTextures[o].push(t),this.numFreeTextures++,this.numUsedTextures--;var a=this.usedTextures[o],i=a.indexOf(t);if(i<0)throw new Error("Cannot release a texture that was never provided by this texture manager");a.splice(i,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 qi(t,e){if(t===At.UPLOAD)return Tt.PACKED_2X2_FLOAT32;if(t===At.RENDER||null==t)return function(t){return a().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?t?Tt.PACKED_2X2_FLOAT32:Tt.UNPACKED_FLOAT32:t?Tt.PACKED_2X2_FLOAT16:Tt.UNPACKED_FLOAT16}(e);if(t===At.DOWNLOAD||t===At.PIXELS)return Tt.PACKED_4X1_UNSIGNED_BYTE;throw new Error("Unknown logical texture type "+t)}function $i(t,e,n){return t[0]+"_"+t[1]+"_"+e+"_"+n}var Ki=function(){return 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),a=Fo("rc",this.rank),i=new Array(this.rank);for(r=0;r= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);\n";var is="return -x;",ss="return ceil(x);",us="return floor(x);",ls="return exp(x);",cs="return exp(x) - 1.0;",hs=Zi+"\n return sin(x);\n",ps=Zi+"\n return cos(x);\n",fs=Zi+"\n if (abs(x) > 1.) {\n return NAN;\n }\n return asin(x);\n",ds=Zi+"\n if (abs(x) > 1.) {\n return NAN;\n }\n return acos(x);\n",vs=Zi+"\n return atan(x);\n",ms=Zi+"return log(x + sqrt(x * x + 1.0));",gs=Zi+"\n if (x < 1.0) return NAN;\n return log(x + sqrt(x * x - 1.0));",ys=Zi+"\n if ((x < -1.0) || (x > 1.0)) return NAN;\n return (log(1.0 + x) - log(1.0 - x)) / 2.0;",xs="return x;",bs="return x;",ws="\n vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n",Cs="\n vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n",Es="\n vec4 result;\n\n result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);\n result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);\n result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);\n result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);\n\n return result;\n",Rs=function(){return function(t,e){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=t,this.userCode="\n vec4 unaryOperation(vec4 x) {\n "+e+"\n }\n\n void main() {\n vec4 x = getAAtOutCoords();\n vec4 y = unaryOperation(x);\n\n setOutput(y);\n }\n "}}(),Is=function(){return function(t){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=t;var e=t.length,n=Mo("rc",e),r=Xo(e),o=function(t,e){if(1===t)return"rc";for(var n="",r=0;r0?this.gpgpu.beginQuery():{startMs:H(),endMs:null}},t.prototype.endTimer=function(t){return a().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(this.gpgpu.endQuery(),t):(t.endMs=H(),t)},t.prototype.getQueryTime=function(t){return n(this,void 0,void 0,function(){var e;return r(this,function(n){return a().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,a=e.usage,i=e.isPacked,s=e.slice,u=s&&s.origDataId||t,l=this.dataRefCount.get(u);l>1?this.dataRefCount.set(u,l-1):(this.dataRefCount.delete(u),null!=n&&(this.numBytesInGPU-=this.computeBytes(o,r),this.textureManager.releaseTexture(n,o,a,i)));var c=this.texData.get(t);c.texture=null,c.texShape=null,c.isPacked=!1,c.slice=null},t.prototype.getTexture=function(t){return this.uploadToGPU(t),this.texData.get(t).texture},t.prototype.getDataInfo=function(t){return this.texData.get(t)},t.prototype.getCPUBackend=function(){return a().getBool("WEBGL_CPU_FORWARD")?(null==this.cpuBackend&&(this.cpuBackend=kt.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.sizea().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){var o=Math.floor(t.length/2),i=this.concat(t.slice(0,o),e),s=this.concat(t.slice(o),e);return this.concat([i,s],e)}if(a().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&t[0].rank>1){var u=new ga(t.map(function(t){return t.shape}),e);return this.compileAndRun(u,t)}var l=vn(t.map(function(t){return t.shape}),e),c=t.map(function(t){return t.as2D(-1,v(t.shape.slice(e)))}),h=new ma(c.map(function(t){return t.shape}));return this.compileAndRun(h,c).reshape(l)},t.prototype.neg=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.neg(t);if(a().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,is,t.dtype);var e=new Ji(t.shape,is);return this.compileAndRun(e,[t])},t.prototype.batchMatMul=function(t,e,n,r){var o=n?t.shape[2]:t.shape[1],a=r?e.shape[1]:e.shape[2],i=n?t.shape[1]:t.shape[2],s=t.shape[0];if((1===o||1===a)&&i>1e3){n&&(t=t.transpose([0,2,1])),r&&(e=e.transpose([0,2,1]));var u=1===a?t:t.as3D(s,i,1),l=1===a?2:1,c=1===a?e.as3D(s,1,i):e;return this.multiply(u,c).sum(l,!0)}var h=gt(t.dtype,e.dtype),p=new bi(t.shape,[s,o,a],n,r),f=this.makePackedTensor(p.outputShape,h);return this.compileAndRun(p,[t,e],f)},t.prototype.fusedBatchMatMul=function(t){var e=t.a,n=t.b,r=t.transposeA,o=t.transposeB,a=t.bias,i=t.activation,s=t.preluActivationWeights,u=r?e.shape[2]:e.shape[1],l=o?n.shape[1]:n.shape[2],c=e.shape[0],h=gt(e.dtype,n.dtype),p=null!=a,f=null!=s,d=i?Ns(i,!0):null,v=new bi(e.shape,[c,u,l],r,o,p,d,f),m=this.makePackedTensor(v.outputShape,h),g=[e,n];return a&&g.push(a),s&&g.push(s),this.compileAndRun(v,g,m)},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 aa(ra,t.shape,e.shape),i=new aa(oa,t.shape,e.shape),s=[this.makeComplexComponentTensorHandle(t,n.complexTensors.real),this.makeComplexComponentTensorHandle(t,n.complexTensors.imag),this.makeComplexComponentTensorHandle(e,r.complexTensors.real),this.makeComplexComponentTensorHandle(e,r.complexTensors.imag)],u=this.compileAndRun(o,s),l=this.compileAndRun(i,s),c=this.complex(u,l);return u.dispose(),l.dispose(),c}if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.multiply(t,e);if(a().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,ua,t.dtype);var h=new ca(ua,t.shape,e.shape),p=this.makeOutputArray(h.outputShape,t.dtype);return this.compileAndRun(h,[t,e],p)},t.prototype.batchNormalization=function(t,e,n,r,o,i){var s=[t,e,n],u=null;null!=i&&(u=i.shape,s.push(i));var l=null;if(null!=o&&(l=o.shape,s.push(o)),a().getBool("WEBGL_PACK_NORMALIZATION")){var c=new na(t.shape,e.shape,n.shape,u,l,r);return this.compileAndRun(c,s)}var h=new ea(t.shape,e.shape,n.shape,u,l,r);return this.compileAndRun(h,s)},t.prototype.localResponseNormalization4D=function(t,e,n,r,o){var i=a().getBool("WEBGL_PACK_NORMALIZATION")?new gi(t.shape,e,n,r,o):new vi(t.shape,e,n,r,o);return this.compileAndRun(i,[t])},t.prototype.LRNGrad=function(t,e,n,r,o,a,i){var s=new mi(e.shape,r,o,a,i);return this.compileAndRun(s,[e,n,t])},t.prototype.tile=function(t,e){if("string"===t.dtype){var n=this.readSync(t.dataId).map(function(t){return K(t)});return So(tr(t.shape,t.dtype,n),e)}var r=new Ki(t.shape,e);return this.compileAndRun(r,[t])},t.prototype.pad=function(t,e,n){var r=a().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Ii(t.shape,e,n):new Ri(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=a().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Xi(t.shape,e):new ji(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 $a(t.shape,e.size,n);return this.compileAndRun(r,[t,e])},t.prototype.batchToSpaceND=function(t,e,n){h(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=Sr(t.shape,e,r),a=Ar(o.length,e.length),i=Tr(t.shape,e,r),s=Dr(n,e.length),u=_r(i,n,e.length);return t.reshape(o).transpose(a).reshape(i).slice(s,u)},t.prototype.spaceToBatchND=function(t,e,n){h(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 a=1+e.length;ae||n===t?r=!0:n=L(t,n+1);return n}(i,o),u=new Li({windowSize:s,inSize:i,batchSize:a,numSegments:o},e),l=u.outputShape,c=l[0],h=l[1],p=this.makeOutputArray([c,h],r);return this.compileAndRun(u,[t,n],p),p.shape[1]===o?p:(n=On(0,o).tile([i/s]),this.segOpCompute(p,e,n,r,o))},t.prototype.argMinMaxReduce=function(t,e,n){var r=[e];if(cn("arg"+n.charAt(0).toUpperCase()+n.slice(1),r,t.rank),!a().getBool("WEBGL_PACK_REDUCE")||t.rank<=2){var o=un(t.shape,r),i=o[0],s=v(o[1]),u=t.as2D(-1,s);return this.argReduce(u,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 Ta(t.shape,n,r);return this.compileAndRun(o,[t])},t.prototype.equal=function(t,e){if(a().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(equal(a, b));\n","bool");var n=new ca("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(a().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(notEqual(a, b));\n","bool");var n=new ca("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(a().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(lessThan(a, b));\n","bool");var n=new ca("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(a().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(lessThanEqual(a, b));\n","bool");var n=new ca("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(a().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(greaterThan(a, b));\n","bool");var n=new ca("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(a().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(greaterThanEqual(a, b));\n","bool");var n=new ca("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 Ji(t.shape,"return float(!(x >= 1.0));");return this.compileAndRun(e,[t])},t.prototype.logicalAnd=function(t,e){if(a().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 ca("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(a().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 ca("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 Wi(t.rank,e.shape,e.rank),o=this.makeOutputArray(r.outputShape,gt(e.dtype,n.dtype));return this.compileAndRun(r,[t,e,n],o)},t.prototype.where=function(t){tn("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");var e=t.dataSync();return To(t.shape,e)},t.prototype.topk=function(t,e,n){return Ao(t.dataSync(),t.shape,t.dtype,e)},t.prototype.min=function(t,e){cn("min",e,t.rank);var n=un(t.shape,e),r=n[0],o=v(n[1]),a=t.as2D(-1,o);return this.reduce(a,"min",a.dtype).reshape(r)},t.prototype.minimum=function(t,e){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.minimum(t,e);var n=a().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new pa("\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 ca("\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=a().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new pa("\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 ca("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);cn("max",e,t.rank);var n=un(t.shape,e),r=n[0],o=v(n[1]),a=t.as2D(-1,o);return this.reduce(a,"max",a.dtype).reshape(r)},t.prototype.maximum=function(t,e){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.maximum(t,e);var n=a().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new pa("\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 ca("\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){cn("all",e,t.rank);var n=un(t.shape,e),r=n[0],o=v(n[1]),a=t.as2D(-1,o);return this.reduce(a,"all",a.dtype).reshape(r)},t.prototype.any=function(t,e){cn("any",e,t.rank);var n=un(t.shape,e),r=n[0],o=v(n[1]),a=t.as2D(-1,o);return this.reduce(a,"any",a.dtype).reshape(r)},t.prototype.squaredDifference=function(t,e){var n=a().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new pa("return (a - b) * (a - b);",t.shape,e.shape):new ca("return (a - b) * (a - b);",t.shape,e.shape);return this.compileAndRun(n,[t,e])},t.prototype.realDivide=function(t,e){if(a().getBool("WEBGL_PACK_BINARY_OPERATIONS")){return this.packedBinaryOp(t,e,"\n // vec4 one = vec4(equal(a, b));\n // return one + (vec4(1.0) - one) * a / b;\n vec4 result = a / b;\n if(a.x == b.x) {\n result.x = 1.;\n }\n if(a.y == b.y) {\n result.y = 1.;\n }\n if(a.z == b.z) {\n result.z = 1.;\n }\n if(a.w == b.w) {\n result.w = 1.;\n }\n\n return result;\n","float32",!0)}var n=new ca("\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(a().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 ca("\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,ia);if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.add(t,e);var n=gt(t.dtype,e.dtype);if(a().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,ia,n);var r=new ca(ia,t.shape,e.shape),o=this.makeOutputArray(r.outputShape,n);return this.compileAndRun(r,[t,e],o)},t.prototype.packedUnaryOp=function(t,e,n){var r=new Rs(t.shape,e),o=this.makePackedTensor(r.outputShape,n);return this.compileAndRun(r,[t],o)},t.prototype.packedBinaryOp=function(t,e,n,r,o){void 0===o&&(o=!1);var a=new pa(n,t.shape,e.shape,o),i=this.makePackedTensor(a.outputShape,r);return this.compileAndRun(a,[t,e],i)},t.prototype.complexSeparableBinaryOp=function(t,e,n){var r=this,o=this.texData.get(t.dataId),a=this.texData.get(e.dataId),i=[[o.complexTensors.real,a.complexTensors.real],[o.complexTensors.imag,a.complexTensors.imag]].map(function(o){var a=o[0],i=o[1],s=r.makeComplexComponentTensorHandle(t,a),u=r.makeComplexComponentTensorHandle(e,i),l=new ca(n,t.shape,e.shape),c=r.makeOutputArray(l.outputShape,gt(a.dtype,i.dtype));return r.compileAndRun(l,[s,u],c)}),s=i[0],u=i[1],l=this.complex(s,u);return s.dispose(),u.dispose(),l},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>a().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 gt(t,e)}),i=t.map(function(t){return t.shape}),s=a().getBool("WEBGL_PACK"),u=s?new _o(t[0].shape,i):new Do(t[0].shape,i),l=s?this.makePackedTensor(u.outputShape,o):this.makeOutputArray(u.outputShape,o);return this.compileAndRun(u,t,l)},t.prototype.subtract=function(t,e){if("complex64"===t.dtype&&"complex64"===e.dtype)return this.complexSeparableBinaryOp(t,e,sa);if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.subtract(t,e);var n=gt(t.dtype,e.dtype);if(a().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,sa,t.dtype);var r=new ca(sa,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=a().getBool("WEBGL_PACK_BINARY_OPERATIONS"),r=n?new pa("\n // isModRound1 has 1 for components with round(mod(b, 2.0)) == 1, 0 otherwise.\n vec4 isModRound1 = vec4(equal(round(mod(b, 2.0)), ivec4(1)));\n vec4 multiplier = sign(a) * isModRound1 + (vec4(1.0) - isModRound1);\n vec4 result = multiplier * pow(abs(a), b);\n\n // Ensure that a^0 = 1, including 0^0 = 1 as this correspond to TF and JS\n bvec4 isExpZero = equal(b, vec4(0.0));\n result.r = isExpZero.r ? 1.0 : result.r;\n result.g = isExpZero.g ? 1.0 : result.g;\n result.b = isExpZero.b ? 1.0 : result.b;\n result.a = isExpZero.a ? 1.0 : result.a;\n\n vec4 isNaN = vec4(lessThan(a, vec4(0.0))) * vec4(lessThan(floor(b), b));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n",t.shape,e.shape):new ca("\nif(a < 0.0 && floor(b) < b){\n return NAN;\n}\nif (b == 0.0) {\n return 1.0;\n}\nreturn (round(mod(b, 2.0)) != 1) ?\n pow(abs(a), b) : sign(a) * pow(abs(a), b);\n",t.shape,e.shape),o=gt(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){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.ceil(t);if(a().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,ss,t.dtype);var e=new Ji(t.shape,ss);return this.compileAndRun(e,[t])},t.prototype.floor=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.floor(t);if(a().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,us,t.dtype);var e=new Ji(t.shape,us);return this.compileAndRun(e,[t])},t.prototype.sign=function(t){var e=new Ji(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 Ji(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 Ji(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 Ji(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 Ji(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){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.exp(t);if(a().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,ls,t.dtype);var e=new Ji(t.shape,ls);return this.compileAndRun(e,[t])},t.prototype.expm1=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.expm1(t);if(a().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,cs,t.dtype);var e=new Ji(t.shape,cs);return this.compileAndRun(e,[t])},t.prototype.log=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.log(t);if(a().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,"\n vec4 result = log(x);\n vec4 isNaN = vec4(lessThan(x, vec4(0.0)));\n result.r = isNaN.r == 1.0 ? NAN : result.r;\n result.g = isNaN.g == 1.0 ? NAN : result.g;\n result.b = isNaN.b == 1.0 ? NAN : result.b;\n result.a = isNaN.a == 1.0 ? NAN : result.a;\n\n return result;\n",t.dtype);var e=new Ji(t.shape,"if (x < 0.0) return NAN;\n return log(x);");return this.compileAndRun(e,[t])},t.prototype.log1p=function(t){var e=new Ji(t.shape,"return log(1.0 + x);");return this.compileAndRun(e,[t])},t.prototype.sqrt=function(t){var e=new Ji(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 Ji(t.shape,"return inversesqrt(x);");return this.compileAndRun(e,[t])},t.prototype.square=function(t){var e=new Ji(t.shape,"return x * x;");return this.compileAndRun(e,[t])},t.prototype.reciprocal=function(t){var e=new Ji(t.shape,"return 1.0 / x;");return this.compileAndRun(e,[t])},t.prototype.relu=function(t){var e;return e=a().getBool("WEBGL_PACK")?new Rs(t.shape,ws):new Ji(t.shape,ns),this.compileAndRun(e,[t])},t.prototype.relu6=function(t){var e;return e=a().getBool("WEBGL_PACK")?new Rs(t.shape,Cs):new Ji(t.shape,rs),this.compileAndRun(e,[t])},t.prototype.prelu=function(t,e){var n=a().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new pa(ha,t.shape,e.shape):new ca(la,t.shape,e.shape);return this.compileAndRun(n,[t,e])},t.prototype.elu=function(t){if(a().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,Es,t.dtype);var e=new Ji(t.shape,os);return this.compileAndRun(e,[t])},t.prototype.eluDer=function(t,e){var n=a().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new pa("\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 ca("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 Ji(t.shape,as);return this.compileAndRun(e,[t])},t.prototype.int=function(t){var e=new Ji(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=a().getBool("WEBGL_PACK_CLIP")?new da(t.shape):new fa(t.shape)).getCustomSetupFunc(e,n);return this.compileAndRun(r,[t],null,o)},t.prototype.abs=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.abs(t);if(a().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,es,t.dtype);var e=new Ji(t.shape,es);return this.compileAndRun(e,[t])},t.prototype.complexAbs=function(t){var e=this.texData.get(t.dataId),n=new va(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 Ji(t.shape,"return 1.0 / (1.0 + exp(-1.0 * x));");return this.compileAndRun(e,[t])},t.prototype.softplus=function(t){var e=new Ji(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 Ji(t.shape,hs);return this.compileAndRun(e,[t])},t.prototype.cos=function(t){var e=new Ji(t.shape,ps);return this.compileAndRun(e,[t])},t.prototype.tan=function(t){var e=new Ji(t.shape,"return tan(x);");return this.compileAndRun(e,[t])},t.prototype.asin=function(t){var e=new Ji(t.shape,fs);return this.compileAndRun(e,[t])},t.prototype.acos=function(t){var e=new Ji(t.shape,ds);return this.compileAndRun(e,[t])},t.prototype.atan=function(t){var e=new Ji(t.shape,vs);return this.compileAndRun(e,[t])},t.prototype.atan2=function(t,e){var n=a().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new pa("\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 ca("\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 Ji(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 Ji(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 Ji(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 Ji(t.shape,ms);return this.compileAndRun(e,[t])},t.prototype.acosh=function(t){var e=new Ji(t.shape,gs);return this.compileAndRun(e,[t])},t.prototype.atanh=function(t){var e=new Ji(t.shape,ys);return this.compileAndRun(e,[t])},t.prototype.erf=function(t){var e=new Ji(t.shape,'\n // Error function is calculated approximately with elementary function.\n // See "Handbook of Mathematical Functions with Formulas,\n // Graphs, and Mathematical Tables", Abramowitz and Stegun.\n float p = 0.3275911;\n float a1 = 0.254829592;\n float a2 = -0.284496736;\n float a3 = 1.421413741;\n float a4 = -1.453152027;\n float a5 = 1.061405429;\n\n float sign = sign(x);\n x = abs(x);\n float t = 1.0 / (1.0 + p * x);\n return sign * (1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x));\n');return this.compileAndRun(e,[t])},t.prototype.step=function(t,e){var n=new Ji(t.shape,function(t){return void 0===t&&(t=0),Zi+"\n return x > 0.0 ? 1.0 : float("+t+");\n "}(e));return this.compileAndRun(n,[t])},t.prototype.conv2dByMatMul=function(t,e,n,r,o,i){var s=t.shape,u=this.texData.get(t.dataId),l=n.inChannels,c=s[0]*s[1]*s[2],p=n.outChannels,f="channelsLast"===n.dataFormat,d=(1===c||1===p)&&l>1e3,v=s[2]%2!=0&&!!u.isPacked;if(d||!a().getBool("WEBGL_LAZILY_UNPACK")||!a().getBool("WEBGL_PACK_BINARY_OPERATIONS")||!v){var m=f?s[0]*s[1]*s[2]:s[0]*s[2]*s[3],g=this.reshape(t,[1,m,n.inChannels]),y=this.reshape(e,[1,n.inChannels,n.outChannels]);return this.reshape(this.fusedBatchMatMul({a:g,b:y,transposeA:!1,transposeB:!1,bias:r,activation:o,preluActivationWeights:i}),n.outShape)}var x=f?s[0]*s[1]*(s[2]+1):s[0]*s[2]*(s[3]+1),b=ut.make([1,x,n.inChannels],{dataId:t.dataId},t.dtype,this),w=u.shape;u.shape=u.shape.slice(),u.shape[u.shape.length-2]++,h(we(u.shape,b.shape),function(){return"packed reshape "+u.shape+" to "+b.shape+" isn't free"});var C=this.reshape(e,[1,n.inChannels,n.outChannels]),E=this.fusedBatchMatMul({a:b,b:C,transposeA:!1,transposeB:!1,bias:r,activation:o,preluActivationWeights:i}),R=this.texData.get(E.dataId);return h(R.isPacked,function(){return"batchMatMul result is expected to be packed"}),u.shape=w,R.shape=n.outShape,ut.make(n.outShape,{dataId:E.dataId},E.dtype,this)},t.prototype.conv2dWithIm2Row=function(t,e,n,r,o,a){var i=n.filterWidth,s=n.filterHeight,u=n.inChannels,l=n.outWidth,c=n.outHeight,h="channelsLast"===n.dataFormat,p=i*s*u,f=c*l,d=[p,f],v=t.squeeze([0]),m=e.reshape([1,p,-1]),g=new di(d,v.shape,n),y=this.compileAndRun(g,[v]).reshape([1,d[0],d[1]]),x=null!=r,b=null!=a,w=o?Ns(o,!0):null,C=new bi(y.shape,[1,f,n.outChannels],!0,!1,x,w,b),E=[y,m];r&&E.push(r),b&&E.push(a);var R=this.compileAndRun(C,E);return h?R.reshape([1,c,l,n.outChannels]):R.reshape([1,n.outChannels,c,l])},t.prototype.fusedConv2d=function(t){var e=t.input,n=t.filter,r=t.convInfo,o=t.bias,i=t.activation,s=t.preluActivationWeights;if(1===r.filterHeight&&1===r.filterWidth&&1===r.dilationHeight&&1===r.dilationWidth&&1===r.strideHeight&&1===r.strideWidth&&("SAME"===r.padInfo.type||"VALID"===r.padInfo.type))return this.conv2dByMatMul(e,n,r,o,i,s);if(a().getBool("WEBGL_CONV_IM2COL")&&1===e.shape[0])return this.conv2dWithIm2Row(e,n,r,o,i,s);var u=null!=o,l=null!=s,c=i?Ns(i,!1):null,h=new Ia(r,u,c,l),p=[e,n];return o&&p.push(o),s&&p.push(s),this.compileAndRun(h,p)},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(a().getBool("WEBGL_CONV_IM2COL")&&1===t.shape[0])return this.conv2dWithIm2Row(t,e,n);var r=new Ia(n);return this.compileAndRun(r,[t,e])},t.prototype.conv2dDerInput=function(t,e,n){var r=new ba(n);return this.compileAndRun(r,[t,e])},t.prototype.conv2dDerFilter=function(t,e,n){var r=new xa(n);return this.compileAndRun(r,[t,e])},t.prototype.fusedDepthwiseConv2D=function(t){var e,n=t.input,r=t.filter,o=t.convInfo,i=t.bias,s=t.activation,u=t.preluActivationWeights,l=a().getBool("WEBGL_PACK_DEPTHWISECONV")&&o.strideWidth<=2&&o.outChannels/o.inChannels==1,c=s?Ns(s,l):null,h=[n,r],p=null!=i,f=null!=u;return p&&h.push(i),f&&h.push(u),l?(e=new Sa(o,p,c,f),this.compileAndRun(e,h,this.makePackedTensor(o.outShape,n.dtype))):(e=new Na(o,p,c,f),this.compileAndRun(e,h))},t.prototype.depthwiseConv2D=function(t,e,n){var r;return a().getBool("WEBGL_PACK_DEPTHWISECONV")&&n.strideWidth<=2&&n.outChannels/n.inChannels==1?(r=new Sa(n),this.compileAndRun(r,[t,e],this.makePackedTensor(n.outShape,t.dtype))):(r=new Na(n),this.compileAndRun(r,[t,e]))},t.prototype.depthwiseConv2DDerInput=function(t,e,n){var r=new Ra(n);return this.compileAndRun(r,[t,e])},t.prototype.depthwiseConv2DDerFilter=function(t,e,n){var r=new Ea(n);return this.compileAndRun(r,[t,e])},t.prototype.conv3d=function(t,e,n){var r=new ka(n);return this.compileAndRun(r,[t,e])},t.prototype.conv3dDerInput=function(t,e,n){var r=new Ca(n);return this.compileAndRun(r,[t,e])},t.prototype.conv3dDerFilter=function(t,e,n){var r=new wa(n);return this.compileAndRun(r,[t,e])},t.prototype.maxPool=function(t,e){var n=new ki(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 ki(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 ki(r,"max",!0),a=this.compileAndRun(o,[e]),i=new yi(r),s=this.makeOutputArray(i.outputShape,e.dtype),u=this.compileAndRun(i,[t,a],s);return a.dispose(),u},t.prototype.avgPoolBackprop=function(t,e,n){var r=new Zo(n),o=this.makeOutputArray(r.outputShape,e.dtype);return this.compileAndRun(r,[t],o)},t.prototype.cast=function(t,e){return go(t,e,this)},t.prototype.unstack=function(t,e){for(var n=t.shape[e],r=new Array(t.rank-1),o=0,a=0;a1,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],a="NHWC"===n?t.shape[2]:t.shape[3],i="NHWC"===n?t.shape[3]:t.shape[1],s=o*e,u=a*e,l=i/(e*e),c=new Fa("NHWC"===n?[r,s,u,l]:[r,l,s,u],e,n);return this.compileAndRun(c,[t])},t.prototype.split=function(t,e,n){return No(t,e,n)},t.prototype.scatterND=function(t,e,n){var r=Pr(0,t,n),o=r.sliceRank,a=r.numUpdates,i=r.sliceSize,s=r.strides,u=r.outputSize,l=[u/i,i],c=t.reshape([a,o]),h=e.reshape([a,i]);if(0===u)return yo(bn([]),n);var p=Cn(0),f=new Pi(a,o,c.rank,h.rank,s,l);return this.compileAndRun(f,[h,c,p]).reshape(n)},t.prototype.sparseToDense=function(t,e,n,r){var o=Pr(0,t,n),a=o.sliceRank,i=o.numUpdates,s=o.strides,u=o.outputSize,l=new Pi(i,a,t.rank,e.rank,s,[u,1],!1);return this.compileAndRun(l,[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 za(Ua,t.shape,e),o=new za(Va,t.shape,e),a=[this.makeComplexComponentTensorHandle(t,n.complexTensors.real),this.makeComplexComponentTensorHandle(t,n.complexTensors.imag)],i=this.compileAndRun(r,a),s=this.compileAndRun(o,a),u=this.complex(i,s).as2D(t.shape[0],t.shape[1]);return i.dispose(),s.dispose(),u},t.prototype.gatherND=function(t,e){var n=e.shape,r=n[n.length-1],o=Or(t,e),a=o[0],i=o[1],s=o[2],u=o[3],l=e.reshape([i,r]),c=t.reshape([t.size/s,s]),h=new Ka(r,u,[i,s]);return this.compileAndRun(h,[c,l]).reshape(a)},t.prototype.fill=function(t,e,n){if("string"===(n=n||B(e))){var r=k(n,v(t));return r.fill(e),ut.make(t,{values:r},n)}var o=new Ga(t,e),a=o.getCustomSetupFunc(e),i=this.makeOutputArray(t,n);return this.compileAndRun(o,[],i,a)},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 xo(t,e,n)},t.prototype.makeOutputArray=function(t,e){return ut.make(t,{},e,this)},t.prototype.makePackedTensor=function(t,e){var n=ut.make(t,{},e,this);return this.texData.get(n.dataId).isPacked=!0,n},t.prototype.unpackTensor=function(t){var e=new Is(t.shape);return this.compileAndRun(e,[t],ut.make(e.outputShape,{},t.dtype,this))},t.prototype.packTensor=function(t){var e=new Ei(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 Ai(r,n.shape);return this.compileAndRun(o,[n],null,null,!0).reshape(e)},t.prototype.decode=function(t){var e,n=this.texData.get(t),r=n.isPacked,o=n.shape,a=n.dtype,i=ye(o),s=Pt(o),u=this.makeTensorHandle(o,"float32");return this.texData.get(u.dataId).isPacked=!0,this.texData.get(u.dataId).dtype=a,this.texData.get(u.dataId).texShape=s.map(function(t){return 2*t}),e=r?new Oa(i,s):new _a(i,s),this.compileAndRun(e,[{shape:i,dtype:a,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=I(n.dtype,0),n;var s=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&&v(e.shape)<=a().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 u,l={shape:n.shape,texData:this.texData.get(n.dataId),isUniform:!1},c=function(t,e,n){var r="";e.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,a=t.constructor.name;return a+="_"+r+"_"+o}(t,s,l),h=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}}),s=i.map(function(t){return t.shapeInfo}),u={logicalShape:r.shape,texShape:r.texData.texShape,isUniform:!1,isPacked:r.texData.isPacked,flatOffset:null},l=Uo(i,u,o,e.usesPackedTextures),c=t.createProgram(l),h=null,p=t.getUniformLocation(c,"NAN",!1);1===a().getNumber("WEBGL_VERSION")&&(h=t.getUniformLocation(c,"INFINITY",!1));for(var f={},d=0;d0)return 32}return 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,a=n.values,i=n.texture,s=n.usage,u=n.isPacked;if(null==i){var l,c=null!=this.activeTimers;c&&(l=H());var h=n.texShape;if(null==h&&(h=xe(r,u),n.texShape=h),null!=a){var p=ye(r),f=void 0,d=h[1],m=h[0],g=a instanceof Uint8Array;u?(d=(e=Lt(h[0],h[1]))[0],m=e[1],f=new Wa(p,[m,d],g)):f=new La(p,[m,d],g);var y=this.makeTensorHandle([m,d],o);this.texData.get(y.dataId).usage=g?At.PIXELS:At.UPLOAD,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(y.dataId),d,m,a);var x=this.makeTensorHandle(f.outputShape,y.dtype);x.size=v(f.outputShape),this.texData.get(x.dataId).isPacked=u,this.compileAndRun(f,[y],x);var b=this.texData.get(x.dataId);n.texture=b.texture,n.texShape=b.texShape,n.isPacked=b.isPacked,n.usage=b.usage,this.disposeData(y.dataId),this.texData.delete(x.dataId),n.values=null,c&&(this.uploadWaitMs+=H()-l)}else{var w=this.acquireTexture(h,s,o,u);n.texture=w}}},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]*D(e)},t}();Nt()&&kt.registerBackend("webgl",function(){return new As},2);var Ts=mn({abs_:function(t){var e=rn(t,"x","abs");return"complex64"===e.dtype?kt.runKernel(function(t){return t.complexAbs(e)},{$x:e}):kt.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))}}})}}),Ds=mn({acos_:function(t){var e=rn(t,"x","acos");return kt.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(Cn(1).sub(n.toFloat().square()).sqrt()).neg()}}})}}),_s=mn({acosh_:function(t){var e=rn(t,"x","acosh");return kt.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())}}})}}),Os=mn({asin_:function(t){var e=rn(t,"x","asin");return kt.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(Cn(1).sub(n.toFloat().square()).sqrt())}}})}}),Fs=mn({asinh_:function(t){var e=rn(t,"x","asinh");return kt.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(Cn(1).add(n.toFloat().square()).sqrt())}}})}}),Ms=mn({atan_:function(t){var e=rn(t,"x","atan");return kt.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))}}})}}),Bs=mn({atanh_:function(t){var e=rn(t,"x","atanh");return kt.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(Cn(1).sub(n.toFloat().square()))}}})}}),Ps=mn({ceil_:function(t){var e=rn(t,"x","ceil");return kt.runKernel(function(t){return t.ceil(e)},{$x:e},function(t){return{$x:function(){return Mn(t)}}})}}),Ls=mn({clipByValue_:function(t,e,n){var r=rn(t,"x","clipByValue");return h(e<=n,function(){return"Error in clip: min ("+e+") must be less than or equal to max ("+n+")."}),kt.runKernel(function(t,o){var a=t.clip(r,e,n);return o([r]),a},{$x:r},function(t,r){var o=r[0];return{$x:function(){return t.where(o.greaterEqual(e).logicalAnd(o.lessEqual(n)),Mn(t))}}})}}),Ws=mn({cos_:function(t){var e=rn(t,"x","cos");return kt.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)}}})}}),Us=mn({cosh_:function(t){var e=rn(t,"x","cosh");return kt.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)}}})}}),Vs=mn({erf_:function(t){var e=rn(t,"x","erf");return h("int32"===e.dtype||"float32"===e.dtype,function(){return"Input dtype must be `int32` or `float32`."}),"int32"===e.dtype&&(e=e.toFloat()),kt.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)))}}})}}),zs=mn({exp_:function(t){var e=rn(t,"x","exp");return kt.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])}}})}}),Gs=mn({expm1_:function(t){var e=rn(t,"x","expm1");return kt.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())}}})}}),Hs=mn({floor_:function(t){var e=rn(t,"x","floor");return kt.runKernel(function(t){return t.floor(e)},{$x:e},function(t){return{$x:function(){return Mn(t)}}})}}),qs=mn({log_:function(t){var e=rn(t,"x","log");return kt.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())}}})}}),$s=mn({log1p_:function(t){var e=rn(t,"x","log1p");return kt.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))}}})}}),Ks=mn({logSigmoid_:function(t){var e=rn(t,"x","logSigmoid");return kt.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())}}})}}),js=mn({neg_:function(t){var e=rn(t,"x","neg");return kt.runKernel(function(t){return t.neg(e)},{$x:e},function(t){return{$x:function(){return t.neg()}}})}}),Xs=mn({reciprocal_:function(t){var e=rn(t,"x","reciprocal");return kt.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())}}})}}),Ys=mn({round_:function(t){var e=rn(t,"x","round");return kt.runKernel(function(t){return t.round(e)},{$x:e},function(t){return{$x:function(){return Mn(t)}}})}}),Qs=mn({rsqrt_:function(t){var e=rn(t,"x","rsqrt");return kt.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()}}})}}),Js=mn({sigmoid_:function(t){var e=rn(t,"x","sigmoid");return kt.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(Cn(1).sub(n)))}}})}}),Zs=mn({sign_:function(t){var e=rn(t,"x","sign");return kt.runKernel(function(t){return t.sign(e)},{$x:e},function(t){return{$x:function(){return Mn(t)}}})}}),tu=mn({isNaN_:function(t){var e=rn(t,"x","isNaN");return kt.runKernel(function(t){return t.isNaN(e)},{$x:e},function(t){return{$x:function(){return Mn(t)}}})}}),eu=mn({isInf_:function(t){var e=rn(t,"x","isInf");return kt.runKernel(function(t){return t.isInf(e)},{$x:e},function(t){return{$x:function(){return Mn(t)}}})}}),nu=mn({isFinite_:function(t){var e=rn(t,"x","isFinite");return kt.runKernel(function(t){return t.isFinite(e)},{$x:e},function(t){return{$x:function(){return Mn(t)}}})}}),ru=mn({sin_:function(t){var e=rn(t,"x","sin");return kt.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)}}})}}),ou=mn({sinh_:function(t){var e=rn(t,"x","sinh");return kt.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)}}})}}),au=mn({softplus_:function(t){var e=rn(t,"x","softplus");return kt.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())}}})}}),iu=mn({sqrt_:function(t){var e=rn(t,"x","sqrt");return kt.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))}}})}}),su=mn({square_:function(t){var e=rn(t,"x","square");return kt.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))}}})}}),uu=mn({step_:function(t,e){void 0===e&&(e=0);var n=rn(t,"x","step");return kt.runKernel(function(t){return t.step(n,e)},{$x:n},function(t){return{$x:function(){return Mn(t)}}})}}),lu=mn({tan_:function(t){var e=rn(t,"x","tan");return kt.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())}}})}}),cu=mn({tanh_:function(t){var e=rn(t,"x","tanh");return kt.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 Cn(1).sub(n.square()).mulStrict(t)}}})}});function hu(t,e,n,r,o,a){var i,s,u=rn(t,"x","batchNorm"),l=rn(e,"mean","batchNorm"),c=rn(n,"variance","batchNorm");return null!=o&&(i=rn(o,"scale","batchNorm")),null!=r&&(s=rn(r,"offset","batchNorm")),h(2===u.rank,function(){return"Error in batchNorm3D: x must be rank 3 but got rank "+u.rank+"."}),h(2===l.rank||1===l.rank,function(){return"Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank "+l.rank+"."}),h(2===c.rank||1===c.rank,function(){return"Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank "+c.rank+"."}),null!=i&&h(2===i.rank||1===i.rank,function(){return"Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank "+i.rank+"."}),null!=s&&h(2===s.rank||1===s.rank,function(){return"Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank "+s.rank+"."}),du(u,l,c,s,i,a)}function pu(t,e,n,r,o,a){var i,s,u=rn(t,"x","batchNorm"),l=rn(e,"mean","batchNorm"),c=rn(n,"variance","batchNorm");return null!=o&&(i=rn(o,"scale","batchNorm")),null!=r&&(s=rn(r,"offset","batchNorm")),h(3===u.rank,function(){return"Error in batchNorm3D: x must be rank 3 but got rank "+u.rank+"."}),h(3===l.rank||1===l.rank,function(){return"Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank "+l.rank+"."}),h(3===c.rank||1===c.rank,function(){return"Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank "+c.rank+"."}),null!=i&&h(3===i.rank||1===i.rank,function(){return"Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank "+i.rank+"."}),null!=s&&h(3===s.rank||1===s.rank,function(){return"Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank "+s.rank+"."}),du(u,l,c,s,i,a)}function fu(t,e,n,r,o,a){var i,s,u=rn(t,"x","batchNorm"),l=rn(e,"mean","batchNorm"),c=rn(n,"variance","batchNorm");return null!=o&&(i=rn(o,"scale","batchNorm")),null!=r&&(s=rn(r,"offset","batchNorm")),h(4===u.rank,function(){return"Error in batchNorm4D: x must be rank 4 but got rank "+u.rank+"."}),h(4===l.rank||1===l.rank,function(){return"Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank "+l.rank+"."}),h(4===c.rank||1===c.rank,function(){return"Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank "+c.rank+"."}),null!=i&&h(4===i.rank||1===i.rank,function(){return"Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank "+i.rank+"."}),null!=s&&h(4===s.rank||1===s.rank,function(){return"Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank "+s.rank+"."}),du(u,l,c,s,i,a)}function du(t,e,n,r,o,a){null==a&&(a=.001);var i,s,u,l=rn(t,"x","batchNorm"),c=rn(e,"mean","batchNorm"),p=rn(n,"variance","batchNorm");null!=o&&(i=rn(o,"scale","batchNorm")),null!=r&&(s=rn(r,"offset","batchNorm")),h(c.rank===p.rank,function(){return"Batch normalization gradient requires mean and variance to have equal ranks."}),h(null==s||c.rank===s.rank,function(){return"Batch normalization gradient requires mean and offset to have equal ranks."}),h(null==i||c.rank===i.rank,function(){return"Batch normalization gradient requires mean and scale to have equal ranks."}),u=0===l.rank||1===l.rank?l.as4D(1,1,1,l.size):2===l.rank?l.as4D(1,1,l.shape[0],l.shape[1]):3===l.rank?l.as4D(1,l.shape[0],l.shape[1],l.shape[2]):l;return kt.runKernel(function(t,e){var n=t.batchNormalization(u,vu(c),vu(p),a,vu(i),vu(s));return e([l,c,p,i]),n},{$x:l,$mean:c,$variance:p,$scale:i,$offset:s},function(t,e){var n=e,r=n[0],o=n[1],i=n[2],s=n[3],l=null==s?Cn(1):s,c=no(o.shape,u.shape),h=[];if(1===o.rank){for(var p=0;p0&&(e=e.sum(n)),e.reshape(r.shape)},$b:function(){var e=t,n=no(o.shape,a);return n.length>0&&(e=e.sum(n)),e.reshape(o.shape)}}})}}),_u=mn({addN_:function(t){h(Array.isArray(t),function(){return"The argument passed to tf.addN() must be a list of tensors"}),h(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 rn(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(!m(t.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});var r=e;return kt.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})}}),Ou=mn({addStrict_:function(t,e){var n=rn(t,"a","addStrict"),r=rn(e,"b","addStrict");return p(n.shape,r.shape,"Error in addStrict: "),n.add(r)}}),Fu=mn({atan2_:function(t,e){var n,r=rn(t,"a","atan2"),o=rn(e,"b","atan2");n=xt(r,o),r=n[0],o=n[1];var a=ro(r.shape,o.shape);return kt.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=Du(n.square(),r.square()),o=t.mul(r.div(e)),i=no(n.shape,a);return i.length>0&&(o=o.sum(i)),o.reshape(n.shape)},$b:function(){var e=Du(n.square(),r.square()),o=js(t.mul(n.div(e))),i=no(r.shape,a);return i.length>0&&(o=o.sum(i)),o.reshape(r.shape)}}})}}),Mu=mn({div_:function(t,e){var n,r=rn(t,"a","div"),o=rn(e,"b","div");if(n=xt(r,o),r=n[0],o=n[1],"int32"===r.dtype&&"int32"===o.dtype)return Pu(r,o);var a=ro(r.shape,o.shape);return kt.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=no(n.shape,a);return o.length>0?e.sum(o).reshape(n.shape):e},$b:function(){var e=t.mul(n.toFloat()),o=no(r.shape,a);o.length>0&&(e=e.sum(o).reshape(r.shape));var i=r.square();return e.div(i.toFloat()).neg()}}})}}),Bu=mn({divStrict_:function(t,e){var n=rn(t,"a","div"),r=rn(e,"b","div");return p(n.shape,r.shape,"Error in divideStrict: "),n.div(r)}}),Pu=mn({floorDiv_:function(t,e){var n,r=rn(t,"a","floorDiv"),o=rn(e,"b","floorDiv");n=xt(r,o),r=n[0],o=n[1];var a=ro(r.shape,o.shape);return kt.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=no(n.shape,a);return o.length>0?e.sum(o).reshape(n.shape):e},$b:function(){var e=t.mul(n.toFloat()),o=no(r.shape,a);o.length>0&&(e=e.sum(o).reshape(r.shape));var i=r.square();return e.div(i.toFloat()).neg()}}})}}),Lu=mn({maximum_:function(t,e){var n,r=rn(t,"a","maximum"),o=rn(e,"b","maximum");return n=xt(r,o),r=n[0],o=n[1],"bool"===r.dtype&&(r=r.toInt(),o=o.toInt()),ro(r.shape,o.shape),kt.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())}}})}}),Wu=mn({maximumStrict_:function(t,e){var n=rn(t,"a","maximumStrict"),r=rn(e,"b","maximumStrict");return p(n.shape,r.shape,"Error in maximumStrict: "),n.maximum(r)}}),Uu=mn({minimum_:function(t,e){var n,r=rn(t,"a","minimum"),o=rn(e,"b","minimum");return n=xt(r,o),r=n[0],o=n[1],"bool"===r.dtype&&(r=r.toInt(),o=o.toInt()),ro(r.shape,o.shape),kt.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())}}})}}),Vu=mn({minimumStrict_:function(t,e){var n=rn(t,"a","minimumStrict"),r=rn(e,"b","minimumStrict");return p(n.shape,r.shape,"Error in minimumStrict: "),n.minimum(r)}}),zu=mn({mod_:function(t,e){var n,r=rn(t,"a","mod"),o=rn(e,"b","mod");n=xt(r,o),r=n[0],o=n[1];var a=ro(r.shape,o.shape);return kt.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=no(n.shape,a);return e.length>0?t.sum(e).reshape(n.shape):t},$b:function(){var e=t.mul(n.div(r).floor().neg()),o=no(r.shape,a);return o.length>0?e.sum(o).reshape(r.shape):e}}})}}),Gu=mn({modStrict_:function(t,e){var n=rn(t,"a","modStrict"),r=rn(e,"b","modStrict");return p(n.shape,r.shape,"Error in modStrict: "),n.mod(r)}}),Hu=mn({mul_:function(t,e){var n,r=rn(t,"a","mul"),o=rn(e,"b","mul");n=xt(r,o),r=n[0],o=n[1];var a=ro(r.shape,o.shape);return kt.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=no(n.shape,a);return o.length>0?e.sum(o).reshape(n.shape):e},$b:function(){var e=t.mul(n.toFloat()),o=no(r.shape,a);return o.length>0?e.sum(o).reshape(r.shape):e}}})}}),qu=mn({mulStrict_:function(t,e){var n=rn(t,"a","mul"),r=rn(e,"b","mul");return p(n.shape,r.shape,"Error in multiplyStrict: "),n.mul(r)}}),$u=mn({pow_:function(t,e){var n=rn(t,"base","pow"),r=rn(e,"exp","pow"),o=ro(n.shape,r.shape);return t=n.cast(gt(n.dtype,r.dtype)),e=r.cast(gt(n.dtype,r.dtype)),kt.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],a=e[2];return{$base:function(){var e=r.toFloat(),a=t.mul(e.mul(n.pow(e.sub(Cn(1))))),i=no(n.shape,o);return i.length>0&&(a=a.sum(i)),a.reshape(n.shape)},$exp:function(){var e=n.greater(0),i=n.log().where(e,Mn(n)),s=t.mul(a.mul(i)),u=no(r.shape,o);return u.length>0&&(s=s.sum(u)),s.reshape(r.shape)}}})}}),Ku=mn({powStrict_:function(t,e){return p(t.shape,e.shape,"Error in powStrict: "),t.pow(e)}}),ju=mn({squaredDifference_:function(t,e){var n,r=rn(t,"a","squaredDifference"),o=rn(e,"b","squaredDifference");return n=xt(r,o),r=n[0],o=n[1],ro(r.shape,o.shape),kt.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=Cn(2);return{$a:function(){return t.mul(n.sub(r).mul(o))},$b:function(){return t.mul(r.sub(n).mul(o))}}})}}),Xu=mn({squaredDifferenceStrict_:function(t,e){var n=rn(t,"a","squaredDifferenceStrict"),r=rn(e,"b","squaredDifferenceStrict");return p(n.shape,r.shape,"Error in squaredDifferenceStrict: "),n.squaredDifference(r)}}),Yu=mn({sub_:function(t,e){var n,r=rn(t,"a","sub"),o=rn(e,"b","sub");n=xt(r,o),r=n[0],o=n[1];var a=ro(r.shape,o.shape);return kt.runKernel(function(t){return t.subtract(r,o)},{$a:r,$b:o},function(t){return{$a:function(){var e=t,n=no(r.shape,a);return n.length>0&&(e=e.sum(n)),e.reshape(r.shape)},$b:function(){var e=t,n=no(o.shape,a);return n.length>0&&(e=e.sum(n)),e.neg().reshape(o.shape)}}})}}),Qu=mn({subStrict_:function(t,e){var n=rn(t,"a","subStrict"),r=rn(e,"b","subStrict");return p(n.shape,r.shape,"Error in subStrict: "),n.sub(r)}});var Ju=mn({equal_:function(t,e){var n,r=rn(t,"a","equal"),o=rn(e,"b","equal");return n=xt(r,o),r=n[0],o=n[1],ro(r.shape,o.shape),kt.runKernel(function(t){return t.equal(r,o)},{$a:r,$b:o})}}),Zu=mn({equalStrict_:function(t,e){var n=rn(t,"a","equalStrict"),r=rn(e,"b","equalStrict");return p(n.shape,r.shape,"Error in equalStrict: "),n.equal(r)}}),tl=mn({greater_:function(t,e){var n,r=rn(t,"a","greater"),o=rn(e,"b","greater");return n=xt(r,o),r=n[0],o=n[1],ro(r.shape,o.shape),kt.runKernel(function(t){return t.greater(r,o)},{$a:r,$b:o})}}),el=mn({greaterEqual_:function(t,e){var n,r=rn(t,"a","greaterEqual"),o=rn(e,"b","greaterEqual");return n=xt(r,o),r=n[0],o=n[1],ro(r.shape,o.shape),kt.runKernel(function(t,e){var n=t.greaterEqual(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 Mn(n)},$b:function(){return Mn(r)}}})}}),nl=mn({greaterEqualStrict_:function(t,e){var n=rn(t,"a","greaterEqualStrict"),r=rn(e,"b","greaterEqualStrict");return p(n.shape,r.shape,"Error in greaterEqualStrict: "),n.greaterEqual(r)}}),rl=mn({greaterStrict_:function(t,e){var n=rn(t,"a","greaterStrict"),r=rn(e,"b","greaterStrict");return p(n.shape,r.shape,"Error in greaterStrict: "),n.greater(r)}}),ol=mn({less_:function(t,e){var n,r=rn(t,"a","less"),o=rn(e,"b","less");return n=xt(r,o),r=n[0],o=n[1],ro(r.shape,o.shape),kt.runKernel(function(t){return t.less(r,o)},{$a:r,$b:o})}}),al=mn({lessEqual_:function(t,e){var n,r=rn(t,"a","lessEqual"),o=rn(e,"b","lessEqual");return n=xt(r,o),r=n[0],o=n[1],ro(r.shape,o.shape),kt.runKernel(function(t){return t.lessEqual(r,o)},{$a:r,$b:o})}}),il=mn({lessEqualStrict_:function(t,e){var n=rn(t,"a","lessEqualStrict"),r=rn(e,"b","lessEqualStrict");return p(n.shape,r.shape,"Error in lessEqualStrict: "),n.lessEqual(r)}}),sl=mn({lessStrict_:function(t,e){var n=rn(t,"a","lessStrict"),r=rn(e,"b","lessStrict");return p(n.shape,r.shape,"Error in lessStrict: "),n.less(r)}}),ul=mn({notEqual_:function(t,e){var n,r=rn(t,"a","notEqual"),o=rn(e,"b","notEqual");return n=xt(r,o),r=n[0],o=n[1],ro(r.shape,o.shape),kt.runKernel(function(t){return t.notEqual(r,o)},{$a:r,$b:o})}}),ll=mn({notEqualStrict_:function(t,e){var n=rn(t,"a","notEqualStrict"),r=rn(e,"b","notEqualStrict");return p(n.shape,r.shape,"Error in notEqualStrict: "),n.notEqual(r)}});function cl(t,e){for(var n=[],r=t;r0,function(){return"mask cannot be scalar"}),p(u.slice(i,i+s),a.shape,"mask's shape must match the first K dimensions of tensor's shape,"),l=1,c=i;c=2&&i.rank>=2&&a.rank===i.rank,function(){return"Error in matMul: inputs must have the same rank of at least 2, got ranks "+a.rank+" and "+i.rank+"."}),h(m(p,f),function(){return"Error in matMul: outer dimensions ("+p+") and ("+f+") of Tensors with shapes "+a.shape+" and "+i.shape+" must match."}),h(s===u,function(){return"Error in matMul: inner shapes ("+s+") and ("+u+") of Tensors with shapes "+a.shape+" and "+i.shape+" and transposeA="+n+" and transposeB="+r+" must match."});var y=a.shape.slice(0,-2).concat([l,c]),x=n?a.as3D(d,s,l):a.as3D(d,l,s),b=r?i.as3D(g,c,u):i.as3D(g,u,c);return kt.runKernel(function(t,e){var o=t.batchMatMul(x,b,n,r);return e([x,b]),o},{$a:x,$b:b},function(t,e){var o=e,a=o[0],i=o[1];return n||r?!n&&r?{$a:function(){return t.matMul(i,!1,!1)},$b:function(){return t.matMul(a,!0,!1)}}:n&&!r?{$a:function(){return i.matMul(t,!1,!0)},$b:function(){return a.matMul(t,!1,!1)}}:{$a:function(){return i.matMul(t,!0,!0)},$b:function(){return t.matMul(a,!0,!0)}}:{$a:function(){return t.matMul(i,!1,!0)},$b:function(){return a.matMul(t,!0,!1)}}}).reshape(y)}}),Tl=mn({dot_:function(t,e){var n=rn(t,"t1","dot"),r=rn(e,"t2","dot");h(!(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],a=1===r.rank?r.size:r.shape[0];return h(o===a,function(){return"Error in dot: inner dimensions of inputs must match, but got "+o+" and "+a+"."}),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]))}}),Dl=mn({outerProduct_:function(t,e){var n=rn(t,"v1","outerProduct"),r=rn(e,"v2","outerProduct");return h(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))}});var _l=mn({reverse_:function(t,e){var n=rn(t,"x","reverse");if(0===n.rank)return n.clone();var r=E(e,n.shape);return kt.runKernel(function(t){return t.reverse(n,r)},{$x:n},function(t){return{$x:function(){return t.reverse(r)}}}).reshapeAs(n)}}),Ol=mn({reverse1d_:function(t){var e=rn(t,"x","reverse");return h(1===e.rank,function(){return"Error in reverse1D: x must be rank 1 but got rank "+e.rank+"."}),_l(e,0)}}),Fl=mn({reverse2d_:function(t,e){var n=rn(t,"x","reverse");return h(2===n.rank,function(){return"Error in reverse2D: x must be rank 2 but got rank "+n.rank+"."}),_l(n,e)}}),Ml=mn({reverse3d_:function(t,e){var n=rn(t,"x","reverse");return h(3===n.rank,function(){return"Error in reverse3D: x must be rank 3 but got rank "+n.rank+"."}),_l(n,e)}}),Bl=mn({reverse4d_:function(t,e){var n=rn(t,"x","reverse");return h(4===n.rank,function(){return"Error in reverse4D: x must be rank 4 but got rank "+n.rank+"."}),_l(n,e)}});function Pl(t,e,n,r,o,a){var i=rn(t,"x","maxPool"),s=i,u=!1;3===i.rank&&(u=!0,s=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),null==r&&(r=[1,1]),h(4===s.rank,function(){return"Error in maxPool: input must be rank 4 but got rank "+s.rank+"."}),h(vo(n,r),function(){return"Error in maxPool: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+r+"'"}),null!=a&&h(g(o),function(){return"Error in maxPool: pad must be an integer when using, dimRoundingMode "+a+" but got pad "+o+"."});var l=oo(s.shape,e,n,r,o,a),c=kt.runKernel(function(t,e){var n=t.maxPool(s,l);return e([s,n]),n},{x:s},function(t,a){var i=a[0],s=a[1];return{x:function(){return function(t,e,n,r,o,a,i,s){var u=rn(t,"dy","maxPoolBackprop"),l=rn(e,"input","maxPoolBackprop"),c=rn(n,"output","maxPoolBackprop");h(l.rank===u.rank,function(){return"Rank of input ("+l.rank+") does not match rank of dy ("+u.rank+")"}),null==a&&(a=[1,1]),h(vo(o,a),function(){return"Error in maxPoolBackProp: Either strides or dilations must be 1. Got strides "+o+" and dilations '"+a+"'"}),h(4===u.rank,function(){return"Error in maxPoolBackprop: dy must be rank 4 but got rank "+u.rank+"."}),h(4===l.rank,function(){return"Error in maxPoolBackprop: input must be rank 4 but got rank "+l.rank+"."}),null!=s&&h(g(i),function(){return"Error in maxPoolBackprop: pad must be an integer when using, dimRoundingMode "+s+" but got pad "+i+"."});var p=oo(l.shape,r,o,a,i,s);return kt.runKernel(function(t){return t.maxPoolBackprop(u,l,c,p)},{$dy:u,$input:l})}(t,i,s,e,n,r,o)}}});return u?c.as3D(c.shape[1],c.shape[2],c.shape[3]):c}function Ll(t,e,n,r,o,a){var i=rn(t,"x","avgPool","float32");null==r&&(r=[1,1]),h(vo(n,r),function(){return"Error in avgPool: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+r+"'"});var s=i,u=!1;3===i.rank&&(u=!0,s=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),h(4===s.rank,function(){return"Error in avgPool: x must be rank 4 but got rank "+s.rank+"."}),null!=a&&h(g(o),function(){return"Error in avgPool: pad must be an integer when using, dimRoundingMode "+a+" but got pad "+o+"."});var l=oo(s.shape,e,n,r,o,a),c=kt.runKernel(function(t){return t.avgPool(s,l)},{x:s},function(t){return{x:function(){return function(t,e,n,r,o,a){var i=rn(t,"dy","avgPoolBackprop"),s=rn(e,"input","avgPoolBackprop");h(s.rank===i.rank,function(){return"Rank of input ("+s.rank+") does not match rank of dy ("+i.rank+")"}),null==o&&(o=[1,1]),h(vo(r,o),function(){return"Error in avgPoolBackprop: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+o+"'"});var u=s,l=i,c=!1;3===s.rank&&(c=!0,u=s.as4D(1,s.shape[0],s.shape[1],s.shape[2]),l=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),h(4===l.rank,function(){return"Error in avgPoolBackprop: dy must be rank 4 but got rank "+l.rank+"."}),h(4===u.rank,function(){return"Error in avgPoolBackprop: input must be rank 4 but got rank "+u.rank+"."});var p=oo(u.shape,n,r,o,a),f=kt.runKernel(function(t){return t.avgPoolBackprop(l,u,p)},{dy4D:l,input4D:u});return c?f.as3D(f.shape[1],f.shape[2],f.shape[3]):f}(t,s,e,n,r,o)}}});return c=c.cast(i.dtype),u?c.as3D(c.shape[1],c.shape[2],c.shape[3]):c}var Wl=mn({maxPool_:function(t,e,n,r,o){return Pl(t,e,n,1,r,o)}}),Ul=mn({avgPool_:function(t,e,n,r,o){return Ll(t,e,n,1,r,o)}}),Vl=mn({pool_:function(t,e,n,r,o,a){null==o&&(o=[1,1]),null==a&&(a=1),0===r&&(r="valid");var i=rn(t,"x","maxPool"),s=i,u=!1;3===i.rank&&(u=!0,s=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),h(vo(a,o),function(){return"Error in pool: Either strides or dilations must be 1. Got strides "+a+" and dilations '"+o+"'"});var l,c=oo(s.shape,e,a,o,r),p=[c.dilationHeight,c.dilationWidth];l="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]]})}([c.filterHeight,c.filterWidth],p):[[0,0],[0,0]];var f=1===p[0]&&1===p[1],d=function(t,e,n){var r=n.map(function(t){return t[0]}),o=n.map(function(t){return t[1]}),a=t.concat(r,o),i=e.map(function(t,e){return(t-a[e]%t)%t}),s=o.map(function(t,e){return t+i[e]}),u=e.map(function(t,e){return[r[e],s[e]]}),l=e.map(function(t,e){return[0,i[e]]});return[u,l]}([c.inHeight,c.inWidth],p,l),v=d[0],m=d[1],g=f?r:"valid",y=f?s:wr(s,p,v),x=("avg"===n?function(){return Ll(y,e,a,1,g)}:function(){return Pl(y,e,a,1,g)})(),b=f?x:nr(x,p,m);return u?b.as3D(b.shape[1],b.shape[2],b.shape[3]):b}}),zl=mn({maxPool3d_:function(t,e,n,r,o,a,i){void 0===a&&(a="NDHWC");var s=rn(t,"x","maxPool3d"),u=s,l=!1;4===s.rank&&(l=!0,u=s.as5D(1,s.shape[0],s.shape[1],s.shape[2],s.shape[3])),null==i&&(i=[1,1,1]),h(5===u.rank,function(){return"Error in maxPool3d: x must be rank 5 but got rank "+u.rank+"."}),h("NDHWC"===a,function(){return"Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of "+a}),h(vo(n,i),function(){return"Error in maxPool3d: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+i+"'"}),null!=o&&h(g(r),function(){return"Error in maxPool3d: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+r+"."});var c=ao(u.shape,e,n,i,r,o,a),p=kt.runKernel(function(t,e){var n=t.maxPool3d(u,c);return e([u,n]),n},{x:u},function(t,a){var s=a[0],u=a[1];return{x:function(){return function(t,e,n,r,o,a,i,s){var u=rn(t,"dy","maxPool3dBackprop"),l=rn(e,"input","maxPool3dBackprop"),c=rn(n,"output","maxPool3dBackprop"),p=u,f=l,d=c,v=!1;4===l.rank&&(v=!0,p=u.as5D(1,u.shape[0],u.shape[1],u.shape[2],u.shape[3]),f=l.as5D(1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]),d=c.as5D(1,c.shape[0],c.shape[1],c.shape[2],c.shape[3])),h(5===p.rank,function(){return"Error in maxPool3dBackprop: dy must be rank 5 but got rank "+p.rank+"."}),h(5===f.rank,function(){return"Error in maxPool3dBackprop: input must be rank 5 but got rank "+f.rank+"."}),h(5===d.rank,function(){return"Error in maxPool3dBackprop: output must be rank 5 but got rank "+d.rank+"."}),null==a&&(a=[1,1,1]),h(vo(o,a),function(){return"Error in maxPool3dBackprop: Either strides or dilations must be 1. Got strides "+o+" and dilations '"+a+"'"}),null!=s&&h(g(i),function(){return"Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode "+s+" but got pad "+i+"."});var m=ao(f.shape,r,o,a,i,s),y=kt.runKernel(function(t){return t.maxPool3dBackprop(p,f,d,m)},{dy5D:p,input5D:f});return v?y.as4D(y.shape[1],y.shape[2],y.shape[3],y.shape[4]):y}(t,s,u,e,n,i,r,o)}}});return l?p.as4D(p.shape[1],p.shape[2],p.shape[3],p.shape[4]):p}}),Gl=mn({avgPool3d_:function(t,e,n,r,o,a,i){void 0===a&&(a="NDHWC");var s=rn(t,"x","avgPool3d","float32"),u=s,l=!1;4===s.rank&&(l=!0,u=s.as5D(1,s.shape[0],s.shape[1],s.shape[2],s.shape[3])),null==i&&(i=[1,1,1]),h(5===u.rank,function(){return"Error in avgPool3d: x must be rank 5 but got rank "+u.rank+"."}),h("NDHWC"===a,function(){return"Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of "+a}),h(vo(n,i),function(){return"Error in avgPool3d: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+i+"'"}),null!=o&&h(g(r),function(){return"Error in avgPool3d: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+r+"."});var c=ao(u.shape,e,n,i,r,o,a),p=kt.runKernel(function(t){return t.avgPool3d(u,c)},{x:u},function(t){return{x:function(){return function(t,e,n,r,o,a,i){var s=rn(t,"dy","avgPool3dBackprop"),u=rn(e,"input","avgPool3dBackprop"),l=s,c=u,p=!1;4===u.rank&&(p=!0,l=s.as5D(1,s.shape[0],s.shape[1],s.shape[2],s.shape[3]),c=u.as5D(1,u.shape[0],u.shape[1],u.shape[2],u.shape[3])),h(5===l.rank,function(){return"Error in avgPool3dBackprop: dy must be rank 5 but got rank "+l.rank+"."}),h(5===c.rank,function(){return"Error in avgPool3dBackprop: input must be rank 5 but got rank "+c.rank+"."}),null==o&&(o=[1,1,1]),h(vo(r,o),function(){return"Error in avgPool3dBackprop: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+o+"'"}),null!=i&&h(g(a),function(){return"Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+a+"."});var f=ao(c.shape,n,r,o,a,i),d=kt.runKernel(function(t){return t.avgPool3dBackprop(l,c,f)},{dy5D:l,input5D:c});return p?d.as4D(d.shape[1],d.shape[2],d.shape[3],d.shape[4]):d}(t,u,e,n,i,r,o)}}});return p=p.cast(u.dtype),l?p.as4D(p.shape[1],p.shape[2],p.shape[3],p.shape[4]):p}});var Hl=mn({slice_:function(t,e,n){var r,o,a=rn(t,"x","slice");if(0===a.rank)throw new Error("Slicing scalar is not possible");(r="number"==typeof e?[e].concat(new Array(a.rank-1).fill(0)):e.length=0?t:(h(-1===t,function(){return"Negative size values should be exactly -1 but got "+t+" for the slice() size at index "+e+"."}),a.shape[e]-r[e])}),function(t,e,n){h(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+")."}),h(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){h(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(a)),e.reshape(r.shape)}}})}}),cc=mn({relu_:function(t){var e=rn(t,"x","relu");return"bool"===e.dtype?e.toInt():kt.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())}}})}}),hc=mn({relu6_:function(t){var e=rn(t,"x","relu6");return"bool"===e.dtype?e.toInt():kt.runKernel(function(t,n){var r=t.relu6(e);return n([e]),r},{$x:e},function(t,e){var n=e[0],r=n.lessEqual(6).mul(n.step());return{$x:function(){return t.mulStrict(r.toFloat())}}})}}),pc=mn({selu_:function(t){var e=rn(t,"x","selu");return kt.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(Cn(0)),r=Cn(Yi),o=Cn(Qi),a=t.mul(o),i=t.mul(r).mul(n.toFloat().exp());return Au(e,a,i)}}})}});var fc=mn({transpose_:function(t,e){var n=rn(t,"x","transpose");return null==e&&(e=n.shape.map(function(t,e){return e}).reverse()),h(n.rank===e.length,function(){return"Error in transpose: rank of input "+n.rank+" must match length of perm "+e+"."}),e.forEach(function(t){h(t>=0&&to)throw new Error("'k' passed to topk() must be <= the last dimension ("+o+") but got "+e);var a=kt.runKernel(function(t){return t.topk(r,e,n)},{$x:r});return{values:a[0],indices:a[1]}}});var wc=mn({scatterND_:function(t,e,n){var r=rn(t,"indices","scatterND","int32"),o=rn(e,"updates","scatterND");return Br(o,r,n),kt.runKernel(function(t){return t.scatterND(r,o,n)},{$indices:r,$updates:o})}});var Cc=mn({fft_:function(t){h("complex64"===t.dtype,function(){return"The dtype for tf.spectral.fft() must be complex64 but got "+t.dtype+"."});var e=t.shape[t.shape.length-1],n=t.size/e,r=t.as2D(n,e);return kt.runKernel(function(t){return t.fft(r)},{input:t}).reshape(t.shape)}}),Ec=mn({ifft_:function(t){h("complex64"===t.dtype,function(){return"The dtype for tf.spectral.ifft() must be complex64 but got "+t.dtype+"."});var e=t.shape[t.shape.length-1],n=t.size/e,r=t.as2D(n,e);return kt.runKernel(function(t){return t.ifft(r)},{input:t}).reshape(t.shape)}}),Rc=mn({rfft_:function(t,e){h("float32"===t.dtype,function(){return"The dtype for rfft() must be real value but got "+t.dtype});var n,r=t.shape[t.shape.length-1],o=t.size/r;if(null!=e&&er){var s=t.shape.map(function(t){return t});s[t.shape.length-1]=e-r,n=t.concat(Tn(s),t.shape.length-1),r=e}else n=t;var u=n.zerosLike(),l=gn(n,u).as2D(o,r),c=Cc(l),p=Math.floor(r/2)+1,f=yn(c),d=xn(c),v=f.split([p,r-p],f.shape.length-1),m=d.split([p,r-p],d.shape.length-1),g=n.shape.slice();return g[n.shape.length-1]=p,gn(v[0],m[0]).reshape(g)}}),Ic=mn({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=Ec(r);return yn(o)}var a=[n,2*(e-1)],i=yn(t).as2D(n,e),s=xn(t).as2D(n,e),u=i.slice([0,1],[n,e-2]).reverse(1),l=s.slice([0,1],[n,e-2]).reverse(1).mul(Cn(-1)),c=i.concat(u,1),h=s.concat(l,1);return r=gn(c,h).as2D(a[0],a[1]),o=Ec(r),yn(o)}}),kc=Object.freeze({fft:Cc,ifft:Ec,rfft:Rc,irfft:Ic});var Nc=mn({sparseToDense_:function(t,e,n,r){void 0===r&&(r=0);var o=rn(t,"sparseIndices","sparseToDense","int32"),a=rn(e,"sparseValues","sparseToDense"),i=rn(r,"defaultValue","sparseToDense",a.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,a=t.rank>1?t.shape[1]:1;if(n.length!==a)throw new Error("outputShape has incorrect number of elements:, "+n.length+", should be: "+a+".");var i=e.size;if(0!==e.rank&&(1!==e.rank||i!==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,a,n,i),kt.runKernel(function(t){return t.sparseToDense(o,a,n,i)},{$sparseIndices:o,$sparseValues:a,$defaultValue:i})}});var Sc=mn({gatherND_:function(t,e){var n=rn(e,"indices","gatherND","int32"),r=rn(t,"x","gatherND");return kt.runKernel(function(t){return t.gatherND(r,n)},{$x:r,$indices:n})}});var Ac=mn({diag_:function(t){var e=rn(t,"x","diag").flatten(),n=t.shape.concat(t.shape);return kt.runKernel(function(t){return t.diag(e)},{$x:e}).reshape(n)}});var Tc=mn({dropout_:function(t,e,n,r){var o=rn(t,"x","dropout");if(h("float32"===o.dtype,function(){return"x has to be a floating point tensor since it's going to be scaled, but got a "+o.dtype+" tensor instead."}),h(e>=0&&e<1,function(){return"rate must be a float in the range [0, 1), but got "+e+"."}),0===e)return t instanceof ut?o.clone():o;var a=function(t,e){if(null==e)return t.shape.slice();if(m(t.shape,e))return e;if(t.shape.length===e.length){for(var n=[],r=0;r1,function(){return"inTopK() expects the predictions to be of rank 2 or higher, but got "+n.rank}),h(n.rank-1===a.rank,function(){return"predictions rank should be 1 larger than targets rank, but got predictions rank "+n.rank+" and targets rank "+a.rank}),p(n.shape.slice(0,n.shape.length-1),a.shape,"predictions's shape should be align with the targets' shape, except the last dimension."),i=n.shape[n.shape.length-1],h(o>0&&o<=i,function(){return"'k' passed to inTopK() must be > 0 && <= the predictions last dimension ("+i+"), but got "+o}),[4,n.data()];case 1:return s=r.sent(),[4,a.data()];case 2:for(u=r.sent(),l=[s.length/i,i],f=l[1],d=I("bool",c=l[0]),v=0;v1?s.div(Cn(i)):s}if(n===Pc.SUM_BY_NONZERO_WEIGHTS){if(null==o)return a.sum().div(Cn(r.size));var u=o.mul(An(r.shape)).notEqual(Cn(0)).sum().toFloat();return a.sum().div(u)}throw Error("Unknown reduction: "+n)}}),Vc=mn({cosineDistance_:function(t,e,n,r,o){void 0===o&&(o=Pc.SUM_BY_NONZERO_WEIGHTS);var a=rn(t,"labels","cosineDistance"),i=rn(e,"predictions","cosineDistance"),s=null;null!=r&&(s=rn(r,"weights","cosineDistance")),p(a.shape,i.shape,"Error in cosineDistance: ");var u=Cn(1).sub(a.mul(i).sum(n,!0));return Uc(u,s,o)}}),zc=mn({hingeLoss_:function(t,e,n,r){void 0===r&&(r=Pc.SUM_BY_NONZERO_WEIGHTS);var o=rn(t,"labels","hingeLoss"),a=rn(e,"predictions","hingeLoss"),i=null;null!=n&&(i=rn(n,"weights","hingeLoss")),p(o.shape,a.shape,"Error in hingeLoss: ");var s=Cn(1);o=Cn(2).mul(o).sub(s);var u=s.sub(o.mul(a)).relu();return Uc(u,i,r)}}),Gc=mn({huberLoss_:function(t,e,n,r,o){void 0===r&&(r=1),void 0===o&&(o=Pc.SUM_BY_NONZERO_WEIGHTS);var a=rn(t,"labels","huberLoss"),i=rn(e,"predictions","huberLoss"),s=null;null!=n&&(s=rn(n,"weights","huberLoss")),p(a.shape,i.shape,"Error in huberLoss: ");var u=Cn(r),l=i.sub(a).abs(),c=Uu(l,u),h=l.sub(c),f=Cn(.5).mul(c.square()).add(u.mul(h));return Uc(f,s,o)}}),Hc=mn({logLoss_:function(t,e,n,r,o){void 0===r&&(r=1e-7),void 0===o&&(o=Pc.SUM_BY_NONZERO_WEIGHTS);var a=rn(t,"labels","logLoss"),i=rn(e,"predictions","logLoss"),s=null;null!=n&&(s=rn(n,"weights","logLoss")),p(a.shape,i.shape,"Error in logLoss: ");var u=Cn(1),l=Cn(r),c=a.mul(i.add(l).log()).neg().sub(u.sub(a).mul(u.sub(i).add(l).log()));return Uc(c,s,o)}}),qc=mn({meanSquaredError_:function(t,e,n,r){void 0===r&&(r=Pc.SUM_BY_NONZERO_WEIGHTS);var o=rn(t,"labels","meanSquaredError"),a=rn(e,"predictions","meanSquaredError"),i=null;null!=n&&(i=rn(n,"weights","meanSquaredError")),p(o.shape,a.shape,"Error in meanSquaredError: ");var s=o.squaredDifference(a);return Uc(s,i,r)}}),$c=mn({sigmoidCrossEntropy_:function(t,e,n,r,o){void 0===r&&(r=0),void 0===o&&(o=Pc.SUM_BY_NONZERO_WEIGHTS);var a=rn(t,"multiClassLabels","sigmoidCrossEntropy"),i=rn(e,"logits","sigmoidCrossEntropy"),s=null;if(null!=n&&(s=rn(n,"weights","sigmoidCrossEntropy")),p(a.shape,i.shape,"Error in sigmoidCrossEntropy: "),r>0){var u=Cn(r),l=Cn(1),c=Cn(.5);a=a.mul(l.sub(u)).add(c.mul(u))}var h=function(t,e){var n=rn(t,"labels","sigmoidCrossEntropyWithLogits"),r=rn(e,"logits","sigmoidCrossEntropyWithLogits");p(n.shape,r.shape,"Error in sigmoidCrossEntropyWithLogits: ");var o=r.relu(),a=r.mul(n),i=r.abs().neg().exp().log1p();return o.sub(a).add(i)}(a,i);return Uc(h,s,o)}}),Kc=mn({softmaxCrossEntropy_:function(t,e,n,r,o){void 0===r&&(r=0),void 0===o&&(o=Pc.SUM_BY_NONZERO_WEIGHTS);var a=rn(t,"onehotLabels","softmaxCrossEntropy"),i=rn(e,"logits","softmaxCrossEntropy"),s=null;if(null!=n&&(s=rn(n,"weights","softmaxCrossEntropy")),p(a.shape,i.shape,"Error in softmaxCrossEntropy: "),r>0){var u=Cn(r),l=Cn(1),c=Cn(a.shape[1]);a=a.mul(l.sub(u)).add(u.div(c))}var h=function(t,e,n){if(void 0===n&&(n=-1),-1===n&&(n=e.rank-1),n!==e.rank-1)throw Error("Softmax cross entropy along a non-last dimension is not yet supported. Labels / logits was rank "+e.rank+" and dim was "+n);return Xr(function(t,e,r){var o=e.logSumExp([n],!0),a=e.toFloat().sub(o);return r([t,a]),{value:a.mul(t).neg().sum([n]),gradFunc:function(t,e){var r=e[0],o=e[1],a=ln(t.shape,[n]);return[t.reshape(a).mul(r.toFloat().sub(o.exp())),t.reshape(a).mul(o.exp().sub(r.toFloat()))]}}})(t,e)}(a,i);return Uc(h,s,o)}}),jc=Object.freeze({get Reduction(){return Pc},absoluteDifference:Wc,computeWeightedLoss:Uc,cosineDistance:Vc,hingeLoss:zc,huberLoss:Gc,logLoss:Hc,meanSquaredError:qc,sigmoidCrossEntropy:$c,softmaxCrossEntropy:Kc});function Xc(t,e){return void 0===e&&(e=!1),kt.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=ur(n),a=t.clone(),i=Rn([[1]],[1,1]),s=i.clone(),u=n>=r?r:n,l=function(t){var e,u=a,l=s,c=o;e=kt.tidy(function(){var e=a.slice([t,t],[n-t,1]),u=e.norm(),l=a.slice([t,t],[1,1]),c=Rn([[-1]]).where(l.greater(0),Rn([[1]])),h=l.sub(c.mul(u)),p=e.div(h);s=1===p.shape[0]?i.clone():i.concat(p.slice([1,0],[p.shape[0]-1,p.shape[1]]),0);var f=c.matMul(h).div(u).neg(),d=a.slice([t,0],[n-t,r]),v=f.mul(s);if(0===t)a=d.sub(v.matMul(s.transpose().matMul(d)));else{var m=d.sub(v.matMul(s.transpose().matMul(d)));a=a.slice([0,0],[t,r]).concat(m,0)}var g=o.slice([0,t],[n,o.shape[1]-t]);if(0===t)o=g.sub(g.matMul(s).matMul(v.transpose()));else{var y=g.sub(g.matMul(s).matMul(v.transpose()));o=o.slice([0,0],[n,t]).concat(y,1)}return[s,a,o]}),s=e[0],a=e[1],o=e[2],ze([u,l,c])},c=0;cr&&(o=o.slice([0,0],[n,r]),a=a.slice([0,0],[r,r])),[o,a]})}var Yc=mn({gramSchmidt_:function(t){var e;if(Array.isArray(t)){e=!1,h(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){h(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 Xc(t,e);var n=t.shape.slice(0,t.shape.length-2).reduce(function(t,e){return t*e}),r=kr(t.reshape([n,t.shape[t.shape.length-2],t.shape[t.shape.length-1]]),0),o=[],a=[];return r.forEach(function(t){var n=Xc(t,e),r=n[0],i=n[1];o.push(r),a.push(i)}),[Er(o,0).reshape(t.shape),Er(a,0).reshape(t.shape)]}}),Jc=Object.freeze({gramSchmidt:Yc,qr:Qc});function Zc(t,e,n,r,o){null==r&&(r=.5),null==o&&(o=Number.NEGATIVE_INFINITY);var a=t.shape[0];return n=Math.min(n,a),h(0<=r&&r<=1,function(){return"iouThreshold must be in [0, 1], but was '"+r+"'"}),h(2===t.rank,function(){return"boxes must be a 2D tensor, but was of rank '"+t.rank+"'"}),h(4===t.shape[1],function(){return"boxes must have 4 columns, but 2nd dimension was "+t.shape[1]}),h(1===e.rank,function(){return"scores must be a 1D tensor"}),h(e.shape[0]===a,function(){return"scores has incompatible shape with boxes. Expected "+a+", but was "+e.shape[0]}),{maxOutputSize:n,iouThreshold:r,scoreThreshold:o}}var th=mn({resizeBilinear_:function(t,e,n){void 0===n&&(n=!1);var r=rn(t,"images","resizeBilinear");h(3===r.rank||4===r.rank,function(){return"Error in resizeBilinear: x must be rank 3 or 4, but got rank "+r.rank+"."}),h(2===e.length,function(){return"Error in resizeBilinear: new shape must 2D, but got shape "+e+"."});var o=r,a=!1;3===r.rank&&(a=!0,o=r.as4D(1,r.shape[0],r.shape[1],r.shape[2]));var i=e[0],s=e[1],u=kt.runKernel(function(t,e){return e([o]),t.resizeBilinear(o,i,s,n)},{batchImages:o},function(t,e){return{batchImages:function(){return kt.runKernel(function(r){return r.resizeBilinearBackprop(t,e[0],n)},{})}}});return a?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}}),eh=mn({resizeNearestNeighbor_:function(t,e,n){void 0===n&&(n=!1);var r=rn(t,"images","resizeNearestNeighbor");h(3===r.rank||4===r.rank,function(){return"Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank "+r.rank+"."}),h(2===e.length,function(){return"Error in resizeNearestNeighbor: new shape must 2D, but got shape "+e+"."}),h("float32"===r.dtype||"int32"===r.dtype,function(){return"`images` must have `int32` or `float32` as dtype"});var o=r,a=!1;3===r.rank&&(a=!0,o=r.as4D(1,r.shape[0],r.shape[1],r.shape[2]));var i=e[0],s=e[1],u=kt.runKernel(function(t,e){return e([o]),t.resizeNearestNeighbor(o,i,s,n)},{batchImages:o},function(t,e){return{batchImages:function(){return kt.runKernel(function(r){return r.resizeNearestNeighborBackprop(t,e[0],n)},{})}}});return a?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}}),nh=mn({nonMaxSuppression_:function(t,e,n,r,o){void 0===r&&(r=.5),void 0===o&&(o=Number.NEGATIVE_INFINITY);var a=rn(t,"boxes","nonMaxSuppression"),i=rn(e,"scores","nonMaxSuppression"),s=Zc(a,i,n,r,o);return n=s.maxOutputSize,r=s.iouThreshold,o=s.scoreThreshold,kt.runKernel(function(t){return t.nonMaxSuppression(a,i,n,r,o)},{$boxes:a})}}),rh=function(t,e,o,a,i){return void 0===a&&(a=.5),void 0===i&&(i=Number.NEGATIVE_INFINITY),n(this,void 0,void 0,function(){var n,s,u,l,c,h,p;return r(this,function(r){switch(r.label){case 0:return n=rn(t,"boxes","nonMaxSuppressionAsync"),s=rn(e,"scores","nonMaxSuppressionAsync"),u=Zc(n,s,o,a,i),o=u.maxOutputSize,a=u.iouThreshold,i=u.scoreThreshold,[4,Promise.all([n.data(),s.data()])];case 1:return l=r.sent(),c=l[0],h=l[1],p=Io(c,h,o,a,i),n!==t&&n.dispose(),s!==e&&s.dispose(),[2,p]}})})},oh=mn({cropAndResize_:function(t,e,n,r,o,a){var i=rn(t,"image","cropAndResize","float32"),s=rn(e,"boxes","cropAndResize","float32"),u=rn(n,"boxInd","cropAndResize","int32");o=o||"bilinear",a=a||0;var l=s.shape[0];return h(4===i.rank,function(){return"Error in cropAndResize: image must be rank 4,but got rank "+i.rank+"."}),h(2===s.rank&&4===s.shape[1],function(){return"Error in cropAndResize: boxes must be have size ["+l+",4] but had shape "+s.shape+"."}),h(1===u.rank&&u.shape[0]===l,function(){return"Error in cropAndResize: boxInd must be have size ["+l+"] but had shape "+s.shape+"."}),h(2===r.length,function(){return"Error in cropAndResize: cropSize must be of length 2, but got length "+r.length+"."}),h(r[0]>=1&&r[1]>=1,function(){return"cropSize must be atleast [1,1], but was "+r}),h("bilinear"===o||"nearest"===o,function(){return"method must be bilinear or nearest, but was "+o}),kt.runKernel(function(t,e){return t.cropAndResize(i,s,u,r,o,a)},{$image:i,$boxes:s})}}),ah=Object.freeze({resizeBilinear:th,resizeNearestNeighbor:eh,nonMaxSuppression:nh,nonMaxSuppressionAsync:rh,cropAndResize:oh});var ih=mn({matMul_:function(t){var e,n=t.a,r=t.b,o=t.transposeA,a=void 0!==o&&o,i=t.transposeB,s=void 0!==i&&i,u=t.bias,l=t.activation,c=void 0===l?"linear":l,p=t.preluActivationWeights,f=rn(n,"a","fused matMul"),d=rn(r,"b","fused matMul");e=xt(f,d),f=e[0],d=e[1];var g=a?f.shape[f.rank-2]:f.shape[f.rank-1],y=s?d.shape[d.rank-1]:d.shape[d.rank-2],x=a?f.shape[f.rank-1]:f.shape[f.rank-2],b=s?d.shape[d.rank-2]:d.shape[d.rank-1],w=f.shape.slice(0,-2),C=d.shape.slice(0,-2),E=v(w),R=v(C);h(f.rank>=2&&d.rank>=2&&f.rank===d.rank,function(){return"Error in fused matMul: inputs must have the same rank of at least 2, got ranks "+f.rank+" and "+d.rank+"."}),h(m(w,C),function(){return"Error in fused matMul: outer dimensions ("+w+") and ("+C+") of Tensors with shapes "+f.shape+" and "+d.shape+" must match."}),h(g===y,function(){return"Error in fused matMul: inner shapes ("+g+") and ("+y+") of Tensors with shapes "+f.shape+" and "+d.shape+" and transposeA="+a+" and transposeB="+s+" must match."});var I,k,N=f.shape.slice(0,-2).concat([x,b]),S=a?f.as3D(E,g,x):f.as3D(E,x,g),A=s?d.as3D(R,b,y):d.as3D(R,y,b);null!=u&&ro(N,(I=xt(I=rn(u,"bias","fused matMul"),f)[0]).shape),null!=p&&(k=rn(p,"prelu weights","fused matMul"));var T={$a:S,$b:A};return null!=u&&(T.$bias=I),null!=p&&(T.$preluActivationWeights=k),kt.runKernel(function(t,e){var n=t.fusedBatchMatMul({a:S,b:A,transposeA:a,transposeB:s,bias:I,activation:c,preluActivationWeights:k});return e([S,A,n]),n},T,function(t,e){var n,r=e[0],o=e[1],i=e[2];if(null==c||"linear"===c)n=t;else{if("relu"!==c)throw new Error("Gradient for activation "+c+" has not been implemented yet.");n=t.mul(i.step())}var l={};return null!=u&&(l={$bias:function(){var t=n,e=no(I.shape,n.shape);return e.length>0&&(t=t.sum(e)),t.reshape(I.shape)}}),a||s?!a&&s?Object.assign({$a:function(){return n.matMul(o,!1,!1)},$b:function(){return n.matMul(r,!0,!1)}},l):a&&!s?Object.assign({$a:function(){return o.matMul(n,!1,!0)},$b:function(){return r.matMul(n,!1,!1)}},l):Object.assign({$a:function(){return o.matMul(n,!0,!0)},$b:function(){return n.matMul(r,!0,!0)}},l):Object.assign({$a:function(){return n.matMul(o,!1,!0)},$b:function(){return r.matMul(n,!0,!1)}},l)}).reshape(N)}}),sh=mn({conv2d_:function(t){var e=t.x,n=t.filter,r=t.strides,o=t.pad,a=t.dataFormat,i=void 0===a?"NHWC":a,s=t.dilations,u=void 0===s?[1,1]:s,l=t.dimRoundingMode,c=t.bias,p=t.activation,f=void 0===p?"linear":p,d=t.preluActivationWeights,v=rn(e,"x","conv2d"),m=rn(n,"filter","conv2d"),y=v,x=!1;3===v.rank&&(x=!0,y=v.as4D(1,v.shape[0],v.shape[1],v.shape[2])),h(4===y.rank,function(){return"Error in fused conv2d: input must be rank 4, but got rank "+y.rank+"."}),h(4===m.rank,function(){return"Error in fused conv2d: filter must be rank 4, but got rank "+m.rank+"."}),null!=l&&h(g(o),function(){return"Error in fused conv2d: pad must be an integer when using, dimRoundingMode "+l+" but got pad "+o+"."}),h(y.shape[3]===m.shape[2],function(){return"Error in conv2d: depth of input ("+y.shape[3]+") must match input depth for filter "+m.shape[2]+"."}),h(vo(r,u),function(){return"Error in conv2D: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+u+"'"}),h("NHWC"===i,function(){return"Error in conv2d: got dataFormat of "+i+" but only NHWC is currently supported."});var b,w,C=io(y.shape,m.shape,r,u,o,l);null!=c&&(b=xt(b=rn(c,"bias","fused conv2d"),v)[0],ro(C.outShape,b.shape)),null!=d&&(w=rn(d,"prelu weights","fused conv2d"));var E={x:y,$filter:m};null!=c&&(E.$bias=b),null!=d&&(E.$preluActivationWeights=w);var R=kt.runKernel(function(t,e){var n=t.fusedConv2d({input:y,filter:m,convInfo:C,bias:b,activation:f,preluActivationWeights:w});return e([m,y,n]),n},E,function(t,e){var n,a=e,i=a[0],s=a[1],l=a[2];if(null==f||"linear"===f)n=t;else{if("relu"!==f)throw new Error("Gradient for activation "+f+" has not been implemented yet.");n=t.mul(l.step())}h(fo(u),function(){return"Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '"+u+"'"});var p={};return null!=c&&(p={$bias:function(){var t=n,e=no(b.shape,n.shape);return e.length>0&&(t=t.sum(e)),t.reshape(b.shape)}}),Object.assign({x:function(){return Cl(s.shape,n,i,r,o)},$filter:function(){return wl(s,n,i.shape,r,o)}},p)});return x?R.as3D(R.shape[1],R.shape[2],R.shape[3]):R}}),uh=mn({depthwiseConv2d_:function(t){var e=t.x,n=t.filter,r=t.strides,o=t.pad,a=(t.dataFormat,t.dilations),i=void 0===a?[1,1]:a,s=t.dimRoundingMode,u=t.bias,l=t.activation,c=void 0===l?"linear":l,p=t.preluActivationWeights,f=rn(e,"x","depthwiseConv2d"),d=rn(n,"filter","depthwiseConv2d"),v=f,m=!1;3===f.rank&&(m=!0,v=f.as4D(1,f.shape[0],f.shape[1],f.shape[2])),h(4===v.rank,function(){return"Error in fused depthwiseConv2d: input must be rank 4, but got rank "+v.rank+"."}),h(4===d.rank,function(){return"Error in fused depthwiseConv2d: filter must be rank 4, but got rank "+d.rank+"."}),h(v.shape[3]===d.shape[2],function(){return"Error in fused depthwiseConv2d: number of input channels ("+v.shape[3]+") must match the inChannels dimension in filter "+d.shape[2]+"."}),null==i&&(i=[1,1]),h(vo(r,i),function(){return"Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+i+"'"}),null!=s&&h(g(o),function(){return"Error in fused depthwiseConv2d: pad must be an integer when using dimRoundingMode "+s+" but got pad "+o+"."});var y,x,b=io(v.shape,d.shape,r,i,o,s,!0);null!=u&&(y=xt(y=rn(u,"bias","fused conv2d"),f)[0],ro(b.outShape,y.shape)),null!=p&&(x=rn(p,"prelu weights","fused depthwiseConv2d"));var w={x:v,$filter:d};null!=u&&(w.$bias=y),null!=p&&(w.$preluActivationWeights=x);var C=kt.runKernel(function(t,e){var n=t.fusedDepthwiseConv2D({input:v,filter:d,convInfo:b,bias:y,activation:c,preluActivationWeights:x});return e([v,d,n]),n},w,function(t,e){h(fo(i),function(){return"Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '"+i+"'"});var n,r=e[0],o=e[1],a=e[2];if(null==c||"linear"===c)n=t;else{if("relu"!==c)throw new Error("Gradient for activation "+c+" has not been implemented yet.");n=t.mul(a.step())}var s={};return null!=u&&(s={$bias:function(){var t=n,e=no(y.shape,n.shape);return e.length>0&&(t=t.sum(e)),t.reshape(y.shape)}}),Object.assign({x:function(){return Rl(r.shape,n,o,b)},$filter:function(){return Il(r,n,o.shape,b)}},s)});return m?C.as3D(C.shape[1],C.shape[2],C.shape[3]):C}}),lh=Object.freeze({matMul:ih,conv2d:sh,depthwiseConv2d:uh}),ch=Object.freeze({image:ah,linalg:Jc,losses:jc,spectral:kc,fused:lh,signal:Bc,conv1d:yl,conv2d:xl,conv3d:bl,depthwiseConv2d:El,separableConv2d:kl,conv2dTranspose:Nl,conv3dTranspose:Sl,op:mn,batchNormalization2d:gu,batchNormalization3d:yu,batchNormalization4d:xu,batchNormalization:bu,batchNorm:wu,batchNorm2d:Cu,batchNorm3d:Eu,batchNorm4d:Ru,booleanMaskAsync:dl,complex:gn,real:yn,imag:xn,concat:Bn,concat1d:Pn,concat2d:Ln,concat3d:Wn,concat4d:Un,split:Vn,matMul:Al,dot:Tl,outerProduct:Dl,reverse:_l,reverse1d:Ol,reverse2d:Fl,reverse3d:Ml,reverse4d:Bl,maxPool:Wl,avgPool:Ul,pool:Vl,maxPool3d:zl,avgPool3d:Gl,slice:Hl,slice1d:ql,slice2d:$l,slice3d:Kl,slice4d:jl,abs:Ts,acos:Ds,acosh:_s,asin:Os,asinh:Fs,atan:Ms,atanh:Bs,ceil:Ps,clipByValue:Ls,cos:Ws,cosh:Us,erf:Vs,exp:zs,expm1:Gs,floor:Hs,log:qs,log1p:$s,logSigmoid:Ks,neg:js,reciprocal:Xs,round:Ys,rsqrt:Qs,sigmoid:Js,sign:Zs,isNaN:tu,isInf:eu,isFinite:nu,sin:ru,sinh:ou,softplus:au,sqrt:iu,square:su,step:uu,tan:lu,tanh:cu,all:Yl,any:Ql,argMax:Jl,argMin:Zl,logSumExp:tc,max:ec,mean:nc,min:rc,moments:oc,sum:ac,prod:ic,equal:Ju,equalStrict:Zu,greater:tl,greaterEqual:el,greaterEqualStrict:nl,greaterStrict:rl,less:ol,lessEqual:al,lessEqualStrict:il,lessStrict:sl,notEqual:ul,notEqualStrict:ll,add:Du,addN:_u,addStrict:Ou,atan2:Fu,div:Mu,divStrict:Bu,floorDiv:Pu,maximum:Lu,maximumStrict:Wu,minimum:Uu,minimumStrict:Vu,mod:zu,modStrict:Gu,mul:Hu,mulStrict:qu,pow:$u,powStrict:Ku,squaredDifference:ju,squaredDifferenceStrict:Xu,sub:Yu,subStrict:Qu,elu:sc,leakyRelu:uc,prelu:lc,relu:cc,relu6:hc,selu:pc,logicalAnd:Iu,logicalNot:ku,logicalOr:Nu,logicalXor:Su,where:Au,whereAsync:Tu,buffer:tr,print:er,batchToSpaceND:nr,cast:rr,clone:or,cumsum:ar,depthToSpace:ir,expandDims:sr,eye:ur,multinomial:lr,oneHot:cr,pad:hr,pad1d:pr,pad2d:fr,pad3d:dr,pad4d:vr,rand:mr,randomNormal:gr,randomGamma:yr,randomUniform:xr,reshape:br,spaceToBatchND:wr,squeeze:Cr,stack:Er,tile:Rr,truncatedNormal:Ir,unstack:kr,setdiff1dAsync:Nr,fill:Dn,linspace:_n,ones:An,range:On,scalar:Cn,tensor:bn,tensor1d:En,tensor2d:Rn,tensor3d:In,tensor4d:kn,tensor5d:Nn,tensor6d:Sn,zeros:Tn,onesLike:Fn,zerosLike:Mn,transpose:fc,softmax:Qr,logSoftmax:Jr,localResponseNormalization:dc,norm:vc,gather:pl,unsortedSegmentSum:fl,basicLSTMCell:mc,multiRNNCell:gc,movingAverage:yc,stridedSlice:xc,topk:bc,scatterND:wc,fft:Cc,ifft:Ec,rfft:Rc,irfft:Ic,sparseToDense:Nc,gatherND:Sc,diag:Ac,dropout:Tc,hannWindow:_c,hammingWindow:Oc,frame:Fc,stft:Mc,inTopKAsync:Lc});function hh(t,e,n,r){if("linear"===n)return t.linear(e);if("relu"===n)return t.relu(e);if("elu"===n)return t.elu(e);if("relu6"===n)return t.relu6(e);if("prelu"===n)return t.prelu(e,r);throw new Error("Activation "+n+" has not been implemented for the CPU backend.")}var ph=function(){function t(){if(this.blockSize=48,this.firstUse=!0,a().get("IS_BROWSER")){var t="undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(300,150):"undefined"!=typeof document?document.createElement("canvas"):null;null!==t&&(this.fromPixels2DContext=t.getContext("2d"))}this.data=new Zr(this,kt)}return t.prototype.register=function(t,e,n){if(this.firstUse&&(this.firstUse=!1,a().get("IS_NODE")&&tn("\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,o=t.data instanceof Uint8Array,i="undefined"!=typeof ImageData&&t instanceof ImageData,s="undefined"!=typeof HTMLVideoElement&&t instanceof HTMLVideoElement,u="undefined"!=typeof HTMLImageElement&&t instanceof HTMLImageElement,l=s?[t.videoWidth,t.videoHeight]:[t.width,t.height],c=l[0],h=l[1];if(a().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,c,h).data;else if(i||o)n=t.data;else{if(!u&&!s)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=c,this.fromPixels2DContext.canvas.height=h,this.fromPixels2DContext.drawImage(t,0,0,c,h),n=this.fromPixels2DContext.getImageData(0,0,c,h).data}if(4===e)r=new Int32Array(n);else{var p=c*h;r=new Int32Array(p*e);for(var f=0;fp&&(p=m,f=d)}u[c]=f}return i},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=gt(t.dtype,"int32"),a=Tn(t.shape,o),i=this.readSync(a.dataId),s=this.readSync(t.dataId),u=t.shape[t.rank-1],l=r?function(t,e){return t+u-e-1}:function(t,e){return t+e},c=0;ce?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:v(e.shape.slice(1)),c=0;c=0&&e>=0?n:(n+e)%e})},t.prototype.max=function(t,e){this.assertNotComplex(t,"max"),cn("max",e,t.rank);for(var n=un(t.shape,e),r=n[0],o=n[1],a=Tn(r,t.dtype),i=v(o),s=this.readSync(a.dataId),u=this.readSync(t.dataId),l=0;lh&&(h=f)}s[l]=h}return a},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"),cn("all",e,t.rank);for(var n=un(t.shape,e),r=n[0],o=n[1],a=Tn(r,t.dtype),i=v(o),s=this.readSync(a.dataId),u=this.readSync(t.dataId),l=0;l0?n[r]=1:n[r]=0;return ut.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 ut.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 ut.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),a=0;a=1?o[a]:o[a]*(i+1)}return ut.make(e.shape,{values:n})},t.prototype.selu=function(t){this.assertNotComplex(t,"selu");for(var e=Yi,n=Qi,r=new Float32Array(t.size),o=this.readSync(t.dataId),a=0;a=0?n*i:e*(Math.exp(i)-1)}return ut.make(t.shape,{values:r})},t.prototype.clip=function(t,e,n){this.assertNotComplex(t,"clip");for(var r=new Float32Array(t.size),o=this.readSync(t.dataId),a=0;an?n:i-e,i=r[o]0?1:e}return ut.make(t.shape,{values:n})},t.prototype.fusedConv2d=function(t){var e=t.input,n=t.filter,r=t.convInfo,o=t.bias,a=t.activation,i=t.preluActivationWeights,s=this.conv2d(e,n,r);return o&&(s=this.add(s,o)),a&&(s=hh(this,s,a,i)),s},t.prototype.conv2d=function(t,e,n){this.assertNotComplex([t,e],"conv2d");for(var r=n.filterHeight,o=n.filterWidth,a=n.dilationHeight,i=n.dilationWidth,s=n.padInfo.left,u=n.padInfo.top,l="channelsLast"===n.dataFormat,c=tr(n.outShape,t.dtype),h=t.strides[0],p=l?t.strides[1]:t.strides[2],f=l?t.strides[2]:1,d=l?1:t.strides[1],v=c.strides[0],m=l?c.strides[1]:c.strides[2],g=l?c.strides[2]:1,y=l?1:c.strides[1],x=this.readSync(t.dataId),b=this.readSync(e.dataId),w=c.values,C=0;C=n.inHeight))for(var T=S*e.strides[0],D=E+A*p,_=0;_=n.inWidth))for(var P=D+B*f,L=T+M*e.strides[1],W=0;W=n.inDepth))for(var R=C*e.strides[0],I=g+E*t.strides[1],k=0;k=n.inHeight))for(var D=R+A*e.strides[1],_=I+T*t.strides[2],O=0;O=n.inWidth))for(var L=D+B*e.strides[2],W=_+P*n.inChannels,U=L,V=0;V=n.inHeight))for(var C=b*e.strides[0],E=v+w*t.strides[1],R=0;R=n.inWidth))for(var A=C+N*e.strides[1],T=E+S*n.inChannels,D=I,_=A,O=0;OD?D=P:"avg"===n&&(_+=P,O++)}if(isNaN(D))break}d[k+N*g+w]="avg"===n?_/O:D}return f.toTensor()},t.prototype.maxPool=function(t,e){return this.pool(t,e,"max")},t.prototype.maxPoolPositions=function(t,e){for(var n=tr(e.outShape,"int32"),r=e.strideHeight,o=e.strideWidth,a=e.dilationHeight,i=e.dilationWidth,s=e.effectiveFilterHeight,u=e.effectiveFilterWidth,l=e.padInfo.top,c=e.padInfo.left,h=this.bufferSync(t),p=0;pC&&(C=S,E=I*u+N)}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),a=r.strideHeight,i=r.strideWidth,s=r.dilationHeight,u=r.dilationWidth,l=r.effectiveFilterHeight,c=r.effectiveFilterWidth,h=c-1-r.padInfo.left,p=l-1-r.padInfo.top,f=tr(e.shape,"float32"),d=this.bufferSync(o),v=this.bufferSync(t),m=0;m=r.outHeight||Math.floor(R)!==R))for(var I=0;I=r.outWidth||Math.floor(k)!==k)){var N=l*c-1-d.get(m,R,k,g)===E*c+I?1:0;if(0!==N)C+=v.get(m,R,k,g)*N}}}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,a=n.filterHeight,i=n.filterWidth,s=n.dilationHeight,u=n.dilationWidth,l=n.effectiveFilterHeight,c=n.effectiveFilterWidth,h=c-1-n.padInfo.left,p=l-1-n.padInfo.top,f=tr(e.shape,"float32"),d=1/(a*i),v=this.bufferSync(t),m=0;m=n.outHeight||Math.floor(R)!==R))for(var I=0;I=n.outWidth||Math.floor(k)!==k))C+=v.get(m,R,k,g)}}f.set(C*d,m,y,x,g)}return f.toTensor()},t.prototype.pool3d=function(t,e,n){this.assertNotComplex(t,"pool3d");for(var r=e.strideDepth,o=e.strideHeight,a=e.strideWidth,i=e.dilationDepth,s=e.dilationHeight,u=e.dilationWidth,l=e.effectiveFilterDepth,c=e.effectiveFilterHeight,h=e.effectiveFilterWidth,p=e.padInfo.front,f=e.padInfo.top,d=e.padInfo.left,v="max"===n?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,m=this.readSync(t.dataId),g=tr(e.outShape,t.dtype),y=g.values,x=e.outShape[1]*e.outShape[2]*e.outShape[3]*e.outShape[4],b=e.outShape[2]*e.outShape[3]*e.outShape[4],w=e.outShape[3]*e.outShape[4],C=e.outShape[4],E=0;Ez?z=Y:"avg"===n&&(G+=Y,H++),isNaN(z))break}if(isNaN(z))break}if(isNaN(z))break}y[V+k]="avg"===n?G/H:z}}}return g.toTensor()},t.prototype.avgPool3d=function(t,e){return this.assertNotComplex(t,"avgPool3d"),this.pool3d(t,e,"avg").toFloat()},t.prototype.avgPool3dBackprop=function(t,e,n){this.assertNotComplex([t,e],"avgPool3dBackprop");for(var r=n.strideDepth,o=n.strideHeight,a=n.strideWidth,i=n.filterDepth,s=n.filterHeight,u=n.filterWidth,l=n.dilationDepth,c=n.dilationHeight,h=n.dilationWidth,p=n.effectiveFilterDepth,f=n.effectiveFilterHeight,d=n.effectiveFilterWidth,v=p-1-n.padInfo.front,m=d-1-n.padInfo.left,g=f-1-n.padInfo.top,y=tr(e.shape,"float32"),x=1/(i*s*u),b=this.bufferSync(t),w=0;w=n.outDepth||Math.floor(D)!==D))for(var _=0;_=n.outHeight||Math.floor(O)!==O))for(var F=0;F=n.outWidth||Math.floor(M)!==M))A+=b.get(w,D,O,M,C)}}}y.set(A*x,w,E,R,I,C)}return y.toTensor()},t.prototype.maxPool3d=function(t,e){return this.assertNotComplex(t,"maxPool3d"),this.pool3d(t,e,"max").toFloat()},t.prototype.maxPool3dPositions=function(t,e){for(var n=tr(e.outShape,"int32"),r=e.strideDepth,o=e.strideHeight,a=e.strideWidth,i=e.dilationDepth,s=e.dilationHeight,u=e.dilationWidth,l=e.effectiveFilterDepth,c=e.effectiveFilterHeight,h=e.effectiveFilterWidth,p=e.padInfo.front,f=e.padInfo.top,d=e.padInfo.left,v=this.bufferSync(t),m=0;m=T&&(T=L,D=O*c*h+M*c+P)}n.set(D,m,y,C,k,g)}}}return n.toTensor()},t.prototype.maxPool3dBackprop=function(t,e,n,r){this.assertNotComplex([e,n],"maxPool3dBackprop");for(var o=this.maxPool3dPositions(e,r),a=r.strideDepth,i=r.strideHeight,s=r.strideWidth,u=r.dilationDepth,l=r.dilationHeight,c=r.dilationWidth,h=r.effectiveFilterDepth,p=r.effectiveFilterHeight,f=r.effectiveFilterWidth,d=h-1-r.padInfo.front,v=f-1-r.padInfo.left,m=p-1-r.padInfo.top,g=tr(e.shape,"float32"),y=this.bufferSync(o),x=this.bufferSync(t),b=0;b=r.outDepth||Math.floor(T)!==T))for(var D=0;D=r.outHeight||Math.floor(_)!==_))for(var O=0;O=r.outWidth||Math.floor(F)!==F)){var M=h*p*f-1-y.get(b,T,_,F,w)===A*p*f+D*f+O?1:0;if(0!==M)S+=x.get(b,T,_,F,w)*M}}}}g.set(S,b,C,E,R,w)}return g.toTensor()},t.prototype.cast=function(t,e){return go(t,e,this)},t.prototype.reshape=function(t,e){return yo(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,a=o[0],i=o[1],s=o[2],u=o[3],l=this.readSync(t.dataId),c=new Float32Array(v([a,e,n,u])),h=[r&&e>1?i-1:i,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],m=h[1]/p[1],g=0;g1?a-1:a,n&&c>1?i-1:i],f=[n&&l>1?l-1:l,n&&c>1?c-1:c],d=p[0]/f[0],v=p[1]/f[1],m=this.readSync(t.dataId),g=0,y=0;y1?i-1:i,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?a-1:a,n&&c>1?i-1:i],d=[n&&l>1?l-1:l,n&&c>1?c-1:c],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=l)){var M=C+F*t.strides[1],B=F*v;if(E===Math.min(a-1,n?Math.round(B):Math.floor(B)))for(var P=0;P=c)){var W=M+L*t.strides[2],U=L*m;N===Math.min(i-1,n?Math.round(U):Math.floor(U))&&(_+=p[W+D])}}}}h[S+D]=_}return kn(h,e.shape,e.dtype)},t.prototype.batchNormalization=function(t,e,n,r,o,a){this.assertNotComplex([t,e,n,o,a],"batchNorm");for(var i=this.readSync(t.dataId),s=this.readSync(e.dataId),u=this.readSync(n.dataId),l=o?this.readSync(o.dataId):new Float32Array([1]),c=a?this.readSync(a.dataId):new Float32Array([0]),h=new Float32Array(i.length),p=c.length,f=l.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 kn(h,t.shape)},t.prototype.localResponseNormalization4D=function(t,e,n,r,o){this.assertNotComplex(t,"localResponseNormalization4D");var a=t.shape[3],i=a-1,s=this.readSync(t.dataId),u=t.size,l=new Float32Array(u);function c(t){for(var n=t%a,r=t-n+Math.max(0,n-e),o=t-n+Math.min(n+e,i),u=0;r<=o;r++){var l=s[r];u+=l*l}return u}for(var h=0;h=0&&a[i]1,function(){return"blockSize should be > 1 for depthToSpace, but was: "+e});for(var r=t.shape[0],o=t.shape[1],a=t.shape[2],i=t.shape[3],s=o*e,u=a*e,l=i/(e*e),c=this.readSync(t.dataId),p=new Float32Array(r*s*u*l),f=0,d=0;d=s))for(var N=p>1?(R-C)*(u-1)/(p-1):0,S=f>1?(I-E)*(l-1)/(f-1):0,A=0;A1?C*(u-1)+A*N:.5*(C+R)*(u-1);if(T<0||T>u-1)for(var D=0;D1?E*(l-1)+D*S:.5*(E+I)*(l-1))<0||q>l-1)for(_=0;_1?E*(l-1)+D*S:.5*(E+I)*(l-1))<0||q>l-1)for(_=0;_=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();h(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 Ah(t){if(-1===t.indexOf(Nh))throw new Error("The url string provided does not contain a scheme. Supported schemes are: "+Sh.getSchemes().join(","));return{scheme:t.split(Nh)[0],path:t.split(Nh)[1]}}function Th(t,e,o){return void 0===o&&(o=!1),n(this,void 0,void 0,function(){var n,a,i,s,u,l,c,p,f;return r(this,function(r){switch(r.label){case 0:return h(t!==e,function(){return"Old path and new path are the same: '"+t+"'"}),h((n=kh.getLoadHandlers(t)).length>0,function(){return"Copying failed because no load handler is found for source URL "+t+"."}),h(n.length<2,function(){return"Copying failed because more than one ("+n.length+") load handlers for source URL "+t+"."}),a=n[0],h((i=kh.getSaveHandlers(e)).length>0,function(){return"Copying failed because no save handler is found for destination URL "+e+"."}),h(i.length<2,function(){return"Copying failed because more than one ("+n.length+") save handlers for destination URL "+e+"."}),s=i[0],u=Ah(t).scheme,l=Ah(t).path,c=u===Ah(t).scheme,[4,a.load()];case 1:return p=r.sent(),o&&c?[4,Sh.getManager(u).removeModel(l)]:[3,3];case 2:r.sent(),r.label=3;case 3:return[4,s.save(p)];case 4:return f=r.sent(),!o||c?[3,6]:[4,Sh.getManager(u).removeModel(l)];case 5:r.sent(),r.label=6;case 6:return[2,f.modelArtifactsInfo]}})})}var Dh="models_store",_h="model_info_store";function Oh(){if(!a().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 Fh(t){var e=t.result;e.createObjectStore(Dh,{keyPath:"modelPath"}),e.createObjectStore(_h,{keyPath:"modelPath"})}var Mh=function(){function t(t){if(this.indexedDB=Oh(),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 n(this,void 0,void 0,function(){return r(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 n(this,void 0,void 0,function(){return r(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 Fh(o)},o.onsuccess=function(){var a=o.result;if(null==e){var i=a.transaction(Dh,"readonly"),s=i.objectStore(Dh).get(n.modelPath);s.onsuccess=function(){if(null==s.result)return a.close(),r(new Error("Cannot find model with path '"+n.modelPath+"' in IndexedDB."));t(s.result.modelArtifacts)},s.onerror=function(t){return a.close(),r(s.error)},i.oncomplete=function(){return a.close()}}else{var u,l=Ih(e),c=a.transaction(_h,"readwrite"),h=c.objectStore(_h),p=h.put({modelPath:n.modelPath,modelArtifactsInfo:l});p.onsuccess=function(){var o=(u=a.transaction(Dh,"readwrite")).objectStore(Dh).put({modelPath:n.modelPath,modelArtifacts:e,modelArtifactsInfo:l});o.onsuccess=function(){return t({modelArtifactsInfo:l})},o.onerror=function(t){var e=(h=c.objectStore(_h)).delete(n.modelPath);e.onsuccess=function(){return a.close(),r(o.error)},e.onerror=function(t){return a.close(),r(o.error)}}},p.onerror=function(t){return a.close(),r(p.error)},c.oncomplete=function(){null==u?a.close():u.oncomplete=function(){return a.close()}}}},o.onerror=function(t){return r(o.error)}})},t.URL_SCHEME="indexeddb://",t}(),Bh=function(t){return a().getBool("IS_BROWSER")&&!Array.isArray(t)&&t.startsWith(Mh.URL_SCHEME)?(e=t.slice(Mh.URL_SCHEME.length),new Mh(e)):null;var e};kh.registerSaveRouter(Bh),kh.registerLoadRouter(Bh);var Ph=function(){function t(){this.indexedDB=Oh()}return t.prototype.listModels=function(){return n(this,void 0,void 0,function(){var t=this;return r(this,function(e){return[2,new Promise(function(e,n){var r=t.indexedDB.open("tensorflowjs",1);r.onupgradeneeded=function(){return Fh(r)},r.onsuccess=function(){var t=r.result,o=t.transaction(_h,"readonly"),a=o.objectStore(_h).getAll();a.onsuccess=function(){for(var t={},n=0,r=a.result;n0,function(){return"promises must be a none empty array"})}(t),function(t,e){h(t>=0&&t<=1,function(){return"Progress fraction must be in range [0, 1], but got startFraction "+t}),h(e>=0&&e<=1,function(){return"Progress fraction must be in range [0, 1], but got endFraction "+e}),h(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(a){return a.then(function(a){var i=n+ ++o/t.length*(r-n);return e(i),a}),a}))}function rp(t,e){return n(this,void 0,void 0,function(){var n,o,i,s,u,l,c,h,p;return r(this,function(r){switch(r.label){case 0:return null==e&&(e={}),n=null==e.fetchFunc?a().platform.fetch:e.fetchFunc,o=t.map(function(t){return n(t,e.requestInit,{isBinary:!0})}),i=0,s=.5,null!=e.onProgress?[3,2]:[4,Promise.all(o)];case 1:return u=r.sent(),[3,4];case 2:return[4,np(o,e.onProgress,i,s)];case 3:u=r.sent(),r.label=4;case 4:return l=u.map(function(t){return t.arrayBuffer()}),c=.5,h=1,null!=e.onProgress?[3,6]:[4,Promise.all(l)];case 5:return p=r.sent(),[3,8];case 6:return[4,np(l,e.onProgress,c,h)];case 7:p=r.sent(),r.label=8;case 8:return[2,p]}})})}function op(t){var e=this;return function(o,a,i){return void 0===a&&(a=""),n(e,void 0,void 0,function(){var e,n,s,u,l,c,h,p,f,d;return r(this,function(r){switch(r.label){case 0:if(e=o.map(function(){return!1}),n={},s=null!=i?i.map(function(){return!1}):[],u=[],o.forEach(function(t,r){var o=0;t.weights.forEach(function(t){var a="quantization"in t?t.quantization.dtype:t.dtype,l=gh[a]*v(t.shape),c=function(){e[r]=!0,null==n[r]&&(n[r]=[]),n[r].push({manifestEntry:t,groupOffset:o,sizeBytes:l})};null!=i?i.forEach(function(e,n){e===t.name&&(c(),s[n]=!0)}):c(),u.push(t.name),o+=l})}),!s.every(function(t){return t}))throw l=i.filter(function(t,e){return!s[e]}),new Error("Could not find weights in manifest with names: "+l.join(", ")+". \nManifest JSON has weights with names: "+u.join(", ")+".");return c=e.reduce(function(t,e,n){return e&&t.push(n),t},[]),h=[],c.forEach(function(t){o[t].paths.forEach(function(t){var e=a+(a.endsWith("/")?"":"/")+t;h.push(e)})}),[4,t(h)];case 1:return p=r.sent(),f={},d=0,c.forEach(function(t){for(var e=o[t].paths.length,r=0,a=0;a0,function(){return"URL path for http must not be null, undefined or empty."}),Array.isArray(t)&&h(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 n(this,void 0,void 0,function(){var e,n,o,a;return r(this,function(r){switch(r.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}],o={modelTopology:t.modelTopology,format:t.format,generatedBy:t.generatedBy,convertedBy:t.convertedBy,userDefinedMetadata:t.userDefinedMetadata,weightsManifest:n},e.body.append("model.json",new Blob([JSON.stringify(o)],{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((a=r.sent()).ok)return[2,{modelArtifactsInfo:Ih(t),responses:[a]}];throw new Error("BrowserHTTPRequest.save() failed due to HTTP response status "+a.status+".")}})})},t.prototype.load=function(){return n(this,void 0,void 0,function(){var t,e,n,o,a,i,s,u;return r(this,function(r){switch(r.label){case 0:return[4,this.fetch(this.path,this.requestInit)];case 1:if(!(t=r.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.");r.label=2;case 2:return r.trys.push([2,4,,5]),[4,t.json()];case 3:return e=r.sent(),[3,5];case 4:throw r.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(o=e.modelTopology,a=e.weightsManifest,null==o&&null==a)throw new Error("The JSON from HTTP path "+this.path+" contains neither model topology or manifest for weights.");return null==a?[3,7]:[4,this.loadWeights(a)];case 6:u=r.sent(),i=u[0],s=u[1],r.label=7;case 7:return[2,{modelTopology:o,weightSpecs:i,weightData:s}]}})})},t.prototype.loadWeights=function(t){return n(this,void 0,void 0,function(){var e,n,o,a,i,s,u,l,c,h,p;return r(this,function(r){switch(r.label){case 0:for(e=Array.isArray(this.path)?this.path[1]:this.path,n=function(t){var e=t.lastIndexOf("/"),n=t.lastIndexOf("?"),r=t.substring(0,e),o=n>e?t.substring(n):"";return[r+"/",o]}(e),o=n[0],a=n[1],i=this.weightPathPrefix||o,s=[],u=0,l=t;u0&&Number.isInteger(n),function(){return"If provided, numClasses must be a positive integer, but got "+n}),h(1===r.rank,function(){return"Expected the rank of labels to be 1, but got "+r.rank}),h(1===o.rank,function(){return"Expected the rank of predictions to be 1, but got "+o.rank}),h(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."}),h(n>0&&Number.isInteger(n),function(){return"numClasses is required to be a positive integer, but got "+n});var a=cr(r.asType("int32"),n),i=cr(o.asType("int32"),n);return a.transpose().matMul(i).asType("int32")}}),fp=Object.freeze({confusionMatrix:pp});var dp=mn({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.");var n="undefined"!=typeof HTMLVideoElement&&t instanceof HTMLVideoElement;if(n&&n&&t.readyState<2)throw new Error("The video element has not loaded data yet. Please wait for `loadeddata` event on the